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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
435ff3174248bfe89a5bc43622a3e57b8eda0030 | 6,497 | cc | C++ | Alignment/CocoaFit/src/FittedEntriesSet.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | Alignment/CocoaFit/src/FittedEntriesSet.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | Alignment/CocoaFit/src/FittedEntriesSet.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | // COCOA class implementation file
//Id: FittedEntriesSet.cc
//CAT: Model
//
// History: v1.0
// Pedro Arce
#include <fstream>
#include <map>
#include "Alignment/CocoaFit/interface/FittedEntriesSet.h"
#include "Alignment/CocoaModel/interface/Model.h"
#include "Alignment/CocoaModel/interface/Measurement.h"
#include "Alignment/CocoaModel/interface/OpticalObject.h"
#include "Alignment/CocoaModel/interface/Entry.h"
#ifdef MAT_MESCHACH
#include "Alignment/CocoaFit/interface/MatrixMeschach.h"
#endif
//
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@2
FittedEntriesSet::FittedEntriesSet(MatrixMeschach* AtWAMatrix) {
//- theTime = Model::MeasurementsTime();
theDate = Measurement::getCurrentDate();
theTime = Measurement::getCurrentTime();
theMinEntryQuality = 2;
theEntriesErrorMatrix = AtWAMatrix;
Fill();
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@2
FittedEntriesSet::FittedEntriesSet(const std::vector<ALIstring>& wl) {
//- theTime = Model::MeasurementsTime();
theDate = wl[0];
theTime = "99:99";
theMinEntryQuality = 2;
theEntriesErrorMatrix = (MatrixMeschach*)nullptr;
FillEntriesFromFile(wl);
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
FittedEntriesSet::FittedEntriesSet(const std::vector<FittedEntriesSet*>& vSets) {
theDate = "99/99/99";
theTime = "99:99";
theMinEntryQuality = 2;
theEntriesErrorMatrix = (MatrixMeschach*)nullptr;
FillEntriesAveragingSets(vSets);
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@2
void FittedEntriesSet::Fill() {
FillEntries();
FillCorrelations();
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@2
void FittedEntriesSet::FillEntries() {
//---------- Store Fitted Entries
//----- Iterate over entry list
std::vector<Entry*>::const_iterator vecite;
for (vecite = Model::EntryList().begin(); vecite != Model::EntryList().end(); ++vecite) {
//--- Only for good quality parameters (='unk')
if ((*vecite)->quality() >= theMinEntryQuality) {
// ALIdouble dimv = (*vecite)->ValueDimensionFactor();
// ALIdouble dims = (*vecite)->SigmaDimensionFactor();
ALIint ipos = (*vecite)->fitPos();
FittedEntry* fe = new FittedEntry((*vecite), ipos, sqrt(theEntriesErrorMatrix->Mat()->me[ipos][ipos]));
//- std::cout << fe << "IN fit FE " << fe->theValue<< " " << fe->Sigma()<< " " << sqrt(theEntriesErrorMatrix->Mat()->me[NoEnt][NoEnt]) / dims<< std::endl;
theFittedEntries.push_back(fe);
}
}
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@2
void FittedEntriesSet::FillCorrelations() {
//------ Count the number of entries that will be in the set
ALIuint nent = 0;
std::vector<Entry*>::const_iterator vecite;
for (vecite = Model::EntryList().begin(); vecite != Model::EntryList().end(); ++vecite) {
if ((*vecite)->quality() > theMinEntryQuality) {
nent++;
}
}
CreateCorrelationMatrix(nent);
//---------- Store correlations
ALIuint ii;
for (ii = 0; ii < nent; ii++) {
for (ALIuint jj = ii + 1; jj < nent; jj++) {
ALIdouble corr = theEntriesErrorMatrix->Mat()->me[ii][jj];
if (corr != 0) {
corr /= (sqrt(theEntriesErrorMatrix->Mat()->me[ii][ii]) / sqrt(theEntriesErrorMatrix->Mat()->me[jj][jj]));
theCorrelationMatrix[ii][jj] = corr;
}
}
}
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@2
void FittedEntriesSet::CreateCorrelationMatrix(const ALIuint nent) {
std::vector<ALIdouble> vd(nent, 0.);
std::vector<std::vector<ALIdouble> > vvd(nent, vd);
theCorrelationMatrix = vvd;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@2
void FittedEntriesSet::FillEntriesFromFile(const std::vector<ALIstring>& wl) {
ALIuint siz = wl.size();
for (ALIuint ii = 1; ii < siz; ii += 3) {
FittedEntry* fe = new FittedEntry(wl[ii], ALIUtils::getFloat(wl[ii + 1]), ALIUtils::getFloat(wl[ii + 2]));
theFittedEntries.push_back(fe);
}
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@2
void FittedEntriesSet::FillEntriesAveragingSets(const std::vector<FittedEntriesSet*>& vSets) {
std::vector<FittedEntry*> vFEntry;
ALIuint nEntry = vSets[0]->FittedEntries().size();
// ALIuint setssiz = vSets.size();
for (ALIuint ii = 0; ii < nEntry; ii++) { // loop to FittedEntry's
if (ALIUtils::debug >= 5)
std::cout << "FillEntriesAveragingSets entry " << ii << std::endl;
vFEntry.clear();
for (ALIuint jj = 0; jj < vSets.size(); jj++) { // look for FittedEntry ii in each Sets
if (ALIUtils::debug >= 5)
std::cout << "FillEntriesAveragingSets set " << jj << std::endl;
//----- Check all have the same number of entries
if (vSets[jj]->FittedEntries().size() != nEntry) {
std::cerr << "!!! FATAL ERROR FittedEntriesSet::FillEntriesAveragingSets set number " << jj
<< " has different number of entries = " << vSets[jj]->FittedEntries().size()
<< " than first set = " << nEntry << std::endl;
exit(1);
}
vFEntry.push_back(vSets[jj]->FittedEntries()[ii]);
}
FittedEntry* fe = new FittedEntry(vFEntry);
if (ALIUtils::debug >= 5)
std::cout << "FillEntriesAveragingSets new fentry " << fe->getValue() << " " << fe->getSigma() << std::endl;
theFittedEntries.push_back(fe);
}
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@2
void FittedEntriesSet::SetOptOEntries() {
if (ALIUtils::debug >= 5)
std::cout << " FittedEntriesSet::SetOptOEntries " << theFittedEntries.size() << std::endl;
std::vector<FittedEntry*>::const_iterator ite;
for (ite = theFittedEntries.begin(); ite != theFittedEntries.end(); ++ite) {
FittedEntry* fe = (*ite);
OpticalObject* opto = Model::getOptOByName(fe->getOptOName());
Entry* entry = Model::getEntryByName(fe->getOptOName(), fe->getEntryName());
entry->setValue(fe->getValue());
entry->setSigma(fe->getSigma());
if (ALIUtils::debug >= 5)
std::cout << " FittedEntriesSet::SetOptOEntries() " << opto->name() << " " << entry->name() << std::endl;
opto->setGlobalCoordinates();
opto->setOriginalEntryValues();
}
}
| 38.672619 | 167 | 0.558104 | [
"vector",
"model"
] |
4360980ba6afaf23fd8326360becd9918a4ed443 | 12,740 | cc | C++ | api/video_codecs/video_encoder_software_fallback_wrapper.cc | 18165/webrtc | b118d428499844749df6dd28aa3dbc8d5e1484fe | [
"BSD-3-Clause"
] | 2 | 2019-08-06T16:33:09.000Z | 2020-05-01T09:23:18.000Z | api/video_codecs/video_encoder_software_fallback_wrapper.cc | lyapple2008/webrtc_simplify | c4f9bdc72d8e2648c4f4b1934d22ae94a793b553 | [
"BSD-3-Clause"
] | null | null | null | api/video_codecs/video_encoder_software_fallback_wrapper.cc | lyapple2008/webrtc_simplify | c4f9bdc72d8e2648c4f4b1934d22ae94a793b553 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "api/video_codecs/video_encoder_software_fallback_wrapper.h"
#include <stdint.h>
#include <cstdio>
#include <string>
#include <utility>
#include <vector>
#include "absl/memory/memory.h"
#include "absl/types/optional.h"
#include "api/video/video_bitrate_allocation.h"
#include "api/video/video_frame.h"
#include "api/video_codecs/video_codec.h"
#include "common_types.h" // NOLINT(build/include)
#include "modules/video_coding/include/video_error_codes.h"
#include "rtc_base/checks.h"
#include "rtc_base/logging.h"
#include "system_wrappers/include/field_trial.h"
namespace webrtc {
namespace {
const char kVp8ForceFallbackEncoderFieldTrial[] =
"WebRTC-VP8-Forced-Fallback-Encoder-v2";
bool EnableForcedFallback() {
return field_trial::IsEnabled(kVp8ForceFallbackEncoderFieldTrial);
}
bool IsForcedFallbackPossible(const VideoCodec& codec_settings) {
return codec_settings.codecType == kVideoCodecVP8 &&
codec_settings.numberOfSimulcastStreams <= 1 &&
codec_settings.VP8().numberOfTemporalLayers == 1;
}
void GetForcedFallbackParamsFromFieldTrialGroup(int* param_min_pixels,
int* param_max_pixels,
int minimum_max_pixels) {
RTC_DCHECK(param_min_pixels);
RTC_DCHECK(param_max_pixels);
std::string group =
webrtc::field_trial::FindFullName(kVp8ForceFallbackEncoderFieldTrial);
if (group.empty())
return;
int min_pixels;
int max_pixels;
int min_bps;
if (sscanf(group.c_str(), "Enabled-%d,%d,%d", &min_pixels, &max_pixels,
&min_bps) != 3) {
RTC_LOG(LS_WARNING)
<< "Invalid number of forced fallback parameters provided.";
return;
}
if (min_pixels <= 0 || max_pixels < minimum_max_pixels ||
max_pixels < min_pixels || min_bps <= 0) {
RTC_LOG(LS_WARNING) << "Invalid forced fallback parameter value provided.";
return;
}
*param_min_pixels = min_pixels;
*param_max_pixels = max_pixels;
}
class VideoEncoderSoftwareFallbackWrapper final : public VideoEncoder {
public:
VideoEncoderSoftwareFallbackWrapper(
std::unique_ptr<webrtc::VideoEncoder> sw_encoder,
std::unique_ptr<webrtc::VideoEncoder> hw_encoder);
~VideoEncoderSoftwareFallbackWrapper() override;
int32_t InitEncode(const VideoCodec* codec_settings,
int32_t number_of_cores,
size_t max_payload_size) override;
int32_t RegisterEncodeCompleteCallback(
EncodedImageCallback* callback) override;
int32_t Release() override;
int32_t Encode(const VideoFrame& frame,
const std::vector<VideoFrameType>* frame_types) override;
int32_t SetRateAllocation(const VideoBitrateAllocation& bitrate_allocation,
uint32_t framerate) override;
EncoderInfo GetEncoderInfo() const override;
private:
bool InitFallbackEncoder();
// If |forced_fallback_possible_| is true:
// The forced fallback is requested if the resolution is less than or equal to
// |max_pixels_|. The resolution is allowed to be scaled down to
// |min_pixels_|.
class ForcedFallbackParams {
public:
bool IsValid(const VideoCodec& codec) const {
return codec.width * codec.height <= max_pixels_;
}
bool active_ = false;
int min_pixels_ = 320 * 180;
int max_pixels_ = 320 * 240;
};
bool TryInitForcedFallbackEncoder();
bool TryReInitForcedFallbackEncoder();
void ValidateSettingsForForcedFallback();
bool IsForcedFallbackActive() const;
void MaybeModifyCodecForFallback();
// Settings used in the last InitEncode call and used if a dynamic fallback to
// software is required.
VideoCodec codec_settings_;
int32_t number_of_cores_;
size_t max_payload_size_;
// The last bitrate/framerate set, and a flag for noting they are set.
bool rates_set_;
VideoBitrateAllocation bitrate_allocation_;
uint32_t framerate_;
// The last channel parameters set, and a flag for noting they are set.
bool channel_parameters_set_;
uint32_t packet_loss_;
int64_t rtt_;
bool use_fallback_encoder_;
const std::unique_ptr<webrtc::VideoEncoder> encoder_;
const std::unique_ptr<webrtc::VideoEncoder> fallback_encoder_;
EncodedImageCallback* callback_;
bool forced_fallback_possible_;
ForcedFallbackParams forced_fallback_;
};
VideoEncoderSoftwareFallbackWrapper::VideoEncoderSoftwareFallbackWrapper(
std::unique_ptr<webrtc::VideoEncoder> sw_encoder,
std::unique_ptr<webrtc::VideoEncoder> hw_encoder)
: number_of_cores_(0),
max_payload_size_(0),
rates_set_(false),
framerate_(0),
channel_parameters_set_(false),
packet_loss_(0),
rtt_(0),
use_fallback_encoder_(false),
encoder_(std::move(hw_encoder)),
fallback_encoder_(std::move(sw_encoder)),
callback_(nullptr),
forced_fallback_possible_(EnableForcedFallback()) {
if (forced_fallback_possible_) {
GetForcedFallbackParamsFromFieldTrialGroup(
&forced_fallback_.min_pixels_, &forced_fallback_.max_pixels_,
encoder_->GetEncoderInfo().scaling_settings.min_pixels_per_frame -
1); // No HW below.
}
}
VideoEncoderSoftwareFallbackWrapper::~VideoEncoderSoftwareFallbackWrapper() =
default;
bool VideoEncoderSoftwareFallbackWrapper::InitFallbackEncoder() {
RTC_LOG(LS_WARNING) << "Encoder falling back to software encoding.";
const int ret = fallback_encoder_->InitEncode(
&codec_settings_, number_of_cores_, max_payload_size_);
use_fallback_encoder_ = (ret == WEBRTC_VIDEO_CODEC_OK);
if (!use_fallback_encoder_) {
RTC_LOG(LS_ERROR) << "Failed to initialize software-encoder fallback.";
fallback_encoder_->Release();
return false;
}
// Replay callback, rates, and channel parameters.
if (callback_)
fallback_encoder_->RegisterEncodeCompleteCallback(callback_);
if (rates_set_)
fallback_encoder_->SetRateAllocation(bitrate_allocation_, framerate_);
// Since we're switching to the fallback encoder, Release the real encoder. It
// may be re-initialized via InitEncode later, and it will continue to get
// Set calls for rates and channel parameters in the meantime.
encoder_->Release();
return true;
}
int32_t VideoEncoderSoftwareFallbackWrapper::InitEncode(
const VideoCodec* codec_settings,
int32_t number_of_cores,
size_t max_payload_size) {
// Store settings, in case we need to dynamically switch to the fallback
// encoder after a failed Encode call.
codec_settings_ = *codec_settings;
number_of_cores_ = number_of_cores;
max_payload_size_ = max_payload_size;
// Clear stored rate/channel parameters.
rates_set_ = false;
ValidateSettingsForForcedFallback();
// Try to reinit forced software codec if it is in use.
if (TryReInitForcedFallbackEncoder()) {
return WEBRTC_VIDEO_CODEC_OK;
}
// Try to init forced software codec if it should be used.
if (TryInitForcedFallbackEncoder()) {
return WEBRTC_VIDEO_CODEC_OK;
}
forced_fallback_.active_ = false;
int32_t ret =
encoder_->InitEncode(codec_settings, number_of_cores, max_payload_size);
if (ret == WEBRTC_VIDEO_CODEC_OK) {
if (use_fallback_encoder_) {
RTC_LOG(LS_WARNING)
<< "InitEncode OK, no longer using the software fallback encoder.";
fallback_encoder_->Release();
use_fallback_encoder_ = false;
}
if (callback_)
encoder_->RegisterEncodeCompleteCallback(callback_);
return ret;
}
// Try to instantiate software codec.
if (InitFallbackEncoder()) {
return WEBRTC_VIDEO_CODEC_OK;
}
// Software encoder failed, use original return code.
return ret;
}
int32_t VideoEncoderSoftwareFallbackWrapper::RegisterEncodeCompleteCallback(
EncodedImageCallback* callback) {
callback_ = callback;
int32_t ret = encoder_->RegisterEncodeCompleteCallback(callback);
if (use_fallback_encoder_)
return fallback_encoder_->RegisterEncodeCompleteCallback(callback);
return ret;
}
int32_t VideoEncoderSoftwareFallbackWrapper::Release() {
return use_fallback_encoder_ ? fallback_encoder_->Release()
: encoder_->Release();
}
int32_t VideoEncoderSoftwareFallbackWrapper::Encode(
const VideoFrame& frame,
const std::vector<VideoFrameType>* frame_types) {
if (use_fallback_encoder_)
return fallback_encoder_->Encode(frame, frame_types);
int32_t ret = encoder_->Encode(frame, frame_types);
// If requested, try a software fallback.
bool fallback_requested = (ret == WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE);
if (fallback_requested && InitFallbackEncoder()) {
// Start using the fallback with this frame.
return fallback_encoder_->Encode(frame, frame_types);
}
return ret;
}
int32_t VideoEncoderSoftwareFallbackWrapper::SetRateAllocation(
const VideoBitrateAllocation& bitrate_allocation,
uint32_t framerate) {
rates_set_ = true;
bitrate_allocation_ = bitrate_allocation;
framerate_ = framerate;
int32_t ret = encoder_->SetRateAllocation(bitrate_allocation_, framerate);
if (use_fallback_encoder_)
return fallback_encoder_->SetRateAllocation(bitrate_allocation_, framerate);
return ret;
}
VideoEncoder::EncoderInfo VideoEncoderSoftwareFallbackWrapper::GetEncoderInfo()
const {
EncoderInfo fallback_encoder_info = fallback_encoder_->GetEncoderInfo();
EncoderInfo default_encoder_info = encoder_->GetEncoderInfo();
EncoderInfo info =
use_fallback_encoder_ ? fallback_encoder_info : default_encoder_info;
if (forced_fallback_possible_) {
const auto settings = forced_fallback_.active_
? fallback_encoder_info.scaling_settings
: default_encoder_info.scaling_settings;
info.scaling_settings =
settings.thresholds
? VideoEncoder::ScalingSettings(settings.thresholds->low,
settings.thresholds->high,
forced_fallback_.min_pixels_)
: VideoEncoder::ScalingSettings::kOff;
} else {
info.scaling_settings = default_encoder_info.scaling_settings;
}
return info;
}
bool VideoEncoderSoftwareFallbackWrapper::IsForcedFallbackActive() const {
return (forced_fallback_possible_ && use_fallback_encoder_ &&
forced_fallback_.active_);
}
bool VideoEncoderSoftwareFallbackWrapper::TryInitForcedFallbackEncoder() {
if (!forced_fallback_possible_ || use_fallback_encoder_) {
return false;
}
// Fallback not active.
if (!forced_fallback_.IsValid(codec_settings_)) {
return false;
}
// Settings valid, try to instantiate software codec.
RTC_LOG(LS_INFO) << "Request forced SW encoder fallback: "
<< codec_settings_.width << "x" << codec_settings_.height;
if (!InitFallbackEncoder()) {
return false;
}
forced_fallback_.active_ = true;
return true;
}
bool VideoEncoderSoftwareFallbackWrapper::TryReInitForcedFallbackEncoder() {
if (!IsForcedFallbackActive()) {
return false;
}
// Forced fallback active.
if (!forced_fallback_.IsValid(codec_settings_)) {
RTC_LOG(LS_INFO) << "Stop forced SW encoder fallback, max pixels exceeded.";
return false;
}
// Settings valid, reinitialize the forced fallback encoder.
if (fallback_encoder_->InitEncode(&codec_settings_, number_of_cores_,
max_payload_size_) !=
WEBRTC_VIDEO_CODEC_OK) {
RTC_LOG(LS_ERROR) << "Failed to init forced SW encoder fallback.";
return false;
}
return true;
}
void VideoEncoderSoftwareFallbackWrapper::ValidateSettingsForForcedFallback() {
if (!forced_fallback_possible_)
return;
if (!IsForcedFallbackPossible(codec_settings_)) {
if (IsForcedFallbackActive()) {
fallback_encoder_->Release();
use_fallback_encoder_ = false;
}
RTC_LOG(LS_INFO) << "Disable forced_fallback_possible_ due to settings.";
forced_fallback_possible_ = false;
}
}
} // namespace
std::unique_ptr<VideoEncoder> CreateVideoEncoderSoftwareFallbackWrapper(
std::unique_ptr<VideoEncoder> sw_fallback_encoder,
std::unique_ptr<VideoEncoder> hw_encoder) {
return absl::make_unique<VideoEncoderSoftwareFallbackWrapper>(
std::move(sw_fallback_encoder), std::move(hw_encoder));
}
} // namespace webrtc
| 34.339623 | 80 | 0.72967 | [
"vector"
] |
cb1a63783537fa34e05a210ee6ed3ad074b60929 | 4,756 | cpp | C++ | src/code/BinaryFileParser.cpp | zoloypzuo/ZeloPy | 43d9242a509737fe1bb66deba73aa9e749b53c62 | [
"MIT"
] | null | null | null | src/code/BinaryFileParser.cpp | zoloypzuo/ZeloPy | 43d9242a509737fe1bb66deba73aa9e749b53c62 | [
"MIT"
] | null | null | null | src/code/BinaryFileParser.cpp | zoloypzuo/ZeloPy | 43d9242a509737fe1bb66deba73aa9e749b53c62 | [
"MIT"
] | null | null | null | // BinaryFileParser.cpp
// created on 2020/2/26
// author @zoloypzuo
#include "BinaryFileParser.h"
BinaryFileParser::BinaryFileParser(BufferedInputStream *buf_file_stream) {
file_stream = buf_file_stream;
}
CodeObject *BinaryFileParser::parse() {
int magic_number = file_stream->read_int();
printf("magic number is 0x%x\n", magic_number);
int moddate = file_stream->read_int();
printf("moddate is 0x%x\n", moddate);
char object_type = file_stream->read();
if (object_type == 'c') {
CodeObject *result = get_code_object();
printf("parse OK!\n");
return result;
}
return nullptr;
}
CodeObject *BinaryFileParser::get_code_object() {
int argcount = file_stream->read_int();
int nlocals = file_stream->read_int();
int stacksize = file_stream->read_int();
int flags = file_stream->read_int();
printf("flags is 0x%x\n", flags);
HiString *byte_codes = get_byte_codes();
ArrayList<HiObject *> *consts = get_consts();
ArrayList<HiObject *> *names = get_names();
ArrayList<HiObject *> *var_names = get_var_names();
ArrayList<HiObject *> *free_vars = get_free_vars();
ArrayList<HiObject *> *cell_vars = get_cell_vars();
HiString *file_name = get_file_name();
HiString *module_name = get_name();
int begin_line_no = file_stream->read_int();
HiString *lnotab = get_no_table();
return new CodeObject(argcount, nlocals, stacksize, flags, byte_codes,
consts, names, var_names, free_vars, cell_vars, file_name, module_name,
begin_line_no, lnotab);
}
HiString *BinaryFileParser::get_string() {
int length = file_stream->read_int();
char *str_value = new char[length];
for (int i = 0; i < length; i++) {
str_value[i] = file_stream->read();
}
auto *s = new HiString(str_value, length);
delete[] str_value;
return s;
}
HiString *BinaryFileParser::get_name() {
char ch = file_stream->read();
if (ch == 's') {
return get_string();
} else if (ch == 't') {
HiString *str = get_string();
_string_table.add(str);
return str;
} else if (ch == 'R') {
return _string_table.get(file_stream->read_int());
}
return nullptr;
}
HiString *BinaryFileParser::get_file_name() {
return get_name();
}
HiString *BinaryFileParser::get_byte_codes() {
assert(file_stream->read() == 's');
return get_string();
}
HiString *BinaryFileParser::get_no_table() {
char ch = file_stream->read();
if (ch != 's' && ch != 't') {
file_stream->unread();
return nullptr;
}
return get_string();
}
ArrayList<HiObject *> *BinaryFileParser::get_consts() {
if (file_stream->read() == '(') {
return get_tuple();
}
file_stream->unread();
return nullptr;
}
ArrayList<HiObject *> *BinaryFileParser::get_names() {
if (file_stream->read() == '(') {
return get_tuple();
}
file_stream->unread();
return nullptr;
}
ArrayList<HiObject *> *BinaryFileParser::get_var_names() {
if (file_stream->read() == '(') {
return get_tuple();
}
file_stream->unread();
return nullptr;
}
ArrayList<HiObject *> *BinaryFileParser::get_free_vars() {
if (file_stream->read() == '(') {
return get_tuple();
}
file_stream->unread();
return nullptr;
}
ArrayList<HiObject *> *BinaryFileParser::get_cell_vars() {
if (file_stream->read() == '(') {
return get_tuple();
}
file_stream->unread();
return nullptr;
}
ArrayList<HiObject *> *BinaryFileParser::get_tuple() {
int length = file_stream->read_int();
HiString *str;
auto *list = new ArrayList<HiObject *>(length);
for (int i = 0; i < length; i++) {
char obj_type = file_stream->read();
switch (obj_type) {
case 'c':
printf("got a code object\n");
list->add(get_code_object());
break;
case 'i':
list->add(new HiInteger(file_stream->read_int()));
break;
case 'N':
list->add(Universe::HiNone);
break;
case 't':
str = get_string();
list->add(str);
_string_table.add(str);
break;
case 's':
list->add(get_string());
break;
case 'R':
list->add(_string_table.get(file_stream->read_int()));
break;
default:
printf("parser, unrecognized type : %c\n", obj_type);
}
}
return list;
}
int BinaryFileParser::get_int() {
assert(false);
return 0;
}
| 25.031579 | 97 | 0.58095 | [
"object"
] |
cb1ac4fbddf3f7bdef1db83f559868fe986e0f18 | 1,427 | hpp | C++ | include/codegen/include/GlobalNamespace/ObjectiveListItemsList.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/GlobalNamespace/ObjectiveListItemsList.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/GlobalNamespace/ObjectiveListItemsList.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: HMUI.UIItemsList`1
#include "HMUI/UIItemsList_1.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: ObjectiveListItem
class ObjectiveListItem;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Autogenerated type: ObjectiveListItemsList
class ObjectiveListItemsList : public HMUI::UIItemsList_1<GlobalNamespace::ObjectiveListItem*> {
public:
// public System.Void .ctor()
// Offset: 0xC32F50
// Implemented from: HMUI.UIItemsList`1
// Base method: System.Void UIItemsList`1::.ctor()
// 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 ObjectiveListItemsList* New_ctor();
}; // ObjectiveListItemsList
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::ObjectiveListItemsList*, "", "ObjectiveListItemsList");
#pragma pack(pop)
| 37.552632 | 98 | 0.704975 | [
"object"
] |
cb1bac345c2671f8f672796ed28b2ba768daa53d | 9,451 | cpp | C++ | tdcpg/src/v20211118/model/Backup.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | tdcpg/src/v20211118/model/Backup.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | tdcpg/src/v20211118/model/Backup.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/tdcpg/v20211118/model/Backup.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Tdcpg::V20211118::Model;
using namespace std;
Backup::Backup() :
m_backupIdHasBeenSet(false),
m_backupTypeHasBeenSet(false),
m_backupMethodHasBeenSet(false),
m_backupDataTimeHasBeenSet(false),
m_backupDataSizeHasBeenSet(false),
m_backupTaskStartTimeHasBeenSet(false),
m_backupTaskEndTimeHasBeenSet(false),
m_backupTaskStatusHasBeenSet(false)
{
}
CoreInternalOutcome Backup::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("BackupId") && !value["BackupId"].IsNull())
{
if (!value["BackupId"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `Backup.BackupId` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_backupId = value["BackupId"].GetInt64();
m_backupIdHasBeenSet = true;
}
if (value.HasMember("BackupType") && !value["BackupType"].IsNull())
{
if (!value["BackupType"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Backup.BackupType` IsString=false incorrectly").SetRequestId(requestId));
}
m_backupType = string(value["BackupType"].GetString());
m_backupTypeHasBeenSet = true;
}
if (value.HasMember("BackupMethod") && !value["BackupMethod"].IsNull())
{
if (!value["BackupMethod"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Backup.BackupMethod` IsString=false incorrectly").SetRequestId(requestId));
}
m_backupMethod = string(value["BackupMethod"].GetString());
m_backupMethodHasBeenSet = true;
}
if (value.HasMember("BackupDataTime") && !value["BackupDataTime"].IsNull())
{
if (!value["BackupDataTime"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Backup.BackupDataTime` IsString=false incorrectly").SetRequestId(requestId));
}
m_backupDataTime = string(value["BackupDataTime"].GetString());
m_backupDataTimeHasBeenSet = true;
}
if (value.HasMember("BackupDataSize") && !value["BackupDataSize"].IsNull())
{
if (!value["BackupDataSize"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `Backup.BackupDataSize` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_backupDataSize = value["BackupDataSize"].GetInt64();
m_backupDataSizeHasBeenSet = true;
}
if (value.HasMember("BackupTaskStartTime") && !value["BackupTaskStartTime"].IsNull())
{
if (!value["BackupTaskStartTime"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Backup.BackupTaskStartTime` IsString=false incorrectly").SetRequestId(requestId));
}
m_backupTaskStartTime = string(value["BackupTaskStartTime"].GetString());
m_backupTaskStartTimeHasBeenSet = true;
}
if (value.HasMember("BackupTaskEndTime") && !value["BackupTaskEndTime"].IsNull())
{
if (!value["BackupTaskEndTime"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Backup.BackupTaskEndTime` IsString=false incorrectly").SetRequestId(requestId));
}
m_backupTaskEndTime = string(value["BackupTaskEndTime"].GetString());
m_backupTaskEndTimeHasBeenSet = true;
}
if (value.HasMember("BackupTaskStatus") && !value["BackupTaskStatus"].IsNull())
{
if (!value["BackupTaskStatus"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Backup.BackupTaskStatus` IsString=false incorrectly").SetRequestId(requestId));
}
m_backupTaskStatus = string(value["BackupTaskStatus"].GetString());
m_backupTaskStatusHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void Backup::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_backupIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "BackupId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_backupId, allocator);
}
if (m_backupTypeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "BackupType";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_backupType.c_str(), allocator).Move(), allocator);
}
if (m_backupMethodHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "BackupMethod";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_backupMethod.c_str(), allocator).Move(), allocator);
}
if (m_backupDataTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "BackupDataTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_backupDataTime.c_str(), allocator).Move(), allocator);
}
if (m_backupDataSizeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "BackupDataSize";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_backupDataSize, allocator);
}
if (m_backupTaskStartTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "BackupTaskStartTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_backupTaskStartTime.c_str(), allocator).Move(), allocator);
}
if (m_backupTaskEndTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "BackupTaskEndTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_backupTaskEndTime.c_str(), allocator).Move(), allocator);
}
if (m_backupTaskStatusHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "BackupTaskStatus";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_backupTaskStatus.c_str(), allocator).Move(), allocator);
}
}
int64_t Backup::GetBackupId() const
{
return m_backupId;
}
void Backup::SetBackupId(const int64_t& _backupId)
{
m_backupId = _backupId;
m_backupIdHasBeenSet = true;
}
bool Backup::BackupIdHasBeenSet() const
{
return m_backupIdHasBeenSet;
}
string Backup::GetBackupType() const
{
return m_backupType;
}
void Backup::SetBackupType(const string& _backupType)
{
m_backupType = _backupType;
m_backupTypeHasBeenSet = true;
}
bool Backup::BackupTypeHasBeenSet() const
{
return m_backupTypeHasBeenSet;
}
string Backup::GetBackupMethod() const
{
return m_backupMethod;
}
void Backup::SetBackupMethod(const string& _backupMethod)
{
m_backupMethod = _backupMethod;
m_backupMethodHasBeenSet = true;
}
bool Backup::BackupMethodHasBeenSet() const
{
return m_backupMethodHasBeenSet;
}
string Backup::GetBackupDataTime() const
{
return m_backupDataTime;
}
void Backup::SetBackupDataTime(const string& _backupDataTime)
{
m_backupDataTime = _backupDataTime;
m_backupDataTimeHasBeenSet = true;
}
bool Backup::BackupDataTimeHasBeenSet() const
{
return m_backupDataTimeHasBeenSet;
}
int64_t Backup::GetBackupDataSize() const
{
return m_backupDataSize;
}
void Backup::SetBackupDataSize(const int64_t& _backupDataSize)
{
m_backupDataSize = _backupDataSize;
m_backupDataSizeHasBeenSet = true;
}
bool Backup::BackupDataSizeHasBeenSet() const
{
return m_backupDataSizeHasBeenSet;
}
string Backup::GetBackupTaskStartTime() const
{
return m_backupTaskStartTime;
}
void Backup::SetBackupTaskStartTime(const string& _backupTaskStartTime)
{
m_backupTaskStartTime = _backupTaskStartTime;
m_backupTaskStartTimeHasBeenSet = true;
}
bool Backup::BackupTaskStartTimeHasBeenSet() const
{
return m_backupTaskStartTimeHasBeenSet;
}
string Backup::GetBackupTaskEndTime() const
{
return m_backupTaskEndTime;
}
void Backup::SetBackupTaskEndTime(const string& _backupTaskEndTime)
{
m_backupTaskEndTime = _backupTaskEndTime;
m_backupTaskEndTimeHasBeenSet = true;
}
bool Backup::BackupTaskEndTimeHasBeenSet() const
{
return m_backupTaskEndTimeHasBeenSet;
}
string Backup::GetBackupTaskStatus() const
{
return m_backupTaskStatus;
}
void Backup::SetBackupTaskStatus(const string& _backupTaskStatus)
{
m_backupTaskStatus = _backupTaskStatus;
m_backupTaskStatusHasBeenSet = true;
}
bool Backup::BackupTaskStatusHasBeenSet() const
{
return m_backupTaskStatusHasBeenSet;
}
| 29.350932 | 144 | 0.698445 | [
"model"
] |
cb1f280a3ee2e6c612bea7e88763b1c8a17326a3 | 7,277 | cpp | C++ | src/wallet/test/wallet_sapling_transactions_validations_tests.cpp | PivxLiteDev/PivxLite | 648d4a193b61b1996b41e9f6c6c468875c757cdd | [
"MIT"
] | null | null | null | src/wallet/test/wallet_sapling_transactions_validations_tests.cpp | PivxLiteDev/PivxLite | 648d4a193b61b1996b41e9f6c6c468875c757cdd | [
"MIT"
] | 3 | 2020-02-06T10:15:07.000Z | 2022-01-13T00:08:49.000Z | src/wallet/test/wallet_sapling_transactions_validations_tests.cpp | PivxLiteDev/PivxLite | 648d4a193b61b1996b41e9f6c6c468875c757cdd | [
"MIT"
] | 9 | 2020-03-10T14:14:25.000Z | 2022-03-05T13:43:35.000Z | // Copyright (c) 2020 The PIVX developers
// Copyright (c) 2019-2021 The PIVXL developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or https://www.opensource.org/licenses/mit-license.php.
#include "wallet/test/wallet_test_fixture.h"
#include "primitives/block.h"
#include "sapling/transaction_builder.h"
#include "sapling/sapling_operation.h"
#include "wallet/wallet.h"
#include <boost/test/unit_test.hpp>
/*
* A text fixture with a preloaded 100-blocks regtest chain, with sapling activating at block 101,
* and a wallet containing the key used for the coinbase outputs.
*/
struct TestSaplingChainSetup: public TestChain100Setup
{
std::unique_ptr<CWallet> pwalletMain;
TestSaplingChainSetup() : TestChain100Setup()
{
initZKSNARKS(); // init zk-snarks lib
bool fFirstRun;
pwalletMain = std::make_unique<CWallet>("testWallet", CWalletDBWrapper::CreateMock());
pwalletMain->LoadWallet(fFirstRun);
RegisterValidationInterface(pwalletMain.get());
int SAPLING_ACTIVATION_HEIGHT = 101;
UpdateNetworkUpgradeParameters(Consensus::UPGRADE_V5_0, SAPLING_ACTIVATION_HEIGHT);
// setup wallet
{
LOCK(pwalletMain->cs_wallet);
pwalletMain->SetMinVersion(FEATURE_SAPLING);
gArgs.ForceSetArg("-keypool", "5");
pwalletMain->SetupSPKM(true);
// import coinbase key used to generate the 100-blocks chain
BOOST_CHECK(pwalletMain->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey()));
}
WalletRescanReserver reserver(pwalletMain.get());
BOOST_CHECK(reserver.reserve());
pwalletMain->RescanFromTime(0, reserver, true /* update */);
}
~TestSaplingChainSetup()
{
UnregisterValidationInterface(pwalletMain.get());
}
};
BOOST_FIXTURE_TEST_SUITE(wallet_sapling_transactions_validations_tests, TestSaplingChainSetup)
static SaplingOperation createOperationAndBuildTx(std::unique_ptr<CWallet>& pwallet,
std::vector<SendManyRecipient> recipients,
int nextBlockHeight,
bool selectTransparentCoins)
{
// Create the operation
SaplingOperation operation(Params().GetConsensus(), nextBlockHeight, pwallet.get());
auto operationResult = operation.setRecipients(recipients)
->setSelectTransparentCoins(selectTransparentCoins)
->setSelectShieldedCoins(!selectTransparentCoins)
->build();
BOOST_ASSERT_MSG(operationResult, operationResult.getError().c_str());
CValidationState state;
BOOST_ASSERT_MSG(
CheckTransaction(operation.getFinalTx(), state, true),
"Invalid Sapling transaction");
return operation;
}
// Test double spend notes in the mempool and in blocks.
BOOST_AUTO_TEST_CASE(test_in_block_and_mempool_notes_double_spend)
{
auto ret = pwalletMain->getNewAddress("coinbase");
BOOST_CHECK(ret);
CTxDestination coinbaseDest = *ret.getObjResult();
BOOST_ASSERT_MSG(ret, "cannot create address");
BOOST_ASSERT_MSG(IsValidDestination(coinbaseDest), "invalid destination");
BOOST_ASSERT_MSG(IsMine(*pwalletMain, coinbaseDest), "destination not from wallet");
// create the chain
int tipHeight = WITH_LOCK(cs_main, return chainActive.Tip()->nHeight);
BOOST_CHECK_EQUAL(tipHeight, 100);
const CScript& scriptPubKey = GetScriptForDestination(coinbaseDest);
int nGenerateBlocks = 110;
for (int i = tipHeight; i < nGenerateBlocks; ++i) {
CreateAndProcessBlock({}, scriptPubKey);
SyncWithValidationInterfaceQueue();
}
// Verify that we are at block 110
tipHeight = WITH_LOCK(cs_main, return chainActive.Tip()->nHeight);
BOOST_CHECK_EQUAL(tipHeight, nGenerateBlocks);
// Verify that the wallet has all of the coins
BOOST_CHECK_EQUAL(pwalletMain->GetAvailableBalance(), CAmount(250 * COIN * 10)); // 10 blocks available
BOOST_CHECK_EQUAL(pwalletMain->GetImmatureBalance(), CAmount(250 * COIN * 100)); // 100 blocks immature
// Now that we have the chain, let's shield 100 PIVs
// single recipient
std::vector<SendManyRecipient> recipients;
libzcash::SaplingPaymentAddress pa = pwalletMain->GenerateNewSaplingZKey("sapling1");
recipients.emplace_back(pa, CAmount(100 * COIN), "", false);
// Create the operation and build the transaction
SaplingOperation operation = createOperationAndBuildTx(pwalletMain, recipients, tipHeight + 1, true);
// broadcast the tx to the network
std::string retHash;
BOOST_ASSERT_MSG(operation.send(retHash), "error committing and broadcasting the transaction");
// Generate a five blocks to fully confirm the tx and test balance
for (int i = 1; i <= 5; ++i) {
CreateAndProcessBlock({}, scriptPubKey, false /*fNoMempoolTx*/);
}
SyncWithValidationInterfaceQueue();
BOOST_CHECK_EQUAL(pwalletMain->GetAvailableShieldedBalance(), CAmount(100 * COIN)); // 100 shield PIVs
BOOST_CHECK_EQUAL(pwalletMain->GetUnconfirmedShieldedBalance(), CAmount(0)); // 0 shield PIVs
// ##############################################
// Context set!
// Now let's try to double spend the same note twice in the same block
// first generate a valid tx spending only one note
// Create the operation and build the transaction
auto res = pwalletMain->getNewAddress("receiveValid");
BOOST_CHECK(res);
CTxDestination tDest2 = *res.getObjResult();
std::vector<SendManyRecipient> recipients2;
recipients2.emplace_back(tDest2, CAmount(90 * COIN), false);
SaplingOperation operation2 = createOperationAndBuildTx(pwalletMain, recipients2, tipHeight + 1, false);
// Create a second transaction that spends the same note with a different output now
res = pwalletMain->getNewAddress("receiveInvalid");
BOOST_CHECK(res);
CTxDestination tDest3 = *res.getObjResult();;
std::vector<SendManyRecipient> recipients3;
recipients3.emplace_back(tDest3, CAmount(5 * COIN), false);
SaplingOperation operation3 = createOperationAndBuildTx(pwalletMain, recipients3, tipHeight + 1, false);
// Now that both transactions were created, broadcast the first one
std::string retTxHash2;
BOOST_CHECK(operation2.send(retTxHash2));
// Now broadcast the second one, this one should fail when tried to enter in the mempool as there is already another note spending the same nullifier
std::string retTxHash3;
auto opResult3 = operation3.send(retTxHash3);
BOOST_CHECK(!opResult3);
BOOST_CHECK(opResult3.getError().find("bad-txns-nullifier-double-spent"));
// let's now test it inside a block
// create the block with the two transactions and test validity
const CBlock& block = CreateAndProcessBlock({operation3.getFinalTx()}, scriptPubKey, false /*fNoMempoolTx*/);
SyncWithValidationInterfaceQueue();
{
LOCK(cs_main);
// Same tip as before, no block connection
BOOST_CHECK(chainActive.Tip()->GetBlockHash() != block.GetHash());
BOOST_ASSERT_MSG(chainActive.Tip()->nHeight, 115);
}
}
BOOST_AUTO_TEST_SUITE_END()
| 42.805882 | 153 | 0.703312 | [
"vector"
] |
cb1f66c83838f02de54ecadcbb39caf4632538e0 | 19,320 | cpp | C++ | src/analyses/reaching_definitions.cpp | mina1604/cbmc | bd1d87a2cd93e9fe1b1791b5fbc38d4505cb78b7 | [
"BSD-4-Clause"
] | null | null | null | src/analyses/reaching_definitions.cpp | mina1604/cbmc | bd1d87a2cd93e9fe1b1791b5fbc38d4505cb78b7 | [
"BSD-4-Clause"
] | 2 | 2019-04-15T16:40:08.000Z | 2019-04-16T14:18:53.000Z | src/analyses/reaching_definitions.cpp | mina1604/cbmc | bd1d87a2cd93e9fe1b1791b5fbc38d4505cb78b7 | [
"BSD-4-Clause"
] | null | null | null | /*******************************************************************\
Module: Range-based reaching definitions analysis (following Field-
Sensitive Program Dependence Analysis, Litvak et al., FSE 2010)
Author: Michael Tautschnig
Date: February 2013
\*******************************************************************/
/// \file
/// Range-based reaching definitions analysis (following Field- Sensitive
/// Program Dependence Analysis, Litvak et al., FSE 2010)
#include "reaching_definitions.h"
#include <memory>
#include <util/pointer_offset_size.h>
#include <util/prefix.h>
#include <util/make_unique.h>
#include <pointer-analysis/value_set_analysis_fi.h>
#include "is_threaded.h"
#include "dirty.h"
/// This ensures that all domains are constructed with the appropriate pointer
/// back to the analysis engine itself. Using a factory is a tad verbose
/// but it works well with the ait infrastructure.
class rd_range_domain_factoryt : public ai_domain_factoryt<rd_range_domaint>
{
public:
rd_range_domain_factoryt(
sparse_bitvector_analysist<reaching_definitiont> *_bv_container)
: bv_container(_bv_container)
{
PRECONDITION(bv_container != nullptr);
}
std::unique_ptr<statet> make(locationt) const override
{
auto p = util_make_unique<rd_range_domaint>(bv_container);
CHECK_RETURN(p->is_bottom());
return std::unique_ptr<statet>(p.release());
}
private:
sparse_bitvector_analysist<reaching_definitiont> *const bv_container;
};
reaching_definitions_analysist::reaching_definitions_analysist(
const namespacet &_ns)
: concurrency_aware_ait<rd_range_domaint>(
util_make_unique<rd_range_domain_factoryt>(this)),
ns(_ns)
{
}
reaching_definitions_analysist::~reaching_definitions_analysist()=default;
/// Given the passed variable name `identifier` it collects data from
/// `bv_container` for each `ID` in `values[identifier]` and stores them into
/// `export_cache[identifier]`. Namely, for each `reaching_definitiont` instance
/// `rd` obtained from `bv_container` it associates `rd.definition_at` with the
/// bit-range `(rd.bit_begin, rd.bit_end)`.
///
/// This function is only used to fill in the cache `export_cache` for the
/// `output` method.
void rd_range_domaint::populate_cache(const irep_idt &identifier) const
{
assert(bv_container);
valuest::const_iterator v_entry=values.find(identifier);
if(v_entry==values.end() ||
v_entry->second.empty())
return;
ranges_at_loct &export_entry=export_cache[identifier];
for(const auto &id : v_entry->second)
{
const reaching_definitiont &v=bv_container->get(id);
export_entry[v.definition_at].insert(
std::make_pair(v.bit_begin, v.bit_end));
}
}
void rd_range_domaint::transform(
const irep_idt &function_from,
locationt from,
const irep_idt &function_to,
locationt to,
ai_baset &ai,
const namespacet &ns)
{
reaching_definitions_analysist *rd=
dynamic_cast<reaching_definitions_analysist*>(&ai);
INVARIANT_STRUCTURED(
rd!=nullptr,
bad_cast_exceptiont,
"ai has type reaching_definitions_analysist");
assert(bv_container);
// kill values
if(from->is_dead())
transform_dead(ns, from);
// kill thread-local values
else if(from->is_start_thread())
transform_start_thread(ns, *rd);
// do argument-to-parameter assignments
else if(from->is_function_call())
transform_function_call(ns, function_from, from, function_to, *rd);
// cleanup parameters
else if(from->is_end_function())
transform_end_function(ns, function_from, from, function_to, to, *rd);
// lhs assignments
else if(from->is_assign())
transform_assign(ns, from, function_from, from, *rd);
// initial (non-deterministic) value
else if(from->is_decl())
transform_assign(ns, from, function_from, from, *rd);
#if 0
// handle return values
if(to->is_function_call())
{
const code_function_callt &code=to_code_function_call(to->code);
if(code.lhs().is_not_nil())
{
rw_range_set_value_sett rw_set(ns, rd->get_value_sets());
goto_rw(to, rw_set);
const bool is_must_alias=rw_set.get_w_set().size()==1;
forall_rw_range_set_w_objects(it, rw_set)
{
const irep_idt &identifier=it->first;
// ignore symex::invalid_object
const symbolt *symbol_ptr;
if(ns.lookup(identifier, symbol_ptr))
continue;
assert(symbol_ptr!=0);
const range_domaint &ranges=rw_set.get_ranges(it);
if(is_must_alias &&
(!rd->get_is_threaded()(from) ||
(!symbol_ptr->is_shared() &&
!rd->get_is_dirty()(identifier))))
for(const auto &range : ranges)
kill(identifier, range.first, range.second);
}
}
}
#endif
}
/// Computes an instance obtained from a `*this` by transformation over `DEAD v`
/// GOTO instruction. The operation simply removes `v` from `this->values`.
void rd_range_domaint::transform_dead(
const namespacet &,
locationt from)
{
const irep_idt &identifier = to_code_dead(from->code).get_identifier();
valuest::iterator entry=values.find(identifier);
if(entry!=values.end())
{
values.erase(entry);
export_cache.erase(identifier);
}
}
void rd_range_domaint::transform_start_thread(
const namespacet &ns,
reaching_definitions_analysist &rd)
{
for(valuest::iterator it=values.begin();
it!=values.end();
) // no ++it
{
const irep_idt &identifier=it->first;
if(!ns.lookup(identifier).is_shared() &&
!rd.get_is_dirty()(identifier))
{
export_cache.erase(identifier);
valuest::iterator next=it;
++next;
values.erase(it);
it=next;
}
else
++it;
}
}
void rd_range_domaint::transform_function_call(
const namespacet &ns,
const irep_idt &function_from,
locationt from,
const irep_idt &function_to,
reaching_definitions_analysist &rd)
{
const code_function_callt &code=to_code_function_call(from->code);
// only if there is an actual call, i.e., we have a body
if(function_from != function_to)
{
for(valuest::iterator it=values.begin();
it!=values.end();
) // no ++it
{
const irep_idt &identifier=it->first;
// dereferencing may introduce extra symbols
const symbolt *sym;
if((ns.lookup(identifier, sym) ||
!sym->is_shared()) &&
!rd.get_is_dirty()(identifier))
{
export_cache.erase(identifier);
valuest::iterator next=it;
++next;
values.erase(it);
it=next;
}
else
++it;
}
const symbol_exprt &fn_symbol_expr=to_symbol_expr(code.function());
const code_typet &code_type=
to_code_type(ns.lookup(fn_symbol_expr.get_identifier()).type);
for(const auto ¶m : code_type.parameters())
{
const irep_idt &identifier=param.get_identifier();
if(identifier.empty())
continue;
auto param_bits = pointer_offset_bits(param.type(), ns);
if(param_bits.has_value())
gen(from, identifier, 0, to_range_spect(*param_bits));
else
gen(from, identifier, 0, -1);
}
}
else
{
// handle return values of undefined functions
if(to_code_function_call(from->code).lhs().is_not_nil())
transform_assign(ns, from, function_from, from, rd);
}
}
void rd_range_domaint::transform_end_function(
const namespacet &ns,
const irep_idt &function_from,
locationt from,
const irep_idt &function_to,
locationt to,
reaching_definitions_analysist &rd)
{
locationt call = to;
--call;
const code_function_callt &code=to_code_function_call(call->code);
valuest new_values;
new_values.swap(values);
values=rd[call].values;
for(const auto &new_value : new_values)
{
const irep_idt &identifier=new_value.first;
if(!rd.get_is_threaded()(call) ||
(!ns.lookup(identifier).is_shared() &&
!rd.get_is_dirty()(identifier)))
{
for(const auto &id : new_value.second)
{
const reaching_definitiont &v=bv_container->get(id);
kill(v.identifier, v.bit_begin, v.bit_end);
}
}
for(const auto &id : new_value.second)
{
const reaching_definitiont &v=bv_container->get(id);
gen(v.definition_at, v.identifier, v.bit_begin, v.bit_end);
}
}
const code_typet &code_type = to_code_type(ns.lookup(function_from).type);
for(const auto ¶m : code_type.parameters())
{
const irep_idt &identifier=param.get_identifier();
if(identifier.empty())
continue;
valuest::iterator entry=values.find(identifier);
if(entry!=values.end())
{
values.erase(entry);
export_cache.erase(identifier);
}
}
// handle return values
if(code.lhs().is_not_nil())
{
#if 0
rd_range_domaint *rd_state=
dynamic_cast<rd_range_domaint*>(&(rd.get_state(call)));
assert(rd_state!=0);
rd_state->
#endif
transform_assign(ns, from, function_to, call, rd);
}
}
void rd_range_domaint::transform_assign(
const namespacet &ns,
locationt from,
const irep_idt &function_to,
locationt to,
reaching_definitions_analysist &rd)
{
rw_range_set_value_sett rw_set(ns, rd.get_value_sets());
goto_rw(function_to, to, rw_set);
const bool is_must_alias=rw_set.get_w_set().size()==1;
forall_rw_range_set_w_objects(it, rw_set)
{
const irep_idt &identifier=it->first;
// ignore symex::invalid_object
const symbolt *symbol_ptr;
if(ns.lookup(identifier, symbol_ptr))
continue;
INVARIANT_STRUCTURED(
symbol_ptr!=nullptr,
nullptr_exceptiont,
"Symbol is in symbol table");
const range_domaint &ranges=rw_set.get_ranges(it);
if(is_must_alias &&
(!rd.get_is_threaded()(from) ||
(!symbol_ptr->is_shared() &&
!rd.get_is_dirty()(identifier))))
for(const auto &range : ranges)
kill(identifier, range.first, range.second);
for(const auto &range : ranges)
gen(from, identifier, range.first, range.second);
}
}
void rd_range_domaint::kill(
const irep_idt &identifier,
const range_spect &range_start,
const range_spect &range_end)
{
assert(range_start>=0);
// -1 for objects of infinite/unknown size
if(range_end==-1)
{
kill_inf(identifier, range_start);
return;
}
assert(range_end>range_start);
valuest::iterator entry=values.find(identifier);
if(entry==values.end())
return;
bool clear_export_cache=false;
values_innert new_values;
for(values_innert::iterator
it=entry->second.begin();
it!=entry->second.end();
) // no ++it
{
const reaching_definitiont &v=bv_container->get(*it);
if(v.bit_begin >= range_end)
++it;
else if(v.bit_end!=-1 &&
v.bit_end <= range_start)
++it;
else if(v.bit_begin >= range_start &&
v.bit_end!=-1 &&
v.bit_end <= range_end) // rs <= a < b <= re
{
clear_export_cache=true;
entry->second.erase(it++);
}
else if(v.bit_begin >= range_start) // rs <= a <= re < b
{
clear_export_cache=true;
reaching_definitiont v_new=v;
v_new.bit_begin=range_end;
new_values.insert(bv_container->add(v_new));
entry->second.erase(it++);
}
else if(v.bit_end==-1 ||
v.bit_end > range_end) // a <= rs < re < b
{
clear_export_cache=true;
reaching_definitiont v_new=v;
v_new.bit_end=range_start;
reaching_definitiont v_new2=v;
v_new2.bit_begin=range_end;
new_values.insert(bv_container->add(v_new));
new_values.insert(bv_container->add(v_new2));
entry->second.erase(it++);
}
else // a <= rs < b <= re
{
clear_export_cache=true;
reaching_definitiont v_new=v;
v_new.bit_end=range_start;
new_values.insert(bv_container->add(v_new));
entry->second.erase(it++);
}
}
if(clear_export_cache)
export_cache.erase(identifier);
values_innert::iterator it=entry->second.begin();
for(const auto &id : new_values)
{
while(it!=entry->second.end() && *it<id)
++it;
if(it==entry->second.end() || id<*it)
{
entry->second.insert(it, id);
}
else if(it!=entry->second.end())
{
assert(*it==id);
++it;
}
}
}
void rd_range_domaint::kill_inf(
const irep_idt &,
const range_spect &range_start)
{
assert(range_start>=0);
#if 0
valuest::iterator entry=values.find(identifier);
if(entry==values.end())
return;
XXX export_cache_available=false;
// makes the analysis underapproximating
rangest &ranges=entry->second;
for(rangest::iterator it=ranges.begin();
it!=ranges.end();
) // no ++it
if(it->second.first!=-1 &&
it->second.first <= range_start)
++it;
else if(it->first >= range_start) // rs <= a < b <= re
{
ranges.erase(it++);
}
else // a <= rs < b < re
{
it->second.first=range_start;
++it;
}
#endif
}
/// A utility function which updates internal data structures by inserting a
/// new reaching definition record, for the variable name `identifier`, written
/// in given GOTO instruction referenced by `from`, at the range of bits defined
/// by `range_start` and `range_end`.
bool rd_range_domaint::gen(
locationt from,
const irep_idt &identifier,
const range_spect &range_start,
const range_spect &range_end)
{
// objects of size 0 like union U { signed : 0; };
if(range_start==0 && range_end==0)
return false;
assert(range_start>=0);
// -1 for objects of infinite/unknown size
assert(range_end>range_start || range_end==-1);
reaching_definitiont v;
v.identifier=identifier;
v.definition_at=from;
v.bit_begin=range_start;
v.bit_end=range_end;
if(!values[identifier].insert(bv_container->add(v)).second)
return false;
export_cache.erase(identifier);
#if 0
range_spect merged_range_end=range_end;
std::pair<valuest::iterator, bool> entry=
values.insert(std::make_pair(identifier, rangest()));
rangest &ranges=entry.first->second;
if(!entry.second)
{
for(rangest::iterator it=ranges.begin();
it!=ranges.end();
) // no ++it
{
if(it->second.second!=from ||
(it->second.first!=-1 && it->second.first <= range_start) ||
(range_end!=-1 && it->first >= range_end))
++it;
else if(it->first > range_start) // rs < a < b,re
{
if(range_end!=-1)
merged_range_end=std::max(range_end, it->second.first);
ranges.erase(it++);
}
else if(it->second.first==-1 ||
(range_end!=-1 &&
it->second.first >= range_end)) // a <= rs < re <= b
{
// nothing to do
return false;
}
else // a <= rs < b < re
{
it->second.first=range_end;
return true;
}
}
}
ranges.insert(std::make_pair(
range_start,
std::make_pair(merged_range_end, from)));
#endif
return true;
}
void rd_range_domaint::output(std::ostream &out) const
{
out << "Reaching definitions:\n";
if(has_values.is_known())
{
out << has_values.to_string() << '\n';
return;
}
for(const auto &value : values)
{
const irep_idt &identifier=value.first;
const ranges_at_loct &ranges=get(identifier);
out << " " << identifier << "[";
for(ranges_at_loct::const_iterator itl=ranges.begin();
itl!=ranges.end();
++itl)
for(rangest::const_iterator itr=itl->second.begin();
itr!=itl->second.end();
++itr)
{
if(itr!=itl->second.begin() ||
itl!=ranges.begin())
out << ";";
out << itr->first << ":" << itr->second;
out << "@" << itl->first->location_number;
}
out << "]\n";
clear_cache(identifier);
}
}
/// \return returns true iff there is something new
bool rd_range_domaint::merge_inner(
values_innert &dest,
const values_innert &other)
{
bool more=false;
#if 0
ranges_at_loct::iterator itr=it->second.begin();
for(const auto &o : ito->second)
{
while(itr!=it->second.end() && itr->first<o.first)
++itr;
if(itr==it->second.end() || o.first<itr->first)
{
it->second.insert(o);
more=true;
}
else if(itr!=it->second.end())
{
assert(itr->first==o.first);
for(const auto &o_range : o.second)
more=gen(itr->second, o_range.first, o_range.second) ||
more;
++itr;
}
}
#else
values_innert::iterator itr=dest.begin();
for(const auto &id : other)
{
while(itr!=dest.end() && *itr<id)
++itr;
if(itr==dest.end() || id<*itr)
{
dest.insert(itr, id);
more=true;
}
else if(itr!=dest.end())
{
assert(*itr==id);
++itr;
}
}
#endif
return more;
}
/// \return returns true iff there is something new
bool rd_range_domaint::merge(
const rd_range_domaint &other,
locationt,
locationt)
{
bool changed=has_values.is_false();
has_values=tvt::unknown();
valuest::iterator it=values.begin();
for(const auto &value : other.values)
{
while(it!=values.end() && it->first<value.first)
++it;
if(it==values.end() || value.first<it->first)
{
values.insert(value);
changed=true;
}
else if(it!=values.end())
{
assert(it->first==value.first);
if(merge_inner(it->second, value.second))
{
changed=true;
export_cache.erase(it->first);
}
++it;
}
}
return changed;
}
/// \return returns true iff there is something new
bool rd_range_domaint::merge_shared(
const rd_range_domaint &other,
locationt,
locationt,
const namespacet &ns)
{
// TODO: dirty vars
#if 0
reaching_definitions_analysist *rd=
dynamic_cast<reaching_definitions_analysist*>(&ai);
assert(rd!=0);
#endif
bool changed=has_values.is_false();
has_values=tvt::unknown();
valuest::iterator it=values.begin();
for(const auto &value : other.values)
{
const irep_idt &identifier=value.first;
if(!ns.lookup(identifier).is_shared()
/*&& !rd.get_is_dirty()(identifier)*/)
continue;
while(it!=values.end() && it->first<value.first)
++it;
if(it==values.end() || value.first<it->first)
{
values.insert(value);
changed=true;
}
else if(it!=values.end())
{
assert(it->first==value.first);
if(merge_inner(it->second, value.second))
{
changed=true;
export_cache.erase(it->first);
}
++it;
}
}
return changed;
}
const rd_range_domaint::ranges_at_loct &rd_range_domaint::get(
const irep_idt &identifier) const
{
populate_cache(identifier);
static ranges_at_loct empty;
export_cachet::const_iterator entry=export_cache.find(identifier);
if(entry==export_cache.end())
return empty;
else
return entry->second;
}
void reaching_definitions_analysist::initialize(
const goto_functionst &goto_functions)
{
auto value_sets_=util_make_unique<value_set_analysis_fit>(ns);
(*value_sets_)(goto_functions);
value_sets=std::move(value_sets_);
is_threaded=util_make_unique<is_threadedt>(goto_functions);
is_dirty=util_make_unique<dirtyt>(goto_functions);
concurrency_aware_ait<rd_range_domaint>::initialize(goto_functions);
}
| 24.611465 | 80 | 0.645238 | [
"transform"
] |
cb24bba24a2f9651d26fc97a3a3becf5ebb193c7 | 8,573 | cpp | C++ | external/bsd/llvm/dist/llvm/lib/Target/R600/SIFoldOperands.cpp | calmsacibis995/minix | dfba95598f553b6560131d35a76658f1f8c9cf38 | [
"Unlicense"
] | null | null | null | external/bsd/llvm/dist/llvm/lib/Target/R600/SIFoldOperands.cpp | calmsacibis995/minix | dfba95598f553b6560131d35a76658f1f8c9cf38 | [
"Unlicense"
] | null | null | null | external/bsd/llvm/dist/llvm/lib/Target/R600/SIFoldOperands.cpp | calmsacibis995/minix | dfba95598f553b6560131d35a76658f1f8c9cf38 | [
"Unlicense"
] | null | null | null | //===-- SIFoldOperands.cpp - Fold operands --- ----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
/// \file
//===----------------------------------------------------------------------===//
//
#include "AMDGPU.h"
#include "AMDGPUSubtarget.h"
#include "SIInstrInfo.h"
#include "llvm/CodeGen/LiveIntervalAnalysis.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/Debug.h"
#include "llvm/Target/TargetMachine.h"
#define DEBUG_TYPE "si-fold-operands"
using namespace llvm;
namespace {
class SIFoldOperands : public MachineFunctionPass {
public:
static char ID;
public:
SIFoldOperands() : MachineFunctionPass(ID) {
initializeSIFoldOperandsPass(*PassRegistry::getPassRegistry());
}
bool runOnMachineFunction(MachineFunction &MF) override;
const char *getPassName() const override {
return "SI Fold Operands";
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<MachineDominatorTree>();
AU.setPreservesCFG();
MachineFunctionPass::getAnalysisUsage(AU);
}
};
struct FoldCandidate {
MachineInstr *UseMI;
unsigned UseOpNo;
MachineOperand *OpToFold;
uint64_t ImmToFold;
FoldCandidate(MachineInstr *MI, unsigned OpNo, MachineOperand *FoldOp) :
UseMI(MI), UseOpNo(OpNo) {
if (FoldOp->isImm()) {
OpToFold = nullptr;
ImmToFold = FoldOp->getImm();
} else {
assert(FoldOp->isReg());
OpToFold = FoldOp;
}
}
bool isImm() const {
return !OpToFold;
}
};
} // End anonymous namespace.
INITIALIZE_PASS_BEGIN(SIFoldOperands, DEBUG_TYPE,
"SI Fold Operands", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
INITIALIZE_PASS_END(SIFoldOperands, DEBUG_TYPE,
"SI Fold Operands", false, false)
char SIFoldOperands::ID = 0;
char &llvm::SIFoldOperandsID = SIFoldOperands::ID;
FunctionPass *llvm::createSIFoldOperandsPass() {
return new SIFoldOperands();
}
static bool isSafeToFold(unsigned Opcode) {
switch(Opcode) {
case AMDGPU::V_MOV_B32_e32:
case AMDGPU::V_MOV_B32_e64:
case AMDGPU::V_MOV_B64_PSEUDO:
case AMDGPU::S_MOV_B32:
case AMDGPU::S_MOV_B64:
case AMDGPU::COPY:
return true;
default:
return false;
}
}
static bool updateOperand(FoldCandidate &Fold,
const TargetRegisterInfo &TRI) {
MachineInstr *MI = Fold.UseMI;
MachineOperand &Old = MI->getOperand(Fold.UseOpNo);
assert(Old.isReg());
if (Fold.isImm()) {
Old.ChangeToImmediate(Fold.ImmToFold);
return true;
}
MachineOperand *New = Fold.OpToFold;
if (TargetRegisterInfo::isVirtualRegister(Old.getReg()) &&
TargetRegisterInfo::isVirtualRegister(New->getReg())) {
Old.substVirtReg(New->getReg(), New->getSubReg(), TRI);
return true;
}
// FIXME: Handle physical registers.
return false;
}
static bool tryAddToFoldList(std::vector<FoldCandidate> &FoldList,
MachineInstr *MI, unsigned OpNo,
MachineOperand *OpToFold,
const SIInstrInfo *TII) {
if (!TII->isOperandLegal(MI, OpNo, OpToFold)) {
// Operand is not legal, so try to commute the instruction to
// see if this makes it possible to fold.
unsigned CommuteIdx0;
unsigned CommuteIdx1;
bool CanCommute = TII->findCommutedOpIndices(MI, CommuteIdx0, CommuteIdx1);
if (CanCommute) {
if (CommuteIdx0 == OpNo)
OpNo = CommuteIdx1;
else if (CommuteIdx1 == OpNo)
OpNo = CommuteIdx0;
}
if (!CanCommute || !TII->commuteInstruction(MI))
return false;
if (!TII->isOperandLegal(MI, OpNo, OpToFold))
return false;
}
FoldList.push_back(FoldCandidate(MI, OpNo, OpToFold));
return true;
}
bool SIFoldOperands::runOnMachineFunction(MachineFunction &MF) {
MachineRegisterInfo &MRI = MF.getRegInfo();
const SIInstrInfo *TII =
static_cast<const SIInstrInfo *>(MF.getSubtarget().getInstrInfo());
const SIRegisterInfo &TRI = TII->getRegisterInfo();
for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
BI != BE; ++BI) {
MachineBasicBlock &MBB = *BI;
MachineBasicBlock::iterator I, Next;
for (I = MBB.begin(); I != MBB.end(); I = Next) {
Next = std::next(I);
MachineInstr &MI = *I;
if (!isSafeToFold(MI.getOpcode()))
continue;
MachineOperand &OpToFold = MI.getOperand(1);
bool FoldingImm = OpToFold.isImm();
// FIXME: We could also be folding things like FrameIndexes and
// TargetIndexes.
if (!FoldingImm && !OpToFold.isReg())
continue;
// Folding immediates with more than one use will increase program side.
// FIXME: This will also reduce register usage, which may be better
// in some cases. A better heuristic is needed.
if (FoldingImm && !TII->isInlineConstant(OpToFold) &&
!MRI.hasOneUse(MI.getOperand(0).getReg()))
continue;
// FIXME: Fold operands with subregs.
if (OpToFold.isReg() &&
(!TargetRegisterInfo::isVirtualRegister(OpToFold.getReg()) ||
OpToFold.getSubReg()))
continue;
std::vector<FoldCandidate> FoldList;
for (MachineRegisterInfo::use_iterator
Use = MRI.use_begin(MI.getOperand(0).getReg()), E = MRI.use_end();
Use != E; ++Use) {
MachineInstr *UseMI = Use->getParent();
const MachineOperand &UseOp = UseMI->getOperand(Use.getOperandNo());
// FIXME: Fold operands with subregs.
if (UseOp.isReg() && UseOp.getSubReg() && OpToFold.isReg()) {
continue;
}
APInt Imm;
if (FoldingImm) {
unsigned UseReg = UseOp.getReg();
const TargetRegisterClass *UseRC
= TargetRegisterInfo::isVirtualRegister(UseReg) ?
MRI.getRegClass(UseReg) :
TRI.getRegClass(UseReg);
Imm = APInt(64, OpToFold.getImm());
// Split 64-bit constants into 32-bits for folding.
if (UseOp.getSubReg()) {
if (UseRC->getSize() != 8)
continue;
if (UseOp.getSubReg() == AMDGPU::sub0) {
Imm = Imm.getLoBits(32);
} else {
assert(UseOp.getSubReg() == AMDGPU::sub1);
Imm = Imm.getHiBits(32);
}
}
// In order to fold immediates into copies, we need to change the
// copy to a MOV.
if (UseMI->getOpcode() == AMDGPU::COPY) {
unsigned DestReg = UseMI->getOperand(0).getReg();
const TargetRegisterClass *DestRC
= TargetRegisterInfo::isVirtualRegister(DestReg) ?
MRI.getRegClass(DestReg) :
TRI.getRegClass(DestReg);
unsigned MovOp = TII->getMovOpcode(DestRC);
if (MovOp == AMDGPU::COPY)
continue;
UseMI->setDesc(TII->get(MovOp));
}
}
const MCInstrDesc &UseDesc = UseMI->getDesc();
// Don't fold into target independent nodes. Target independent opcodes
// don't have defined register classes.
if (UseDesc.isVariadic() ||
UseDesc.OpInfo[Use.getOperandNo()].RegClass == -1)
continue;
if (FoldingImm) {
MachineOperand ImmOp = MachineOperand::CreateImm(Imm.getSExtValue());
tryAddToFoldList(FoldList, UseMI, Use.getOperandNo(), &ImmOp, TII);
continue;
}
tryAddToFoldList(FoldList, UseMI, Use.getOperandNo(), &OpToFold, TII);
// FIXME: We could try to change the instruction from 64-bit to 32-bit
// to enable more folding opportunites. The shrink operands pass
// already does this.
}
for (FoldCandidate &Fold : FoldList) {
if (updateOperand(Fold, TRI)) {
// Clear kill flags.
if (!Fold.isImm()) {
assert(Fold.OpToFold && Fold.OpToFold->isReg());
Fold.OpToFold->setIsKill(false);
}
DEBUG(dbgs() << "Folded source from " << MI << " into OpNo " <<
Fold.UseOpNo << " of " << *Fold.UseMI << '\n');
}
}
}
}
return false;
}
| 29.975524 | 80 | 0.611221 | [
"vector"
] |
cb272e61d327ad602109ce7ee36b04f38562da61 | 10,998 | hpp | C++ | src/parser/parser.hpp | giag3/peng-utils | f0883ffbf3b422de2e0ea326861114b1f5809037 | [
"MIT"
] | 1 | 2022-03-28T11:20:50.000Z | 2022-03-28T11:20:50.000Z | src/parser/parser.hpp | giag3/peng-utils | f0883ffbf3b422de2e0ea326861114b1f5809037 | [
"MIT"
] | null | null | null | src/parser/parser.hpp | giag3/peng-utils | f0883ffbf3b422de2e0ea326861114b1f5809037 | [
"MIT"
] | null | null | null | #include "../vars.hpp"
#include "../files/source_file.hpp"
#include "../compiler/variable.hpp"
// *****************
// STACK VARIABLES
// *****************
/**
* @brief The parser_expression_id enum
*/
enum class parser_expression_id {
VARIABLE, METHOD, NUMBER, OPERATOR, BRACKET, STACK_VALUE
};
/**
* @brief The pe_operator_character enum
*/
enum class pe_operator {
NULL_OPERATOR, LEFT_BRACKET, RIGHT_BRACKET, PLUS, MINUS,
STAR, FORWARD_SLASH, AMPERSAND, DOUBLE_AMPERSAND, VERTICAL_BAR,
DOUBLE_VERTICAL_BAR, NEGATE, EQUAL, ASSIGN, LESSER,
GREATER, LESSER_OR_EQUAL, GREATER_OR_EQUAL, REFERENCE, POINTER,
NOT_EQUAL, BOOL_NEGATE, ASSIGN_ADD, ASSIGN_SUBTRACT, ASSIGN_MULTIPLY,
ASSIGN_DIVIDE, LEFT_INC_ONE, LEFT_DEC_ONE, RIGHT_INC_ONE, RIGHT_DEC_ONE,
MODULO, ASSIGN_MODULO, RIGHT_SHIFT, LEFT_SHIFT, ASSIGN_RIGHT_SHIFT,
ASSIGN_LEFT_SHIFT, XOR, ASSIGN_XOR, ASSIGN_VERTICAL_BAR, ASSIGN_AMPERSAND,
NEGATE_VALUE, CAST, TERNARY_QUESTION_MARK, TERNARY_COLON
};
// Variable operations
enum class VARIABLE_OPERATION {
ASSIGN, ADD, SUBTRACT, MULTIPLY, DIVIDE, MODULO, AND, OR, XOR, SHL, SHR
};
// It's faster to create everything on stack rather than
// casting to a sub-class from a super-class using dynamic cast
class parser_expression {
public:
// The variable
variable var;
// The method
method m;
// The method's object nclass
nclass* obj_nclass;
// A number
long long number;
// An operator
pe_operator _operator;
// The id of the parser expression
parser_expression_id pe_id;
// Stack value
parser_expression(TYPE& type) {
// Save type in the variable
var.get_type() = type;
// Set value
pe_id = parser_expression_id::STACK_VALUE;
}
// Operator constructor
parser_expression(pe_operator _operator) : _operator(_operator) {
if (_operator == pe_operator::LEFT_BRACKET || _operator == pe_operator::RIGHT_BRACKET)
pe_id = parser_expression_id::BRACKET;
else
pe_id = parser_expression_id::OPERATOR;
};
// Number constructor
parser_expression(long long number) : number(number) {
var.get_type() = {DATA_TYPE::INT};
pe_id = parser_expression_id::NUMBER;
};
// Variable constructor
parser_expression(variable var) : var(var) {
pe_id = parser_expression_id::VARIABLE;
};
// Method constructor
parser_expression(method m, nclass* obj_nclass, variable var) : m(m), obj_nclass(obj_nclass), var(var) {
var.get_type() = m.get_type();
pe_id = parser_expression_id::METHOD;
};
// Is bracket
bool is_bracket() {
return pe_id == parser_expression_id::BRACKET && (_operator == pe_operator::LEFT_BRACKET || _operator == pe_operator::RIGHT_BRACKET);
}
// Is number
bool is_number() {
return pe_id == parser_expression_id::NUMBER;
}
// Is operator
bool is_operator() {
return pe_id == parser_expression_id::OPERATOR;
}
// Is variable
bool is_variable() {
return pe_id == parser_expression_id::VARIABLE;
}
// Is stack value
bool is_stack_val() {
return pe_id == parser_expression_id::STACK_VALUE;
}
// Is method
bool is_method() {
return pe_id == parser_expression_id::METHOD;
}
#ifdef DEBUG
// Debug printing utility
std::string to_str(pe_operator& pe) {
switch (pe) {
case pe_operator::PLUS: return "+";
case pe_operator::MINUS: return "-";
case pe_operator::NEGATE: return "$";
case pe_operator::STAR: return "*";
case pe_operator::EQUAL: return "==";
case pe_operator::LESSER: return "<";
case pe_operator::LESSER_OR_EQUAL: return "<=";
case pe_operator::GREATER: return ">";
case pe_operator::GREATER_OR_EQUAL: return ">=";
case pe_operator::FORWARD_SLASH: return "/";
case pe_operator::LEFT_BRACKET: return "(";
case pe_operator::RIGHT_BRACKET: return ")";
case pe_operator::REFERENCE:
case pe_operator::AMPERSAND: return "&";
}
return "";
}
// Debug printing utility
// Prints the expr
void print() {
switch (pe_id) {
case parser_expression_id::NUMBER: std::cout << number; break;
case parser_expression_id::VARIABLE: std::cout << var.get_name(); break;
case parser_expression_id::METHOD: std::cout << m.get_name(); break;
case parser_expression_id::OPERATOR: std::cout << to_str(_operator); break;
}
}
#endif
};
/**
* @brief The parser class
*/
class parser {
public:
/**
* @brief parse_value_and_assign Parse a value and assign to the variable
* @param var the variable to assign to
* @param file the file to be parsed
* @return the type of the value
*/
TYPE parse_value_and_assign(variable& var, source_file& file, std::vector<char> terchars = {';', ','}, bool push = true, VARIABLE_OPERATION var_op = VARIABLE_OPERATION::ASSIGN);
/**
* @brief Parses a value and assigns it to an effective address
* @param eff the effective address to assign to
* @param file the file to be parsed
* @param terchars the terminate characters
* @param type the type of the eff (size)
* @return
*/
TYPE parse_value_and_assign_to_eff(effective_address<reg64>& eff, source_file& file, std::vector<char> terchars, TYPE& type);
/**
* @brief parse_value_and_assign_to_reg Parse a value and assign to the reg in a memory
* @param reg the register pointer
* @param var the variable to assign to
* @param offset the offset
* @param file the file to be parsed
* @return the returning type
*/
TYPE parse_value_and_assign_to_reg(unsigned char reg, std::vector<char> terchars, source_file& file, TYPE& type);
/**
* @brief Parses a string (Needs to end with a ", meaning the first " has already been parsed)
* @param file the file to be parsed
* @param ending_char the character to end at
* @return the parsed string
*/
static std::string parse_string(source_file& file, char ending_char);
/**
* @brief Parses a string (Needs to end with a ", meaning the first " has already been parsed)
* @param file the file to be parsed
* @return the parsed string
*/
static std::string parse_string(source_file& file);
/**
* @brief Parses a character (Needs to end with a ', meaning the first ' has already been parsed)
* @param file the file to be parsed
* @return the parsed character
*/
static char parse_char(source_file& file);
/**
* @brief Parses a value from a source file
* @param file the source file
* @param teminate_characters characters at which to terminate
* @param type the type of the value
* @param push whether we wanna push this value to stack
*/
void parse_value(source_file& file, std::vector<char> teminate_characters, TYPE* type, bool push = true, bool remove = true);
/**
* @brief Pushes this pe to stack
* @param type the type of the pe
* @param pe the parser expression
*/
void push_to_stack(TYPE& type, parser_expression& pe);
/**
* @brief Pushes last pe (from postfix buffer) to stack
*/
void push_to_stack();
/**
* @brief Move pe expr to reg
* @param reg the register
* @param type the type of the pe
* @param pe the parser expression
*/
void move_to_reg(unsigned char reg, TYPE& type, parser_expression& pe);
/**
* @brief Move pe expr to eff
* @param eff the effective address
* @param type the type of the pe
* @param pe the parser expression
*/
void move_to_eff(effective_address<reg64>& eff, TYPE& type, parser_expression& pe);
/**
* @brief Method/var evaluation check
* @param token the next token
*/
void expr_check(std::string token);
/**
* @brief evaluate Evaluates the postfix notation
*/
void evaluate(int start = 0);
/**
* @brief terminate Checks whether to terminate the loop
* @return
*/
bool terminate();
/**
* @brief mov_to_variable Moves this parser variable to a variable
* @param var the variable
*/
void mov_to_variable(variable& var);
/**
* @brief Does the operation to the variable
* @param var the variable
*/
void do_to_variable(VARIABLE_OPERATION var_op, variable& var);
/**
* @brief pop_until_left_bracket Pops from stack until a left bracket is found
*/
void pop_until_left_bracket();
/**
* @brief pop_until_precedence Pops until an operator has a lower precedence
* @param precedence the precedence
*/
void pop_until_precedence(unsigned char precedence);
/**
* @brief operator_and_precedence_from_token Returns the operator and the precedence from a string
* @param precedence the returning precedence
* @param token the token
* @return the returning operator
*/
pe_operator operator_and_precedence_from_token(unsigned char& precedence, std::string& token);
/**
* @brief to_postfix_notation Converts value to postfix notation
*/
void to_postfix_notation();
/**
* @brief Checks the left operators
*/
void check_left_operator();
/**
* @brief do_operation Does the operation defined by the operator
* @param pe the operator
* @param pe1 first operand
* @param pe2 second operand
*/
void do_operation(pe_operator& pe, parser_expression& pe1, parser_expression& pe2);
/**
* @brief Evaluates the top of pe_stack
*/
void evaluate_operator();
/**
* @brief Pops values till the end
*/
void pop_till_end();
/**
* @brief push_cast_type_symbol Pushes a cast type symbol
* @param type the type to cast to
*/
void push_cast_type_symbol(const TYPE& type);
public:
// Parser expression stack
std::stack<parser_expression> pe_stack;
// The type stack
std::stack<TYPE> type_stack;
// Output value buffer
std::vector<parser_expression> postfix_buffer;
// Save values for quicker re-use
source_file* file;
// All the termination characters
// ) - terminates at the closing bracket
std::vector<char>* terminate_characters;
// Termination character
char terminate_character;
// Assignment values
variable* assign_var;
uint assign_offset;
bool push;
int bracket_count = 0;
// The type of the desired variable
TYPE* type = nullptr;
};
| 30.465374 | 181 | 0.634752 | [
"object",
"vector"
] |
cb28a0b4aedfb301ec50fbbe7290e2a5e2b5536d | 6,838 | cpp | C++ | search/src/LayeredImage.cpp | fraserw/kbmod | 65d69746d1dd8de867f8da147d73c09439d28b41 | [
"BSD-2-Clause"
] | 16 | 2018-07-23T11:39:05.000Z | 2022-01-27T17:15:42.000Z | search/src/LayeredImage.cpp | fraserw/kbmod | 65d69746d1dd8de867f8da147d73c09439d28b41 | [
"BSD-2-Clause"
] | 42 | 2017-06-19T22:55:41.000Z | 2018-03-15T02:49:39.000Z | search/src/LayeredImage.cpp | fraserw/kbmod | 65d69746d1dd8de867f8da147d73c09439d28b41 | [
"BSD-2-Clause"
] | 7 | 2018-07-23T11:39:04.000Z | 2022-01-27T18:43:02.000Z | /*
* LayeredImage.cpp
*
* Created on: Jul 11, 2017
* Author: kbmod-usr
*/
#include "LayeredImage.h"
namespace kbmod {
LayeredImage::LayeredImage(std::string path) {
filePath = path;
int fBegin = path.find_last_of("/");
int fEnd = path.find_last_of(".fits")-4;
fileName = path.substr(fBegin, fEnd-fBegin);
readHeader();
science = RawImage(width, height);
mask = RawImage(width, height);
variance = RawImage(width, height);
loadLayers();
}
LayeredImage::LayeredImage(std::string name, int w, int h,
float noiseStDev, float pixelVariance, double time)
{
fileName = name;
pixelsPerImage = w*h;
width = w;
height = h;
captureTime = time;
std::vector<float> rawSci(pixelsPerImage);
std::random_device r;
std::default_random_engine generator(r());
std::normal_distribution<float> distrib(0.0, noiseStDev);
for (float& p : rawSci) p = distrib(generator);
science = RawImage(w,h, rawSci);
mask = RawImage(w,h,std::vector<float>(pixelsPerImage, 0.0));
variance = RawImage(w,h,std::vector<float>(pixelsPerImage, pixelVariance));
}
/* Read the image dimensions and capture time from header */
void LayeredImage::readHeader()
{
fitsfile *fptr;
int status = 0;
int mjdStatus = 0;
int fileNotFound;
// Open header to read MJD
if (fits_open_file(&fptr, filePath.c_str(), READONLY, &status))
throw std::runtime_error("Could not open file");
//fits_report_error(stderr, status);
// Read image capture time, ignore error if does not exist
captureTime = 0.0;
fits_read_key(fptr, TDOUBLE, "MJD", &captureTime, NULL, &mjdStatus);
if (fits_close_file(fptr, &status))
fits_report_error(stderr, status);
// Reopen header for first layer to get image dimensions
if (fits_open_file(&fptr, (filePath+"[1]").c_str(), READONLY, &status))
fits_report_error(stderr, status);
// Read image Dimensions
if (fits_read_keys_lng(fptr, "NAXIS", 1, 2, dimensions, &fileNotFound, &status))
fits_report_error(stderr, status);
width = dimensions[0];
height = dimensions[1];
// Calculate pixels per image from dimensions x*y
pixelsPerImage = dimensions[0]*dimensions[1];
if (fits_close_file(fptr, &status))
fits_report_error(stderr, status);
}
void LayeredImage::loadLayers()
{
// Load images from file into layers' pixels
readFitsImg((filePath+"[1]").c_str(), science.getDataRef());
readFitsImg((filePath+"[2]").c_str(), mask.getDataRef());
readFitsImg((filePath+"[3]").c_str(), variance.getDataRef());
}
void LayeredImage::readFitsImg(const char *name, float *target)
{
fitsfile *fptr;
int nullval = 0;
int anynull;
int status = 0;
if (fits_open_file(&fptr, name, READONLY, &status))
fits_report_error(stderr, status);
if (fits_read_img(fptr, TFLOAT, 1, pixelsPerImage,
&nullval, target, &anynull, &status))
fits_report_error(stderr, status);
if (fits_close_file(fptr, &status))
fits_report_error(stderr, status);
}
void LayeredImage::addObject(float x, float y, float flux, PointSpreadFunc psf)
{
std::vector<float> k = psf.getKernel();
int dim = psf.getDim();
float initialX = x-static_cast<float>(psf.getRadius());
float initialY = y-static_cast<float>(psf.getRadius());
int count = 0;
// Does x/y order need to be flipped?
for (int i=0; i<dim; ++i)
{
for (int j=0; j<dim; ++j)
{
science.addPixelInterp(initialX+static_cast<float>(i),
initialY+static_cast<float>(j),
flux*k[count]);
count++;
}
}
}
void LayeredImage::maskObject(float x, float y, PointSpreadFunc psf)
{
std::vector<float> k = psf.getKernel();
int dim = psf.getDim();
float initialX = x-static_cast<float>(psf.getRadius());
float initialY = y-static_cast<float>(psf.getRadius());
// Does x/y order need to be flipped?
for (int i=0; i<dim; ++i)
{
for (int j=0; j<dim; ++j)
{
science.maskPixelInterp(initialX+static_cast<float>(i),
initialY+static_cast<float>(j));
}
}
}
void LayeredImage::growMask()
{
science.growMask();
variance.growMask();
}
void LayeredImage::convolve(PointSpreadFunc psf)
{
PointSpreadFunc psfSQ(psf.getStdev());
psfSQ.squarePSF();
science.convolve(psf);
variance.convolve(psfSQ);
}
void LayeredImage::applyMaskFlags(int flags, std::vector<int> exceptions)
{
science.applyMask(flags, exceptions, mask);
variance.applyMask(flags, exceptions, mask);
}
/* Mask all pixels that are not 0 in master mask */
void LayeredImage::applyMasterMask(RawImage masterM)
{
science.applyMask(0xFFFFFF, {}, masterM);
variance.applyMask(0xFFFFFF, {}, masterM);
}
void LayeredImage::applyMaskThreshold(float thresh)
{
float *sciPix = science.getDataRef();
float *varPix = variance.getDataRef();
for (int i=0; i<pixelsPerImage; ++i)
{
if (sciPix[i]>thresh)
{
sciPix[i] = NO_DATA;
varPix[i] = NO_DATA;
}
}
}
void LayeredImage::subtractTemplate(RawImage subTemplate)
{
assert( getHeight() == subTemplate.getHeight() &&
getWidth() == subTemplate.getWidth());
float *sciPix = science.getDataRef();
float *tempPix = subTemplate.getDataRef();
for (unsigned i=0; i<getPPI(); ++i) sciPix[i] -= tempPix[i];
}
void LayeredImage::saveLayers(std::string path)
{
fitsfile *fptr;
int status = 0;
long naxes[2] = {0,0};
fits_create_file(&fptr, (path+fileName+".fits").c_str(), &status);
fits_create_img(fptr, SHORT_IMG, 0, naxes, &status);
fits_update_key(fptr, TDOUBLE, "MJD", &captureTime,
"[d] Generated Image time", &status);
fits_close_file(fptr, &status);
fits_report_error(stderr, status);
science.saveToExtension(path+fileName+".fits");
mask.saveToExtension(path+fileName+".fits");
variance.saveToExtension(path+fileName+".fits");
}
void LayeredImage::saveSci(std::string path) {
science.saveToFile(path+fileName+"SCI.fits");
}
void LayeredImage::saveMask(std::string path) {
mask.saveToFile(path+fileName+"MASK.fits");
}
void LayeredImage::saveVar(std::string path){
variance.saveToFile(path+fileName+"VAR.fits");
}
void LayeredImage::setScience(RawImage& im)
{
checkDims(im);
science = im;
}
void LayeredImage::setMask(RawImage& im)
{
checkDims(im);
mask = im;
}
void LayeredImage::setVariance(RawImage& im)
{
checkDims(im);
variance = im;
}
void LayeredImage::checkDims(RawImage& im)
{
if (im.getWidth() != getWidth())
throw std::runtime_error("Image width does not match");
if (im.getHeight() != getHeight())
throw std::runtime_error("Image height does not match");
}
RawImage& LayeredImage::getScience() {
return science;
}
RawImage& LayeredImage::getMask() {
return mask;
}
RawImage& LayeredImage::getVariance() {
return variance;
}
float* LayeredImage::getSDataRef() {
return science.getDataRef();
}
float* LayeredImage::getMDataRef() {
return mask.getDataRef();
}
float* LayeredImage::getVDataRef() {
return variance.getDataRef();
}
double LayeredImage::getTime()
{
return captureTime;
}
} /* namespace kbmod */
| 24.775362 | 81 | 0.70196 | [
"vector"
] |
cb2a9419fc0725a6e80e3c32d97559c885313f9d | 3,363 | cpp | C++ | source/Irrlicht/CMeshCache.cpp | JaviCervera/irrlicht | 02623fda3ed1ebc97cb9e0df148e132c08b6f41b | [
"IJG"
] | 30 | 2018-10-26T12:54:11.000Z | 2022-02-04T18:18:57.000Z | source/Irrlicht/CMeshCache.cpp | JaviCervera/irrlicht | 02623fda3ed1ebc97cb9e0df148e132c08b6f41b | [
"IJG"
] | 8 | 2021-02-07T17:34:18.000Z | 2021-03-08T11:03:13.000Z | source/Irrlicht/CMeshCache.cpp | JaviCervera/irrlicht | 02623fda3ed1ebc97cb9e0df148e132c08b6f41b | [
"IJG"
] | 26 | 2018-11-20T18:11:39.000Z | 2022-01-28T21:05:30.000Z | // Copyright (C) 2002-2012 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CMeshCache.h"
#include "IAnimatedMesh.h"
#include "IMesh.h"
namespace irr
{
namespace scene
{
static const io::SNamedPath emptyNamedPath;
CMeshCache::~CMeshCache()
{
clear();
}
//! adds a mesh to the list
void CMeshCache::addMesh(const io::path& filename, IAnimatedMesh* mesh)
{
mesh->grab();
MeshEntry e ( filename );
e.Mesh = mesh;
Meshes.push_back(e);
}
//! Removes a mesh from the cache.
void CMeshCache::removeMesh(const IMesh* const mesh)
{
if ( !mesh )
return;
for (u32 i=0; i<Meshes.size(); ++i)
{
if (Meshes[i].Mesh == mesh || (Meshes[i].Mesh && Meshes[i].Mesh->getMesh(0) == mesh))
{
Meshes[i].Mesh->drop();
Meshes.erase(i);
return;
}
}
}
//! Returns amount of loaded meshes
u32 CMeshCache::getMeshCount() const
{
return Meshes.size();
}
//! Returns current number of the mesh
s32 CMeshCache::getMeshIndex(const IMesh* const mesh) const
{
for (u32 i=0; i<Meshes.size(); ++i)
{
if (Meshes[i].Mesh == mesh || (Meshes[i].Mesh && Meshes[i].Mesh->getMesh(0) == mesh))
return (s32)i;
}
return -1;
}
//! Returns a mesh based on its index number
IAnimatedMesh* CMeshCache::getMeshByIndex(u32 number)
{
if (number >= Meshes.size())
return 0;
return Meshes[number].Mesh;
}
//! Returns a mesh based on its name.
IAnimatedMesh* CMeshCache::getMeshByName(const io::path& name)
{
MeshEntry e ( name );
s32 id = Meshes.binary_search(e);
return (id != -1) ? Meshes[id].Mesh : 0;
}
//! Get the name of a loaded mesh, based on its index.
const io::SNamedPath& CMeshCache::getMeshName(u32 index) const
{
if (index >= Meshes.size())
return emptyNamedPath;
return Meshes[index].NamedPath;
}
//! Get the name of a loaded mesh, if there is any.
const io::SNamedPath& CMeshCache::getMeshName(const IMesh* const mesh) const
{
if (!mesh)
return emptyNamedPath;
for (u32 i=0; i<Meshes.size(); ++i)
{
if (Meshes[i].Mesh == mesh || (Meshes[i].Mesh && Meshes[i].Mesh->getMesh(0) == mesh))
return Meshes[i].NamedPath;
}
return emptyNamedPath;
}
//! Renames a loaded mesh.
bool CMeshCache::renameMesh(u32 index, const io::path& name)
{
if (index >= Meshes.size())
return false;
Meshes[index].NamedPath.setPath(name);
Meshes.sort();
return true;
}
//! Renames a loaded mesh.
bool CMeshCache::renameMesh(const IMesh* const mesh, const io::path& name)
{
for (u32 i=0; i<Meshes.size(); ++i)
{
if (Meshes[i].Mesh == mesh || (Meshes[i].Mesh && Meshes[i].Mesh->getMesh(0) == mesh))
{
Meshes[i].NamedPath.setPath(name);
Meshes.sort();
return true;
}
}
return false;
}
//! returns if a mesh already was loaded
bool CMeshCache::isMeshLoaded(const io::path& name)
{
return getMeshByName(name) != 0;
}
//! Clears the whole mesh cache, removing all meshes.
void CMeshCache::clear()
{
for (u32 i=0; i<Meshes.size(); ++i)
Meshes[i].Mesh->drop();
Meshes.clear();
}
//! Clears all meshes that are held in the mesh cache but not used anywhere else.
void CMeshCache::clearUnusedMeshes()
{
for (u32 i=0; i<Meshes.size(); ++i)
{
if (Meshes[i].Mesh->getReferenceCount() == 1)
{
Meshes[i].Mesh->drop();
Meshes.erase(i);
--i;
}
}
}
} // end namespace scene
} // end namespace irr
| 18.787709 | 87 | 0.66072 | [
"mesh"
] |
cb2d6325e4e17f844c313a7919451695a9d879b6 | 8,127 | cpp | C++ | src/sched/entry/ze/allreduce/ze_onesided_allreduce_entry.cpp | intel/oneccl | b7d66de16e17f88caffd7c6df4cd5e12b266af84 | [
"Apache-2.0"
] | 26 | 2019-11-18T09:45:28.000Z | 2020-03-02T17:00:24.000Z | src/sched/entry/ze/allreduce/ze_onesided_allreduce_entry.cpp | intel/oneccl | b7d66de16e17f88caffd7c6df4cd5e12b266af84 | [
"Apache-2.0"
] | 8 | 2020-02-05T20:34:23.000Z | 2020-02-21T22:26:22.000Z | src/sched/entry/ze/allreduce/ze_onesided_allreduce_entry.cpp | intel/oneccl | b7d66de16e17f88caffd7c6df4cd5e12b266af84 | [
"Apache-2.0"
] | 9 | 2019-11-21T16:58:47.000Z | 2020-02-26T15:40:04.000Z | /*
Copyright 2016-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.
*/
#include "common/stream/stream.hpp"
#include "sched/entry/ze/allreduce/ze_onesided_allreduce_entry.hpp"
#include "sched/entry/ze/ze_primitives.hpp"
#include "sched/entry/ze/ze_cache.hpp"
#include "sched/queue/queue.hpp"
#include <string>
using namespace ccl;
using namespace ccl::ze;
ze_onesided_allreduce_entry::ze_onesided_allreduce_entry(ccl_sched* sched,
ccl_buffer send_buf,
ccl_buffer recv_buf,
size_t cnt,
const ccl_datatype& dtype,
reduction op,
ccl_comm* comm,
std::vector<ze_event_handle_t> wait_events,
const size_t buf_offset_cnt)
: ze_base_entry(sched, comm, 3 /* request additional events */, wait_events),
send_buf(send_buf),
recv_buf(recv_buf),
cnt(cnt),
dtype(dtype),
op(op),
buf_size_bytes(dtype.size() * cnt),
buf_offset_bytes(dtype.size() * buf_offset_cnt) {}
void ze_onesided_allreduce_entry::init_ze_hook() {
/* create kernels */
ccl_buffer right_send_buf;
ccl_buffer right_recv_buf;
int peer_rank = (comm_rank + 1) % comm_size;
send_buf_ptr = static_cast<char*>(send_buf.get_ptr()) + buf_offset_bytes;
recv_buf_ptr = static_cast<char*>(recv_buf.get_ptr()) + buf_offset_bytes;
if (send_buf_ptr == recv_buf_ptr) {
sched->get_memory().handle_manager.get(peer_rank, 1, right_send_buf, comm);
sched->get_memory().handle_manager.get(peer_rank, 1, right_recv_buf, comm);
}
else {
sched->get_memory().handle_manager.get(peer_rank, 0, right_send_buf, comm);
sched->get_memory().handle_manager.get(peer_rank, 1, right_recv_buf, comm);
}
right_send_buf_ptr = static_cast<char*>(right_send_buf.get_ptr()) + buf_offset_bytes;
right_recv_buf_ptr = static_cast<char*>(right_recv_buf.get_ptr()) + buf_offset_bytes;
void* tmp_buf_ptr{};
if (global_data::env().enable_kernel_1s_copy_ops) {
main_kernel_name = "reduce_local_outofplace_kernel_";
ccl::alloc_param alloc_param(buf_size_bytes, buffer_type::ze, buffer_place::device);
tmp_buf_ptr = sched->alloc_buffer(alloc_param).get_ptr();
}
else {
main_kernel_name = "allreduce_kernel_";
}
main_kernel_name += to_string(dtype.idx()) + "_" + ccl_reduction_to_str(op);
LOG_DEBUG("get kernel: name: ", main_kernel_name);
global_data::get().ze_data->cache->get(context, device, "kernels.spv", &module);
global_data::get().ze_data->cache->get(worker_idx, module, main_kernel_name, &main_kernel);
ze_kernel_args_t allreduce_kernel_args{ &comm_rank, &comm_size, &cnt,
&send_buf_ptr, &recv_buf_ptr, &right_send_buf_ptr,
&right_recv_buf_ptr };
ze_kernel_args_t reduce_local_kernel_args{ &comm_rank, &comm_size, &cnt,
&send_buf_ptr, &tmp_buf_ptr, &recv_buf_ptr };
auto& main_kernel_args = (global_data::env().enable_kernel_1s_copy_ops)
? reduce_local_kernel_args
: allreduce_kernel_args;
LOG_DEBUG("kernel ", main_kernel, " args:\n", to_string(main_kernel_args));
set_kernel_args(main_kernel, main_kernel_args);
ze_group_size_t group_size;
get_suggested_group_size(main_kernel, cnt, &group_size);
LOG_DEBUG("suggested group size: ", to_string(group_size));
get_suggested_group_count(group_size, cnt, &group_count);
LOG_DEBUG("suggested group count: ", to_string(group_count));
ZE_CALL(zeKernelSetGroupSize,
(main_kernel, group_size.groupSizeX, group_size.groupSizeY, group_size.groupSizeZ));
if (global_data::env().enable_kernel_1s_ipc_wa) {
LOG_DEBUG("get kernel: name: ", empty_kernel_name);
global_data::get().ze_data->cache->get(
worker_idx, module, empty_kernel_name, &empty_kernel);
CCL_THROW_IF_NOT(empty_kernel, "null empty_kernel");
/* use allreduce_kernel_args since they have pointers to peer mem */
set_kernel_args(empty_kernel, allreduce_kernel_args);
}
if (empty_kernel) {
empty_kernel_event = ze_base_entry::create_event();
}
if (global_data::env().enable_kernel_1s_copy_ops) {
copy_from_peer_event = ze_base_entry::create_event();
reduce_local_kernel_event = ze_base_entry::create_event();
}
/* do appends */
if (empty_kernel) {
LOG_DEBUG("append empty kernel");
ze_group_count_t empty_group_count = { 1, 1, 1 };
ZE_CALL(zeCommandListAppendLaunchKernel,
(ze_base_entry::get_comp_list(),
empty_kernel,
&empty_group_count,
empty_kernel_event,
0,
nullptr));
}
if (global_data::env().enable_kernel_1s_copy_ops) {
LOG_DEBUG("one-sided multi-phase algorithm");
ZE_CALL(zeCommandListAppendMemoryCopy,
(ze_base_entry::get_copy_list(),
tmp_buf_ptr,
right_send_buf_ptr,
buf_size_bytes,
copy_from_peer_event,
(empty_kernel_event) ? 1 : 0,
&empty_kernel_event));
ZE_CALL(zeCommandListAppendLaunchKernel,
(ze_base_entry::get_comp_list(),
main_kernel,
&group_count,
reduce_local_kernel_event,
1,
©_from_peer_event));
ZE_CALL(zeCommandListAppendMemoryCopy,
(ze_base_entry::get_copy_list(),
right_recv_buf_ptr,
recv_buf_ptr,
buf_size_bytes,
ze_base_entry::entry_event,
1,
&reduce_local_kernel_event));
}
else {
LOG_DEBUG("one-sided monolithic algorithm");
ZE_CALL(zeCommandListAppendLaunchKernel,
(ze_base_entry::get_comp_list(),
main_kernel,
&group_count,
ze_base_entry::entry_event,
(empty_kernel_event) ? 1 : 0,
&empty_kernel_event));
}
}
void ze_onesided_allreduce_entry::finalize_ze_hook() {
if (empty_kernel_event) {
global_data::get().ze_data->cache->push(
worker_idx, module, empty_kernel_name, empty_kernel);
}
global_data::get().ze_data->cache->push(worker_idx, module, main_kernel_name, main_kernel);
}
void ze_onesided_allreduce_entry::start() {
size_t kernel_counter = 0;
if (global_data::env().enable_kernel_sync) {
kernel_counter = global_data::get().ze_data->kernel_counter++;
}
if (kernel_counter == 0) {
ze_base_entry::start();
}
else {
global_data::get().ze_data->kernel_counter--;
status = ccl_sched_entry_status_again;
}
}
void ze_onesided_allreduce_entry::update() {
ze_base_entry::update();
if (global_data::env().enable_kernel_sync && global_data::get().ze_data->kernel_counter > 0) {
global_data::get().ze_data->kernel_counter--;
}
}
| 39.451456 | 100 | 0.612034 | [
"vector"
] |
cb2ed2ec0329acdd383905a5b32f89856499846d | 774 | cpp | C++ | src/polytype.cpp | bryancatanzaro/copperhead-compiler | 11067c1d4bb1c850e88f9038782c41a6be3edd3c | [
"Apache-2.0"
] | 3 | 2016-01-18T18:26:45.000Z | 2020-11-16T15:31:14.000Z | src/polytype.cpp | bryancatanzaro/copperhead-compiler | 11067c1d4bb1c850e88f9038782c41a6be3edd3c | [
"Apache-2.0"
] | null | null | null | src/polytype.cpp | bryancatanzaro/copperhead-compiler | 11067c1d4bb1c850e88f9038782c41a6be3edd3c | [
"Apache-2.0"
] | 1 | 2015-03-18T01:34:49.000Z | 2015-03-18T01:34:49.000Z | #include "polytype.hpp"
using std::vector;
using std::shared_ptr;
using std::static_pointer_cast;
namespace backend {
polytype_t::polytype_t(vector<shared_ptr<const monotype_t> >&& vars,
shared_ptr<const monotype_t> monotype)
: type_t(*this), m_vars(std::move(vars)), m_monotype(monotype) {}
const monotype_t& polytype_t::monotype() const {
return *m_monotype;
}
polytype_t::const_iterator polytype_t::begin() const {
return boost::make_indirect_iterator(m_vars.cbegin());
}
polytype_t::const_iterator polytype_t::end() const {
return boost::make_indirect_iterator(m_vars.cend());
}
shared_ptr<const polytype_t> polytype_t::ptr() const {
return static_pointer_cast<const polytype_t>(this->shared_from_this());
}
}
| 24.967742 | 75 | 0.719638 | [
"vector"
] |
cb2f963e41d2d27754e3f2454b1a147ae090d28b | 688 | cpp | C++ | Dataset/Leetcode/valid/46/595.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/valid/46/595.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/valid/46/595.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | class Solution {
public:
vector<vector<int>> XXX(vector<int>& nums) {
vector<vector<int>> res;
vector<int> path;
vector<bool> vis(nums.size(), false);
function<void(int i)> get_path = [&](int k) {
if(k == nums.size()) {
res.push_back(path);
return ;
}
for(int i = 0; i < nums.size(); ++i) {
if(vis[i] == true) continue;
vis[i] = true;
path.push_back(nums[i]);
get_path(k + 1);
path.pop_back();
vis[i] = false;
}
};
get_path(0);
return res;
}
};
| 25.481481 | 53 | 0.405523 | [
"vector"
] |
cb33d2b02fc896214b98fb010dfc3fdef2395c04 | 24,874 | cpp | C++ | openstudiocore/src/isomodel/Test/SimModel_GTest.cpp | Acidburn0zzz/OpenStudio | 8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd | [
"MIT"
] | null | null | null | openstudiocore/src/isomodel/Test/SimModel_GTest.cpp | Acidburn0zzz/OpenStudio | 8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd | [
"MIT"
] | null | null | null | openstudiocore/src/isomodel/Test/SimModel_GTest.cpp | Acidburn0zzz/OpenStudio | 8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd | [
"MIT"
] | null | null | null | /***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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 <gtest/gtest.h>
#include "ISOModelFixture.hpp"
#include "../SimModel.hpp"
#include "../UserModel.hpp"
#include <resources.hxx>
#include <sstream>
using namespace openstudio::isomodel;
using namespace openstudio;
void testGenericFunctions() {
double scalar = 2;
double test[] = {0,1,2,3,4,5,6,7,8,9,10,11};
Vector vTest = Vector(12), vTest2 = Vector(12);
for(unsigned int i = 0;i<vTest.size();i++){
vTest[i] = i;
vTest2[i] = 11-i;
}
for(unsigned int i = 0;i<12;i++){
EXPECT_DOUBLE_EQ(i, test[i]);
EXPECT_DOUBLE_EQ(i, vTest[i]);
EXPECT_DOUBLE_EQ(11 - i, vTest2[i]);
}
Vector results = mult(test,scalar,12);
for(unsigned int i = 0;i<12;i++){
EXPECT_DOUBLE_EQ(i*scalar, results[i]);
}
results = mult(vTest, scalar);
for(unsigned int i = 0;i<vTest.size();i++){
EXPECT_DOUBLE_EQ(i * scalar, results[i]);
}
results = mult(vTest, test);
for(unsigned int i = 0;i<vTest.size();i++){
EXPECT_DOUBLE_EQ(i * i, results[i]);
}
results = mult(vTest, vTest);
for(unsigned int i = 0;i<vTest.size();i++){
EXPECT_DOUBLE_EQ(i * i, results[i]);
}
results = div(vTest, scalar);
for(unsigned int i = 0;i<vTest.size();i++){
EXPECT_DOUBLE_EQ(i / scalar, results[i]);
}
results = div(scalar, vTest);
EXPECT_DOUBLE_EQ(std::numeric_limits<double>::max(), results[0]);
for(unsigned int i = 1;i<vTest.size();i++){
EXPECT_DOUBLE_EQ(scalar / i, results[i]);
}
results = div(vTest, vTest);
EXPECT_DOUBLE_EQ(std::numeric_limits<double>::max(), results[0]); //0 / 0
for(unsigned int i = 1;i<vTest.size();i++){
EXPECT_DOUBLE_EQ(1, results[i]);
}
results = sum(vTest, vTest);
for(unsigned int i = 0;i<vTest.size();i++){
EXPECT_DOUBLE_EQ(i + i, results[i]);
}
results = sum(vTest, scalar);
for(unsigned int i = 0;i<vTest.size();i++){
EXPECT_DOUBLE_EQ(i + scalar, results[i]);
}
results = dif(vTest, vTest);
for(unsigned int i = 0;i<vTest.size();i++){
EXPECT_DOUBLE_EQ(0, results[i]);
}
results = dif(vTest, scalar);
for(unsigned int i = 0;i<vTest.size();i++){
EXPECT_DOUBLE_EQ(i - scalar, results[i]);
}
results = dif(scalar, vTest);
for(unsigned int i = 0;i<vTest.size();i++){
EXPECT_DOUBLE_EQ(scalar - i, results[i]);
}
EXPECT_DOUBLE_EQ(11, openstudio::isomodel::maximum(vTest));
results = maximum(vTest,vTest2);
EXPECT_DOUBLE_EQ(11, results[0]);
EXPECT_DOUBLE_EQ(10, results[1]);
EXPECT_DOUBLE_EQ(9, results[2]);
EXPECT_DOUBLE_EQ(8, results[3]);
EXPECT_DOUBLE_EQ(7, results[4]);
EXPECT_DOUBLE_EQ(6, results[5]);
EXPECT_DOUBLE_EQ(6, results[6]);
EXPECT_DOUBLE_EQ(7, results[7]);
EXPECT_DOUBLE_EQ(8, results[8]);
EXPECT_DOUBLE_EQ(9, results[9]);
EXPECT_DOUBLE_EQ(10, results[10]);
EXPECT_DOUBLE_EQ(11, results[11]);
for(unsigned int i = 0;i<12;i++){
EXPECT_DOUBLE_EQ(11-i, vTest2[i]);
}
results = maximum(vTest2,10);
EXPECT_DOUBLE_EQ(11, results[0]);
for(unsigned int i = 1;i<vTest2.size();i++){
EXPECT_DOUBLE_EQ(10, results[i]);
}
EXPECT_DOUBLE_EQ(0, openstudio::isomodel::minimum(vTest));
results = minimum(vTest,1);
EXPECT_DOUBLE_EQ(0, results[0]);
for(unsigned int i = 1;i<vTest.size();i++){
EXPECT_DOUBLE_EQ(1, results[i]);
}
results = pow(vTest, 3);
for(unsigned int i = 0;i<vTest.size();i++){
EXPECT_DOUBLE_EQ(i*i*i, results[i]);
}
for(unsigned int i = 0;i<vTest.size();i++){
if(i%2==0){
vTest[i] = -1 * vTest[i];
}
}
results = abs(vTest);
for(unsigned int i = 0;i<vTest.size();i++){
EXPECT_DOUBLE_EQ(i, results[i]);
}
}
TEST_F(ISOModelFixture, SimModel)
{
//testGenericFunctions();
UserModel userModel;
userModel.load(resourcesPath() / openstudio::toPath("isomodel/exampleModel.ISO"));
ASSERT_TRUE(userModel.valid());
SimModel simModel = userModel.toSimModel();
ISOResults results = simModel.simulate();
EXPECT_DOUBLE_EQ(0, results.monthlyResults[0].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Heating) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[1].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Heating) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[2].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Heating) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[3].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Heating) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[4].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Heating) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[5].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Heating) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[6].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Heating) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[7].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Heating) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[8].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Heating) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[9].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Heating) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[10].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Heating) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[11].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Heating) );
EXPECT_DOUBLE_EQ(0.34017664200890202, results.monthlyResults[0].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Cooling) );
EXPECT_DOUBLE_EQ(0.47747797661595698, results.monthlyResults[1].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Cooling) );
EXPECT_DOUBLE_EQ(1.3169933074695126, results.monthlyResults[2].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Cooling) );
EXPECT_DOUBLE_EQ(2.4228760061905459, results.monthlyResults[3].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Cooling) );
EXPECT_DOUBLE_EQ(3.7268950868670396, results.monthlyResults[4].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Cooling) );
EXPECT_DOUBLE_EQ(4.5866846768048868, results.monthlyResults[5].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Cooling) );
EXPECT_DOUBLE_EQ(5.2957488941600186, results.monthlyResults[6].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Cooling) );
EXPECT_DOUBLE_EQ(4.7728355657234216, results.monthlyResults[7].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Cooling) );
EXPECT_DOUBLE_EQ(3.9226543241145793, results.monthlyResults[8].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Cooling) );
EXPECT_DOUBLE_EQ(2.5539052604147932, results.monthlyResults[9].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Cooling) );
EXPECT_DOUBLE_EQ(1.2308504332601247, results.monthlyResults[10].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Cooling) );
EXPECT_DOUBLE_EQ(0.39346302413410666, results.monthlyResults[11].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Cooling) );
EXPECT_DOUBLE_EQ(3.0435906070795506, results.monthlyResults[0].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::InteriorLights) );
EXPECT_DOUBLE_EQ(2.7490495805879811, results.monthlyResults[1].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::InteriorLights) );
EXPECT_DOUBLE_EQ(3.0435906070795506, results.monthlyResults[2].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::InteriorLights) );
EXPECT_DOUBLE_EQ(2.9454102649156932, results.monthlyResults[3].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::InteriorLights) );
EXPECT_DOUBLE_EQ(3.0435906070795506, results.monthlyResults[4].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::InteriorLights) );
EXPECT_DOUBLE_EQ(2.9454102649156932, results.monthlyResults[5].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::InteriorLights) );
EXPECT_DOUBLE_EQ(3.0435906070795506, results.monthlyResults[6].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::InteriorLights) );
EXPECT_DOUBLE_EQ(3.0435906070795506, results.monthlyResults[7].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::InteriorLights) );
EXPECT_DOUBLE_EQ(2.9454102649156932, results.monthlyResults[8].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::InteriorLights) );
EXPECT_DOUBLE_EQ(3.0435906070795506, results.monthlyResults[9].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::InteriorLights) );
EXPECT_DOUBLE_EQ(2.9454102649156932, results.monthlyResults[10].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::InteriorLights) );
EXPECT_DOUBLE_EQ(3.0435906070795506, results.monthlyResults[11].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::InteriorLights) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[0].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::ExteriorLights) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[1].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::ExteriorLights) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[2].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::ExteriorLights) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[3].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::ExteriorLights) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[4].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::ExteriorLights) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[5].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::ExteriorLights) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[6].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::ExteriorLights) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[7].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::ExteriorLights) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[8].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::ExteriorLights) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[9].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::ExteriorLights) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[10].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::ExteriorLights) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[11].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::ExteriorLights) );
EXPECT_DOUBLE_EQ(0.63842346693363961, results.monthlyResults[0].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Fans) );
EXPECT_DOUBLE_EQ(0.58652953302205624, results.monthlyResults[1].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Fans) );
EXPECT_DOUBLE_EQ(1.1594322752799191, results.monthlyResults[2].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Fans) );
EXPECT_DOUBLE_EQ(2.0941842853293839, results.monthlyResults[3].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Fans) );
EXPECT_DOUBLE_EQ(3.2204732233014375, results.monthlyResults[4].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Fans) );
EXPECT_DOUBLE_EQ(3.9634287108669861, results.monthlyResults[5].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Fans) );
EXPECT_DOUBLE_EQ(4.5761426152904692, results.monthlyResults[6].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Fans) );
EXPECT_DOUBLE_EQ(4.1242847167812258, results.monthlyResults[7].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Fans) );
EXPECT_DOUBLE_EQ(3.3896293582675732, results.monthlyResults[8].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Fans) );
EXPECT_DOUBLE_EQ(2.2071953370955941, results.monthlyResults[9].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Fans) );
EXPECT_DOUBLE_EQ(1.0817759398239362, results.monthlyResults[10].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Fans) );
EXPECT_DOUBLE_EQ(0.60343839818338818, results.monthlyResults[11].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Fans) );
EXPECT_DOUBLE_EQ(0.10115033983397403, results.monthlyResults[0].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Pumps) );
EXPECT_DOUBLE_EQ(0.092928384780081766, results.monthlyResults[1].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Pumps) );
EXPECT_DOUBLE_EQ(0.18369777229888676, results.monthlyResults[2].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Pumps) );
EXPECT_DOUBLE_EQ(0.33179772221319914, results.monthlyResults[3].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Pumps) );
EXPECT_DOUBLE_EQ(0.51024434068463553, results.monthlyResults[4].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Pumps) );
EXPECT_DOUBLE_EQ(0.62795649247899088, results.monthlyResults[5].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Pumps) );
EXPECT_DOUBLE_EQ(0.72503346859816364, results.monthlyResults[6].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Pumps) );
EXPECT_DOUBLE_EQ(0.65344214660243516, results.monthlyResults[7].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Pumps) );
EXPECT_DOUBLE_EQ(0.53704504808815079, results.monthlyResults[8].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Pumps) );
EXPECT_DOUBLE_EQ(0.34970293228646099, results.monthlyResults[9].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Pumps) );
EXPECT_DOUBLE_EQ(0.17139408183562516, results.monthlyResults[10].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Pumps) );
EXPECT_DOUBLE_EQ(0.095607386329774752, results.monthlyResults[11].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::Pumps) );
EXPECT_DOUBLE_EQ(2.7583969507693009, results.monthlyResults[0].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::InteriorEquipment) );
EXPECT_DOUBLE_EQ(2.4914553103722721, results.monthlyResults[1].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::InteriorEquipment) );
EXPECT_DOUBLE_EQ(2.7583969507693009, results.monthlyResults[2].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::InteriorEquipment) );
EXPECT_DOUBLE_EQ(2.6694164039702915, results.monthlyResults[3].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::InteriorEquipment) );
EXPECT_DOUBLE_EQ(2.7583969507693009, results.monthlyResults[4].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::InteriorEquipment) );
EXPECT_DOUBLE_EQ(2.6694164039702915, results.monthlyResults[5].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::InteriorEquipment) );
EXPECT_DOUBLE_EQ(2.7583969507693009, results.monthlyResults[6].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::InteriorEquipment) );
EXPECT_DOUBLE_EQ(2.7583969507693009, results.monthlyResults[7].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::InteriorEquipment) );
EXPECT_DOUBLE_EQ(2.6694164039702915, results.monthlyResults[8].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::InteriorEquipment) );
EXPECT_DOUBLE_EQ(2.7583969507693009, results.monthlyResults[9].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::InteriorEquipment) );
EXPECT_DOUBLE_EQ(2.6694164039702915, results.monthlyResults[10].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::InteriorEquipment) );
EXPECT_DOUBLE_EQ(2.7583969507693009, results.monthlyResults[11].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::InteriorEquipment) );
EXPECT_DOUBLE_EQ(1.868625049820434, results.monthlyResults[0].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::Heating) );
EXPECT_DOUBLE_EQ(0.94352030602805137, results.monthlyResults[1].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::Heating) );
EXPECT_DOUBLE_EQ(0.11607038752689436, results.monthlyResults[2].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::Heating) );
EXPECT_DOUBLE_EQ(0.0029172731542854565, results.monthlyResults[3].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::Heating) );
EXPECT_DOUBLE_EQ(1.4423899246658913e-05, results.monthlyResults[4].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::Heating) );
EXPECT_DOUBLE_EQ(2.348596441320849e-10, results.monthlyResults[5].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::Heating) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[6].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::Heating) );
EXPECT_DOUBLE_EQ(1.4643812476787042e-11, results.monthlyResults[7].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::Heating) );
EXPECT_DOUBLE_EQ(3.1551923170925401e-07, results.monthlyResults[8].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::Heating) );
EXPECT_DOUBLE_EQ(0.0017593638950890019, results.monthlyResults[9].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::Heating) );
EXPECT_DOUBLE_EQ(0.09860920039620702, results.monthlyResults[10].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::Heating) );
EXPECT_DOUBLE_EQ(1.4290645202713919, results.monthlyResults[11].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::Heating) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[0].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::WaterSystems) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[1].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::WaterSystems) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[2].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::WaterSystems) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[3].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::WaterSystems) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[4].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::WaterSystems) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[5].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::WaterSystems) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[6].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::WaterSystems) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[7].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::WaterSystems) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[8].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::WaterSystems) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[9].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::WaterSystems) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[10].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::WaterSystems) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[11].getEndUse(EndUseFuelType::Electricity, EndUseCategoryType::WaterSystems) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[0].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::Cooling) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[1].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::Cooling) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[2].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::Cooling) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[3].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::Cooling) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[4].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::Cooling) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[5].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::Cooling) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[6].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::Cooling) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[7].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::Cooling) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[8].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::Cooling) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[9].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::Cooling) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[10].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::Cooling) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[11].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::Cooling) );
EXPECT_DOUBLE_EQ(8.0840634632175608, results.monthlyResults[0].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::InteriorEquipment) );
EXPECT_DOUBLE_EQ(7.3017347409706996, results.monthlyResults[1].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::InteriorEquipment) );
EXPECT_DOUBLE_EQ(8.0840634632175608, results.monthlyResults[2].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::InteriorEquipment) );
EXPECT_DOUBLE_EQ(7.8232872224686067, results.monthlyResults[3].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::InteriorEquipment) );
EXPECT_DOUBLE_EQ(8.0840634632175608, results.monthlyResults[4].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::InteriorEquipment) );
EXPECT_DOUBLE_EQ(7.8232872224686067, results.monthlyResults[5].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::InteriorEquipment) );
EXPECT_DOUBLE_EQ(8.0840634632175608, results.monthlyResults[6].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::InteriorEquipment) );
EXPECT_DOUBLE_EQ(8.0840634632175608, results.monthlyResults[7].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::InteriorEquipment) );
EXPECT_DOUBLE_EQ(7.8232872224686067, results.monthlyResults[8].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::InteriorEquipment) );
EXPECT_DOUBLE_EQ(8.0840634632175608, results.monthlyResults[9].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::InteriorEquipment) );
EXPECT_DOUBLE_EQ(7.8232872224686067, results.monthlyResults[10].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::InteriorEquipment) );
EXPECT_DOUBLE_EQ(8.0840634632175608, results.monthlyResults[11].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::InteriorEquipment) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[0].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::WaterSystems) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[1].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::WaterSystems) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[2].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::WaterSystems) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[3].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::WaterSystems) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[4].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::WaterSystems) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[5].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::WaterSystems) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[6].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::WaterSystems) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[7].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::WaterSystems) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[8].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::WaterSystems) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[9].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::WaterSystems) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[10].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::WaterSystems) );
EXPECT_DOUBLE_EQ(0, results.monthlyResults[11].getEndUse(EndUseFuelType::Gas, EndUseCategoryType::WaterSystems) );
}
| 74.473054 | 146 | 0.791147 | [
"vector"
] |
cb343bd9a044b3c95e82039503a42a2c693dfb98 | 9,577 | cpp | C++ | Source/Engine/Core/RHI/D3D12/D3D12Common.cpp | flygod1159/Kaguya | 47dbb3940110ed490d0b70eed31383cfc82bc8df | [
"MIT"
] | 1 | 2022-01-13T16:32:40.000Z | 2022-01-13T16:32:40.000Z | Source/Engine/Core/RHI/D3D12/D3D12Common.cpp | flygod1159/Kaguya | 47dbb3940110ed490d0b70eed31383cfc82bc8df | [
"MIT"
] | null | null | null | Source/Engine/Core/RHI/D3D12/D3D12Common.cpp | flygod1159/Kaguya | 47dbb3940110ed490d0b70eed31383cfc82bc8df | [
"MIT"
] | null | null | null | #include "D3D12Common.h"
LPCWSTR GetCommandQueueTypeString(ED3D12CommandQueueType CommandQueueType)
{
// clang-format off
switch (CommandQueueType)
{
case ED3D12CommandQueueType::Direct: return L"3D";
case ED3D12CommandQueueType::AsyncCompute: return L"Async Compute";
case ED3D12CommandQueueType::Copy1: return L"Copy 1";
case ED3D12CommandQueueType::Copy2: return L"Copy 2";
default: return L"<unknown>";
}
// clang-format on
}
LPCWSTR GetCommandQueueTypeFenceString(ED3D12CommandQueueType CommandQueueType)
{
// clang-format off
switch (CommandQueueType)
{
case ED3D12CommandQueueType::Direct: return L"3D Fence";
case ED3D12CommandQueueType::AsyncCompute: return L"Async Compute Fence";
case ED3D12CommandQueueType::Copy1: return L"Copy 1 Fence";
case ED3D12CommandQueueType::Copy2: return L"Copy 2 Fence";
default: return L"<unknown>";
}
// clang-format on
}
LPCWSTR GetAutoBreadcrumbOpString(D3D12_AUTO_BREADCRUMB_OP Op)
{
#define STRINGIFY(x) \
case x: \
return L#x
switch (Op)
{
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_SETMARKER);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_BEGINEVENT);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_ENDEVENT);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_DRAWINSTANCED);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_DRAWINDEXEDINSTANCED);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_EXECUTEINDIRECT);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_DISPATCH);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_COPYBUFFERREGION);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_COPYTEXTUREREGION);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_COPYRESOURCE);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_COPYTILES);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_RESOLVESUBRESOURCE);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_CLEARRENDERTARGETVIEW);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_CLEARUNORDEREDACCESSVIEW);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_CLEARDEPTHSTENCILVIEW);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_EXECUTEBUNDLE);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_PRESENT);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_RESOLVEQUERYDATA);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_BEGINSUBMISSION);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_ENDSUBMISSION);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_DECODEFRAME);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_PROCESSFRAMES);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_ATOMICCOPYBUFFERUINT);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_ATOMICCOPYBUFFERUINT64);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_RESOLVESUBRESOURCEREGION);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_WRITEBUFFERIMMEDIATE);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_DECODEFRAME1);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_SETPROTECTEDRESOURCESESSION);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_DECODEFRAME2);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_PROCESSFRAMES1);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_BUILDRAYTRACINGACCELERATIONSTRUCTURE);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_EMITRAYTRACINGACCELERATIONSTRUCTUREPOSTBUILDINFO);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_COPYRAYTRACINGACCELERATIONSTRUCTURE);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_DISPATCHRAYS);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_INITIALIZEMETACOMMAND);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_EXECUTEMETACOMMAND);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_ESTIMATEMOTION);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_RESOLVEMOTIONVECTORHEAP);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_SETPIPELINESTATE1);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_INITIALIZEEXTENSIONCOMMAND);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_EXECUTEEXTENSIONCOMMAND);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_DISPATCHMESH);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_ENCODEFRAME);
STRINGIFY(D3D12_AUTO_BREADCRUMB_OP_RESOLVEENCODEROUTPUTMETADATA);
default:
return L"<unknown>";
}
#undef STRINGIFY
}
LPCWSTR GetDredAllocationTypeString(D3D12_DRED_ALLOCATION_TYPE Type)
{
#define STRINGIFY(x) \
case x: \
return L#x
switch (Type)
{
STRINGIFY(D3D12_DRED_ALLOCATION_TYPE_COMMAND_QUEUE);
STRINGIFY(D3D12_DRED_ALLOCATION_TYPE_COMMAND_ALLOCATOR);
STRINGIFY(D3D12_DRED_ALLOCATION_TYPE_PIPELINE_STATE);
STRINGIFY(D3D12_DRED_ALLOCATION_TYPE_COMMAND_LIST);
STRINGIFY(D3D12_DRED_ALLOCATION_TYPE_FENCE);
STRINGIFY(D3D12_DRED_ALLOCATION_TYPE_DESCRIPTOR_HEAP);
STRINGIFY(D3D12_DRED_ALLOCATION_TYPE_HEAP);
STRINGIFY(D3D12_DRED_ALLOCATION_TYPE_QUERY_HEAP);
STRINGIFY(D3D12_DRED_ALLOCATION_TYPE_COMMAND_SIGNATURE);
STRINGIFY(D3D12_DRED_ALLOCATION_TYPE_PIPELINE_LIBRARY);
STRINGIFY(D3D12_DRED_ALLOCATION_TYPE_VIDEO_DECODER);
STRINGIFY(D3D12_DRED_ALLOCATION_TYPE_VIDEO_PROCESSOR);
STRINGIFY(D3D12_DRED_ALLOCATION_TYPE_RESOURCE);
STRINGIFY(D3D12_DRED_ALLOCATION_TYPE_PASS);
STRINGIFY(D3D12_DRED_ALLOCATION_TYPE_CRYPTOSESSION);
STRINGIFY(D3D12_DRED_ALLOCATION_TYPE_CRYPTOSESSIONPOLICY);
STRINGIFY(D3D12_DRED_ALLOCATION_TYPE_PROTECTEDRESOURCESESSION);
STRINGIFY(D3D12_DRED_ALLOCATION_TYPE_VIDEO_DECODER_HEAP);
STRINGIFY(D3D12_DRED_ALLOCATION_TYPE_COMMAND_POOL);
STRINGIFY(D3D12_DRED_ALLOCATION_TYPE_COMMAND_RECORDER);
STRINGIFY(D3D12_DRED_ALLOCATION_TYPE_STATE_OBJECT);
STRINGIFY(D3D12_DRED_ALLOCATION_TYPE_METACOMMAND);
STRINGIFY(D3D12_DRED_ALLOCATION_TYPE_SCHEDULINGGROUP);
STRINGIFY(D3D12_DRED_ALLOCATION_TYPE_VIDEO_MOTION_ESTIMATOR);
STRINGIFY(D3D12_DRED_ALLOCATION_TYPE_VIDEO_MOTION_VECTOR_HEAP);
STRINGIFY(D3D12_DRED_ALLOCATION_TYPE_VIDEO_EXTENSION_COMMAND);
STRINGIFY(D3D12_DRED_ALLOCATION_TYPE_VIDEO_ENCODER);
STRINGIFY(D3D12_DRED_ALLOCATION_TYPE_VIDEO_ENCODER_HEAP);
STRINGIFY(D3D12_DRED_ALLOCATION_TYPE_INVALID);
default:
return L"<unknown>";
}
#undef STRINGIFY
}
D3D12Exception::D3D12Exception(const char* File, int Line, HRESULT ErrorCode)
: Exception(File, Line)
, ErrorCode(ErrorCode)
{
}
const char* D3D12Exception::GetErrorType() const noexcept
{
return "[D3D12]";
}
std::string D3D12Exception::GetError() const
{
#define STRINGIFY(x) \
case x: \
Error = #x; \
break
std::string Error;
// https://docs.microsoft.com/en-us/windows/win32/direct3d12/d3d12-graphics-reference-returnvalues
switch (ErrorCode)
{
STRINGIFY(D3D12_ERROR_ADAPTER_NOT_FOUND);
STRINGIFY(D3D12_ERROR_DRIVER_VERSION_MISMATCH);
STRINGIFY(DXGI_ERROR_INVALID_CALL);
STRINGIFY(DXGI_ERROR_WAS_STILL_DRAWING);
STRINGIFY(E_FAIL);
STRINGIFY(E_INVALIDARG);
STRINGIFY(E_OUTOFMEMORY);
STRINGIFY(E_NOTIMPL);
STRINGIFY(E_NOINTERFACE);
// This just follows the documentation
// DXGI
STRINGIFY(DXGI_ERROR_ACCESS_DENIED);
STRINGIFY(DXGI_ERROR_ACCESS_LOST);
STRINGIFY(DXGI_ERROR_ALREADY_EXISTS);
STRINGIFY(DXGI_ERROR_CANNOT_PROTECT_CONTENT);
STRINGIFY(DXGI_ERROR_DEVICE_HUNG);
STRINGIFY(DXGI_ERROR_DEVICE_REMOVED);
STRINGIFY(DXGI_ERROR_DEVICE_RESET);
STRINGIFY(DXGI_ERROR_DRIVER_INTERNAL_ERROR);
STRINGIFY(DXGI_ERROR_FRAME_STATISTICS_DISJOINT);
STRINGIFY(DXGI_ERROR_GRAPHICS_VIDPN_SOURCE_IN_USE);
// DXERR(DXGI_ERROR_INVALID_CALL); // Already defined
STRINGIFY(DXGI_ERROR_MORE_DATA);
STRINGIFY(DXGI_ERROR_NAME_ALREADY_EXISTS);
STRINGIFY(DXGI_ERROR_NONEXCLUSIVE);
STRINGIFY(DXGI_ERROR_NOT_CURRENTLY_AVAILABLE);
STRINGIFY(DXGI_ERROR_NOT_FOUND);
// DXERR(DXGI_ERROR_REMOTE_CLIENT_DISCONNECTED); // Reserved
// DXERR(DXGI_ERROR_REMOTE_OUTOFMEMORY); // Reserved
STRINGIFY(DXGI_ERROR_RESTRICT_TO_OUTPUT_STALE);
STRINGIFY(DXGI_ERROR_SDK_COMPONENT_MISSING);
STRINGIFY(DXGI_ERROR_SESSION_DISCONNECTED);
STRINGIFY(DXGI_ERROR_UNSUPPORTED);
STRINGIFY(DXGI_ERROR_WAIT_TIMEOUT);
// DXERR(DXGI_ERROR_WAS_STILL_DRAWING); // Already defined
default:
{
char Buffer[64] = {};
sprintf_s(Buffer, "HRESULT of 0x%08X", static_cast<UINT>(ErrorCode));
Error = Buffer;
}
break;
}
return Error;
#undef STRINGIFY
}
D3D12SyncHandle::operator bool() const noexcept
{
return Fence != nullptr;
}
auto D3D12SyncHandle::GetValue() const noexcept -> UINT64
{
assert(static_cast<bool>(*this));
return Value;
}
auto D3D12SyncHandle::IsComplete() const -> bool
{
assert(static_cast<bool>(*this));
return Fence->IsFenceComplete(Value);
}
auto D3D12SyncHandle::WaitForCompletion() const -> void
{
assert(static_cast<bool>(*this));
Fence->HostWaitForValue(Value);
}
void D3D12InputLayout::AddVertexLayoutElement(
std::string_view SemanticName,
UINT SemanticIndex,
DXGI_FORMAT Format,
UINT InputSlot)
{
D3D12_INPUT_ELEMENT_DESC& Desc = InputElements.emplace_back();
Desc.SemanticName = SemanticName.data();
Desc.SemanticIndex = SemanticIndex;
Desc.Format = Format;
Desc.InputSlot = InputSlot;
Desc.AlignedByteOffset = D3D12_APPEND_ALIGNED_ELEMENT;
Desc.InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA;
Desc.InstanceDataStepRate = 0;
}
D3D12_RESOURCE_STATES CResourceState::GetSubresourceState(UINT Subresource) const
{
if (TrackingMode == ETrackingMode::PerResource)
{
return ResourceState;
}
return SubresourceStates[Subresource];
}
void CResourceState::SetSubresourceState(UINT Subresource, D3D12_RESOURCE_STATES State)
{
// If setting all subresources, or the resource only has a single subresource, set the per-resource state
if (Subresource == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES || SubresourceStates.size() == 1)
{
TrackingMode = ETrackingMode::PerResource;
ResourceState = State;
}
else
{
// If we previous tracked resource per resource level, we need to update all
// all subresource states before proceeding
if (TrackingMode == ETrackingMode::PerResource)
{
TrackingMode = ETrackingMode::PerSubresource;
for (auto& SubresourceState : SubresourceStates)
{
SubresourceState = ResourceState;
}
}
SubresourceStates[Subresource] = State;
}
}
| 34.44964 | 106 | 0.82009 | [
"3d"
] |
cb353de0a4828adf43527d254a285d87a380219f | 10,043 | cpp | C++ | apps/SoapySDRProbe.cpp | bastille-attic/SoapySDR | 7976f888ea03d128bfc0c2ebe49ce8316ce9e2ea | [
"BSL-1.0"
] | 1 | 2018-06-05T18:13:55.000Z | 2018-06-05T18:13:55.000Z | apps/SoapySDRProbe.cpp | cjcliffe/SoapySDR | af830bc209e10f4289c0516374ce043f238b4d01 | [
"BSL-1.0"
] | null | null | null | apps/SoapySDRProbe.cpp | cjcliffe/SoapySDR | af830bc209e10f4289c0516374ce043f238b4d01 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2015-2017 Josh Blum
// Copyright (c) 2016-2016 Bastille Networks
// SPDX-License-Identifier: BSL-1.0
#include <SoapySDR/Device.hpp>
#include <sstream>
template <typename Type>
std::string toString(const std::vector<Type> &options)
{
std::stringstream ss;
if (options.empty()) return "";
for (size_t i = 0; i < options.size(); i++)
{
if (not ss.str().empty()) ss << ", ";
ss << options[i];
}
return ss.str();
}
std::string toString(const SoapySDR::Range &range)
{
std::stringstream ss;
ss << "[" << range.minimum() << ", " << range.maximum();
if (range.step() != 0.0) ss << ", " << range.step();
ss << "]";
return ss.str();
}
std::string toString(const SoapySDR::RangeList &range, const double scale)
{
const size_t MAXRLEN = 10; //for abbreviating long lists
std::stringstream ss;
for (size_t i = 0; i < range.size(); i++)
{
if (range.size() >= MAXRLEN and i >= MAXRLEN/2 and i < (range.size()-MAXRLEN/2))
{
if (i == MAXRLEN) ss << ", ...";
continue;
}
if (not ss.str().empty()) ss << ", ";
if (range[i].minimum() == range[i].maximum()) ss << (range[i].minimum()/scale);
else ss << "[" << (range[i].minimum()/scale) << ", " << (range[i].maximum()/scale) << "]";
}
return ss.str();
}
std::string toString(const std::vector<double> &nums, const double scale)
{
std::stringstream ss;
if (nums.size() > 3)
{
ss << "[" << (nums.front()/scale) << ", " << (nums.back()/scale) << "]";
return ss.str();
}
for (size_t i = 0; i < nums.size(); i++)
{
if (not ss.str().empty()) ss << ", ";
ss << (nums[i]/scale);
}
return "[" + ss.str() + "]";
}
std::string toString(const SoapySDR::ArgInfo &argInfo, const std::string indent = " ")
{
std::stringstream ss;
//name, or use key if missing
std::string name = argInfo.name;
if (argInfo.name.empty()) name = argInfo.key;
ss << indent << " * " << name;
//optional description
std::string desc = argInfo.description;
const std::string replace("\n"+indent+" ");
for (size_t pos = 0; (pos=desc.find("\n", pos)) != std::string::npos; pos+=replace.size())
{
desc.replace(pos, 1, replace);
}
if (not desc.empty()) ss << " - " << desc << std::endl << indent << " ";
//other fields
ss << " [key=" << argInfo.key;
if (not argInfo.units.empty()) ss << ", units=" << argInfo.units;
if (not argInfo.value.empty()) ss << ", default=" << argInfo.value;
//type
switch (argInfo.type)
{
case SoapySDR::ArgInfo::BOOL: ss << ", type=bool"; break;
case SoapySDR::ArgInfo::INT: ss << ", type=int"; break;
case SoapySDR::ArgInfo::FLOAT: ss << ", type=float"; break;
case SoapySDR::ArgInfo::STRING: ss << ", type=string"; break;
}
//optional range/enumeration
if (argInfo.range.minimum() < argInfo.range.maximum()) ss << ", range=" << toString(argInfo.range);
if (not argInfo.options.empty()) ss << ", options=(" << toString(argInfo.options) << ")";
ss << "]";
return ss.str();
}
std::string toString(const SoapySDR::ArgInfoList &argInfos)
{
std::stringstream ss;
for (size_t i = 0; i < argInfos.size(); i++)
{
ss << toString(argInfos[i]) << std::endl;
}
return ss.str();
}
static std::string probeChannel(SoapySDR::Device *device, const int dir, const size_t chan)
{
std::stringstream ss;
std::string dirName = (dir==SOAPY_SDR_TX)?"TX":"RX";
ss << std::endl;
ss << "----------------------------------------------------" << std::endl;
ss << "-- " << dirName << " Channel " << chan << std::endl;
ss << "----------------------------------------------------" << std::endl;
// info
const auto info = device->getChannelInfo(dir, chan);
if (info.size() > 0)
{
ss << " Channel Information:" << std::endl;
for (const auto &it : info)
{
ss << " " << it.first << "=" << it.second << std::endl;
}
}
ss << " Full-duplex: " << (device->getFullDuplex(dir, chan)?"YES":"NO") << std::endl;
ss << " Supports AGC: " << (device->hasGainMode(dir, chan)?"YES":"NO") << std::endl;
//formats
std::string formats = toString(device->getStreamFormats(dir, chan));
if (not formats.empty()) ss << " Stream formats: " << formats << std::endl;
//native
double fullScale = 0.0;
std::string native = device->getNativeStreamFormat(dir, chan, fullScale);
ss << " Native format: " << native << " [full-scale=" << fullScale << "]" << std::endl;
//stream args
std::string streamArgs = toString(device->getStreamArgsInfo(dir, chan));
if (not streamArgs.empty()) ss << " Stream args:" << std::endl << streamArgs;
//antennas
std::string antennas = toString(device->listAntennas(dir, chan));
if (not antennas.empty()) ss << " Antennas: " << antennas << std::endl;
//corrections
std::vector<std::string> correctionsList;
if (device->hasDCOffsetMode(dir, chan)) correctionsList.push_back("DC removal");
if (device->hasDCOffset(dir, chan)) correctionsList.push_back("DC offset");
if (device->hasIQBalance(dir, chan)) correctionsList.push_back("IQ balance");
std::string corrections = toString(correctionsList);
if (not corrections.empty()) ss << " Corrections: " << corrections << std::endl;
//gains
ss << " Full gain range: " << toString(device->getGainRange(dir, chan)) << " dB" << std::endl;
std::vector<std::string> gainsList = device->listGains(dir, chan);
for (size_t i = 0; i < gainsList.size(); i++)
{
const std::string name = gainsList[i];
ss << " " << name << " gain range: " << toString(device->getGainRange(dir, chan, name)) << " dB" << std::endl;
}
//frequencies
ss << " Full freq range: " << toString(device->getFrequencyRange(dir, chan), 1e6) << " MHz" << std::endl;
std::vector<std::string> freqsList = device->listFrequencies(dir, chan);
for (size_t i = 0; i < freqsList.size(); i++)
{
const std::string name = freqsList[i];
ss << " " << name << " freq range: " << toString(device->getFrequencyRange(dir, chan, name), 1e6) << " MHz" << std::endl;
}
//freq args
std::string freqArgs = toString(device->getFrequencyArgsInfo(dir, chan));
if (not freqArgs.empty()) ss << " Tune args:" << std::endl << freqArgs;
//rates
ss << " Sample rates: " << toString(device->getSampleRateRange(dir, chan), 1e6) << " MSps" << std::endl;
//bandwidths
const auto bws = device->getBandwidthRange(dir, chan);
if (not bws.empty()) ss << " Filter bandwidths: " << toString(bws, 1e6) << " MHz" << std::endl;
//sensors
std::string sensors = toString(device->listSensors(dir, chan));
if (not sensors.empty()) ss << " Sensors: " << sensors << std::endl;
//settings
std::string settings = toString(device->getSettingInfo(dir, chan));
if (not settings.empty()) ss << " Other Settings:" << std::endl << settings;
return ss.str();
}
std::string SoapySDRDeviceProbe(SoapySDR::Device *device)
{
std::stringstream ss;
/*******************************************************************
* Identification info
******************************************************************/
ss << std::endl;
ss << "----------------------------------------------------" << std::endl;
ss << "-- Device identification" << std::endl;
ss << "----------------------------------------------------" << std::endl;
ss << " driver=" << device->getDriverKey() << std::endl;
ss << " hardware=" << device->getHardwareKey() << std::endl;
for (const auto &it : device->getHardwareInfo())
{
ss << " " << it.first << "=" << it.second << std::endl;
}
/*******************************************************************
* Available peripherals
******************************************************************/
ss << std::endl;
ss << "----------------------------------------------------" << std::endl;
ss << "-- Peripheral summary" << std::endl;
ss << "----------------------------------------------------" << std::endl;
size_t numRxChans = device->getNumChannels(SOAPY_SDR_RX);
size_t numTxChans = device->getNumChannels(SOAPY_SDR_TX);
ss << " Channels: " << numRxChans << " Rx, " << numTxChans << " Tx" << std::endl;
ss << " Timestamps: " << (device->hasHardwareTime()?"YES":"NO") << std::endl;
std::string clockSources = toString(device->listClockSources());
if (not clockSources.empty()) ss << " Clock sources: " << clockSources << std::endl;
std::string timeSources = toString(device->listTimeSources());
if (not timeSources.empty()) ss << " Time sources: " << timeSources << std::endl;
std::string sensors = toString(device->listSensors());
if (not sensors.empty()) ss << " Sensors: " << sensors << std::endl;
std::string registers = toString(device->listRegisterInterfaces());
if (not registers.empty()) ss << " Registers: " << registers << std::endl;
std::string settings = toString(device->getSettingInfo());
if (not settings.empty()) ss << " Other Settings:" << std::endl << settings;
std::string gpios = toString(device->listGPIOBanks());
if (not gpios.empty()) ss << " GPIOs: " << gpios << std::endl;
std::string uarts = toString(device->listUARTs());
if (not uarts.empty()) ss << " UARTs: " << uarts << std::endl;
/*******************************************************************
* Per-channel info
******************************************************************/
for (size_t chan = 0; chan < numRxChans; chan++)
{
ss << probeChannel(device, SOAPY_SDR_RX, chan);
}
for (size_t chan = 0; chan < numTxChans; chan++)
{
ss << probeChannel(device, SOAPY_SDR_TX, chan);
}
return ss.str();
}
| 36.387681 | 132 | 0.529722 | [
"vector"
] |
cb3a00f7a0541eaf25a876bf2669b2c48b742bc2 | 10,474 | cpp | C++ | src/demos/irrlicht/demo_IRR_fourbar.cpp | zzhou292/chrono-collision | c2a20e171bb0eb8819636d370887aa32d68547c6 | [
"BSD-3-Clause"
] | 1 | 2020-01-18T02:39:17.000Z | 2020-01-18T02:39:17.000Z | src/demos/irrlicht/demo_IRR_fourbar.cpp | zzhou292/chrono-collision | c2a20e171bb0eb8819636d370887aa32d68547c6 | [
"BSD-3-Clause"
] | 7 | 2021-10-20T04:43:35.000Z | 2021-12-24T08:44:31.000Z | src/demos/irrlicht/demo_IRR_fourbar.cpp | zzhou292/chrono-collision | c2a20e171bb0eb8819636d370887aa32d68547c6 | [
"BSD-3-Clause"
] | 2 | 2021-12-09T05:32:31.000Z | 2021-12-12T17:31:18.000Z | // =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Alessandro Tasora
// =============================================================================
//
// Demo code about
// - using IRRLICHT as a realtime 3D viewer of a four-bar mechanism
// - using the IRRLICHT graphical user interface (GUI) to handle user-input
// via mouse.
//
// =============================================================================
#include "chrono/physics/ChLinkMotorRotationSpeed.h"
#include "chrono/physics/ChSystemNSC.h"
#include "chrono_irrlicht/ChIrrApp.h"
// Use the namespaces of Chrono
using namespace chrono;
using namespace chrono::irrlicht;
// Use the main namespaces of Irrlicht
using namespace irr;
using namespace irr::core;
using namespace irr::scene;
using namespace irr::video;
using namespace irr::io;
using namespace irr::gui;
// Some static data (this is a simple application, we can do this ;) just to allow easy GUI manipulation
IGUIStaticText* text_motorspeed = 0;
// The MyEventReceiver class will be used to manage input
// from the GUI graphical user interface (the interface will
// be created with the basic -yet flexible- platform
// independent toolset of Irrlicht).
class MyEventReceiver : public IEventReceiver {
public:
MyEventReceiver(ChSystemNSC* system, IrrlichtDevice* device, std::shared_ptr<ChLinkMotorRotationSpeed> motor) {
// store pointer to physical system & other stuff so we can tweak them by user keyboard
msystem = system;
mdevice = device;
mmotor = motor;
}
bool OnEvent(const SEvent& event) {
// check if user moved the sliders with mouse..
if (event.EventType == EET_GUI_EVENT) {
s32 id = event.GUIEvent.Caller->getID();
IGUIEnvironment* env = mdevice->getGUIEnvironment();
switch (event.GUIEvent.EventType) {
case EGET_SCROLL_BAR_CHANGED:
if (id == 101) // id of 'motor speed' slider..
{
s32 pos = ((IGUIScrollBar*)event.GUIEvent.Caller)->getPos();
double newspeed = 10 * (double)pos / 100.0;
// set the speed into motor object
if (auto mfun = std::dynamic_pointer_cast<ChFunction_Const>(mmotor->GetSpeedFunction()))
mfun->Set_yconst(newspeed);
// show speed as formatted text in interface screen
char message[50];
sprintf(message, "Motor speed: %g [rad/s]", newspeed);
text_motorspeed->setText(core::stringw(message).c_str());
}
break;
default:
break;
}
}
return false;
}
private:
ChSystemNSC* msystem;
IrrlichtDevice* mdevice;
std::shared_ptr<ChLinkMotorRotationSpeed> mmotor;
};
int main(int argc, char* argv[]) {
GetLog() << "Copyright (c) 2017 projectchrono.org\nChrono version: " << CHRONO_VERSION << "\n\n";
// 1- Create a Chrono physical system
ChSystemNSC my_system;
// Create the Irrlicht visualization (open the Irrlicht device,
// bind a simple user interface, etc. etc.)
ChIrrApp application(&my_system, L"Example of integration of Chrono and Irrlicht, with GUI",
core::dimension2d<u32>(800, 600), false, true);
// Easy shortcuts to add camera, lights, logo and sky in Irrlicht scene:
application.AddTypicalLogo();
application.AddTypicalSky();
application.AddTypicalLights();
application.AddTypicalCamera();
// 2- Create the rigid bodies of the four-bar mechanical system
// (a flywheel, a rod, a rocker, a truss), maybe setting
// position/mass/inertias of their center of mass (COG) etc.
// ..the truss
auto my_body_A = chrono_types::make_shared<ChBody>();
my_system.AddBody(my_body_A);
my_body_A->SetBodyFixed(true); // truss does not move!
// ..the flywheel
auto my_body_B = chrono_types::make_shared<ChBody>();
my_system.AddBody(my_body_B);
my_body_B->SetPos(ChVector<>(0, 0, 0)); // position of COG of flywheel
// ..the rod
auto my_body_C = chrono_types::make_shared<ChBody>();
my_system.AddBody(my_body_C);
my_body_C->SetPos(ChVector<>(4, 0, 0)); // position of COG of rod
// ..the rocker
auto my_body_D = chrono_types::make_shared<ChBody>();
my_system.AddBody(my_body_D);
my_body_D->SetPos(ChVector<>(8, -4, 0)); // position of COG of rod
// 3- Create constraints: the mechanical joints between the
// rigid bodies. Doesn't matter if some constraints are redundant.
// .. a motor between flywheel and truss
auto my_link_AB = chrono_types::make_shared<ChLinkMotorRotationSpeed>();
my_link_AB->Initialize(my_body_A, my_body_B, ChFrame<>(ChVector<>(0, 0, 0)));
my_system.AddLink(my_link_AB);
auto my_speed_function = chrono_types::make_shared<ChFunction_Const>(CH_C_PI); // speed w=3.145 rad/sec
my_link_AB->SetSpeedFunction(my_speed_function);
// .. a revolute joint between flywheel and rod
auto my_link_BC = chrono_types::make_shared<ChLinkLockRevolute>();
my_link_BC->Initialize(my_body_B, my_body_C, ChCoordsys<>(ChVector<>(2, 0, 0)));
my_system.AddLink(my_link_BC);
// .. a revolute joint between rod and rocker
auto my_link_CD = chrono_types::make_shared<ChLinkLockRevolute>();
my_link_CD->Initialize(my_body_C, my_body_D, ChCoordsys<>(ChVector<>(8, 0, 0)));
my_system.AddLink(my_link_CD);
// .. a revolute joint between rocker and truss
auto my_link_DA = chrono_types::make_shared<ChLinkLockRevolute>();
my_link_DA->Initialize(my_body_D, my_body_A, ChCoordsys<>(ChVector<>(8, -8, 0)));
my_system.AddLink(my_link_DA);
//
// Prepare some graphical-user-interface (GUI) items to show
// on the screen
//
// ..add a GUI text and GUI slider to control motor of mechanism via mouse
text_motorspeed =
application.GetIGUIEnvironment()->addStaticText(L"Motor speed:", rect<s32>(300, 85, 400, 100), false);
IGUIScrollBar* scrollbar =
application.GetIGUIEnvironment()->addScrollBar(true, rect<s32>(300, 105, 450, 120), 0, 101);
scrollbar->setMax(100);
// ..Finally create the event receiver, for handling all the GUI (user will use
// buttons/sliders to modify parameters)
MyEventReceiver receiver(&my_system, application.GetDevice(), my_link_AB);
// note how to add the custom event receiver to the default interface:
application.SetUserEventReceiver(&receiver);
//
// Configure the solver with non-default settings
//
// By default, the solver uses the EULER_IMPLICIT_LINEARIZED stepper, that is very fast,
// but may allow some geometric error in constraints (because it is based on constraint
// stabilization). Alternatively, the timestepper EULER_IMPLICIT_PROJECTED is slower,
// but it is based on constraint projection, so gaps in constraints are less noticeable
// (hence avoids the 'spongy' behaviour of the default stepper, which operates only
// on speed-impulse level and keeps constraints'closed' by a continuous stabilization).
my_system.SetTimestepperType(ChTimestepper::Type::EULER_IMPLICIT_LINEARIZED);
//
// THE SOFT-REAL-TIME CYCLE, SHOWING THE SIMULATION
//
// use this array of points to store trajectory of a rod-point
std::vector<chrono::ChVector<> > mtrajectory;
application.SetTimestep(0.001);
while (application.GetDevice()->run()) {
application.BeginScene();
// This will draw 3D assets, but in this basic case we will draw some lines later..
application.DrawAll();
// .. draw a grid
ChIrrTools::drawGrid(application.GetVideoDriver(), 0.5, 0.5);
// .. draw a circle representing flywheel
ChIrrTools::drawCircle(application.GetVideoDriver(), 2.1, ChCoordsys<>(ChVector<>(0, 0, 0), QUNIT));
// .. draw a small circle representing joint BC
ChIrrTools::drawCircle(application.GetVideoDriver(), 0.06,
ChCoordsys<>(my_link_BC->GetMarker1()->GetAbsCoord().pos, QUNIT));
// .. draw a small circle representing joint CD
ChIrrTools::drawCircle(application.GetVideoDriver(), 0.06,
ChCoordsys<>(my_link_CD->GetMarker1()->GetAbsCoord().pos, QUNIT));
// .. draw a small circle representing joint DA
ChIrrTools::drawCircle(application.GetVideoDriver(), 0.06,
ChCoordsys<>(my_link_DA->GetMarker1()->GetAbsCoord().pos, QUNIT));
// .. draw the rod (from joint BC to joint CD)
ChIrrTools::drawSegment(application.GetVideoDriver(), my_link_BC->GetMarker1()->GetAbsCoord().pos,
my_link_CD->GetMarker1()->GetAbsCoord().pos, video::SColor(255, 0, 255, 0));
// .. draw the rocker (from joint CD to joint DA)
ChIrrTools::drawSegment(application.GetVideoDriver(), my_link_CD->GetMarker1()->GetAbsCoord().pos,
my_link_DA->GetMarker1()->GetAbsCoord().pos, video::SColor(255, 255, 0, 0));
// .. draw the trajectory of the rod-point
ChIrrTools::drawPolyline(application.GetVideoDriver(), mtrajectory, video::SColor(255, 0, 150, 0));
// HERE CHRONO INTEGRATION IS PERFORMED: THE
// TIME OF THE SIMULATION ADVANCES FOR A SINGLE
// STEP:
// my_system.DoStepDynamics(0.01);
// We need to add another point to the array of 3d
// points describing the trajectory to be drawn..
mtrajectory.push_back(my_body_C->Point_Body2World(ChVector<>(1, 1, 0)));
// keep only last 150 points..
if (mtrajectory.size() > 150)
mtrajectory.erase(mtrajectory.begin());
// THIS PERFORMS THE TIMESTEP INTEGRATION!!!
application.DoStep();
application.EndScene();
}
return 0;
}
| 42.92623 | 115 | 0.637006 | [
"object",
"vector",
"3d"
] |
cb3e98d2d06237e368489a2af55bfcaa0b42ecf8 | 23,401 | cc | C++ | open_spiel/games/bridge.cc | BrandonKates/open_spiel | f820abe9bdfdbc4bd45c2e933439393d4ad3622a | [
"Apache-2.0"
] | 1 | 2020-09-03T12:28:03.000Z | 2020-09-03T12:28:03.000Z | open_spiel/games/bridge.cc | mithilproof/open_spiel | 72e26013e3f37305d2d1c169123d678d35e6d7c4 | [
"Apache-2.0"
] | null | null | null | open_spiel/games/bridge.cc | mithilproof/open_spiel | 72e26013e3f37305d2d1c169123d678d35e6d7c4 | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 DeepMind Technologies 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.
#include "open_spiel/games/bridge.h"
#include <cstring>
#include <memory>
#include "open_spiel/abseil-cpp/absl/strings/str_format.h"
#include "open_spiel/abseil-cpp/absl/strings/string_view.h"
#include "open_spiel/games/bridge/double_dummy_solver/include/dll.h"
#include "open_spiel/game_parameters.h"
#include "open_spiel/games/bridge/bridge_scoring.h"
#include "open_spiel/spiel.h"
#include "open_spiel/spiel_utils.h"
// Our preferred version of the double_dummy_solver defines a DDS_EXTERNAL
// macro to add a prefix to the exported symbols to avoid name clashes.
// In order to compile with versions of the double_dummy_solver which do not
// do this, we define DDS_EXTERNAL as an identity if it isn't already defined.
#ifndef DDS_EXTERNAL
#define DDS_EXTERNAL(x) x
#endif
namespace open_spiel {
namespace bridge {
namespace {
enum Seat { kNorth, kEast, kSouth, kWest };
const GameType kGameType{/*short_name=*/"bridge",
/*long_name=*/"Contract Bridge",
GameType::Dynamics::kSequential,
GameType::ChanceMode::kExplicitStochastic,
GameType::Information::kImperfectInformation,
GameType::Utility::kZeroSum,
GameType::RewardModel::kTerminal,
/*max_num_players=*/kNumPlayers,
/*min_num_players=*/kNumPlayers,
/*provides_information_state_string=*/false,
/*provides_information_state_tensor=*/false,
/*provides_observation_string=*/true,
/*provides_observation_tensor=*/true,
/*parameter_specification=*/
{
// If true, replace the play phase with a computed
// result based on perfect-information play.
{"use_double_dummy_result", GameParameter(true)},
// If true, the dealer's side is vulnerable.
{"dealer_vul", GameParameter(false)},
// If true, the non-dealer's side is vulnerable.
{"non_dealer_vul", GameParameter(false)},
}};
std::shared_ptr<const Game> Factory(const GameParameters& params) {
return std::shared_ptr<const Game>(new BridgeGame(params));
}
REGISTER_SPIEL_GAME(kGameType, Factory);
// A call is one of Pass, Double, Redouble, or a bid.
// Bids are a combination of a number of tricks (level + 6) and denomination
// (trump suit or no-trumps).
// The calls are represented in sequence: Pass, Dbl, RDbl, 1C, 1D, 1H, 1S, etc.
enum Calls { kPass = 0, kDouble = 1, kRedouble = 2 };
inline constexpr int kFirstBid = kRedouble + 1;
int Bid(int level, Denomination denomination) {
return (level - 1) * kNumDenominations + denomination + kFirstBid;
}
int BidLevel(int bid) { return 1 + (bid - kNumOtherCalls) / kNumDenominations; }
Denomination BidSuit(int bid) {
return Denomination((bid - kNumOtherCalls) % kNumDenominations);
}
// Cards are represented as rank * kNumSuits + suit.
Suit CardSuit(int card) { return Suit(card % kNumSuits); }
int CardRank(int card) { return card / kNumSuits; }
int Card(Suit suit, int rank) {
return rank * kNumSuits + static_cast<int>(suit);
}
constexpr char kRankChar[] = "23456789TJQKA";
constexpr char kSuitChar[] = "CDHS";
// Ours, Left hand opponent, Partner, Right hand opponent
constexpr std::array<absl::string_view, kNumPlayers> kRelativePlayer{
"Us", "LH", "Pd", "RH"};
std::string CardString(int card) {
return {kSuitChar[static_cast<int>(CardSuit(card))],
kRankChar[CardRank(card)]};
}
std::string BidString(int bid) {
if (bid == kPass) return "Pass";
if (bid == kDouble) return "Dbl";
if (bid == kRedouble) return "RDbl";
constexpr char kDenominationChar[] = "CDHSN";
constexpr char kLevelChar[] = "-1234567";
return {kLevelChar[BidLevel(bid)], kDenominationChar[BidSuit(bid)]};
}
// There are two partnerships: players 0 and 2 versus players 1 and 3.
// We call 0 and 2 partnership 0, and 1 and 3 partnership 1.
int Partnership(Player player) { return player & 1; }
} // namespace
BridgeGame::BridgeGame(const GameParameters& params)
: Game(kGameType, params) {}
BridgeState::BridgeState(std::shared_ptr<const Game> game,
bool use_double_dummy_result,
bool is_dealer_vulnerable,
bool is_non_dealer_vulnerable)
: State(game),
use_double_dummy_result_(use_double_dummy_result),
is_vulnerable_{is_dealer_vulnerable, is_non_dealer_vulnerable} {}
std::string BridgeState::ActionToString(Player player, Action action) const {
return (action < kBiddingActionBase) ? CardString(action)
: BidString(action - kBiddingActionBase);
}
std::string BridgeState::ToString() const {
std::string rv =
absl::StrCat("Vul: ",
is_vulnerable_[0] ? (is_vulnerable_[1] ? "All" : "N/S")
: (is_vulnerable_[1] ? "E/W" : "None"),
"\n");
std::string cards[kNumPlayers][kNumSuits];
for (int suit = 0; suit < kNumSuits; ++suit) {
for (int player = 0; player < kNumPlayers; ++player) {
cards[player][suit].push_back(kSuitChar[suit]);
cards[player][suit].push_back(' ');
}
for (int rank = kNumCardsPerSuit - 1; rank >= 0; --rank) {
const auto player = holder_[Card(Suit(suit), rank)];
if (player.has_value()) cards[*player][suit].push_back(kRankChar[rank]);
}
}
// Report the original deal in the terminal state, so that we can easily
// follow the play.
if (phase_ == Phase::kGameOver && !use_double_dummy_result_) {
std::array<Player, kNumCards> deal{};
for (int i = 0; i < kNumCards; ++i) deal[history_[i]] = (i % kNumPlayers);
for (int suit = 0; suit < kNumSuits; ++suit) {
for (int rank = kNumCardsPerSuit - 1; rank >= 0; --rank) {
const auto player = deal[Card(Suit(suit), rank)];
cards[player][suit].push_back(kRankChar[rank]);
}
}
}
// Format the hands
for (int suit = 0; suit < kNumSuits; ++suit) {
for (int player = 0; player < kNumPlayers; ++player) {
if (cards[player][suit].empty()) cards[player][suit] = "none";
}
}
constexpr int kColumnWidth = 8;
std::string padding(kColumnWidth, ' ');
for (int suit = kNumSuits - 1; suit >= 0; --suit)
absl::StrAppend(&rv, padding, cards[kNorth][suit], "\n");
for (int suit = kNumSuits - 1; suit >= 0; --suit)
absl::StrAppend(&rv, absl::StrFormat("%-8s", cards[kWest][suit]), padding,
cards[kEast][suit], "\n");
for (int suit = kNumSuits - 1; suit >= 0; --suit)
absl::StrAppend(&rv, padding, cards[kSouth][suit], "\n");
if (history_.size() > kNumCards) {
absl::StrAppend(&rv, "\nWest North East South\n ");
for (int i = kNumCards; i < history_.size() - num_cards_played_; ++i) {
if (i % kNumPlayers == 3) rv.push_back('\n');
absl::StrAppend(
&rv,
absl::StrFormat("%-6s", BidString(history_[i] - kBiddingActionBase)));
}
}
if (num_cards_played_ > 0) {
absl::StrAppend(&rv, "\n\nN E S W N E S");
Trick trick{kInvalidPlayer, kNoTrump, 0};
Player player = (1 + contract_.declarer) % kNumPlayers;
for (int i = 0; i < num_cards_played_; ++i) {
if (i % kNumPlayers == 0) {
if (i > 0) player = trick.Winner();
absl::StrAppend(&rv, "\n", std::string(3 * player, ' '));
} else {
player = (1 + player) % kNumPlayers;
}
const int card = history_[history_.size() - num_cards_played_ + i];
if (i % kNumPlayers == 0) {
trick = Trick(player, contract_.trumps, card);
} else {
trick.Play(player, card);
}
absl::StrAppend(&rv, CardString(card), " ");
}
absl::StrAppend(&rv, "\n\nDeclarer tricks: ", num_declarer_tricks_);
}
return rv;
}
std::string BridgeState::ObservationString(Player player) const {
// We construct the ObservationString from the ObservationTensor to give
// some indication that the tensor representation is correct & complete.
std::vector<double> tensor(game_->ObservationTensorSize());
ObservationTensor(player, &tensor);
std::string rv;
if (tensor[0] || tensor[1]) {
if (tensor[1]) rv = "Lead ";
auto ptr = tensor.begin() + kNumObservationTypes;
absl::StrAppend(
&rv,
"V:", ptr[1] ? (ptr[3] ? "Both" : "We ") : (ptr[3] ? "They" : "None"),
" ");
ptr += kNumPartnerships * kNumVulnerabilities;
for (int pl = 0; pl < kNumPlayers; ++pl) {
absl::StrAppend(&rv, "[", kRelativePlayer[pl]);
if (ptr[pl]) absl::StrAppend(&rv, " Pass");
for (int bid = 0; bid < kNumBids; ++bid) {
if (ptr[pl + (3 * bid + 1) * kNumPlayers])
absl::StrAppend(&rv, " ", BidString(bid + kFirstBid));
if (ptr[pl + (3 * bid + 2) * kNumPlayers])
absl::StrAppend(&rv, " Dbl(", BidString(bid + kFirstBid), ")");
if (ptr[pl + (3 * bid + 3) * kNumPlayers])
absl::StrAppend(&rv, " RDbl(", BidString(bid + kFirstBid), ")");
}
absl::StrAppend(&rv, "] ");
}
ptr += kNumPlayers * (1 + 3 * kNumBids);
for (int suit = kNumSuits - 1; suit >= 0; --suit) {
if (suit != kNumSuits - 1) rv.push_back('.');
for (int rank = kNumCardsPerSuit - 1; rank >= 0; --rank) {
auto c = Card(Suit(suit), rank);
if (ptr[c]) rv.push_back(kRankChar[rank]);
}
}
} else if (tensor[2]) {
auto ptr = tensor.begin() + kNumObservationTypes;
for (int pl = 0; pl < kNumPlayers; ++pl) {
if (ptr[pl]) absl::StrAppend(&rv, "Decl:", kRelativePlayer[pl], " ");
}
ptr += kNumPlayers;
for (int suit = kNumSuits - 1; suit >= 0; --suit) {
if (suit != kNumSuits - 1) rv.push_back('.');
for (int rank = kNumCardsPerSuit - 1; rank >= 0; --rank) {
auto c = Card(Suit(suit), rank);
if (ptr[c]) rv.push_back(kRankChar[rank]);
}
}
ptr += kNumCards;
absl::StrAppend(&rv, " Table:");
for (int suit = kNumSuits - 1; suit >= 0; --suit) {
if (suit != kNumSuits - 1) rv.push_back('.');
for (int rank = kNumCardsPerSuit - 1; rank >= 0; --rank) {
auto c = Card(Suit(suit), rank);
if (ptr[c]) rv.push_back(kRankChar[rank]);
}
}
ptr += kNumCards;
absl::StrAppend(&rv, " prev[");
for (int pl = 0; pl < kNumPlayers; ++pl) {
for (int c = 0; c < kNumCards; ++c) {
if (ptr[c]) {
if (pl != 0) rv.push_back(' ');
absl::StrAppend(&rv, kRelativePlayer[pl], ":", CardString(c));
}
}
ptr += kNumCards;
}
absl::StrAppend(&rv, "] curr[");
for (int pl = 0; pl < kNumPlayers; ++pl) {
for (int c = 0; c < kNumCards; ++c) {
if (ptr[c]) {
if (rv.back() != '[') rv.push_back(' ');
absl::StrAppend(&rv, kRelativePlayer[pl], ":", CardString(c));
}
}
ptr += kNumCards;
}
absl::StrAppend(&rv, "]");
for (int i = 0; i < kNumTricks; ++i) {
if (ptr[i]) absl::StrAppend(&rv, " Decl:", i);
}
ptr += kNumTricks;
for (int i = 0; i < kNumTricks; ++i) {
if (ptr[i]) absl::StrAppend(&rv, " Def:", i);
}
} else {
rv = "No Observation";
}
return rv;
}
void BridgeState::ObservationTensor(Player player,
std::vector<double>* values) const {
std::fill(values->begin(), values->end(), 0.0);
values->resize(game_->ObservationTensorSize());
if (phase_ == Phase::kGameOver || phase_ == Phase::kDeal) return;
int partnership = Partnership(player);
auto ptr = values->begin();
if (num_cards_played_ > 0) {
// Observation for play phase
if (phase_ == Phase::kPlay) ptr[2] = 1;
ptr += kNumObservationTypes;
// Identity of the declarer.
ptr[(contract_.declarer + kNumPlayers - player) % kNumPlayers] = 1;
ptr += kNumPlayers;
// Our remaining cards.
for (int i = 0; i < kNumCards; ++i)
if (holder_[i] == player) ptr[i] = 1;
ptr += kNumCards;
// Dummy's remaining cards.
const int dummy = contract_.declarer ^ 2;
for (int i = 0; i < kNumCards; ++i)
if (holder_[i] == dummy) ptr[i] = 1;
ptr += kNumCards;
// Indexing into history for recent tricks.
int current_trick = num_cards_played_ / kNumPlayers;
int this_trick_cards_played = num_cards_played_ % kNumPlayers;
int this_trick_start = history_.size() - this_trick_cards_played;
// Previous trick.
if (current_trick > 0) {
int leader = tricks_[current_trick - 1].Leader();
for (int i = 0; i < kNumPlayers; ++i) {
int card = history_[this_trick_start - kNumPlayers + i];
int relative_player = (i + leader + kNumPlayers - player) % kNumPlayers;
ptr[relative_player * kNumCards + card] = 1;
}
}
ptr += kNumPlayers * kNumCards;
// Current trick
int leader = tricks_[current_trick].Leader();
for (int i = 0; i < this_trick_cards_played; ++i) {
int card = history_[this_trick_start + i];
int relative_player = (i + leader + kNumPlayers - player) % kNumPlayers;
ptr[relative_player * kNumCards + card] = 1;
}
ptr += kNumPlayers * kNumCards;
// Number of tricks taken by each side.
ptr[num_declarer_tricks_] = 1;
ptr += kNumTricks;
ptr[num_cards_played_ / 4 - num_declarer_tricks_] = 1;
ptr += kNumTricks;
SPIEL_CHECK_EQ(std::distance(values->begin(), ptr),
kPlayTensorSize + kNumObservationTypes);
SPIEL_CHECK_LE(std::distance(values->begin(), ptr), values->size());
} else {
// Observation for auction or opening lead.
ptr[phase_ == Phase::kPlay ? 1 : 0] = 1;
ptr += kNumObservationTypes;
ptr[is_vulnerable_[partnership]] = 1;
ptr += kNumVulnerabilities;
ptr[is_vulnerable_[1 - partnership]] = 1;
ptr += kNumVulnerabilities;
int last_bid = 0;
for (int i = kNumCards; i < history_.size(); ++i) {
int this_call = history_[i] - kBiddingActionBase;
int relative_bidder = (i + kNumPlayers - player) % kNumPlayers;
if (last_bid == 0 && this_call == kPass) ptr[relative_bidder] = 1;
if (this_call == kDouble) {
ptr[kNumPlayers + (last_bid - kFirstBid) * kNumPlayers * 3 +
kNumPlayers + relative_bidder] = 1;
} else if (this_call == kRedouble) {
ptr[kNumPlayers + (last_bid - kFirstBid) * kNumPlayers * 3 +
kNumPlayers * 2 + relative_bidder] = 1;
} else if (this_call != kPass) {
last_bid = this_call;
ptr[kNumPlayers + (last_bid - kFirstBid) * kNumPlayers * 3 +
relative_bidder] = 1;
}
}
ptr += kNumPlayers * (1 + 3 * kNumBids);
for (int i = 0; i < kNumCards; ++i)
if (holder_[i] == player) ptr[i] = 1;
ptr += kNumCards;
SPIEL_CHECK_EQ(std::distance(values->begin(), ptr),
kAuctionTensorSize + kNumObservationTypes);
SPIEL_CHECK_LE(std::distance(values->begin(), ptr), values->size());
}
}
void BridgeState::ComputeDoubleDummyTricks() {
ddTableDeal dd_table_deal{};
for (int suit = 0; suit < kNumSuits; ++suit) {
for (int rank = 0; rank < kNumCardsPerSuit; ++rank) {
const int player = holder_[Card(Suit(suit), rank)].value();
dd_table_deal.cards[player][suit] += 1 << (2 + rank);
}
}
DDS_EXTERNAL(SetMaxThreads)(0);
const int return_code =
DDS_EXTERNAL(CalcDDtable)(dd_table_deal, &double_dummy_results_);
if (return_code != RETURN_NO_FAULT) {
char error_message[80];
DDS_EXTERNAL(ErrorMessage)(return_code, error_message);
SpielFatalError(absl::StrCat("double_dummy_solver:", error_message));
}
}
std::vector<Action> BridgeState::LegalActions() const {
switch (phase_) {
case Phase::kDeal:
return DealLegalActions();
case Phase::kAuction:
return BiddingLegalActions();
case Phase::kPlay:
return PlayLegalActions();
default:
return {};
}
}
std::vector<Action> BridgeState::DealLegalActions() const {
std::vector<Action> legal_actions;
legal_actions.reserve(kNumCards - history_.size());
for (int i = 0; i < kNumCards; ++i) {
if (!holder_[i].has_value()) legal_actions.push_back(i);
}
return legal_actions;
}
std::vector<Action> BridgeState::BiddingLegalActions() const {
std::vector<Action> legal_actions;
legal_actions.reserve(kNumCalls);
legal_actions.push_back(kBiddingActionBase + kPass);
if (contract_.level > 0 &&
Partnership(contract_.declarer) != Partnership(current_player_) &&
contract_.double_status == kUndoubled) {
legal_actions.push_back(kBiddingActionBase + kDouble);
}
if (contract_.level > 0 &&
Partnership(contract_.declarer) == Partnership(current_player_) &&
contract_.double_status == kDoubled) {
legal_actions.push_back(kBiddingActionBase + kRedouble);
}
for (int bid = Bid(contract_.level, contract_.trumps) + 1; bid < kNumCalls;
++bid) {
legal_actions.push_back(kBiddingActionBase + bid);
}
return legal_actions;
}
std::vector<Action> BridgeState::PlayLegalActions() const {
std::vector<Action> legal_actions;
legal_actions.reserve(kNumCardsPerHand - num_cards_played_ / kNumPlayers);
// Check if we can follow suit.
if (num_cards_played_ % kNumPlayers != 0) {
auto suit = CurrentTrick().LedSuit();
for (int rank = 0; rank < kNumCardsPerSuit; ++rank) {
if (holder_[Card(suit, rank)] == current_player_) {
legal_actions.push_back(Card(suit, rank));
}
}
}
if (!legal_actions.empty()) return legal_actions;
// Otherwise, we can play any of our cards.
for (int card = 0; card < kNumCards; ++card) {
if (holder_[card] == current_player_) legal_actions.push_back(card);
}
return legal_actions;
}
std::vector<std::pair<Action, double>> BridgeState::ChanceOutcomes() const {
std::vector<std::pair<Action, double>> outcomes;
int num_cards_remaining = kNumCards - history_.size();
outcomes.reserve(num_cards_remaining);
const double p = 1.0 / static_cast<double>(num_cards_remaining);
for (int card = 0; card < kNumCards; ++card) {
if (!holder_[card].has_value()) outcomes.emplace_back(card, p);
}
return outcomes;
}
void BridgeState::DoApplyAction(Action action) {
switch (phase_) {
case Phase::kDeal:
return ApplyDealAction(action);
case Phase::kAuction:
return ApplyBiddingAction(action - kBiddingActionBase);
case Phase::kPlay:
return ApplyPlayAction(action);
case Phase::kGameOver:
SpielFatalError("Cannot act in terminal states");
}
}
void BridgeState::ApplyDealAction(int card) {
holder_[card] = (history_.size() % kNumPlayers);
if (history_.size() == kNumCards - 1) {
ComputeDoubleDummyTricks();
phase_ = Phase::kAuction;
current_player_ = kFirstPlayer;
}
}
void BridgeState::ApplyBiddingAction(int call) {
// Track the number of consecutive passes since the last bid (if any).
if (call == kPass) {
++num_passes_;
} else {
num_passes_ = 0;
}
if (call == kDouble) {
SPIEL_CHECK_EQ(contract_.double_status, kUndoubled);
contract_.double_status = kDoubled;
} else if (call == kRedouble) {
SPIEL_CHECK_EQ(contract_.double_status, kDoubled);
contract_.double_status = kRedoubled;
} else if (call == kPass) {
if (num_passes_ == 4) {
// Four consecutive passes can only happen if no-one makes a bid.
// The hand is then over, and each side scores zero points.
phase_ = Phase::kGameOver;
} else if (num_passes_ == 3 && contract_.level > 0) {
// After there has been a bid, three consecutive passes end the auction.
if (use_double_dummy_result_) {
phase_ = Phase::kGameOver;
num_declarer_tricks_ =
double_dummy_results_
.resTable[contract_.trumps][contract_.declarer];
ScoreUp();
} else {
phase_ = Phase::kPlay;
current_player_ = (contract_.declarer + 1) % kNumPlayers;
return;
}
}
} else {
// A bid was made.
auto partnership = Partnership(current_player_);
auto suit = BidSuit(call);
if (!first_bidder_[partnership][suit].has_value())
first_bidder_[partnership][suit] = current_player_;
contract_.level = BidLevel(call);
contract_.trumps = suit;
contract_.declarer = first_bidder_[partnership][suit].value();
contract_.double_status = kUndoubled;
}
current_player_ = (current_player_ + 1) % kNumPlayers;
}
void BridgeState::ApplyPlayAction(int card) {
SPIEL_CHECK_TRUE(holder_[card] == current_player_);
holder_[card] = std::nullopt;
if (num_cards_played_ % kNumPlayers == 0) {
CurrentTrick() = Trick(current_player_, contract_.trumps, card);
} else {
CurrentTrick().Play(current_player_, card);
}
const Player winner = CurrentTrick().Winner();
++num_cards_played_;
if (num_cards_played_ % kNumPlayers == 0) {
current_player_ = winner;
if (Partnership(winner) == Partnership(contract_.declarer))
++num_declarer_tricks_;
} else {
current_player_ = (current_player_ + 1) % kNumPlayers;
}
if (num_cards_played_ == kNumCards) {
phase_ = Phase::kGameOver;
ScoreUp();
}
}
Player BridgeState::CurrentPlayer() const {
if (phase_ == Phase::kDeal) {
return kChancePlayerId;
} else if (phase_ == Phase::kPlay &&
Partnership(current_player_) == Partnership(contract_.declarer)) {
// Declarer chooses cards for both players.
return contract_.declarer;
} else {
return current_player_;
}
}
void BridgeState::ScoreUp() {
int declarer_score = Score(contract_, num_declarer_tricks_,
is_vulnerable_[Partnership(contract_.declarer)]);
for (int pl = 0; pl < kNumPlayers; ++pl) {
returns_[pl] = Partnership(pl) == Partnership(contract_.declarer)
? declarer_score
: -declarer_score;
}
}
Trick::Trick(Player leader, Denomination trumps, int card)
: trumps_(trumps),
led_suit_(CardSuit(card)),
winning_suit_(CardSuit(card)),
winning_rank_(CardRank(card)),
leader_(leader),
winning_player_(leader) {}
void Trick::Play(Player player, int card) {
if (CardSuit(card) == winning_suit_) {
if (CardRank(card) > winning_rank_) {
winning_rank_ = CardRank(card);
winning_player_ = player;
}
} else if (CardSuit(card) == Suit(trumps_)) {
winning_suit_ = Suit(trumps_);
winning_rank_ = CardRank(card);
winning_player_ = player;
}
}
} // namespace bridge
} // namespace open_spiel
| 37.501603 | 80 | 0.623392 | [
"vector"
] |
cb4681d240fe621097331a2d5cceddc3fadbe713 | 6,393 | cpp | C++ | ref.neo/ui/RenderWindow.cpp | Grimace1975/bclcontrib-scriptsharp | 8c1b05024404e9115be96a328c79a8555eca2e4a | [
"MIT"
] | null | null | null | ref.neo/ui/RenderWindow.cpp | Grimace1975/bclcontrib-scriptsharp | 8c1b05024404e9115be96a328c79a8555eca2e4a | [
"MIT"
] | null | null | null | ref.neo/ui/RenderWindow.cpp | Grimace1975/bclcontrib-scriptsharp | 8c1b05024404e9115be96a328c79a8555eca2e4a | [
"MIT"
] | null | null | null | /*
===========================================================================
Doom 3 GPL Source Code
Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 GPL Source Code (?Doom 3 Source Code?).
Doom 3 Source Code 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.
Doom 3 Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#include "../idlib/precompiled.h"
#pragma hdrstop
#include "DeviceContext.h"
#include "Window.h"
#include "UserInterfaceLocal.h"
#include "RenderWindow.h"
idRenderWindow::idRenderWindow(idDeviceContext *d, idUserInterfaceLocal *g) : idWindow(d, g) {
dc = d;
gui = g;
CommonInit();
}
idRenderWindow::idRenderWindow(idUserInterfaceLocal *g) : idWindow(g) {
gui = g;
CommonInit();
}
idRenderWindow::~idRenderWindow() {
renderSystem->FreeRenderWorld( world );
}
void idRenderWindow::CommonInit() {
world = renderSystem->AllocRenderWorld();
needsRender = true;
lightOrigin = idVec4(-128.0f, 0.0f, 0.0f, 1.0f);
lightColor = idVec4(1.0f, 1.0f, 1.0f, 1.0f);
modelOrigin.Zero();
viewOffset = idVec4(-128.0f, 0.0f, 0.0f, 1.0f);
modelAnim = NULL;
animLength = 0;
animEndTime = -1;
modelDef = -1;
updateAnimation = true;
}
void idRenderWindow::BuildAnimation(int time) {
if (!updateAnimation) {
return;
}
if (animName.Length() && animClass.Length()) {
worldEntity.numJoints = worldEntity.hModel->NumJoints();
worldEntity.joints = ( idJointMat * )Mem_Alloc16( worldEntity.numJoints * sizeof( *worldEntity.joints ) );
modelAnim = gameEdit->ANIM_GetAnimFromEntityDef(animClass, animName);
if (modelAnim) {
animLength = gameEdit->ANIM_GetLength(modelAnim);
animEndTime = time + animLength;
}
}
updateAnimation = false;
}
void idRenderWindow::PreRender() {
if (needsRender) {
world->InitFromMap( NULL );
idDict spawnArgs;
spawnArgs.Set("classname", "light");
spawnArgs.Set("name", "light_1");
spawnArgs.Set("origin", lightOrigin.ToVec3().ToString());
spawnArgs.Set("_color", lightColor.ToVec3().ToString());
gameEdit->ParseSpawnArgsToRenderLight( &spawnArgs, &rLight );
lightDef = world->AddLightDef( &rLight );
if ( !modelName[0] ) {
common->Warning( "Window '%s' in gui '%s': no model set", GetName(), GetGui()->GetSourceFile() );
}
memset( &worldEntity, 0, sizeof( worldEntity ) );
spawnArgs.Clear();
spawnArgs.Set("classname", "func_static");
spawnArgs.Set("model", modelName);
spawnArgs.Set("origin", modelOrigin.c_str());
gameEdit->ParseSpawnArgsToRenderEntity( &spawnArgs, &worldEntity );
if ( worldEntity.hModel ) {
idVec3 v = modelRotate.ToVec3();
worldEntity.axis = v.ToMat3();
worldEntity.shaderParms[0] = 1;
worldEntity.shaderParms[1] = 1;
worldEntity.shaderParms[2] = 1;
worldEntity.shaderParms[3] = 1;
modelDef = world->AddEntityDef( &worldEntity );
}
needsRender = false;
}
}
void idRenderWindow::Render( int time ) {
rLight.origin = lightOrigin.ToVec3();
rLight.shaderParms[SHADERPARM_RED] = lightColor.x();
rLight.shaderParms[SHADERPARM_GREEN] = lightColor.y();
rLight.shaderParms[SHADERPARM_BLUE] = lightColor.z();
world->UpdateLightDef(lightDef, &rLight);
if ( worldEntity.hModel ) {
if (updateAnimation) {
BuildAnimation(time);
}
if (modelAnim) {
if (time > animEndTime) {
animEndTime = time + animLength;
}
gameEdit->ANIM_CreateAnimFrame(worldEntity.hModel, modelAnim, worldEntity.numJoints, worldEntity.joints, animLength - (animEndTime - time), vec3_origin, false );
}
worldEntity.axis = idAngles(modelRotate.x(), modelRotate.y(), modelRotate.z()).ToMat3();
world->UpdateEntityDef(modelDef, &worldEntity);
}
}
void idRenderWindow::Draw(int time, float x, float y) {
PreRender();
Render(time);
memset( &refdef, 0, sizeof( refdef ) );
refdef.vieworg = viewOffset.ToVec3();;
//refdef.vieworg.Set(-128, 0, 0);
refdef.viewaxis.Identity();
refdef.shaderParms[0] = 1;
refdef.shaderParms[1] = 1;
refdef.shaderParms[2] = 1;
refdef.shaderParms[3] = 1;
refdef.x = drawRect.x;
refdef.y = drawRect.y;
refdef.width = drawRect.w;
refdef.height = drawRect.h;
refdef.fov_x = 90;
refdef.fov_y = 2 * atan((float)drawRect.h / drawRect.w) * idMath::M_RAD2DEG;
refdef.time = time;
world->RenderScene(&refdef);
}
void idRenderWindow::PostParse() {
idWindow::PostParse();
}
//
//
idWinVar *idRenderWindow::GetWinVarByName(const char *_name, bool fixup, drawWin_t** owner ) {
//
if (idStr::Icmp(_name, "model") == 0) {
return &modelName;
}
if (idStr::Icmp(_name, "anim") == 0) {
return &animName;
}
if (idStr::Icmp(_name, "lightOrigin") == 0) {
return &lightOrigin;
}
if (idStr::Icmp(_name, "lightColor") == 0) {
return &lightColor;
}
if (idStr::Icmp(_name, "modelOrigin") == 0) {
return &modelOrigin;
}
if (idStr::Icmp(_name, "modelRotate") == 0) {
return &modelRotate;
}
if (idStr::Icmp(_name, "viewOffset") == 0) {
return &viewOffset;
}
if (idStr::Icmp(_name, "needsRender") == 0) {
return &needsRender;
}
//
//
return idWindow::GetWinVarByName(_name, fixup, owner);
//
}
bool idRenderWindow::ParseInternalVar(const char *_name, idParser *src) {
if (idStr::Icmp(_name, "animClass") == 0) {
ParseString(src, animClass);
return true;
}
return idWindow::ParseInternalVar(_name, src);
}
| 30.014085 | 342 | 0.690912 | [
"render",
"model"
] |
cb46ba1d1290966038cc2cff4caebc13b2bce1f0 | 17,214 | cpp | C++ | OgreMain/src/OgreRenderTarget.cpp | jondo2010/ogre | c1e836d453b2bca0d4e2eb6a32424fe967092b52 | [
"MIT"
] | null | null | null | OgreMain/src/OgreRenderTarget.cpp | jondo2010/ogre | c1e836d453b2bca0d4e2eb6a32424fe967092b52 | [
"MIT"
] | null | null | null | OgreMain/src/OgreRenderTarget.cpp | jondo2010/ogre | c1e836d453b2bca0d4e2eb6a32424fe967092b52 | [
"MIT"
] | null | null | null | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
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 "OgreStableHeaders.h"
#include "OgreRenderTarget.h"
#include "OgreViewport.h"
#include "OgreException.h"
#include "OgreLogManager.h"
#include "OgreRenderTargetListener.h"
#include "OgrePixelBox.h"
#include "OgreRoot.h"
#include "OgreDepthBuffer.h"
#include "OgreProfiler.h"
#include "OgreTimer.h"
#include <iomanip>
namespace Ogre {
RenderTarget::RenderTarget()
: mPriority(OGRE_DEFAULT_RT_GROUP)
, mFormat( PF_UNKNOWN )
, mDepthBufferPoolId( DepthBuffer::POOL_DEFAULT )
, mPreferDepthTexture( false )
, mDesiredDepthBufferFormat( DepthBuffer::DefaultDepthBufferFormat )
, mDepthBuffer(0)
, mActive(true)
, mHwGamma(false)
, mFSAA(0)
, mFsaaResolveDirty(false)
, mMipmapsDirty(false)
#if OGRE_NO_QUAD_BUFFER_STEREO == 0
, mStereoEnabled(true)
#else
, mStereoEnabled(false)
#endif
{
resetStatistics();
}
RenderTarget::~RenderTarget()
{
// Delete viewports
for (ViewportList::iterator i = mViewportList.begin();
i != mViewportList.end(); ++i)
{
fireViewportRemoved( *i );
OGRE_DELETE *i;
}
//DepthBuffer keeps track of us, avoid a dangling pointer
detachDepthBuffer();
// Write closing message
LogManager::getSingleton().stream(LML_TRIVIAL) << "Render Target '" << mName << "' ";
}
const String& RenderTarget::getName(void) const
{
return mName;
}
void RenderTarget::getMetrics(unsigned int& width, unsigned int& height, unsigned int& colourDepth)
{
width = mWidth;
height = mHeight;
colourDepth = PixelUtil::getNumElemBits( mFormat );
}
unsigned int RenderTarget::getWidth(void) const
{
return mWidth;
}
unsigned int RenderTarget::getHeight(void) const
{
return mHeight;
}
PixelFormat RenderTarget::getFormat(void) const
{
return mFormat;
}
//-----------------------------------------------------------------------
void RenderTarget::getFormatsForPso( PixelFormat outFormats[OGRE_MAX_MULTIPLE_RENDER_TARGETS],
bool outHwGamma[OGRE_MAX_MULTIPLE_RENDER_TARGETS] ) const
{
outFormats[0] = mFormat;
outHwGamma[0] = mHwGamma;
for( size_t i=1; i<OGRE_MAX_MULTIPLE_RENDER_TARGETS; ++i )
{
outFormats[i] = PF_NULL;
outHwGamma[i] = false;
}
}
//-----------------------------------------------------------------------
void RenderTarget::setDepthBufferPool( uint16 poolId )
{
if( mDepthBufferPoolId != poolId )
{
mDepthBufferPoolId = poolId;
detachDepthBuffer();
}
}
//-----------------------------------------------------------------------
uint16 RenderTarget::getDepthBufferPool() const
{
return mDepthBufferPoolId;
}
//-----------------------------------------------------------------------
void RenderTarget::setPreferDepthTexture( bool preferDepthTexture )
{
if( mPreferDepthTexture != preferDepthTexture )
{
mPreferDepthTexture = preferDepthTexture;
detachDepthBuffer();
}
}
//-----------------------------------------------------------------------
bool RenderTarget::prefersDepthTexture() const
{
return mPreferDepthTexture;
}
//-----------------------------------------------------------------------
void RenderTarget::setDesiredDepthBufferFormat( PixelFormat desiredDepthBufferFormat )
{
assert( desiredDepthBufferFormat == PF_D24_UNORM_S8_UINT ||
desiredDepthBufferFormat == PF_D24_UNORM_X8 ||
desiredDepthBufferFormat == PF_D16_UNORM ||
desiredDepthBufferFormat == PF_D32_FLOAT ||
desiredDepthBufferFormat == PF_D32_FLOAT_X24_S8_UINT ||
desiredDepthBufferFormat == PF_D32_FLOAT_X24_X8 );
if( mDesiredDepthBufferFormat != desiredDepthBufferFormat )
{
mDesiredDepthBufferFormat = desiredDepthBufferFormat;
detachDepthBuffer();
}
}
//-----------------------------------------------------------------------
PixelFormat RenderTarget::getDesiredDepthBufferFormat() const
{
return mDesiredDepthBufferFormat;
}
//-----------------------------------------------------------------------
DepthBuffer* RenderTarget::getDepthBuffer() const
{
return mDepthBuffer;
}
//-----------------------------------------------------------------------
bool RenderTarget::attachDepthBuffer( DepthBuffer *depthBuffer, bool exactFormatMatch )
{
bool retVal = false;
if( (retVal = depthBuffer->isCompatible( this, exactFormatMatch )) )
{
detachDepthBuffer();
mDepthBuffer = depthBuffer;
mDepthBuffer->_notifyRenderTargetAttached( this );
}
return retVal;
}
//-----------------------------------------------------------------------
void RenderTarget::detachDepthBuffer()
{
if( mDepthBuffer )
{
mDepthBuffer->_notifyRenderTargetDetached( this );
mDepthBuffer = 0;
}
}
//-----------------------------------------------------------------------
void RenderTarget::_detachDepthBuffer()
{
mDepthBuffer = 0;
}
void RenderTarget::_beginUpdate()
{
// notify listeners (pre)
firePreUpdate();
mStats.triangleCount = 0;
mStats.batchCount = 0;
OgreProfileBeginGPUEvent("RenderTarget: " + getName());
}
void RenderTarget::_endUpdate()
{
// notify listeners (post)
firePostUpdate();
OgreProfileEndGPUEvent("RenderTarget: " + getName());
}
void RenderTarget::_updateViewportCullPhase01( Viewport* viewport, Camera *camera,
const Camera *lodCamera, uint8 firstRq, uint8 lastRq )
{
assert( viewport->getTarget() == this &&
"RenderTarget::_updateViewportCullPhase the requested viewport is "
"not bound to the rendertarget!" );
fireViewportPreUpdate(viewport);
viewport->_updateCullPhase01( camera, lodCamera, firstRq, lastRq );
}
//-----------------------------------------------------------------------
void RenderTarget::_updateViewportRenderPhase02( Viewport* viewport, Camera *camera,
const Camera *lodCamera, uint8 firstRq,
uint8 lastRq, bool updateStatistics )
{
assert( viewport->getTarget() == this &&
"RenderTarget::_updateViewport the requested viewport is "
"not bound to the rendertarget!" );
viewport->_updateRenderPhase02( camera, lodCamera, firstRq, lastRq );
if(updateStatistics)
{
mStats.triangleCount += camera->_getNumRenderedFaces();
mStats.batchCount += camera->_getNumRenderedBatches();
}
fireViewportPostUpdate(viewport);
}
//-----------------------------------------------------------------------
Viewport* RenderTarget::addViewport( float left, float top, float width, float height )
{
// Add viewport to list
Viewport* vp = OGRE_NEW Viewport( this, left, top, width, height );
mViewportList.push_back( vp );
vp->mGlobalIndex = mViewportList.size() - 1;
fireViewportAdded(vp);
return vp;
}
//-----------------------------------------------------------------------
void RenderTarget::removeViewport( Viewport *vp )
{
if( vp->mGlobalIndex >= mViewportList.size() ||
vp != *(mViewportList.begin() + vp->mGlobalIndex) )
{
OGRE_EXCEPT( Exception::ERR_INTERNAL_ERROR, "Viewport had it's mGlobalIndex out of "
"date!!! (or Viewport wasn't created by this RenderTarget",
"RenderTarget::removeViewport" );
}
ViewportList::iterator itor = mViewportList.begin() + vp->mGlobalIndex;
fireViewportRemoved( vp );
OGRE_DELETE vp;
itor = efficientVectorRemove( mViewportList, itor );
//The Viewport that was at the end got swapped and has now a different index
if( itor != mViewportList.end() )
(*itor)->mGlobalIndex = itor - mViewportList.begin();
}
void RenderTarget::removeAllViewports(void)
{
for (ViewportList::iterator it = mViewportList.begin(); it != mViewportList.end(); ++it)
{
fireViewportRemoved( *it );
OGRE_DELETE *it;
}
mViewportList.clear();
}
const RenderTarget::FrameStats& RenderTarget::getStatistics(void) const
{
return mStats;
}
size_t RenderTarget::getTriangleCount(void) const
{
return mStats.triangleCount;
}
size_t RenderTarget::getBatchCount(void) const
{
return mStats.batchCount;
}
void RenderTarget::resetStatistics(void)
{
mStats.triangleCount = 0;
mStats.batchCount = 0;
}
void RenderTarget::getCustomAttribute(const String& name, void* pData)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Attribute not found. " + name, " RenderTarget::getCustomAttribute");
}
//-----------------------------------------------------------------------
void RenderTarget::addListener(RenderTargetListener* listener)
{
mListeners.push_back(listener);
}
//-----------------------------------------------------------------------
void RenderTarget::removeListener(RenderTargetListener* listener)
{
RenderTargetListenerList::iterator i;
for (i = mListeners.begin(); i != mListeners.end(); ++i)
{
if (*i == listener)
{
mListeners.erase(i);
break;
}
}
}
//-----------------------------------------------------------------------
void RenderTarget::removeAllListeners(void)
{
mListeners.clear();
}
//-----------------------------------------------------------------------
void RenderTarget::firePreUpdate(void)
{
RenderTargetEvent evt;
evt.source = this;
RenderTargetListenerList::iterator i, iend;
i = mListeners.begin();
iend = mListeners.end();
for(; i != iend; ++i)
{
(*i)->preRenderTargetUpdate(evt);
}
}
//-----------------------------------------------------------------------
void RenderTarget::firePostUpdate(void)
{
RenderTargetEvent evt;
evt.source = this;
RenderTargetListenerList::iterator i, iend;
i = mListeners.begin();
iend = mListeners.end();
for(; i != iend; ++i)
{
(*i)->postRenderTargetUpdate(evt);
}
}
//-----------------------------------------------------------------------
unsigned short RenderTarget::getNumViewports(void) const
{
return (unsigned short)mViewportList.size();
}
//-----------------------------------------------------------------------
Viewport* RenderTarget::getViewport(unsigned short index)
{
return mViewportList[index];
}
//-----------------------------------------------------------------------
bool RenderTarget::isActive() const
{
return mActive;
}
//-----------------------------------------------------------------------
void RenderTarget::setActive( bool state )
{
mActive = state;
}
//-----------------------------------------------------------------------
void RenderTarget::fireViewportPreUpdate(Viewport* vp)
{
RenderTargetViewportEvent evt;
evt.source = vp;
RenderTargetListenerList::iterator i, iend;
i = mListeners.begin();
iend = mListeners.end();
for(; i != iend; ++i)
{
(*i)->preViewportUpdate(evt);
}
}
//-----------------------------------------------------------------------
void RenderTarget::fireViewportPostUpdate(Viewport* vp)
{
RenderTargetViewportEvent evt;
evt.source = vp;
RenderTargetListenerList::iterator i, iend;
i = mListeners.begin();
iend = mListeners.end();
for(; i != iend; ++i)
{
(*i)->postViewportUpdate(evt);
}
}
//-----------------------------------------------------------------------
void RenderTarget::fireViewportAdded(Viewport* vp)
{
RenderTargetViewportEvent evt;
evt.source = vp;
RenderTargetListenerList::iterator i, iend;
i = mListeners.begin();
iend = mListeners.end();
for(; i != iend; ++i)
{
(*i)->viewportAdded(evt);
}
}
//-----------------------------------------------------------------------
void RenderTarget::fireViewportRemoved(Viewport* vp)
{
RenderTargetViewportEvent evt;
evt.source = vp;
// Make a temp copy of the listeners
// some will want to remove themselves as listeners when they get this
RenderTargetListenerList tempList = mListeners;
RenderTargetListenerList::iterator i, iend;
i = tempList.begin();
iend = tempList.end();
for(; i != iend; ++i)
{
(*i)->viewportRemoved(evt);
}
}
//-----------------------------------------------------------------------
String RenderTarget::writeContentsToTimestampedFile(const String& filenamePrefix, const String& filenameSuffix)
{
struct tm *pTime;
time_t ctTime; time(&ctTime);
pTime = localtime( &ctTime );
Ogre::StringStream oss;
oss << std::setw(2) << std::setfill('0') << (pTime->tm_mon + 1)
<< std::setw(2) << std::setfill('0') << pTime->tm_mday
<< std::setw(2) << std::setfill('0') << (pTime->tm_year + 1900)
<< "_" << std::setw(2) << std::setfill('0') << pTime->tm_hour
<< std::setw(2) << std::setfill('0') << pTime->tm_min
<< std::setw(2) << std::setfill('0') << pTime->tm_sec
<< std::setw(3) << std::setfill('0') <<
(Root::getSingleton().getTimer()->getMilliseconds() % 1000);
String filename = filenamePrefix + oss.str() + filenameSuffix;
writeContentsToFile(filename);
return filename;
}
//-----------------------------------------------------------------------
void RenderTarget::writeContentsToFile(const String& filename)
{
PixelFormat pf = suggestPixelFormat();
uchar *data = OGRE_ALLOC_T(uchar, mWidth * mHeight * PixelUtil::getNumElemBytes(pf), MEMCATEGORY_RENDERSYS);
PixelBox pb(mWidth, mHeight, 1, pf, data);
copyContentsToMemory(pb);
Image().loadDynamicImage(data, mWidth, mHeight, 1, pf, false, 1, 0).save(filename);
OGRE_FREE(data, MEMCATEGORY_RENDERSYS);
}
//-----------------------------------------------------------------------
bool RenderTarget::isPrimary(void) const
{
// RenderWindow will override and return true for the primary window
return false;
}
//-----------------------------------------------------------------------
bool RenderTarget::isStereoEnabled(void) const
{
return mStereoEnabled;
}
//-----------------------------------------------------------------------
RenderTarget::Impl *RenderTarget::_getImpl()
{
return 0;
}
}
| 34.019763 | 119 | 0.516033 | [
"render",
"object"
] |
cb4937e0b1f134daa9d6724c2393c037b7386974 | 13,934 | cpp | C++ | src/Game.cpp | digladieux/TP5_SMA | 450153930410982c79dc79c5694885268fd4a04d | [
"Apache-2.0"
] | null | null | null | src/Game.cpp | digladieux/TP5_SMA | 450153930410982c79dc79c5694885268fd4a04d | [
"Apache-2.0"
] | null | null | null | src/Game.cpp | digladieux/TP5_SMA | 450153930410982c79dc79c5694885268fd4a04d | [
"Apache-2.0"
] | null | null | null | /**
* \file Game.cpp
* \author Gladieux Cunha Dimitri & Gonzales Florian
* \brief Fichier d'implementation de la classe Game
* \date 2018-12-03
*/
#include "../header/Game.hpp"
#include "../header/Grid.hpp"
#include "../header/FemaleCharacter.hpp"
#include "../header/TownHall.hpp"
#include "../header/mt19937ar.h"
#include "../header/CollectionPoint.hpp"
#include "../header/Constantes.hpp"
#include "../header/json.hpp"
#include "../header/StrategyJob.hpp"
#include "../header/StrategyLowRessources.hpp"
#include "../header/StrategyClosestCollectionPoint.hpp"
#include "../header/StateWorkingCollectionPoint.hpp"
#include "../header/StateAddingRessources.hpp"
#include "../header/Exception.hpp"
#include "../header/Report.hpp"
#include "math.h"
#include <unistd.h>
#include <limits>
/**
* \brief Redefinission du type nlohmann (son auteur)::json par json
*/
using json = nlohmann::json;
/**
* \fn Game::Game(std::vector<unsigned int> &vector_map, std::vector<unsigned int> &vector_character, unsigned int config_choice, const Date &date, const unsigned int display_choice, const unsigned int strategy_choice)
* \brief Constructeur de la classe Game
* \param &vector_map Vecteur contenant la liste des points de collecte
* \param &vector_character Vecteur contenant la liste des personnages
* \param config_choice Entier definissant le choix de la configuration de la simulation
* \param &date Date de depart de la simulation
* \param display_choice Entier definissant le choix d'affichage de la simulation
* \param strategy_choice Entier definissant le choix de la strategie de chaque personnage
*/
Game::Game(std::vector<unsigned int> &vector_map, std::vector<unsigned int> &vector_character, unsigned int config_choice, const Date &date, const unsigned int display_choice, const unsigned int strategy_choice) : map(new Grid(vector_map, vector_character, strategy_choice)), turn(date), number_of_birth_this_turn(0), number_of_death_this_turn(0), how_to_display(display_choice), strategy(strategy_choice), map_choice(vector_map), character_choice(vector_character)
{
report = new Report *[2]();
report[0] = new Report();
report[1] = new Report();
Constantes::getAllJson();
Constantes::setConfiguration(config_choice);
if (display_choice > 2)
{
throw InvalidDisplayChoice(display_choice);
}
}
/**
* \fn Game::~Game()
* \brief Destructeur de la classe Game
*/
Game::~Game()
{
delete map;
delete report[0];
delete report[1] ;
delete [] report ;
}
/**
* \fn Game::Game(const Game& game) :
* \brief Constructeur de copie de la classe Game
* \param &game Jeu que l'on veut copier
*/
Game::Game(const Game& game) : map(game.map), turn(game.turn), number_of_birth_this_turn(game.number_of_birth_this_turn), number_of_death_this_turn(game.number_of_death_this_turn), how_to_display(game.how_to_display), strategy(game.strategy), map_choice(game.map_choice), character_choice (game.character_choice)
{
report = new Report *[2]();
for (unsigned int i = 0 ; i < 2 ; i ++)
{
report[i] = game.report[i] ;
}
}
/**
* \fn Game &Game::operator=(const Game &new_game)
* \brief Surcharge de l'operateur d'affectation
* \param &new_game Jeu que l'on veut copier
* \return Le nouveau jeu
*/
Game &Game::operator=(const Game &new_game)
{
if (this != &new_game) /* On verifie que le jeu n'est pas le meme que l'on veut copier */
{
map = new_game.map;
turn = new_game.turn;
number_of_birth_this_turn = new_game.number_of_birth_this_turn;
number_of_death_this_turn = new_game.number_of_death_this_turn;
how_to_display = new_game.how_to_display;
strategy = new_game.strategy;
map_choice = new_game.map_choice;
character_choice = new_game.character_choice;
report = new Report *[2]();
for (unsigned int i = 0 ; i < 2 ; i ++)
{
report[i] = new_game.report[i] ;
}
}
return *this;
}
/**
* \fn void Game::reset(const unsigned int new_strategy) noexcept
* \brief Remise a de la simulation
* \param new_strategy Changement de strategy pour les joueurs
*/
void Game::reset(const unsigned int new_strategy) noexcept
{
turn = Date(1, 1, 60);
delete map;
strategy = new_strategy;
map = new Grid(map_choice, character_choice, strategy);
}
/**
* \fn void Game::run(unsigned int round)
* \brief Lancement de la simulation
* \param round Nombre de tour de la simulation
*/
void Game::run(unsigned int round)
{
bool flag = true ;
unsigned int i = 0 ;
while ( (flag) && (i < round))
{
++turn;
number_of_death_this_turn = 0;
number_of_birth_this_turn = 0;
lifeOfCharacter();
switch (how_to_display)
{
case 0:
system("clear");
std::cout << "Tour " << i + 1 << std::endl;
turn.display();
display();
usleep(1000);
break;
case 1:
system("clear");
std::cout << "Tour " << i + 1 << std::endl;
turn.display();
display();
std::getchar();
break;
case 2:
break;
default:
throw InvalidDisplayChoice(how_to_display);
}
if (map-> getSizeVectorGroundWithCharacter() == 0)
{
flag = false ;
}
i++ ;
}
writingReport();
}
/**
* \fn void Game::writingReport() noexcept
* \brief Ecriture du rapport pour les 2 equipes
*/
void Game::writingReport() noexcept
{
TownHall *townhall = static_cast<TownHall*>(map->getGroundGrid(0, 0));
writingReportTownHall(townhall, 0);
townhall = static_cast<TownHall*>(map->getGroundGrid(map->getRowNumber() - 1, map->getColumnNumber() - 1));
writingReportTownHall(townhall, 1);
}
/**
* \fn void Game::writingReportTownHall(TownHall *townhall, unsigned int i) noexcept
* \brief Ecriture du rapport pour 1 equipe
* \param townhall Hotel de ville
* \param i Numero de l'equipe auquel l'hotel de ville appartient
*/
void Game::writingReportTownHall(TownHall *townhall, unsigned int i) noexcept
{
report[i]->setLevel(townhall->getLevel());
(townhall->getGroundId() == 0) ? report[i]->setTeam(0) : report[i]->setTeam(1);
report[i]->setRockNumber(townhall->getRockNumber());
report[i]->setWoodNumber(townhall->getWoodNumber());
report[i]->setFishNumber(townhall->getFishNumber());
report[i]->setFoodNumber(townhall->getFoodNumber());
}
/**
* \fn void Game::lifeOfCharacter()
* \brief Lancement de la simulation pour un tour
*/
void Game::lifeOfCharacter()
{
Character *character;
Ground *ground;
unsigned int number_ground_with_character = map->getSizeVectorGroundWithCharacter(),
i = 0,
team;
while (i < number_ground_with_character) /* On regarde la liste de tous les terrains qui contiennent des personnages */
{
bool is_ground_deleted = false;
unsigned int j = 0;
ground = map->getGroundWithCharacter(i);
unsigned int number_character_ground = ground->getVectorSize();
while (j < number_character_ground) /* On regarde la liste de tous les personnages sur ce terrain */
{
character = ground->getCharacter(j);
team = character->getCharacterTeam();
if (!deathOfCharacter(character, i, j)) /* Si le personnage ne meurt pas (plus de vie ou vieilesse) */
{
if (character->getCharacterGender() == SEX::FEMALE) /* Si le personnage est feminin est majeur */
{
if (character->getCharacterCurrentLife() < 1) /* Si il ne va plus avoir de vie, on le fait manger */
{
if ((static_cast<TownHall*>(ground))->removeFishNumber(1))
{
character->giveCharacterLife((unsigned int)Constantes::CONFIG_SIMU["lifeWin"]);
}
else if ((static_cast<TownHall*>(ground))->removeFishNumber(1))
{
character->giveCharacterLife((unsigned int)Constantes::CONFIG_SIMU["lifeWin"]);
}
}
else if ((static_cast<FemaleCharacter*>(character))->getMonthPregnancy(turn) == Constantes::CONFIG_SIMU["monthPregnancy"]) /* Si le personnage peut accoucher */
{
birthOfCharacter(character);
}
j++;
}
else if ((character->getCharacterGender() == SEX::MALE) && (character->getCharacterAge(turn) >= Constantes::CONFIG_SIMU["majority"])) /* Si le personnage est masculin */
{
(static_cast<MaleCharacter*>(character))->executeState(*this, *map, ground, static_cast<MaleCharacter*>(character), i, j, number_ground_with_character, number_character_ground, is_ground_deleted);
}
else
{
j++;
}
}
else /* Si le personnage est mort on actualise le rapport */
{
number_character_ground--;
(team == 0) ? report[0]->incrementNumberOfDeath() : report[1]->incrementNumberOfDeath();
number_of_death_this_turn++;
}
}
if (!is_ground_deleted) /* Si un terrain contient encore des personnages, alors on regarde le suivant */
{
i++;
}
}
/* Le nombre de ressource evolue dans un point de collecte */
unsigned int number_collection_point = map->getSizeVectorGroundWithCollectionPoint() ;
for(unsigned int i = 0 ; i < number_collection_point ; i ++)
{
CollectionPoint * collection_point = (static_cast<CollectionPoint*>(map->getGroundWithCollectionPoint(i))) ;
collection_point->evolutionRessources() ;
}
}
/**
* \fn double Game::euclidienneDistance(const StructCoordinates &a, const StructCoordinates &b)
* \brief Calcul la distance euclidienne entre 2 points de la carte
* \param a Premier point de la carte
* \param b Deuxieme point de la carte
* \return La distance entre ces 2 points
*/
double Game::euclidienneDistance(const StructCoordinates &a, const StructCoordinates &b)
{
double substrate_abscissa = (b.getAbscissa() > a.getAbscissa()) ? b.getAbscissa() - a.getAbscissa() : a.getAbscissa() - b.getAbscissa();
double substrate_ordinate = (b.getOrdinate() > a.getOrdinate()) ? b.getOrdinate() - a.getOrdinate() : a.getOrdinate() - b.getOrdinate();
return sqrt(pow(substrate_abscissa, 2) + pow(substrate_ordinate, 2));
}
/**
* \fn bool Game::deathOfCharacter(Character *character, unsigned int i, unsigned int &j)
* \brief Methode qui va tester si le personnage restera en vie a ce tour
* \param *character Personnage qui va potentiellement mourrir
* \param i Indice du terrain dans le vecteur
* \param j Indice du personnage sur ce terrain
* \return True si le personnage meurt, false sinon
*/
bool Game::deathOfCharacter(Character *character, unsigned int i, unsigned int &j)
{
bool dead = false;
if (character->isDead(turn) || character->decrementCharacterLife()) /* Si le personnage meurt de vieillesse ou de faim */
{
dead = true;
map->getGroundWithCharacter(i)->removeCharacter(j);
delete character;
j--;
}
return dead;
}
/**
* \fn void Game::birthOfCharacter(Character *character)
* \brief Methode qui donne naissance a des personnages
* \param *character Personnage Feminin qui va donner naissance a des enfants
*/
void Game::birthOfCharacter(Character *character)
{
Character *new_character;
for (unsigned int i = 0; i < (static_cast<FemaleCharacter*>(character))->getBabyPerPregnancy(); ++i)
{
if (genrand_real1() < Constantes::CONFIG_SIMU["chanceMale"])
{
new_character = new MaleCharacter(turn, character->getCharacterTeam(), map->getColumnNumber(), strategy);
}
else
{
new_character = new FemaleCharacter(turn, character->getCharacterTeam());
}
map->getGroundGrid(new_character->getCharacterTeam())->addCharacter(new_character);
(new_character->getCharacterTeam() == 0) ? report[0]->incrementNumberOfBirth() : report[1]->incrementNumberOfBirth();
}
(static_cast<FemaleCharacter*>(character))->setTimePregnancy(Date());
(static_cast<FemaleCharacter*>(character))->randomBabyPerPregnancy();
number_of_birth_this_turn += (static_cast<FemaleCharacter*>(character))->getBabyPerPregnancy();
}
/**
* \fn void Game::display(std::ostream &os) const noexcept
* \brief Affichage de la simulation a l'ecran
* \param &os Flux ou l'on va afficher la simulation
*/
void Game::display(std::ostream &os) const noexcept
{
map->display();
os << "Number of birth this turn : " << number_of_birth_this_turn << std::endl;
os << "Number of death this turn : " << number_of_death_this_turn << std::endl;
}
/**
* \fn Date Game::getTurn() const noexcept
* \brief Getteur sur la date du tour actuelle
* \return Le date du tour actuelle
*/
Date Game::getTurn() const noexcept
{
return turn;
}
/**
* \fn Report **Game::getReport() const noexcept
* \brief Getteur sur la liste des rapports de la simulations
* \return Les rapports des 2 equipes
*/
Report **Game::getReport() const noexcept
{
return report;
} | 38.071038 | 466 | 0.629252 | [
"vector"
] |
cb4cf234b11f3a0730fc4eda2472ffaeac104806 | 3,444 | cpp | C++ | Week14 - FCNN/FCNN/MatrixMN.cpp | vega196/2016FallCSE2022 | 314e42d74d9b58e3d6d988729e73dbe16e238f1f | [
"MIT"
] | 26 | 2016-11-29T11:16:31.000Z | 2022-02-28T05:41:20.000Z | Week14 - FCNN/FCNN/MatrixMN.cpp | vega196/2016FallCSE2022 | 314e42d74d9b58e3d6d988729e73dbe16e238f1f | [
"MIT"
] | null | null | null | Week14 - FCNN/FCNN/MatrixMN.cpp | vega196/2016FallCSE2022 | 314e42d74d9b58e3d6d988729e73dbe16e238f1f | [
"MIT"
] | 56 | 2016-11-28T14:58:38.000Z | 2022-02-27T01:00:36.000Z | /////////////////////////////////////////////////////////////////////////////
// Authored by Jeong-Mo Hong for CSE4060 course at Dongguk University CSE //
// jeongmo.hong@gmail.com //
// Do whatever you want license. //
/////////////////////////////////////////////////////////////////////////////
#include <assert.h>
#include "MatrixMN.h"
#define SAFE_DELETE_ARRAY(pointer) if(pointer != nullptr){delete [] pointer; pointer=nullptr;}
template<class T>
void MatrixMN<T>::initialize(const int& _m, const int& _n, const bool init = true)
{
const int num_all_old = num_rows_ * num_cols_;
num_rows_ = _m;
num_cols_ = _n;
SAFE_DELETE_ARRAY(values_);
const int num_all = num_rows_ * num_cols_;
if (num_all_old != num_all) // allocate memory if num_all is changed
{
// check if the matrix is too large
assert((double)num_rows_ * (double)num_cols_ <= (double)INT_MAX);
values_ = new T[num_all];
if (init == true)
for (int i = 0; i < num_all; i++)
values_[i] = (T)0;
}
}
template<class T>
void MatrixMN<T>::multiply(const VectorND<T>& vector, VectorND<T>& result) const
{
assert(num_rows_ <= result.num_dimension_);
assert(num_cols_ <= vector.num_dimension_);
for (int row = 0; row < num_rows_; row++)
{
result.values_[row] = (T)0;
int ix = row*num_cols_;
T temp;
for (int col = 0; col < num_cols_; col++, ix++)
{
temp = values_[ix];
temp *= vector.values_[col];
result.values_[row] += temp;
}
}
}
template<class T>
void MatrixMN<T>::multiplyTransposed(const VectorND<T>& vector, VectorND<T>& result) const
{
assert(num_rows_ <= vector.num_dimension_);
assert(num_cols_ <= result.num_dimension_);
for (int col = 0; col < num_cols_; col++)
{
result.values_[col] = (T)0;
for (int row = 0, ix = col; row < num_rows_; row++, ix += num_cols_)
{
result.values_[col] += values_[ix] * vector.values_[row];
}
}
//Note: You may transpose matrix and then multiply for better performance.
//See Eigen library. http://eigen.tuxfamily.org/index.php?title=Main_Page
}
template<class T>
void MatrixMN<T>::cout()
{
for (int row = 0; row < num_rows_; row++)
{
for (int col = 0; col < num_cols_; col++)
{
std::cout << getValue(row, col) << " ";
}
std::cout << std::endl;
}
}
template<class T>
int MatrixMN<T>::get1DIndex(const int& row, const int& column) const
{
assert(row >= 0);
assert(column >= 0);
assert(row < num_rows_);
assert(row < num_cols_);
// column = i, row = j
return column + row * num_cols_; // data structure is for faster dot product of a row vector and VectorND input.
}
template<class T>
T& MatrixMN<T>::getValue(const int& row, const int& column) const
{
return values_[get1DIndex(row, column)];
}
template class MatrixMN<float>;
template class MatrixMN<double>;
//template void MatrixMN<float>::multiply(const VectorND<float>& vector, VectorND<float>& result) const;
//template void MatrixMN<float>::multiplyTransposed(const VectorND<float>& vector, VectorND<float>& result) const;
//
//template void MatrixMN<double>::multiply(const VectorND<double>& vector, VectorND<double>& result) const;
//template void MatrixMN<double>::multiplyTransposed(const VectorND<double>& vector, VectorND<double>& result) const; | 28.941176 | 120 | 0.609756 | [
"vector"
] |
cb4f4152b91bf4206333e41aa9c2980c1768b4b7 | 3,835 | cpp | C++ | src/py/wrapper/wrapper_2f99a056e37254eeaea9c90166e6ee79.cpp | StatisKit/PGM | 1a82025003a705c668a9ff0ce170457ff40d37c2 | [
"Apache-2.0"
] | 1 | 2021-06-10T04:25:00.000Z | 2021-06-10T04:25:00.000Z | src/py/wrapper/wrapper_2f99a056e37254eeaea9c90166e6ee79.cpp | StatisKit/PGM | 1a82025003a705c668a9ff0ce170457ff40d37c2 | [
"Apache-2.0"
] | null | null | null | src/py/wrapper/wrapper_2f99a056e37254eeaea9c90166e6ee79.cpp | StatisKit/PGM | 1a82025003a705c668a9ff0ce170457ff40d37c2 | [
"Apache-2.0"
] | 5 | 2017-05-02T06:20:42.000Z | 2021-03-15T18:34:12.000Z | #include "_pgm.h"
namespace autowig
{
}
#if defined(_MSC_VER)
#if (_MSC_VER == 1900)
namespace boost
{
template <> class ::statiskit::pgm::MixtureUndirectedGraphProcess::VariationalComputation const volatile * get_pointer<class ::statiskit::pgm::MixtureUndirectedGraphProcess::VariationalComputation const volatile >(class ::statiskit::pgm::MixtureUndirectedGraphProcess::VariationalComputation const volatile *c) { return c; }
}
#endif
#endif
void wrapper_2f99a056e37254eeaea9c90166e6ee79()
{
std::string name_fa414b05d29e5f4ea0b6d6cb5cf81b01 = boost::python::extract< std::string >(boost::python::scope().attr("__name__") + ".statiskit");
boost::python::object module_fa414b05d29e5f4ea0b6d6cb5cf81b01(boost::python::handle< >(boost::python::borrowed(PyImport_AddModule(name_fa414b05d29e5f4ea0b6d6cb5cf81b01.c_str()))));
boost::python::scope().attr("statiskit") = module_fa414b05d29e5f4ea0b6d6cb5cf81b01;
boost::python::scope scope_fa414b05d29e5f4ea0b6d6cb5cf81b01 = module_fa414b05d29e5f4ea0b6d6cb5cf81b01;
std::string name_371d94ac4c135d82a973fb39a0a6d037 = boost::python::extract< std::string >(boost::python::scope().attr("__name__") + ".pgm");
boost::python::object module_371d94ac4c135d82a973fb39a0a6d037(boost::python::handle< >(boost::python::borrowed(PyImport_AddModule(name_371d94ac4c135d82a973fb39a0a6d037.c_str()))));
boost::python::scope().attr("pgm") = module_371d94ac4c135d82a973fb39a0a6d037;
boost::python::scope scope_371d94ac4c135d82a973fb39a0a6d037 = module_371d94ac4c135d82a973fb39a0a6d037;
std::string name_c5364bf6a7375db8ba8ffc4938cdbf83 = boost::python::extract< std::string >(boost::python::scope().attr("__name__") + "._mixture_undirected_graph_process");
boost::python::object module_c5364bf6a7375db8ba8ffc4938cdbf83(boost::python::handle< >(boost::python::borrowed(PyImport_AddModule(name_c5364bf6a7375db8ba8ffc4938cdbf83.c_str()))));
boost::python::scope().attr("_mixture_undirected_graph_process") = module_c5364bf6a7375db8ba8ffc4938cdbf83;
boost::python::scope scope_c5364bf6a7375db8ba8ffc4938cdbf83 = module_c5364bf6a7375db8ba8ffc4938cdbf83;
boost::python::class_< class ::statiskit::pgm::MixtureUndirectedGraphProcess::VariationalComputation, autowig::Held< class ::statiskit::pgm::MixtureUndirectedGraphProcess::VariationalComputation >::Type, boost::python::bases< struct ::statiskit::PolymorphicCopy< struct ::statiskit::pgm::MixtureUndirectedGraphProcess::Computation, class ::statiskit::pgm::MixtureUndirectedGraphProcess::VariationalComputation, struct ::statiskit::pgm::MixtureUndirectedGraphProcess::Computation >, class ::statiskit::Optimization< class ::statiskit::Estimator > > > class_2f99a056e37254eeaea9c90166e6ee79("VariationalComputation", "", boost::python::no_init);
class_2f99a056e37254eeaea9c90166e6ee79.def(boost::python::init< >(""));
class_2f99a056e37254eeaea9c90166e6ee79.def(boost::python::init< class ::statiskit::pgm::MixtureUndirectedGraphProcess::VariationalComputation const & >(""));
if(autowig::Held< class ::statiskit::pgm::MixtureUndirectedGraphProcess::VariationalComputation >::is_class)
{
boost::python::implicitly_convertible< autowig::Held< class ::statiskit::pgm::MixtureUndirectedGraphProcess::VariationalComputation >::Type, autowig::Held< struct ::statiskit::PolymorphicCopy< struct ::statiskit::pgm::MixtureUndirectedGraphProcess::Computation, class ::statiskit::pgm::MixtureUndirectedGraphProcess::VariationalComputation, struct ::statiskit::pgm::MixtureUndirectedGraphProcess::Computation > >::Type >();
boost::python::implicitly_convertible< autowig::Held< class ::statiskit::pgm::MixtureUndirectedGraphProcess::VariationalComputation >::Type, autowig::Held< class ::statiskit::Optimization< class ::statiskit::Estimator > >::Type >();
}
} | 83.369565 | 647 | 0.789048 | [
"object"
] |
cb5020d78d425bae996535f36b1882f704f92e0c | 14,377 | cpp | C++ | Framework/Sources/o2/Render/Windows/RenderImpl.cpp | zenkovich/o2 | cdbf10271f1bf0f3198c8005b13b66e6ca13a9db | [
"MIT"
] | 181 | 2015-12-09T08:53:36.000Z | 2022-03-26T20:48:39.000Z | Framework/Sources/o2/Render/Windows/RenderImpl.cpp | zenkovich/o2 | cdbf10271f1bf0f3198c8005b13b66e6ca13a9db | [
"MIT"
] | 29 | 2016-04-22T08:24:04.000Z | 2022-03-06T07:06:28.000Z | Framework/Sources/o2/Render/Windows/RenderImpl.cpp | zenkovich/o2 | cdbf10271f1bf0f3198c8005b13b66e6ca13a9db | [
"MIT"
] | 13 | 2018-04-24T17:12:04.000Z | 2021-11-12T23:49:53.000Z | #include "o2/stdafx.h"
#ifdef PLATFORM_WINDOWS
#include "o2/Render/Render.h"
#include "o2/Application/Application.h"
#include "o2/Application/Input.h"
#include "o2/Assets/Assets.h"
#include "o2/Events/EventSystem.h"
#include "o2/Render/Font.h"
#include "o2/Render/Mesh.h"
#include "o2/Render/Sprite.h"
#include "o2/Render/Texture.h"
#include "o2/Utils/Debug/Debug.h"
#include "o2/Utils/Debug/Log/LogStream.h"
#include "o2/Utils/Math/Geometry.h"
#include "o2/Utils/Math/Interpolation.h"
namespace o2
{
Render::Render() :
mReady(false), mStencilDrawing(false), mStencilTest(false), mClippingEverything(false)
{
mVertexBufferSize = USHRT_MAX;
mIndexBufferSize = USHRT_MAX;
// Create log stream
mLog = mnew LogStream("Render");
o2Debug.GetLog()->BindStream(mLog);
// Initialize OpenGL
mLog->Out("Initializing OpenGL render..");
mResolution = o2Application.GetContentSize();
GLuint pixelFormat;
static PIXELFORMATDESCRIPTOR pfd = // pfd Tells Windows How We Want Things To Be
{
sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
1, // Version Number
PFD_DRAW_TO_WINDOW | // Format Must Support Window
PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
PFD_DOUBLEBUFFER, // Must Support Double Buffering
PFD_TYPE_RGBA, // Request An RGBA Format
32, // Select Our Color Depth
0, 0, 0, 0, 0, 0, // Color Bits Ignored
0, // No Alpha Buffer
0, // Shift Bit Ignored
0, // No Accumulation Buffer
0, 0, 0, 0, // Accumulation Bits Ignored
16, // 16Bit Z-Buffer (Depth Buffer)
1, // No Stencil Buffer
0, // No Auxiliary Buffer
PFD_MAIN_PLANE, // Main Drawing Layer
0, // Reserved
0, 0, 0 // Layer Masks Ignored
};
mHDC = GetDC(o2Application.mHWnd);
if (!mHDC)
{
mLog->Error("Can't Create A GL Device Context.\n");
return;
}
pixelFormat = ChoosePixelFormat(mHDC, &pfd);
if (!pixelFormat)
{
mLog->Error("Can't Find A Suitable PixelFormat.\n");
return;
}
if (!SetPixelFormat(mHDC, pixelFormat, &pfd))
{
mLog->Error("Can't Set The PixelFormat.\n");
return;
}
mGLContext = wglCreateContext(mHDC);
if (!mGLContext)
{
mLog->Error("Can't Create A GL Rendering Context.\n");
return;
}
if (!wglMakeCurrent(mHDC, mGLContext))
{
mLog->Error("Can't Activate The GL Rendering Context.\n");
return;
}
// Get OpenGL extensions
GetGLExtensions(mLog);
GL_CHECK_ERROR();
// Check compatibles
CheckCompatibles();
// Initialize buffers
mVertexData = mnew UInt8[mVertexBufferSize * sizeof(Vertex2)];
mVertexIndexData = mnew UInt16[mIndexBufferSize];
mLastDrawVertex = 0;
mTrianglesCount = 0;
mCurrentPrimitiveType = PrimitiveType::Polygon;
// Configure OpenGL
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(Vertex2), mVertexData + sizeof(float) * 3);
glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex2), mVertexData + sizeof(float) * 3 + sizeof(unsigned long));
glVertexPointer(3, GL_FLOAT, sizeof(Vertex2), mVertexData + 0);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glLineWidth(1.0f);
GL_CHECK_ERROR();
mLog->Out("GL_VENDOR: " + (String)(char*)glGetString(GL_VENDOR));
mLog->Out("GL_RENDERER: " + (String)(char*)glGetString(GL_RENDERER));
mLog->Out("GL_VERSION: " + (String)(char*)glGetString(GL_VERSION));
HDC dc = GetDC(0);
mDPI.x = GetDeviceCaps(dc, LOGPIXELSX);
mDPI.y = GetDeviceCaps(dc, LOGPIXELSY);
ReleaseDC(0, dc);
InitializeFreeType();
InitializeLinesIndexBuffer();
InitializeLinesTextures();
mCurrentRenderTarget = TextureRef();
if (IsDevMode())
o2Assets.onAssetsRebuilt += MakeFunction(this, &Render::OnAssetsRebuilded);
mReady = true;
}
Render::~Render()
{
if (!mReady)
return;
if (IsDevMode())
o2Assets.onAssetsRebuilt -= MakeFunction(this, &Render::OnAssetsRebuilded);
mSolidLineTexture = TextureRef::Null();
mDashLineTexture = TextureRef::Null();
if (mGLContext)
{
auto fonts = mFonts;
for (auto font : fonts)
delete font;
auto textures = mTextures;
for (auto texture : textures)
delete texture;
if (!wglMakeCurrent(NULL, NULL))
mLog->Error("Release ff DC And RC Failed.\n");
if (!wglDeleteContext(mGLContext))
mLog->Error("Release Rendering Context Failed.\n");
mGLContext = NULL;
}
DeinitializeFreeType();
mReady = false;
}
void Render::CheckCompatibles()
{
//check render targets available
char* extensions[] = { "GL_ARB_framebuffer_object", "GL_EXT_framebuffer_object", "GL_EXT_framebuffer_blit",
"GL_EXT_packed_depth_stencil" };
mRenderTargetsAvailable = true;
for (int i = 0; i < 4; i++)
{
if (!IsGLExtensionSupported(extensions[i]))
mRenderTargetsAvailable = false;
}
//get max texture size
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize.x);
mMaxTextureSize.y = mMaxTextureSize.x;
}
void Render::Begin()
{
if (!mReady)
return;
mLastDrawTexture = NULL;
mLastDrawVertex = 0;
mLastDrawIdx = 0;
mTrianglesCount = 0;
mFrameTrianglesCount = 0;
mDIPCount = 0;
mCurrentPrimitiveType = PrimitiveType::Polygon;
mDrawingDepth = 0.0f;
mScissorInfos.Clear();
mStackScissors.Clear();
mClippingEverything = false;
SetupViewMatrix(mResolution);
UpdateCameraTransforms();
preRender();
preRender.Clear();
}
void Render::DrawPrimitives()
{
if (mLastDrawVertex < 1)
return;
static const GLenum primitiveType[3]{ GL_TRIANGLES, GL_TRIANGLES, GL_LINES };
glDrawElements(primitiveType[(int)mCurrentPrimitiveType], mLastDrawIdx, GL_UNSIGNED_SHORT, mVertexIndexData);
GL_CHECK_ERROR();
mFrameTrianglesCount += mTrianglesCount;
mLastDrawVertex = mTrianglesCount = mLastDrawIdx = 0;
mDIPCount++;
}
void Render::SetupViewMatrix(const Vec2I& viewSize)
{
mCurrentResolution = viewSize;
mCamera = Camera();
float projMat[16];
Math::OrthoProjMatrix(projMat, 0.0f, (float)viewSize.x, (float)viewSize.y, 0.0f, 0.0f, 10.0f);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(0, 0, viewSize.x, viewSize.y);
glLoadMatrixf(projMat);
UpdateCameraTransforms();
}
void Render::End()
{
if (!mReady)
return;
postRender();
postRender.Clear();
DrawPrimitives();
SwapBuffers(mHDC);
GL_CHECK_ERROR();
CheckTexturesUnloading();
CheckFontsUnloading();
}
void Render::Clear(const Color4& color /*= Color4::Blur()*/)
{
glClearColor(color.RF(), color.GF(), color.BF(), color.AF());
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
GL_CHECK_ERROR();
}
void Render::UpdateCameraTransforms()
{
DrawPrimitives();
Vec2F resf = (Vec2F)mCurrentResolution;
glMatrixMode(GL_MODELVIEW);
float modelMatrix[16] =
{
1, 0, 0, 0,
0, -1, 0, 0,
0, 0, 1, 0,
Math::Round(resf.x*0.5f), Math::Round(resf.y*0.5f), -1, 1
};
glLoadMatrixf(modelMatrix);
Basis defaultCameraBasis((Vec2F)mCurrentResolution*-0.5f, Vec2F::Right()*resf.x, Vec2F().Up()*resf.y);
Basis camTransf = mCamera.GetBasis().Inverted()*defaultCameraBasis;
mViewScale = Vec2F(camTransf.xv.Length(), camTransf.yv.Length());
mInvViewScale = Vec2F(1.0f / mViewScale.x, 1.0f / mViewScale.y);
float camTransfMatr[16] =
{
camTransf.xv.x, camTransf.xv.y, 0, 0,
camTransf.yv.x, camTransf.yv.y, 0, 0,
0, 0, 0, 0,
camTransf.origin.x, camTransf.origin.y, 0, 1
};
glMultMatrixf(camTransfMatr);
}
void Render::BeginRenderToStencilBuffer()
{
if (mStencilDrawing || mStencilTest)
return;
DrawPrimitives();
glEnable(GL_STENCIL_TEST);
glStencilFunc(GL_ALWAYS, 0x1, 0xffffffff);
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
GL_CHECK_ERROR();
mStencilDrawing = true;
}
void Render::EndRenderToStencilBuffer()
{
if (!mStencilDrawing)
return;
DrawPrimitives();
glDisable(GL_STENCIL_TEST);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
GL_CHECK_ERROR();
mStencilDrawing = false;
}
void Render::EnableStencilTest()
{
if (mStencilTest || mStencilDrawing)
return;
DrawPrimitives();
glEnable(GL_STENCIL_TEST);
glStencilFunc(GL_EQUAL, 0x1, 0xffffffff);
GL_CHECK_ERROR();
mStencilTest = true;
}
void Render::DisableStencilTest()
{
if (!mStencilTest)
return;
DrawPrimitives();
glDisable(GL_STENCIL_TEST);
mStencilTest = false;
}
void Render::ClearStencil()
{
glClearStencil(0);
glClear(GL_STENCIL_BUFFER_BIT);
GL_CHECK_ERROR();
}
void Render::EnableScissorTest(const RectI& rect)
{
DrawPrimitives();
RectI summaryScissorRect = rect;
if (!mStackScissors.IsEmpty())
{
mScissorInfos.Last().mEndDepth = mDrawingDepth;
if (!mStackScissors.Last().mRenderTarget)
{
RectI lastSummaryClipRect = mStackScissors.Last().mSummaryScissorRect;
mClippingEverything = !summaryScissorRect.IsIntersects(lastSummaryClipRect);
summaryScissorRect = summaryScissorRect.GetIntersection(lastSummaryClipRect);
}
else
{
glEnable(GL_SCISSOR_TEST);
GL_CHECK_ERROR();
mClippingEverything = false;
}
}
else
{
glEnable(GL_SCISSOR_TEST);
GL_CHECK_ERROR();
mClippingEverything = false;
}
mScissorInfos.Add(ScissorInfo(summaryScissorRect, mDrawingDepth));
mStackScissors.Add(ScissorStackEntry(rect, summaryScissorRect));
RectI screenScissorRect = CalculateScreenSpaceScissorRect(summaryScissorRect);
glScissor((int)(screenScissorRect.left + mCurrentResolution.x*0.5f), (int)(screenScissorRect.bottom + mCurrentResolution.y*0.5f),
(int)screenScissorRect.Width(), (int)screenScissorRect.Height());
}
void Render::DisableScissorTest(bool forcible /*= false*/)
{
if (mStackScissors.IsEmpty())
{
mLog->WarningStr("Can't disable scissor test - no scissor were enabled!");
return;
}
DrawPrimitives();
if (forcible)
{
glDisable(GL_SCISSOR_TEST);
GL_CHECK_ERROR();
while (!mStackScissors.IsEmpty() && !mStackScissors.Last().mRenderTarget)
mStackScissors.PopBack();
mScissorInfos.Last().mEndDepth = mDrawingDepth;
}
else
{
if (mStackScissors.Count() == 1)
{
glDisable(GL_SCISSOR_TEST);
GL_CHECK_ERROR();
mStackScissors.PopBack();
mScissorInfos.Last().mEndDepth = mDrawingDepth;
mClippingEverything = false;
}
else
{
mStackScissors.PopBack();
RectI lastClipRect = mStackScissors.Last().mSummaryScissorRect;
mScissorInfos.Last().mEndDepth = mDrawingDepth;
mScissorInfos.Add(ScissorInfo(lastClipRect, mDrawingDepth));
if (mStackScissors.Last().mRenderTarget)
{
glDisable(GL_SCISSOR_TEST);
GL_CHECK_ERROR();
mClippingEverything = false;
}
else
{
RectI screenScissorRect = CalculateScreenSpaceScissorRect(lastClipRect);
glScissor((int)(screenScissorRect.left + mCurrentResolution.x*0.5f), (int)(screenScissorRect.bottom + mCurrentResolution.y*0.5f),
(int)screenScissorRect.Width(), (int)screenScissorRect.Height());
mClippingEverything = lastClipRect == RectI();
}
}
}
}
void Render::DrawBuffer(PrimitiveType primitiveType, Vertex2* vertices, UInt verticesCount,
UInt16* indexes, UInt elementsCount, const TextureRef& texture)
{
if (!mReady)
return;
mDrawingDepth += 1.0f;
if (mClippingEverything)
return;
UInt indexesCount;
if (primitiveType == PrimitiveType::Line)
indexesCount = elementsCount * 2;
else
indexesCount = elementsCount * 3;
if (mLastDrawTexture != texture.mTexture ||
mLastDrawVertex + verticesCount >= mVertexBufferSize ||
mLastDrawIdx + indexesCount >= mIndexBufferSize ||
mCurrentPrimitiveType != primitiveType)
{
DrawPrimitives();
mLastDrawTexture = texture.mTexture;
mCurrentPrimitiveType = primitiveType;
if (primitiveType == PrimitiveType::PolygonWire)
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
else
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
if (mLastDrawTexture)
{
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, mLastDrawTexture->mHandle);
GL_CHECK_ERROR();
}
else glDisable(GL_TEXTURE_2D);
}
memcpy(&mVertexData[mLastDrawVertex * sizeof(Vertex2)], vertices, sizeof(Vertex2)*verticesCount);
for (UInt i = mLastDrawIdx, j = 0; j < indexesCount; i++, j++)
mVertexIndexData[i] = mLastDrawVertex + indexes[j];
if (primitiveType != PrimitiveType::Line)
mTrianglesCount += elementsCount;
mLastDrawVertex += verticesCount;
mLastDrawIdx += indexesCount;
}
void Render::BindRenderTexture(TextureRef renderTarget)
{
if (!renderTarget)
{
UnbindRenderTexture();
return;
}
if (renderTarget->mUsage != Texture::Usage::RenderTarget)
{
mLog->Error("Can't set texture as render target: not render target texture");
UnbindRenderTexture();
return;
}
if (!renderTarget->IsReady())
{
mLog->Error("Can't set texture as render target: texture isn't ready");
UnbindRenderTexture();
return;
}
DrawPrimitives();
if (!mStackScissors.IsEmpty())
{
mScissorInfos.Last().mEndDepth = mDrawingDepth;
glDisable(GL_SCISSOR_TEST);
GL_CHECK_ERROR();
}
mStackScissors.Add(ScissorStackEntry(RectI(), RectI(), true));
glBindFramebufferEXT(GL_FRAMEBUFFER, renderTarget->mFrameBuffer);
GL_CHECK_ERROR();
SetupViewMatrix(renderTarget->GetSize());
mCurrentRenderTarget = renderTarget;
}
void Render::UnbindRenderTexture()
{
if (!mCurrentRenderTarget)
return;
DrawPrimitives();
glBindFramebufferEXT(GL_FRAMEBUFFER, 0);
GL_CHECK_ERROR();
SetupViewMatrix(mResolution);
mCurrentRenderTarget = TextureRef();
DisableScissorTest(true);
mStackScissors.PopBack();
if (!mStackScissors.IsEmpty())
{
glEnable(GL_SCISSOR_TEST);
GL_CHECK_ERROR();
auto clipRect = mStackScissors.Last().mSummaryScissorRect;
glScissor((int)(clipRect.left + mCurrentResolution.x*0.5f),
(int)(clipRect.bottom + mCurrentResolution.y*0.5f),
(int)clipRect.Width(),
(int)clipRect.Height());
mClippingEverything = clipRect == RectI();
}
}
}
#endif // PLATFORM_WINDOWS
| 23.763636 | 134 | 0.693191 | [
"mesh",
"geometry",
"render"
] |
cb51a09ff28cb8f8a2e649d87605318c6c6a3e9b | 2,638 | cpp | C++ | src/diagonal_distribution_slice_import_export.cpp | ekera/qunundrum | deeed6779a5b0e69df9245024225b8a552c2179c | [
"MIT"
] | 4 | 2020-12-09T10:57:05.000Z | 2021-12-27T15:44:47.000Z | src/diagonal_distribution_slice_import_export.cpp | ekera/qunundrum | deeed6779a5b0e69df9245024225b8a552c2179c | [
"MIT"
] | null | null | null | src/diagonal_distribution_slice_import_export.cpp | ekera/qunundrum | deeed6779a5b0e69df9245024225b8a552c2179c | [
"MIT"
] | null | null | null | /*!
* \file diagonal_distribution_slice_import_export.cpp
* \ingroup diagonal_distribution_slice
*
* \brief The definition of functions for importing and exporting slices in
* diagonal probability distributions.
*/
#include "diagonal_distribution_slice.h"
#include "common.h"
#include "errors.h"
#include "math.h"
#include <stdint.h>
#include <stdio.h>
static void diagonal_distribution_slice_import_common(
Diagonal_Distribution_Slice * const slice,
FILE * const file)
{
if (1 != fscanf(file, "%d\n", &(slice->min_log_alpha_r))) {
critical("diagonal_distribution_slice_import_common(): "
"Failed to import min_log_alpha_r.");
}
if (1 != fscanf(file, "%x\n", &(slice->flags))) {
critical("diagonal_distribution_slice_import_common(): "
"Failed to import flags.");
}
slice->total_probability = 0;
for (uint32_t i = 0; i < slice->dimension; i++) {
if (1 != fscanf(file, "%Lg\n", &(slice->norm_vector[i]))) {
critical("diagonal_distribution_slice_import_common(): "
"Failed to import an element in the norm vector.");
}
slice->total_probability += slice->norm_vector[i];
}
if (1 != fscanf(file, "%Lg\n", &(slice->total_error))) {
critical("diagonal_distribution_slice_import_common(): "
"Failed to import the total error.");
}
}
void diagonal_distribution_slice_import(
Diagonal_Distribution_Slice * const slice,
FILE * const file)
{
uint32_t dimension;
if (1 != fscanf(file, "%u\n", &dimension)) {
critical("diagonal_distribution_slice_import(): "
"Failed to import the dimension.");
}
if (dimension != slice->dimension) {
diagonal_distribution_slice_clear(slice);
diagonal_distribution_slice_init(slice, dimension);
}
diagonal_distribution_slice_import_common(slice, file);
}
void diagonal_distribution_slice_init_import(
Diagonal_Distribution_Slice * const slice,
FILE * const file)
{
uint32_t dimension;
if (1 != fscanf(file, "%u\n", &dimension)) {
critical("diagonal_distribution_slice_init_import(): "
"Failed to import the dimension.");
}
diagonal_distribution_slice_init(slice, dimension);
diagonal_distribution_slice_import_common(slice, file);
}
void diagonal_distribution_slice_export(
const Diagonal_Distribution_Slice * const slice,
FILE * const file)
{
fprintf(file, "%u\n", slice->dimension);
fprintf(file, "%d\n", slice->min_log_alpha_r);
fprintf(file, "%.8x\n", slice->flags);
for (uint32_t i = 0; i < slice->dimension; i++) {
fprintf(file, "%.24Lg\n", slice->norm_vector[i]);
}
fprintf(file, "%.24Lg\n", slice->total_error);
}
| 26.918367 | 77 | 0.694845 | [
"vector"
] |
cb557c5d935f8dd7abdf7c896d1f18141e10b832 | 1,113 | hpp | C++ | third_party/boost/simd/function/log1p.hpp | SylvainCorlay/pythran | 908ec070d837baf77d828d01c3e35e2f4bfa2bfa | [
"BSD-3-Clause"
] | 6 | 2018-02-25T22:23:33.000Z | 2021-01-15T15:13:12.000Z | third_party/boost/simd/function/log1p.hpp | SylvainCorlay/pythran | 908ec070d837baf77d828d01c3e35e2f4bfa2bfa | [
"BSD-3-Clause"
] | null | null | null | third_party/boost/simd/function/log1p.hpp | SylvainCorlay/pythran | 908ec070d837baf77d828d01c3e35e2f4bfa2bfa | [
"BSD-3-Clause"
] | 7 | 2017-12-12T12:36:31.000Z | 2020-02-10T14:27:07.000Z | //==================================================================================================
/*!
@file
@copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_LOG1P_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_LOG1P_HPP_INCLUDED
#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{
/*!
@ingroup group-exponential
This function object computes \f$\log(1+x)\f$ with good accuracy even for small
\f$x\f$ values.
@par Header <boost/simd/function/log1p.hpp>
@par Decorators
- std_ for floating entries calls @c std::log1p
@see log, exp, expm1
@par Example:
@snippet log1p.cpp log1p
@par Possible output:
@snippet log1p.txt log1p
**/
IEEEValue log1p(IEEEValue const& x);
} }
#endif
#include <boost/simd/function/scalar/log1p.hpp>
#include <boost/simd/function/simd/log1p.hpp>
#endif
| 23.1875 | 100 | 0.578616 | [
"object"
] |
cb56183c4e4576dac7fd80be5b321c54e95a984a | 11,747 | cc | C++ | chrome/browser/media/router/discovery/dial/dial_media_sink_service_impl.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/media/router/discovery/dial/dial_media_sink_service_impl.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/media/router/discovery/dial/dial_media_sink_service_impl.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/media/router/discovery/dial/dial_media_sink_service_impl.h"
#include <algorithm>
#include "base/bind.h"
#include "base/stl_util.h"
#include "base/strings/strcat.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/media/router/discovery/dial/dial_device_data.h"
namespace media_router {
using SinkAppStatus = DialMediaSinkServiceImpl::SinkAppStatus;
namespace {
constexpr char kLoggerComponent[] = "DialMediaSinkServiceImpl";
static constexpr const char* kDiscoveryOnlyModelNames[3] = {
"eureka dongle", "chromecast audio", "chromecast ultra"};
// Returns true if DIAL (SSDP) was only used to discover this sink, and it is
// not expected to support other DIAL features (app discovery, activity
// discovery, etc.)
// |model_name|: device model name.
bool IsDiscoveryOnly(const std::string& model_name) {
std::string lower_model_name = base::ToLowerASCII(model_name);
return base::Contains(kDiscoveryOnlyModelNames, lower_model_name);
}
SinkAppStatus GetSinkAppStatusFromResponse(const DialAppInfoResult& result) {
if (!result.app_info) {
if (result.result_code == DialAppInfoResultCode::kParsingError ||
result.result_code == DialAppInfoResultCode::kNotFound) {
return SinkAppStatus::kUnavailable;
} else {
return SinkAppStatus::kUnknown;
}
}
return (result.app_info->state == DialAppState::kRunning ||
result.app_info->state == DialAppState::kStopped)
? SinkAppStatus::kAvailable
: SinkAppStatus::kUnavailable;
}
} // namespace
DialMediaSinkServiceImpl::DialMediaSinkServiceImpl(
const OnSinksDiscoveredCallback& on_sinks_discovered_cb,
const scoped_refptr<base::SequencedTaskRunner>& task_runner)
: MediaSinkServiceBase(on_sinks_discovered_cb), task_runner_(task_runner) {
DETACH_FROM_SEQUENCE(sequence_checker_);
}
DialMediaSinkServiceImpl::~DialMediaSinkServiceImpl() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (dial_registry_) {
dial_registry_->OnListenerRemoved();
dial_registry_->UnregisterObserver(this);
dial_registry_ = nullptr;
}
}
void DialMediaSinkServiceImpl::Start() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (dial_registry_)
return;
description_service_ = std::make_unique<DeviceDescriptionService>(
base::BindRepeating(
&DialMediaSinkServiceImpl::OnDeviceDescriptionAvailable,
base::Unretained(this)),
base::BindRepeating(&DialMediaSinkServiceImpl::OnDeviceDescriptionError,
base::Unretained(this)));
app_discovery_service_ = std::make_unique<DialAppDiscoveryService>();
StartTimer();
dial_registry_ =
test_dial_registry_ ? test_dial_registry_ : DialRegistry::GetInstance();
dial_registry_->RegisterObserver(this);
dial_registry_->OnListenerAdded();
}
void DialMediaSinkServiceImpl::OnUserGesture() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(dial_registry_);
dial_registry_->DiscoverNow();
RescanAppInfo();
}
DialAppDiscoveryService* DialMediaSinkServiceImpl::app_discovery_service() {
return app_discovery_service_.get();
}
DialMediaSinkServiceImpl::SinkQueryByAppSubscription
DialMediaSinkServiceImpl::StartMonitoringAvailableSinksForApp(
const std::string& app_name,
const SinkQueryByAppCallback& callback) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
auto& callback_list = sink_queries_[app_name];
if (!callback_list) {
callback_list = std::make_unique<SinkQueryByAppCallbackList>();
callback_list->set_removal_callback(base::BindRepeating(
&DialMediaSinkServiceImpl::MaybeRemoveSinkQueryCallbackList,
base::Unretained(this), app_name, callback_list.get()));
// Start checking if |app_name| is available on existing sinks.
for (const auto& sink : GetSinks())
FetchAppInfoForSink(sink.second, app_name);
}
return callback_list->Add(callback);
}
void DialMediaSinkServiceImpl::SetDialRegistryForTest(
DialRegistry* dial_registry) {
DCHECK(!test_dial_registry_);
test_dial_registry_ = dial_registry;
}
void DialMediaSinkServiceImpl::SetDescriptionServiceForTest(
std::unique_ptr<DeviceDescriptionService> description_service) {
description_service_ = std::move(description_service);
}
void DialMediaSinkServiceImpl::SetAppDiscoveryServiceForTest(
std::unique_ptr<DialAppDiscoveryService> app_discovery_service) {
app_discovery_service_ = std::move(app_discovery_service);
}
void DialMediaSinkServiceImpl::OnDiscoveryComplete() {
std::vector<MediaSinkInternal> sinks_to_update;
std::vector<MediaSinkInternal> sinks_to_remove;
for (const auto& sink : GetSinks()) {
if (!base::Contains(latest_sinks_, sink.first))
sinks_to_remove.push_back(sink.second);
}
for (const auto& latest_sink : latest_sinks_) {
// Sink is added or updated.
const MediaSinkInternal* sink = GetSinkById(latest_sink.first);
if (!sink || *sink != latest_sink.second)
sinks_to_update.push_back(latest_sink.second);
}
// Note: calling |AddOrUpdateSink()| or |RemoveSink()| here won't cause the
// discovery timer to fire again, since it is considered to be still running.
for (const auto& sink : sinks_to_update)
AddOrUpdateSink(sink);
for (const auto& sink : sinks_to_remove)
RemoveSink(sink);
// If discovered sinks are updated, then query results might have changed.
for (const auto& query : sink_queries_)
query.second->Notify(query.first);
MediaSinkServiceBase::OnDiscoveryComplete();
}
void DialMediaSinkServiceImpl::OnDialDeviceEvent(
const DialRegistry::DeviceList& devices) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
current_devices_ = devices;
latest_sinks_.clear();
description_service_->GetDeviceDescriptions(devices);
// Makes sure the timer fires even if there is no device.
StartTimer();
}
void DialMediaSinkServiceImpl::OnDialError(DialRegistry::DialErrorCode type) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (logger_.is_bound()) {
logger_->LogError(
mojom::LogCategory::kDiscovery, kLoggerComponent,
base::StringPrintf("DialErrorCode: %d", static_cast<int>(type)), "", "",
"");
}
}
void DialMediaSinkServiceImpl::OnDeviceDescriptionAvailable(
const DialDeviceData& device_data,
const ParsedDialDeviceDescription& description_data) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (!base::Contains(current_devices_, device_data)) {
return;
}
std::string processed_uuid =
MediaSinkInternal::ProcessDeviceUUID(description_data.unique_id);
MediaSink::Id sink_id =
base::StringPrintf("dial:<%s>", processed_uuid.c_str());
MediaSink sink(sink_id, description_data.friendly_name, SinkIconType::GENERIC,
MediaRouteProviderId::DIAL);
DialSinkExtraData extra_data;
extra_data.app_url = description_data.app_url;
extra_data.model_name = description_data.model_name;
std::string ip_address = device_data.device_description_url().host();
if (!extra_data.ip_address.AssignFromIPLiteral(ip_address)) {
return;
}
MediaSinkInternal dial_sink(sink, extra_data);
latest_sinks_.insert_or_assign(sink_id, dial_sink);
StartTimer();
if (!IsDiscoveryOnly(description_data.model_name)) {
// Start checking if all registered apps are available on |dial_sink|.
for (const auto& query : sink_queries_)
FetchAppInfoForSink(dial_sink, query.first);
}
}
void DialMediaSinkServiceImpl::OnDeviceDescriptionError(
const DialDeviceData& device,
const std::string& error_message) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (logger_.is_bound()) {
logger_->LogError(mojom::LogCategory::kDiscovery, kLoggerComponent,
base::StrCat({"Device id: ", device.device_id(),
", error message: ", error_message}),
"", "", "");
}
}
void DialMediaSinkServiceImpl::OnAppInfoParseCompleted(
const std::string& sink_id,
const std::string& app_name,
DialAppInfoResult result) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
SinkAppStatus app_status = GetSinkAppStatusFromResponse(result);
if (app_status == SinkAppStatus::kUnknown) {
return;
}
SinkAppStatus old_status = GetAppStatus(sink_id, app_name);
SetAppStatus(sink_id, app_name, app_status);
if (old_status == app_status)
return;
// The sink might've been removed before the parse was complete. In that case
// the callbacks won't be notified, but the app status will be saved for later
// use.
if (!GetSinkById(sink_id))
return;
auto query_it = sink_queries_.find(app_name);
if (query_it != sink_queries_.end())
query_it->second->Notify(app_name);
}
void DialMediaSinkServiceImpl::FetchAppInfoForSink(
const MediaSinkInternal& dial_sink,
const std::string& app_name) {
std::string model_name = dial_sink.dial_data().model_name;
if (IsDiscoveryOnly(model_name)) {
return;
}
std::string sink_id = dial_sink.sink().id();
SinkAppStatus app_status = GetAppStatus(sink_id, app_name);
if (app_status != SinkAppStatus::kUnknown)
return;
app_discovery_service_->FetchDialAppInfo(
dial_sink, app_name,
base::BindOnce(&DialMediaSinkServiceImpl::OnAppInfoParseCompleted,
base::Unretained(this)));
}
void DialMediaSinkServiceImpl::RescanAppInfo() {
for (const auto& sink : GetSinks()) {
std::string model_name = sink.second.dial_data().model_name;
if (IsDiscoveryOnly(model_name)) {
continue;
}
for (const auto& query : sink_queries_)
FetchAppInfoForSink(sink.second, query.first);
}
}
SinkAppStatus DialMediaSinkServiceImpl::GetAppStatus(
const std::string& sink_id,
const std::string& app_name) const {
std::string key = sink_id + ':' + app_name;
auto status_it = app_statuses_.find(key);
return status_it == app_statuses_.end() ? SinkAppStatus::kUnknown
: status_it->second;
}
void DialMediaSinkServiceImpl::SetAppStatus(const std::string& sink_id,
const std::string& app_name,
SinkAppStatus app_status) {
std::string key = sink_id + ':' + app_name;
app_statuses_[key] = app_status;
}
void DialMediaSinkServiceImpl::RecordDeviceCounts() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
metrics_.RecordDeviceCountsIfNeeded(GetSinks().size(),
current_devices_.size());
}
void DialMediaSinkServiceImpl::MaybeRemoveSinkQueryCallbackList(
const std::string& app_name,
SinkQueryByAppCallbackList* callback_list) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// There are no more profiles monitoring |app_name|.
if (callback_list->empty())
sink_queries_.erase(app_name);
}
std::vector<MediaSinkInternal> DialMediaSinkServiceImpl::GetAvailableSinks(
const std::string& app_name) const {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
std::vector<MediaSinkInternal> sinks;
for (const auto& sink : GetSinks()) {
if (GetAppStatus(sink.first, app_name) == SinkAppStatus::kAvailable)
sinks.push_back(sink.second);
}
return sinks;
}
void DialMediaSinkServiceImpl::BindLogger(
mojo::PendingRemote<mojom::Logger> pending_remote) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
logger_.Bind(std::move(pending_remote));
}
} // namespace media_router
| 33.950867 | 84 | 0.736358 | [
"vector",
"model"
] |
cb59f63b1d37a8852c535f9f1676629900786606 | 6,648 | cc | C++ | src/appMain/main.cc | russjohnson09/sdl_core | 9de7f1456f1807ae97348f774f7eead0ee92fd6d | [
"BSD-3-Clause"
] | null | null | null | src/appMain/main.cc | russjohnson09/sdl_core | 9de7f1456f1807ae97348f774f7eead0ee92fd6d | [
"BSD-3-Clause"
] | 2 | 2020-04-24T07:00:41.000Z | 2020-04-24T07:39:33.000Z | src/appMain/main.cc | russjohnson09/sdl_core | 9de7f1456f1807ae97348f774f7eead0ee92fd6d | [
"BSD-3-Clause"
] | 1 | 2020-07-31T15:36:12.000Z | 2020-07-31T15:36:12.000Z | /*
* Copyright (c) 2016, Ford Motor Company
* 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 Ford Motor Company nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <signal.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <fstream> // cpplint: Streams are highly discouraged.
#include <iostream> // cpplint: Streams are highly discouraged.
#include <memory>
#include <string>
#include <vector>
// ----------------------------------------------------------------------------
#ifdef ENABLE_LOG
#include "utils/log_message_loop_thread.h"
#endif // ENABLE_LOG
#include "utils/logger.h"
#include "appMain/life_cycle_impl.h"
#include "signal_handlers.h"
#include "config_profile/profile.h"
#include "utils/appenders_loader.h"
#include "utils/signals.h"
#include "utils/system.h"
#if defined(EXTENDED_MEDIA_MODE)
#include <gst/gst.h>
#endif
#include "media_manager/media_manager_impl.h"
CREATE_LOGGERPTR_GLOBAL(logger_, "SDLMain")
namespace {
const std::string kBrowser = "/usr/bin/chromium-browser";
const std::string kBrowserName = "chromium-browser";
const std::string kBrowserParams = "--auth-schemes=basic,digest,ntlm";
const std::string kLocalHostAddress = "127.0.0.1";
#ifdef WEB_HMI
/**
* Initialize HTML based HMI.
* @return true if success otherwise false.
*/
bool InitHmi(std::string hmi_link) {
struct stat sb;
if (stat(hmi_link.c_str(), &sb) == -1) {
LOG4CXX_FATAL(logger_, "HMI index file " << hmi_link << " doesn't exist!");
return false;
}
return utils::System(kBrowser, kBrowserName)
.Add(kBrowserParams)
.Add(hmi_link)
.Execute();
}
#endif // WEB_HMI
} // namespace
/**
* \brief Entry point of the program.
* \param argc number of argument
* \param argv array of arguments
* \return EXIT_SUCCESS or EXIT_FAILURE
*/
int32_t main(int32_t argc, char** argv) {
// Unsubscribe once for all threads
if (!utils::Signals::UnsubscribeFromTermination()) {
// Can't use internal logger here
exit(EXIT_FAILURE);
}
// --------------------------------------------------------------------------
// Components initialization
profile::Profile profile_instance;
std::unique_ptr<main_namespace::LifeCycle> life_cycle(
new main_namespace::LifeCycleImpl(profile_instance));
if ((argc > 1) && (0 != argv)) {
profile_instance.set_config_file_name(argv[1]);
} else {
profile_instance.set_config_file_name("smartDeviceLink.ini");
}
// Reading profile offsets for real-time signals dedicated
// for Low Voltage functionality handling
main_namespace::LowVoltageSignalsOffset signals_offset{
profile_instance.low_voltage_signal_offset(),
profile_instance.wake_up_signal_offset(),
profile_instance.ignition_off_signal_offset()};
// Unsubscribe once for all threads
// except specific thread dedicated for
// Low Voltage signals handling
// Thread will be created later
if (!utils::Signals::UnsubscribeFromLowVoltageSignals(signals_offset)) {
// Can't use internal logger here
exit(EXIT_FAILURE);
}
// --------------------------------------------------------------------------
// Logger initialization
INIT_LOGGER("log4cxx.properties", profile_instance.logs_enabled());
threads::Thread::SetNameForId(threads::Thread::CurrentId(), "MainThread");
if (!utils::appenders_loader.Loaded()) {
LOG4CXX_ERROR(logger_,
"Appenders plugin not loaded, file logging disabled");
}
LOG4CXX_INFO(logger_, "Application started!");
LOG4CXX_INFO(logger_, "SDL version: " << profile_instance.sdl_version());
// Check if no error values were read from config file
if (profile_instance.ErrorOccured()) {
LOG4CXX_FATAL(logger_, profile_instance.ErrorDescription());
FLUSH_LOGGER();
DEINIT_LOGGER();
exit(EXIT_FAILURE);
}
// --------------------------------------------------------------------------
// Components initialization
if (!life_cycle->StartComponents()) {
LOG4CXX_FATAL(logger_, "Failed to start components");
life_cycle->StopComponents();
DEINIT_LOGGER();
exit(EXIT_FAILURE);
}
LOG4CXX_INFO(logger_, "Components Started");
// --------------------------------------------------------------------------
// Third-Party components initialization.
if (!life_cycle->InitMessageSystem()) {
LOG4CXX_FATAL(logger_, "Failed to init message system");
life_cycle->StopComponents();
DEINIT_LOGGER();
_exit(EXIT_FAILURE);
}
LOG4CXX_INFO(logger_, "InitMessageBroker successful");
if (profile_instance.launch_hmi()) {
if (profile_instance.server_address() == kLocalHostAddress) {
LOG4CXX_INFO(logger_, "Start HMI on localhost");
#ifdef WEB_HMI
if (!InitHmi(profile_instance.link_to_web_hmi())) {
LOG4CXX_INFO(logger_, "InitHmi successful");
} else {
LOG4CXX_WARN(logger_, "Failed to init HMI");
}
#endif
}
}
// --------------------------------------------------------------------------
life_cycle->Run();
LOG4CXX_INFO(logger_, "Stop SDL due to caught signal");
life_cycle->StopComponents();
LOG4CXX_INFO(logger_, "Application has been stopped successfuly");
DEINIT_LOGGER();
return EXIT_SUCCESS;
}
| 33.074627 | 79 | 0.677046 | [
"vector"
] |
cb5f70a51c64e6dd7e42cb3d480a494a48b1a890 | 14,915 | hpp | C++ | SYCL/ESIMD/esimd_test_utils.hpp | gmlueck/llvm-test-suite | 7ff842b8fec970561fed78c9347e496538cf74f5 | [
"Apache-2.0"
] | null | null | null | SYCL/ESIMD/esimd_test_utils.hpp | gmlueck/llvm-test-suite | 7ff842b8fec970561fed78c9347e496538cf74f5 | [
"Apache-2.0"
] | null | null | null | SYCL/ESIMD/esimd_test_utils.hpp | gmlueck/llvm-test-suite | 7ff842b8fec970561fed78c9347e496538cf74f5 | [
"Apache-2.0"
] | null | null | null | //==--------- esimd_test_utils.hpp - DPC++ ESIMD on-device test utilities --==//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include <CL/sycl.hpp>
#define NOMINMAX
#include <algorithm>
#include <chrono>
#include <cstring>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
using namespace cl::sycl;
namespace esimd_test {
// This is the class provided to SYCL runtime by the application to decide
// on which device to run, or whether to run at all.
// When selecting a device, SYCL runtime first takes (1) a selector provided by
// the program or a default one and (2) the set of all available devices. Then
// it passes each device to the '()' operator of the selector. Device, for
// which '()' returned the highest number, is selected. If a negative number
// was returned for all devices, then the selection process will cause an
// exception.
class ESIMDSelector : public device_selector {
// Require GPU device unless HOST is requested in SYCL_DEVICE_FILTER env
virtual int operator()(const device &device) const {
if (const char *dev_filter = getenv("SYCL_DEVICE_FILTER")) {
std::string filter_string(dev_filter);
if (filter_string.find("gpu") != std::string::npos)
return device.is_gpu() ? 1000 : -1;
if (filter_string.find("host") != std::string::npos)
return device.is_host() ? 1000 : -1;
std::cerr
<< "Supported 'SYCL_DEVICE_FILTER' env var values are 'gpu' and "
"'host', '"
<< filter_string << "' does not contain such substrings.\n";
return -1;
}
// If "SYCL_DEVICE_FILTER" not defined, only allow gpu device
return device.is_gpu() ? 1000 : -1;
}
};
inline auto createExceptionHandler() {
return [](exception_list l) {
for (auto ep : l) {
try {
std::rethrow_exception(ep);
} catch (sycl::exception &e0) {
std::cout << "sycl::exception: " << e0.what() << std::endl;
} catch (std::exception &e) {
std::cout << "std::exception: " << e.what() << std::endl;
} catch (...) {
std::cout << "generic exception\n";
}
}
};
}
template <typename T>
std::vector<T> read_binary_file(const char *fname, size_t num = 0) {
std::vector<T> vec;
std::ifstream ifs(fname, std::ios::in | std::ios::binary);
if (ifs.good()) {
ifs.unsetf(std::ios::skipws);
std::streampos file_size;
ifs.seekg(0, std::ios::end);
file_size = ifs.tellg();
ifs.seekg(0, std::ios::beg);
size_t max_num = file_size / sizeof(T);
vec.resize(num ? (std::min)(max_num, num) : max_num);
ifs.read(reinterpret_cast<char *>(vec.data()), vec.size() * sizeof(T));
}
return vec;
}
template <typename T>
bool write_binary_file(const char *fname, const std::vector<T> &vec,
size_t num = 0) {
std::ofstream ofs(fname, std::ios::out | std::ios::binary);
if (ofs.good()) {
ofs.write(reinterpret_cast<const char *>(&vec[0]),
(num ? num : vec.size()) * sizeof(T));
ofs.close();
}
return !ofs.bad();
}
template <typename T>
bool cmp_binary_files(const char *fname1, const char *fname2, T tolerance) {
const auto vec1 = read_binary_file<T>(fname1);
const auto vec2 = read_binary_file<T>(fname2);
if (vec1.size() != vec2.size()) {
std::cerr << fname1 << " size is " << vec1.size();
std::cerr << " whereas " << fname2 << " size is " << vec2.size()
<< std::endl;
return false;
}
for (size_t i = 0; i < vec1.size(); i++) {
if (abs(vec1[i] - vec2[i]) > tolerance) {
std::cerr << "Mismatch at " << i << ' ';
if (sizeof(T) == 1) {
std::cerr << (int)vec1[i] << " vs " << (int)vec2[i] << std::endl;
} else {
std::cerr << vec1[i] << " vs " << vec2[i] << std::endl;
}
return false;
}
}
return true;
}
// dump every element of sequence [first, last) to std::cout
template <typename ForwardIt> void dump_seq(ForwardIt first, ForwardIt last) {
using ValueT = typename std::iterator_traits<ForwardIt>::value_type;
std::copy(first, last, std::ostream_iterator<ValueT>{std::cout, " "});
std::cout << std::endl;
}
// Checks wether ranges [first, last) and [ref_first, ref_last) are equal.
// If a mismatch is found, dumps elements that differ and returns true,
// otherwise false is returned.
template <typename ForwardIt, typename RefForwardIt, typename BinaryPredicateT>
bool check_fail_seq(ForwardIt first, ForwardIt last, RefForwardIt ref_first,
RefForwardIt ref_last, BinaryPredicateT is_equal) {
auto mism = std::mismatch(first, last, ref_first, is_equal);
if (mism.first != last) {
std::cout << "mismatch: returned " << *mism.first << std::endl;
std::cout << " expected " << *mism.second << std::endl;
return true;
}
return false;
}
template <typename ForwardIt, typename RefForwardIt>
bool check_fail_seq(ForwardIt first, ForwardIt last, RefForwardIt ref_first,
RefForwardIt ref_last) {
return check_fail_seq(
first, last, ref_first, ref_last,
[](const auto &lhs, const auto &rhs) { return lhs == rhs; });
}
// analog to C++20 bit_cast
template <typename To, typename From,
typename std::enable_if<(sizeof(To) == sizeof(From)) &&
std::is_trivially_copyable<From>::value &&
std::is_trivial<To>::value,
int>::type = 0>
To bit_cast(const From &src) noexcept {
To dst;
std::memcpy(&dst, &src, sizeof(To));
return dst;
}
// Timer class for measuring elasped time
class Timer {
public:
Timer() : start_(std::chrono::steady_clock::now()) {}
double Elapsed() {
auto now = std::chrono::steady_clock::now();
return std::chrono::duration_cast<Duration>(now - start_).count();
}
private:
using Duration = std::chrono::duration<double>;
std::chrono::steady_clock::time_point start_;
};
// e0 is the first event, en is the last event
// find the time difference between the starting time of the e0 and
// the ending time of en, return micro-second
inline double report_time(const std::string &msg, event e0, event en) {
cl_ulong time_start =
e0.get_profiling_info<info::event_profiling::command_start>();
cl_ulong time_end =
en.get_profiling_info<info::event_profiling::command_end>();
double elapsed = (time_end - time_start) / 1e6;
// cerr << msg << elapsed << " msecs" << std::endl;
return elapsed;
}
void display_timing_stats(double const kernelTime,
unsigned int const uiNumberOfIterations,
double const overallTime) {
std::cout << "Number of iterations: " << uiNumberOfIterations << "\n";
std::cout << "[KernelTime]:" << kernelTime << "\n";
std::cout << "[OverallTime][Primary]:" << overallTime << "\n";
}
// Get signed integer of given byte size.
template <int N>
using int_type_t = std::conditional_t<
N == 1, int8_t,
std::conditional_t<
N == 2, int16_t,
std::conditional_t<N == 4, int32_t,
std::conditional_t<N == 8, int64_t, void>>>>;
enum class BinaryOp {
add,
sub,
mul,
div, // <-- only this and above are supported for floating point types
rem,
shl,
shr,
bit_or,
bit_and,
bit_xor, // <-- only this and above are supported for integer types
log_or, // only for simd_mask
log_and // only for simd_mask
};
enum class UnaryOp {
minus_minus_pref,
minus_minus_inf,
plus_plus_pref,
plus_plus_inf,
minus,
plus,
bit_not,
log_not
};
enum class CmpOp { lt, lte, eq, ne, gte, gt };
#define __bin_case(x, s) \
case BinaryOp::x: \
return s
#define __cmp_case(x, s) \
case CmpOp::x: \
return s
#define __un_case(x, s) \
case UnaryOp::x: \
return s
template <class OpClass> const char *Op2Str(OpClass op) {
if constexpr (std::is_same_v<OpClass, BinaryOp>) {
switch (op) {
__bin_case(add, "+");
__bin_case(sub, "-");
__bin_case(mul, "*");
__bin_case(div, "/");
__bin_case(rem, "%");
__bin_case(shl, "<<");
__bin_case(shr, ">>");
__bin_case(bit_or, "|");
__bin_case(bit_and, "&");
__bin_case(bit_xor, "^");
__bin_case(log_or, "||");
__bin_case(log_and, "&&");
}
} else if constexpr (std::is_same_v<OpClass, CmpOp>) {
switch (op) {
__cmp_case(lt, "<");
__cmp_case(lte, "<=");
__cmp_case(eq, "==");
__cmp_case(ne, "!=");
__cmp_case(gte, ">=");
__cmp_case(gt, ">");
}
} else if constexpr (std::is_same_v<OpClass, UnaryOp>) {
switch (op) {
__un_case(minus, "-x");
__un_case(minus_minus_pref, "--x");
__un_case(minus_minus_inf, "x--");
__un_case(plus, "+x");
__un_case(plus_plus_pref, "++x");
__un_case(plus_plus_inf, "x++");
__un_case(bit_not, "~x");
__un_case(log_not, "!x");
}
}
}
template <class OpClass, OpClass Op, class T1, class T2>
inline auto binary_op(T1 x, T2 y) {
if constexpr (std::is_same_v<OpClass, BinaryOp>) {
if constexpr (Op == BinaryOp::add)
return x + y;
else if constexpr (Op == BinaryOp::sub)
return x - y;
else if constexpr (Op == BinaryOp::mul)
return x * y;
else if constexpr (Op == BinaryOp::div)
return x / y;
else if constexpr (Op == BinaryOp::rem)
return x % y;
else if constexpr (Op == BinaryOp::shl)
return x << y;
else if constexpr (Op == BinaryOp::shr)
return x >> y;
else if constexpr (Op == BinaryOp::bit_or)
return x | y;
else if constexpr (Op == BinaryOp::bit_and)
return x & y;
else if constexpr (Op == BinaryOp::bit_xor)
return x ^ y;
else if constexpr (Op == BinaryOp::log_or)
return x || y;
else if constexpr (Op == BinaryOp::log_and)
return x && y;
} else if constexpr (std::is_same_v<OpClass, CmpOp>) {
if constexpr (Op == CmpOp::lt)
return x < y;
else if constexpr (Op == CmpOp::lte)
return x <= y;
else if constexpr (Op == CmpOp::eq)
return x == y;
else if constexpr (Op == CmpOp::ne)
return x != y;
else if constexpr (Op == CmpOp::gte)
return x >= y;
else if constexpr (Op == CmpOp::gt)
return x > y;
}
}
template <UnaryOp Op, class T> inline auto unary_op(T x) {
if constexpr (Op == UnaryOp::minus)
return -x;
else if constexpr (Op == UnaryOp::minus_minus_pref) {
--x;
return x;
} else if constexpr (Op == UnaryOp::minus_minus_inf) {
x--;
return x;
} else if constexpr (Op == UnaryOp::plus)
return +x;
else if constexpr (Op == UnaryOp::plus_plus_pref) {
++x;
return x;
} else if constexpr (Op == UnaryOp::plus_plus_inf) {
x++;
return x;
} else if constexpr (Op == UnaryOp::bit_not)
return ~x;
else if constexpr (Op == UnaryOp::log_not)
return !x;
}
template <int From, int To> struct ConstexprForLoop {
template <class Action> static inline void unroll(Action act) {
if constexpr (From < To) {
act.template run<From>();
}
if constexpr (From < To - 1) {
ConstexprForLoop<From + 1, To>::unroll(act);
}
}
};
template <class OpClass, OpClass... Ops> struct OpSeq {
static constexpr size_t size = sizeof...(Ops);
template <int I> static constexpr OpClass get() {
std::array<OpClass, size> arr = {Ops...};
return arr[I];
}
};
template <BinaryOp... Ops> using BinaryOpSeq = OpSeq<BinaryOp, Ops...>;
static constexpr BinaryOpSeq<BinaryOp::add, BinaryOp::sub, BinaryOp::mul,
BinaryOp::div>
ArithBinaryOps{};
static constexpr BinaryOpSeq<BinaryOp::add, BinaryOp::sub, BinaryOp::mul,
BinaryOp::div, BinaryOp::rem, BinaryOp::shl,
BinaryOp::shr, BinaryOp::bit_or, BinaryOp::bit_and,
BinaryOp::bit_xor>
IntBinaryOps{};
static constexpr BinaryOpSeq<BinaryOp::add, BinaryOp::sub, BinaryOp::mul,
BinaryOp::div, BinaryOp::rem, BinaryOp::bit_or,
BinaryOp::bit_and, BinaryOp::bit_xor>
IntBinaryOpsNoShift{};
static constexpr OpSeq<CmpOp, CmpOp::lt, CmpOp::lte, CmpOp::eq, CmpOp::ne,
CmpOp::gte, CmpOp::gt>
CmpOps{};
static constexpr OpSeq<UnaryOp, UnaryOp::minus, UnaryOp::minus_minus_pref,
UnaryOp::minus_minus_inf, UnaryOp::plus,
UnaryOp::plus_plus_pref, UnaryOp::plus_plus_inf,
UnaryOp::bit_not, UnaryOp::log_not>
UnaryOps{};
// Binary operations iteration
template <class T1, class T2, class F, class OpClass, OpClass... Ops>
struct ApplyBinaryOpAction {
T1 x;
T2 y;
F f;
ApplyBinaryOpAction(T1 x, T2 y, F f) : x(x), y(y), f(f) {}
template <int OpIndex> inline void run() {
constexpr OpClass arr[] = {Ops...};
constexpr auto op = arr[OpIndex];
f(binary_op<OpClass, op>(x, y), op, OpIndex);
}
};
template <class T1, class T2, class F, class OpClass, OpClass... Ops>
inline void apply_ops(OpSeq<OpClass, Ops...> ops, T1 x, T2 y, F f) {
ApplyBinaryOpAction<T1, T2, F, OpClass, Ops...> act(x, y, f);
ConstexprForLoop<0, sizeof...(Ops)>::unroll(act);
}
// Unary operations iteration
template <class T, class F, UnaryOp... Ops> struct ApplyUnaryOpAction {
T x;
F f;
ApplyUnaryOpAction(T x, F f) : x(x), f(f) {}
template <int OpIndex> inline void run() {
constexpr UnaryOp arr[] = {Ops...};
constexpr auto op = arr[OpIndex];
f(unary_op<op>(x), op, OpIndex);
}
};
template <class T, class F, UnaryOp... Ops>
inline void apply_unary_ops(OpSeq<UnaryOp, Ops...> ops, T x, F f) {
ApplyUnaryOpAction<T, F, Ops...> act(x, f);
ConstexprForLoop<0, sizeof...(Ops)>::unroll(act);
}
// All operations
template <class F, class OpClass, OpClass... Ops> struct IterateOpAction {
F f;
IterateOpAction(F f) : f(f) {}
template <int OpIndex> inline void run() {
constexpr OpClass arr[] = {Ops...};
constexpr auto op = arr[OpIndex];
f(op);
}
};
template <class F, class OpClass, OpClass... Ops>
inline void iterate_ops(OpSeq<OpClass, Ops...> ops, F f) {
IterateOpAction<F, OpClass, Ops...> act(f);
ConstexprForLoop<0, sizeof...(Ops)>::unroll(act);
}
} // namespace esimd_test
| 32.213823 | 80 | 0.595307 | [
"vector"
] |
cb60e95af6f794b90769ccd2294d9442e018ae44 | 1,995 | hpp | C++ | lib/builder/BuilderBase.hpp | mensinda/BVHTest | 46e24818f623797c78f2e094434213e3728a114c | [
"Apache-2.0"
] | 4 | 2019-03-09T16:35:00.000Z | 2022-01-12T06:32:05.000Z | lib/builder/BuilderBase.hpp | mensinda/BVHTest | 46e24818f623797c78f2e094434213e3728a114c | [
"Apache-2.0"
] | null | null | null | lib/builder/BuilderBase.hpp | mensinda/BVHTest | 46e24818f623797c78f2e094434213e3728a114c | [
"Apache-2.0"
] | 1 | 2020-09-09T15:47:13.000Z | 2020-09-09T15:47:13.000Z | /*
* Copyright (C) 2018 Daniel Mensinger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "base/BVH.hpp"
#include "base/Command.hpp"
namespace BVHTest::builder {
class BuilderBase : public base::Command {
public:
typedef base::TriWithBB TYPE;
typedef TYPE const & TCREF;
typedef std::vector<TYPE>::iterator ITER;
struct BuildRes {
uint32_t vecPtr;
base::AABB bbox;
};
private:
double vCostInner = 1.2f;
double vCostTri = 1.0f;
protected:
virtual ITER split(ITER _begin, ITER _end, uint32_t _level);
BuildRes build(ITER _begin,
ITER _end,
BVHTest::base::BVH &_bvh,
uint32_t _parent = 0,
bool _isLeftChild = 0,
uint32_t _level = 0);
public:
BuilderBase() = default;
virtual ~BuilderBase();
inline base::CommandType getType() const override { return base::CommandType::BVH_BUILD; }
inline uint64_t getRequiredCommands() const override { return static_cast<uint64_t>(base::CommandType::IMPORT); }
std::vector<base::TriWithBB> boundingVolumesFromMesh(base::Mesh const &_mesh);
void fromJSON(const json &_j) override;
json toJSON() const override;
inline double getCostInner() const noexcept { return vCostInner; }
inline double getCostTri() const noexcept { return vCostTri; }
};
} // namespace BVHTest::builder
| 30.227273 | 115 | 0.659649 | [
"mesh",
"vector"
] |
cb61928e9ef6d4e6275203b4d6181470807f247f | 7,218 | hpp | C++ | src/Graphics/Renderer/Renderer.hpp | ScaryBoxStudios/TheRoom | 880c8730cb5c271def472df76fa655df1970b94b | [
"MIT"
] | 1 | 2015-11-12T11:40:45.000Z | 2015-11-12T11:40:45.000Z | src/Graphics/Renderer/Renderer.hpp | ScaryBoxStudios/TheRoom | 880c8730cb5c271def472df76fa655df1970b94b | [
"MIT"
] | null | null | null | src/Graphics/Renderer/Renderer.hpp | ScaryBoxStudios/TheRoom | 880c8730cb5c271def472df76fa655df1970b94b | [
"MIT"
] | null | null | null | /*********************************************************************************************************************/
/* /===-_---~~~~~~~~~------____ */
/* |===-~___ _,-' */
/* -==\\ `//~\\ ~~~~`---.___.-~~ */
/* ______-==| | | \\ _-~` */
/* __--~~~ ,-/-==\\ | | `\ ,' */
/* _-~ /' | \\ / / \ / */
/* .' / | \\ /' / \ /' */
/* / ____ / | \`\.__/-~~ ~ \ _ _/' / \/' */
/* /-'~ ~~~~~---__ | ~-/~ ( ) /' _--~` */
/* \_| / _) ; ), __--~~ */
/* '~~--_/ _-~/- / \ '-~ \ */
/* {\__--_/} / \\_>- )<__\ \ */
/* /' (_/ _-~ | |__>--<__| | */
/* |0 0 _/) )-~ | |__>--<__| | */
/* / /~ ,_/ / /__>---<__/ | */
/* o o _// /-~_>---<__-~ / */
/* (^(~ /~_>---<__- _-~ */
/* ,/| /__>--<__/ _-~ */
/* ,//('( |__>--<__| / .----_ */
/* ( ( ')) |__>--<__| | /' _---_~\ */
/* `-)) )) ( |__>--<__| | /' / ~\`\ */
/* ,/,'//( ( \__>--<__\ \ /' // || */
/* ,( ( ((, )) ~-__>--<_~-_ ~--____---~' _/'/ /' */
/* `~/ )` ) ,/| ~-_~>--<_/-__ __-~ _/ */
/* ._-~//( )/ )) ` ~~-'_/_/ /~~~~~~~__--~ */
/* ;'( ')/ ,)( ~~~~~~~~~~ */
/* ' ') '( (/ */
/* ' ' ` */
/*********************************************************************************************************************/
#ifndef _RENDERER_HPP_
#define _RENDERER_HPP_
#include <memory>
#include <vector>
#include "GBuffer.hpp"
#include "Light.hpp"
#include "ShadowRenderer.hpp"
#include "../Scene/Transform.hpp"
#include "../Resource/MaterialStore.hpp"
#include "../../Util/WarnGuard.hpp"
WARN_GUARD_ON
#include <glm/glm.hpp>
WARN_GUARD_OFF
class Renderer
{
public:
struct IntMesh
{
Transform transformation;
GLuint vaoId,
eboId,
numIndices;
};
struct IntMaterial
{
GLuint diffTexId,
specTexId,
nmapTexId,
matIndex;
bool useNormalMap;
};
using MaterialVecEntry = std::pair<IntMaterial, std::vector<IntMesh>>;
struct IntForm
{
std::vector<MaterialVecEntry> materials;
GLuint skyboxId = 0;
GLuint irrMapId = 0;
GLuint radMapId = 0;
};
struct ShaderPrograms
{
ShaderProgram geometryPassProg;
ShaderProgram lightPassProg;
};
/*! Initializes the renderer */
void Init(int width, int height, std::unique_ptr<ShaderPrograms> shdrProgs);
/*! Called when window is resized */
void Resize(int width, int height);
/*! Called when updating the game state */
void Update(float dt);
/*! Called when rendering the current frame */
void Render(float interpolation, const IntForm& intForm);
/*! Deinitializes the renderer */
void Shutdown();
/*! Sets the various data stores that hold the GPU handles to data */
void SetDataStores(MaterialStore* matStore);
/*! Sets the view matrix */
void SetView(const glm::mat4& view);
/*! Sets the used shader programs */
void SetShaderPrograms(std::unique_ptr<ShaderPrograms> shdrProgs);
/*! Retrieves the renderer's Lights */
Lights& GetLights();
/*! Retrieves the renderer's cached projection matrix */
const glm::mat4 GetProjection() const;
/*! Retrieves various internal texture handles */
// Array texture size - channel number - texture
using TextureTarget = std::tuple<std::uint8_t, std::uint8_t, GLuint>;
const std::vector<TextureTarget> GetTextureTargets() const;
private:
// Performs the geometry pass rendering step
void GeometryPass(float interpolation, const IntForm& intForm);
// Performs the light pass rendering step
void LightPass(float interpolation, const IntForm& intForm);
// Performs a stencil pass
void StencilPass(const PointLight& pLight);
// The projection matrix
glm::mat4 mProjection;
// The view matrix
glm::mat4 mView;
// The screen size
int mScreenWidth, mScreenHeight;
// The lights that are rendered
Lights mLights;
// References to various data stores
MaterialStore* mMaterialStore;
// Shader programIds of the geometry pass and the lighting pass
std::unique_ptr<ShaderPrograms> mShdrProgs;
// The GBuffer used by the deffered rendering steps
std::unique_ptr<GBuffer> mGBuffer;
// The null program used by the stencil passes
std::unique_ptr<ShaderProgram> mNullProgram;
// The shadow map rendering utility
ShadowRenderer mShadowRenderer;
// Uniform Buffer objects
GLuint mUboMatrices;
};
#endif // ! _RENDERER_HPP_
| 45.1125 | 119 | 0.321142 | [
"geometry",
"render",
"vector",
"transform"
] |
cb61caa46ccebcfa015802d4eeaa688ae5965e1c | 11,644 | cpp | C++ | grid-test/export/macos/obj/src/flixel/util/FlxPool_flixel_math_FlxPoint.cpp | VehpuS/learning-haxe-and-haxeflixel | cb18c074720656797beed7333eeaced2cf323337 | [
"Apache-2.0"
] | null | null | null | grid-test/export/macos/obj/src/flixel/util/FlxPool_flixel_math_FlxPoint.cpp | VehpuS/learning-haxe-and-haxeflixel | cb18c074720656797beed7333eeaced2cf323337 | [
"Apache-2.0"
] | null | null | null | grid-test/export/macos/obj/src/flixel/util/FlxPool_flixel_math_FlxPoint.cpp | VehpuS/learning-haxe-and-haxeflixel | cb18c074720656797beed7333eeaced2cf323337 | [
"Apache-2.0"
] | null | null | null | // Generated by Haxe 4.1.4
#include <hxcpp.h>
#ifndef INCLUDED_Type
#include <Type.h>
#endif
#ifndef INCLUDED_flixel_math_FlxPoint
#include <flixel/math/FlxPoint.h>
#endif
#ifndef INCLUDED_flixel_util_FlxPool_flixel_math_FlxPoint
#include <flixel/util/FlxPool_flixel_math_FlxPoint.h>
#endif
#ifndef INCLUDED_flixel_util_IFlxDestroyable
#include <flixel/util/IFlxDestroyable.h>
#endif
#ifndef INCLUDED_flixel_util_IFlxPool
#include <flixel/util/IFlxPool.h>
#endif
#ifndef INCLUDED_flixel_util_IFlxPooled
#include <flixel/util/IFlxPooled.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_3dc7f803120ba5a4_12_new,"flixel.util.FlxPool_flixel_math_FlxPoint","new",0x4abdd86f,"flixel.util.FlxPool_flixel_math_FlxPoint.new","flixel/util/FlxPool.hx",12,0xdd4de86a)
HX_LOCAL_STACK_FRAME(_hx_pos_3dc7f803120ba5a4_31_get,"flixel.util.FlxPool_flixel_math_FlxPoint","get",0x4ab888a5,"flixel.util.FlxPool_flixel_math_FlxPoint.get","flixel/util/FlxPool.hx",31,0xdd4de86a)
HX_LOCAL_STACK_FRAME(_hx_pos_3dc7f803120ba5a4_42_put,"flixel.util.FlxPool_flixel_math_FlxPoint","put",0x4abf6ade,"flixel.util.FlxPool_flixel_math_FlxPoint.put","flixel/util/FlxPool.hx",42,0xdd4de86a)
HX_LOCAL_STACK_FRAME(_hx_pos_3dc7f803120ba5a4_56_putUnsafe,"flixel.util.FlxPool_flixel_math_FlxPoint","putUnsafe",0xf57edda4,"flixel.util.FlxPool_flixel_math_FlxPoint.putUnsafe","flixel/util/FlxPool.hx",56,0xdd4de86a)
HX_LOCAL_STACK_FRAME(_hx_pos_3dc7f803120ba5a4_65_preAllocate,"flixel.util.FlxPool_flixel_math_FlxPoint","preAllocate",0x522a790f,"flixel.util.FlxPool_flixel_math_FlxPoint.preAllocate","flixel/util/FlxPool.hx",65,0xdd4de86a)
HX_LOCAL_STACK_FRAME(_hx_pos_3dc7f803120ba5a4_72_clear,"flixel.util.FlxPool_flixel_math_FlxPoint","clear",0x8762db5c,"flixel.util.FlxPool_flixel_math_FlxPoint.clear","flixel/util/FlxPool.hx",72,0xdd4de86a)
HX_LOCAL_STACK_FRAME(_hx_pos_3dc7f803120ba5a4_81_get_length,"flixel.util.FlxPool_flixel_math_FlxPoint","get_length",0xb3eaac80,"flixel.util.FlxPool_flixel_math_FlxPoint.get_length","flixel/util/FlxPool.hx",81,0xdd4de86a)
namespace flixel{
namespace util{
void FlxPool_flixel_math_FlxPoint_obj::__construct(::hx::Class classObj){
HX_STACKFRAME(&_hx_pos_3dc7f803120ba5a4_12_new)
HXLINE( 23) this->_count = 0;
HXLINE( 16) this->_pool = ::Array_obj< ::Dynamic>::__new(0);
HXLINE( 27) this->_class = classObj;
}
Dynamic FlxPool_flixel_math_FlxPoint_obj::__CreateEmpty() { return new FlxPool_flixel_math_FlxPoint_obj; }
void *FlxPool_flixel_math_FlxPoint_obj::_hx_vtable = 0;
Dynamic FlxPool_flixel_math_FlxPoint_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< FlxPool_flixel_math_FlxPoint_obj > _hx_result = new FlxPool_flixel_math_FlxPoint_obj();
_hx_result->__construct(inArgs[0]);
return _hx_result;
}
bool FlxPool_flixel_math_FlxPoint_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x0502f3c1;
}
static ::flixel::util::IFlxPool_obj _hx_flixel_util_FlxPool_flixel_math_FlxPoint__hx_flixel_util_IFlxPool= {
( void (::hx::Object::*)(int))&::flixel::util::FlxPool_flixel_math_FlxPoint_obj::preAllocate,
( ::cpp::VirtualArray (::hx::Object::*)())&::flixel::util::FlxPool_flixel_math_FlxPoint_obj::clear_36f85899,
};
::cpp::VirtualArray FlxPool_flixel_math_FlxPoint_obj::clear_36f85899() {
return clear();
}
void *FlxPool_flixel_math_FlxPoint_obj::_hx_getInterface(int inHash) {
switch(inHash) {
case (int)0x5a90a383: return &_hx_flixel_util_FlxPool_flixel_math_FlxPoint__hx_flixel_util_IFlxPool;
}
#ifdef HXCPP_SCRIPTABLE
return super::_hx_getInterface(inHash);
#else
return 0;
#endif
}
::flixel::math::FlxPoint FlxPool_flixel_math_FlxPoint_obj::get(){
HX_STACKFRAME(&_hx_pos_3dc7f803120ba5a4_31_get)
HXLINE( 32) if ((this->_count == 0)) {
HXLINE( 34) return ( ( ::flixel::math::FlxPoint)(::Type_obj::createInstance(this->_class,::cpp::VirtualArray_obj::__new(0))) );
}
HXLINE( 36) return this->_pool->__get(--this->_count).StaticCast< ::flixel::math::FlxPoint >();
}
HX_DEFINE_DYNAMIC_FUNC0(FlxPool_flixel_math_FlxPoint_obj,get,return )
void FlxPool_flixel_math_FlxPoint_obj::put( ::flixel::math::FlxPoint obj){
HX_STACKFRAME(&_hx_pos_3dc7f803120ba5a4_42_put)
HXDLIN( 42) if (::hx::IsNotNull( obj )) {
HXLINE( 44) int i = this->_pool->indexOf(obj,null());
HXLINE( 46) bool _hx_tmp;
HXDLIN( 46) if ((i != -1)) {
HXLINE( 46) _hx_tmp = (i >= this->_count);
}
else {
HXLINE( 46) _hx_tmp = true;
}
HXDLIN( 46) if (_hx_tmp) {
HXLINE( 48) obj->destroy();
HXLINE( 49) this->_pool[this->_count++] = obj;
}
}
}
HX_DEFINE_DYNAMIC_FUNC1(FlxPool_flixel_math_FlxPoint_obj,put,(void))
void FlxPool_flixel_math_FlxPoint_obj::putUnsafe( ::flixel::math::FlxPoint obj){
HX_STACKFRAME(&_hx_pos_3dc7f803120ba5a4_56_putUnsafe)
HXDLIN( 56) if (::hx::IsNotNull( obj )) {
HXLINE( 58) obj->destroy();
HXLINE( 59) this->_pool[this->_count++] = obj;
}
}
HX_DEFINE_DYNAMIC_FUNC1(FlxPool_flixel_math_FlxPoint_obj,putUnsafe,(void))
void FlxPool_flixel_math_FlxPoint_obj::preAllocate(int numObjects){
HX_STACKFRAME(&_hx_pos_3dc7f803120ba5a4_65_preAllocate)
HXDLIN( 65) while(true){
HXDLIN( 65) numObjects = (numObjects - 1);
HXDLIN( 65) if (!(((numObjects + 1) > 0))) {
HXDLIN( 65) goto _hx_goto_4;
}
HXLINE( 67) this->_pool[this->_count++] = ( ( ::flixel::math::FlxPoint)(::Type_obj::createInstance(this->_class,::cpp::VirtualArray_obj::__new(0))) );
}
_hx_goto_4:;
}
HX_DEFINE_DYNAMIC_FUNC1(FlxPool_flixel_math_FlxPoint_obj,preAllocate,(void))
::Array< ::Dynamic> FlxPool_flixel_math_FlxPoint_obj::clear(){
HX_STACKFRAME(&_hx_pos_3dc7f803120ba5a4_72_clear)
HXLINE( 73) this->_count = 0;
HXLINE( 74) ::Array< ::Dynamic> oldPool = this->_pool;
HXLINE( 75) this->_pool = ::Array_obj< ::Dynamic>::__new(0);
HXLINE( 76) return oldPool;
}
HX_DEFINE_DYNAMIC_FUNC0(FlxPool_flixel_math_FlxPoint_obj,clear,return )
int FlxPool_flixel_math_FlxPoint_obj::get_length(){
HX_STACKFRAME(&_hx_pos_3dc7f803120ba5a4_81_get_length)
HXDLIN( 81) return this->_count;
}
HX_DEFINE_DYNAMIC_FUNC0(FlxPool_flixel_math_FlxPoint_obj,get_length,return )
::hx::ObjectPtr< FlxPool_flixel_math_FlxPoint_obj > FlxPool_flixel_math_FlxPoint_obj::__new(::hx::Class classObj) {
::hx::ObjectPtr< FlxPool_flixel_math_FlxPoint_obj > __this = new FlxPool_flixel_math_FlxPoint_obj();
__this->__construct(classObj);
return __this;
}
::hx::ObjectPtr< FlxPool_flixel_math_FlxPoint_obj > FlxPool_flixel_math_FlxPoint_obj::__alloc(::hx::Ctx *_hx_ctx,::hx::Class classObj) {
FlxPool_flixel_math_FlxPoint_obj *__this = (FlxPool_flixel_math_FlxPoint_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(FlxPool_flixel_math_FlxPoint_obj), true, "flixel.util.FlxPool_flixel_math_FlxPoint"));
*(void **)__this = FlxPool_flixel_math_FlxPoint_obj::_hx_vtable;
__this->__construct(classObj);
return __this;
}
FlxPool_flixel_math_FlxPoint_obj::FlxPool_flixel_math_FlxPoint_obj()
{
}
void FlxPool_flixel_math_FlxPoint_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(FlxPool_flixel_math_FlxPoint);
HX_MARK_MEMBER_NAME(_pool,"_pool");
HX_MARK_MEMBER_NAME(_class,"_class");
HX_MARK_MEMBER_NAME(_count,"_count");
HX_MARK_END_CLASS();
}
void FlxPool_flixel_math_FlxPoint_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(_pool,"_pool");
HX_VISIT_MEMBER_NAME(_class,"_class");
HX_VISIT_MEMBER_NAME(_count,"_count");
}
::hx::Val FlxPool_flixel_math_FlxPoint_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 3:
if (HX_FIELD_EQ(inName,"get") ) { return ::hx::Val( get_dyn() ); }
if (HX_FIELD_EQ(inName,"put") ) { return ::hx::Val( put_dyn() ); }
break;
case 5:
if (HX_FIELD_EQ(inName,"_pool") ) { return ::hx::Val( _pool ); }
if (HX_FIELD_EQ(inName,"clear") ) { return ::hx::Val( clear_dyn() ); }
break;
case 6:
if (HX_FIELD_EQ(inName,"length") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( get_length() ); }
if (HX_FIELD_EQ(inName,"_class") ) { return ::hx::Val( _class ); }
if (HX_FIELD_EQ(inName,"_count") ) { return ::hx::Val( _count ); }
break;
case 9:
if (HX_FIELD_EQ(inName,"putUnsafe") ) { return ::hx::Val( putUnsafe_dyn() ); }
break;
case 10:
if (HX_FIELD_EQ(inName,"get_length") ) { return ::hx::Val( get_length_dyn() ); }
break;
case 11:
if (HX_FIELD_EQ(inName,"preAllocate") ) { return ::hx::Val( preAllocate_dyn() ); }
}
return super::__Field(inName,inCallProp);
}
::hx::Val FlxPool_flixel_math_FlxPoint_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 5:
if (HX_FIELD_EQ(inName,"_pool") ) { _pool=inValue.Cast< ::Array< ::Dynamic> >(); return inValue; }
break;
case 6:
if (HX_FIELD_EQ(inName,"_class") ) { _class=inValue.Cast< ::hx::Class >(); return inValue; }
if (HX_FIELD_EQ(inName,"_count") ) { _count=inValue.Cast< int >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void FlxPool_flixel_math_FlxPoint_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_("length",e6,94,07,9f));
outFields->push(HX_("_pool",bb,9c,6d,fd));
outFields->push(HX_("_class",79,bf,3f,44));
outFields->push(HX_("_count",10,8c,4a,46));
super::__GetFields(outFields);
};
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo FlxPool_flixel_math_FlxPoint_obj_sMemberStorageInfo[] = {
{::hx::fsObject /* ::Array< ::Dynamic> */ ,(int)offsetof(FlxPool_flixel_math_FlxPoint_obj,_pool),HX_("_pool",bb,9c,6d,fd)},
{::hx::fsObject /* ::hx::Class */ ,(int)offsetof(FlxPool_flixel_math_FlxPoint_obj,_class),HX_("_class",79,bf,3f,44)},
{::hx::fsInt,(int)offsetof(FlxPool_flixel_math_FlxPoint_obj,_count),HX_("_count",10,8c,4a,46)},
{ ::hx::fsUnknown, 0, null()}
};
static ::hx::StaticInfo *FlxPool_flixel_math_FlxPoint_obj_sStaticStorageInfo = 0;
#endif
static ::String FlxPool_flixel_math_FlxPoint_obj_sMemberFields[] = {
HX_("_pool",bb,9c,6d,fd),
HX_("_class",79,bf,3f,44),
HX_("_count",10,8c,4a,46),
HX_("get",96,80,4e,00),
HX_("put",cf,62,55,00),
HX_("putUnsafe",55,e0,1c,e4),
HX_("preAllocate",00,4a,53,a6),
HX_("clear",8d,71,5b,48),
HX_("get_length",af,04,8f,8f),
::String(null()) };
::hx::Class FlxPool_flixel_math_FlxPoint_obj::__mClass;
void FlxPool_flixel_math_FlxPoint_obj::__register()
{
FlxPool_flixel_math_FlxPoint_obj _hx_dummy;
FlxPool_flixel_math_FlxPoint_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("flixel.util.FlxPool_flixel_math_FlxPoint",fd,74,d7,4c);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(FlxPool_flixel_math_FlxPoint_obj_sMemberFields);
__mClass->mCanCast = ::hx::TCanCast< FlxPool_flixel_math_FlxPoint_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = FlxPool_flixel_math_FlxPoint_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = FlxPool_flixel_math_FlxPoint_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace flixel
} // end namespace util
| 41 | 223 | 0.742442 | [
"object"
] |
cb61e78468234a9bce543d87ae1017176636e8e4 | 5,062 | hpp | C++ | src/Externals/spire/arc-ball/ArcBall.hpp | Haydelj/SCIRun | f7ee04d85349b946224dbff183438663e54b9413 | [
"MIT"
] | null | null | null | src/Externals/spire/arc-ball/ArcBall.hpp | Haydelj/SCIRun | f7ee04d85349b946224dbff183438663e54b9413 | [
"MIT"
] | null | null | null | src/Externals/spire/arc-ball/ArcBall.hpp | Haydelj/SCIRun | f7ee04d85349b946224dbff183438663e54b9413 | [
"MIT"
] | null | null | null | /*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 Scientific Computing and Imaging Institute,
University of Utah.
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 SPIRE_ARC_BALL_H
#define SPIRE_ARC_BALL_H
#include <es-log/trace-log.h>
#include <cstdint>
#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_inverse.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <spire/scishare.h>
namespace spire {
/// A reimplementation of Ken Shoemake's arcball camera. SCIRun 4's camera
/// system is based off of Ken's code. The Code appears in Graphics Gems 4,
/// III.1.
/// Unless specified otherwise, all calculations and variables stored in this
/// class are relative to the target coordinate system (TCS) for which there is
/// a transformation from screen space to TCS given by the screenToTCS
/// constructor parameter.
/// If the screenToTCS parameter in the constructor is left as the identity
/// matrix then all values are given in screen coordinates.
/// Screen coordinates are (x \in [-1,1]) and (y \in [-1,1]) where (0,0) is the
/// center of the screen.
class SCISHARE ArcBall
{
public:
/// \param center Center of the arcball in TCS (screen coordinates if
/// screenToTCS = identity). Generally this will
/// always be (0,0,0). But you may move the center
/// in and out of the screen plane to various effect.
/// \param radius Radius in TCS. For screen coordinates, a good
/// default is 0.75.
/// \param screenToTCS Transformation from screen coordinates
/// to TCS. \p center and \p radius are given in TCS.
ArcBall(const glm::vec3& center, glm::float_t radius, bool inverted = false,
const glm::mat4& screenToTCS = glm::mat4());
/// Initiate an arc ball drag given the mouse click in screen coordinates.
/// \param mouseScreenCoords Mouse screen coordinates.
void beginDrag(const glm::vec2& mouseScreenCoords);
/// Informs the arcball when the mouse has been dragged.
/// \param mouseScreenCoords Mouse screen coordinates.
void drag(const glm::vec2& mouseScreenCoords);
/// Sets the camera to a specific location and up
void setLocationOnSphere(glm::vec3 location, glm::vec3 up);
/// Retrieves the current transformation in TCS.
/// Obtains full transformation of object in question. If the arc ball is
/// being used to control camera rotation, then this will contain all
/// concatenated camera transformations. The current state of the camera
/// is stored in the quaternions mQDown and mQNow. mMatNow is calculated
/// from mQNow.
glm::mat4 getTransformation() const;
glm::quat getQuat() const {return mQNow;}
void setQuat(const glm::quat q) {mQNow = q;}
private:
/// Calculates our position on the ArcBall from 2D mouse position.
/// \param tscMouse TSC coordinates of mouse click.
glm::vec3 mouseOnSphere(const glm::vec3& tscMouse);
/// Construct a unit quaternion from two points on the unit sphere.
static glm::quat quatFromUnitSphere(const glm::vec3& from, const glm::vec3& to);
/// Transform from screen coordinates to the target coordinate system.
glm::mat4 mScreenToTCS;
glm::vec3 mCenter; ///< Center of the arcball in target coordinate system.
glm::float_t mRadius; ///< Radius of the arcball in target coordinate system.
bool invertHemisphere;
glm::vec3 mVSphereDown; ///< vDown mapped to the sphere of 'mRadius' centered at 'mCenter' in TCS.
glm::quat mQDown; ///< State of the rotation since mouse down.
glm::quat mQNow; ///< Current state of the rotation taking into account mouse.
///< Essentially QDrag * QDown (QDown is a applied first, just
///< as in matrix multiplication).
};
} // namespace spire
#endif
| 43.264957 | 106 | 0.700119 | [
"object",
"transform"
] |
cb6a5354ebd2ada52fb88da87ebfe2ac7b05697e | 9,551 | cc | C++ | drogon_ctl/press.cc | Dalot/Drogon | a3319356d6a11d2d319156b43eee8b74c17b803a | [
"MIT"
] | null | null | null | drogon_ctl/press.cc | Dalot/Drogon | a3319356d6a11d2d319156b43eee8b74c17b803a | [
"MIT"
] | null | null | null | drogon_ctl/press.cc | Dalot/Drogon | a3319356d6a11d2d319156b43eee8b74c17b803a | [
"MIT"
] | 1 | 2020-01-28T05:35:28.000Z | 2020-01-28T05:35:28.000Z | /**
*
* press.cc
* An Tao
*
* Copyright 2018, An Tao. All rights reserved.
* https://github.com/an-tao/drogon
* Use of this source code is governed by the MIT license
* that can be found in the License file.
*
* Drogon
*
*/
#include "press.h"
#include "cmd.h"
#include <drogon/DrClassMap.h>
#include <iostream>
#include <memory>
#include <iomanip>
#include <stdlib.h>
#include <unistd.h>
using namespace drogon_ctl;
std::string press::detail()
{
return "Use press command to do stress testing\n"
"Usage:drogon_ctl press <options> <url>\n"
" -n num number of requests(default : 1)\n"
" -t num number of threads(default : 1)\n"
" -c num concurrent connections(default : 1)\n"
// " -k keep alive(default: no)\n"
" -q no progress indication(default: no)\n\n"
"example: drogon_ctl press -n 10000 -c 100 -t 4 -q "
"http://localhost:8080/index.html\n";
}
void outputErrorAndExit(const string_view &err)
{
std::cout << err << std::endl;
exit(1);
}
void press::handleCommand(std::vector<std::string> ¶meters)
{
for (auto iter = parameters.begin(); iter != parameters.end(); iter++)
{
auto ¶m = *iter;
if (param.find("-n") == 0)
{
if (param == "-n")
{
iter++;
if (iter == parameters.end())
{
outputErrorAndExit("No number of requests!");
}
auto &num = *iter;
try
{
_numOfRequests = std::stoll(num);
}
catch (...)
{
outputErrorAndExit("Invalid number of requests!");
}
continue;
}
else
{
auto num = param.substr(2);
try
{
_numOfRequests = std::stoll(num);
}
catch (...)
{
outputErrorAndExit("Invalid number of requests!");
}
continue;
}
}
else if (param.find("-t") == 0)
{
if (param == "-t")
{
iter++;
if (iter == parameters.end())
{
outputErrorAndExit("No number of threads!");
}
auto &num = *iter;
try
{
_numOfThreads = std::stoll(num);
}
catch (...)
{
outputErrorAndExit("Invalid number of threads!");
}
continue;
}
else
{
auto num = param.substr(2);
try
{
_numOfThreads = std::stoll(num);
}
catch (...)
{
outputErrorAndExit("Invalid number of threads!");
}
continue;
}
}
else if (param.find("-c") == 0)
{
if (param == "-c")
{
iter++;
if (iter == parameters.end())
{
outputErrorAndExit("No number of connections!");
}
auto &num = *iter;
try
{
_numOfConnections = std::stoll(num);
}
catch (...)
{
outputErrorAndExit("Invalid number of connections!");
}
continue;
}
else
{
auto num = param.substr(2);
try
{
_numOfConnections = std::stoll(num);
}
catch (...)
{
outputErrorAndExit("Invalid number of connections!");
}
continue;
}
}
// else if (param == "-k")
// {
// _keepAlive = true;
// continue;
// }
else if (param == "-q")
{
_processIndication = false;
}
else if (param[0] != '-')
{
_url = param;
}
}
// std::cout << "n=" << _numOfRequests << std::endl;
// std::cout << "t=" << _numOfThreads << std::endl;
// std::cout << "c=" << _numOfConnections << std::endl;
// std::cout << "q=" << _processIndication << std::endl;
// std::cout << "url=" << _url << std::endl;
if (_url.empty() || _url.find("http") != 0 ||
_url.find("://") == std::string::npos)
{
outputErrorAndExit("Invalid URL");
}
else
{
auto pos = _url.find("://");
auto posOfPath = _url.find("/", pos + 3);
if (posOfPath == std::string::npos)
{
_host = _url;
_path = "/";
}
else
{
_host = _url.substr(0, posOfPath);
_path = _url.substr(posOfPath);
}
}
// std::cout << "host=" << _host << std::endl;
// std::cout << "path=" << _path << std::endl;
doTesting();
}
void press::doTesting()
{
createRequestAndClients();
if (_clients.empty())
{
outputErrorAndExit("No connection!");
}
_stat._startDate = trantor::Date::now();
for (auto &client : _clients)
{
sendRequest(client);
}
_loopPool->wait();
}
void press::createRequestAndClients()
{
_loopPool = std::make_unique<trantor::EventLoopThreadPool>(_numOfThreads);
_loopPool->start();
for (size_t i = 0; i < _numOfConnections; i++)
{
auto client =
HttpClient::newHttpClient(_host, _loopPool->getNextLoop());
client->enableCookies();
_clients.push_back(client);
}
}
void press::sendRequest(const HttpClientPtr &client)
{
auto numOfRequest = _stat._numOfRequestsSent++;
if (numOfRequest >= _numOfRequests)
{
return;
}
auto request = HttpRequest::newHttpRequest();
request->setPath(_path);
request->setMethod(Get);
// std::cout << "send!" << std::endl;
client->sendRequest(
request,
[this, client, request](ReqResult r, const HttpResponsePtr &resp) {
size_t goodNum, badNum;
if (r == ReqResult::Ok)
{
// std::cout << "OK" << std::endl;
goodNum = ++_stat._numOfGoodResponse;
badNum = _stat._numOfBadResponse;
_stat._bytesRecieved += resp->body().length();
auto delay = trantor::Date::now().microSecondsSinceEpoch() -
request->creationDate().microSecondsSinceEpoch();
_stat._totalDelay += delay;
}
else
{
goodNum = _stat._numOfGoodResponse;
badNum = ++_stat._numOfBadResponse;
if (badNum > _numOfRequests / 10)
{
outputErrorAndExit("Too many errors");
}
}
if (goodNum + badNum >= _numOfRequests)
{
outputResults();
}
if (r == ReqResult::Ok)
sendRequest(client);
else
{
client->getLoop()->runAfter(1, [this, client]() {
sendRequest(client);
});
}
if (_processIndication)
{
auto rec = goodNum + badNum;
if (rec % 100000 == 0)
{
std::cout << rec << " responses are received" << std::endl
<< std::endl;
}
}
});
}
void press::outputResults()
{
static std::mutex mtx;
size_t totalSent = 0;
size_t totalRecv = 0;
for (auto &client : _clients)
{
totalSent += client->bytesSent();
totalRecv += client->bytesReceived();
}
auto now = trantor::Date::now();
auto microSecs = now.microSecondsSinceEpoch() -
_stat._startDate.microSecondsSinceEpoch();
double seconds = (double)microSecs / 1000000.0;
size_t rps = _stat._numOfGoodResponse / seconds;
std::cout << std::endl;
std::cout << "TOTALS: " << _numOfConnections << " connect, "
<< _numOfRequests << " requests, " << _stat._numOfGoodResponse
<< " success, " << _stat._numOfBadResponse << " fail"
<< std::endl;
std::cout << "TRAFFIC: " << _stat._bytesRecieved / _stat._numOfGoodResponse
<< " avg bytes, "
<< (totalRecv - _stat._bytesRecieved) / _stat._numOfGoodResponse
<< " avg overhead, " << _stat._bytesRecieved << " bytes, "
<< totalRecv - _stat._bytesRecieved << " overhead" << std::endl;
std::cout << std::setiosflags(std::ios::fixed) << std::setprecision(3)
<< "TIMING: " << seconds << " seconds, " << rps << " rps, "
<< (double)(_stat._totalDelay) / _stat._numOfGoodResponse / 1000
<< " ms avg req time" << std::endl;
std::cout << "SPEED: download " << totalRecv / seconds / 1000
<< " kBps, upload " << totalSent / seconds / 1000 << " kBps"
<< std::endl
<< std::endl;
exit(0);
}
| 29.940439 | 80 | 0.446341 | [
"vector"
] |
cb6f8829054f5e73d751f3805cd0293616a60cea | 22,728 | cc | C++ | runtime/bin/directory.cc | eggfly/sdk | 14bff8387c479d8514269ace694e42e9162c8745 | [
"BSD-3-Clause"
] | 2 | 2020-06-26T23:20:09.000Z | 2021-12-10T05:07:12.000Z | runtime/bin/directory.cc | onuryildriim/sdk | f99631b12c4ae3f1771ef68b1ae8c57a0dd9434d | [
"BSD-3-Clause"
] | null | null | null | runtime/bin/directory.cc | onuryildriim/sdk | f99631b12c4ae3f1771ef68b1ae8c57a0dd9434d | [
"BSD-3-Clause"
] | 3 | 2020-06-23T10:34:27.000Z | 2021-12-10T05:11:35.000Z | // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include <cstdlib>
#include <memory>
#include "bin/directory.h"
#include "bin/dartutils.h"
#include "bin/io_buffer.h"
#include "bin/namespace.h"
#include "bin/typed_data_utils.h"
#include "bin/utils.h"
#include "include/dart_api.h"
#include "platform/assert.h"
#include "platform/syslog.h"
namespace dart {
namespace bin {
char* Directory::system_temp_path_override_ = NULL;
void FUNCTION_NAME(Directory_Current)(Dart_NativeArguments args) {
Namespace* namespc = Namespace::GetNamespace(args, 0);
const char* current = Directory::Current(namespc);
if (current != NULL) {
Dart_Handle str = ThrowIfError(DartUtils::NewString(current));
Dart_SetReturnValue(args, str);
} else {
Dart_SetReturnValue(args, DartUtils::NewDartOSError());
}
}
void FUNCTION_NAME(Directory_SetCurrent)(Dart_NativeArguments args) {
Namespace* namespc = Namespace::GetNamespace(args, 0);
Dart_Handle path = Dart_GetNativeArgument(args, 1);
OSError os_error;
ASSERT(!Dart_IsError(path));
bool result;
{
TypedDataScope data(path);
ASSERT(data.type() == Dart_TypedData_kUint8);
const char* name = data.GetCString();
result = Directory::SetCurrent(namespc, name);
if (!result) {
// Errors must be caught before TypedDataScope data is destroyed.
os_error.Reload();
}
}
if (result) {
Dart_SetBooleanReturnValue(args, true);
} else {
Dart_SetReturnValue(args, DartUtils::NewDartOSError(&os_error));
}
}
void FUNCTION_NAME(Directory_Exists)(Dart_NativeArguments args) {
static const int kExists = 1;
static const int kDoesNotExist = 0;
Namespace* namespc = Namespace::GetNamespace(args, 0);
Dart_Handle path = Dart_GetNativeArgument(args, 1);
OSError os_error;
Directory::ExistsResult result;
{
TypedDataScope data(path);
ASSERT(data.type() == Dart_TypedData_kUint8);
const char* name = data.GetCString();
result = Directory::Exists(namespc, name);
if ((result != Directory::DOES_NOT_EXIST) &&
(result != Directory::EXISTS)) {
// Errors must be caught before TypedDataScope data is destroyed.
os_error.Reload();
}
}
if (result == Directory::EXISTS) {
Dart_SetIntegerReturnValue(args, kExists);
} else if (result == Directory::DOES_NOT_EXIST) {
Dart_SetIntegerReturnValue(args, kDoesNotExist);
} else {
Dart_SetReturnValue(args, DartUtils::NewDartOSError(&os_error));
}
}
void FUNCTION_NAME(Directory_Create)(Dart_NativeArguments args) {
Namespace* namespc = Namespace::GetNamespace(args, 0);
Dart_Handle path = Dart_GetNativeArgument(args, 1);
OSError os_error;
bool result;
{
TypedDataScope data(path);
ASSERT(data.type() == Dart_TypedData_kUint8);
const char* name = data.GetCString();
result = Directory::Create(namespc, name);
if (!result) {
// Errors must be caught before TypedDataScope data is destroyed.
os_error.Reload();
}
}
if (result) {
Dart_SetBooleanReturnValue(args, true);
} else {
Dart_SetReturnValue(args, DartUtils::NewDartOSError(&os_error));
}
}
void FUNCTION_NAME(Directory_SystemTemp)(Dart_NativeArguments args) {
Namespace* namespc = Namespace::GetNamespace(args, 0);
const char* result = Directory::SystemTemp(namespc);
Dart_Handle str = ThrowIfError(DartUtils::NewString(result));
Dart_SetReturnValue(args, str);
}
void FUNCTION_NAME(Directory_CreateTemp)(Dart_NativeArguments args) {
Namespace* namespc = Namespace::GetNamespace(args, 0);
Dart_Handle path = Dart_GetNativeArgument(args, 1);
OSError os_error;
const char* result = NULL;
{
TypedDataScope data(path);
ASSERT(data.type() == Dart_TypedData_kUint8);
const char* name = data.GetCString();
result = Directory::CreateTemp(namespc, name);
if (result == NULL) {
// Errors must be caught before TypedDataScope data is destroyed.
os_error.Reload();
}
}
if (result != NULL) {
Dart_Handle str = ThrowIfError(DartUtils::NewString(result));
Dart_SetReturnValue(args, str);
} else {
Dart_SetReturnValue(args, DartUtils::NewDartOSError(&os_error));
}
}
void FUNCTION_NAME(Directory_Delete)(Dart_NativeArguments args) {
Namespace* namespc = Namespace::GetNamespace(args, 0);
Dart_Handle path = Dart_GetNativeArgument(args, 1);
OSError os_error;
bool result;
{
TypedDataScope data(path);
ASSERT(data.type() == Dart_TypedData_kUint8);
const char* name = data.GetCString();
result = Directory::Delete(namespc, name,
DartUtils::GetNativeBooleanArgument(args, 2));
if (!result) {
// Errors must be caught before TypedDataScope data is destroyed.
os_error.Reload();
}
}
if (result) {
Dart_SetBooleanReturnValue(args, true);
} else {
Dart_SetReturnValue(args, DartUtils::NewDartOSError(&os_error));
}
}
void FUNCTION_NAME(Directory_Rename)(Dart_NativeArguments args) {
Namespace* namespc = Namespace::GetNamespace(args, 0);
Dart_Handle path = Dart_GetNativeArgument(args, 1);
OSError os_error;
bool result;
{
TypedDataScope data(path);
ASSERT(data.type() == Dart_TypedData_kUint8);
const char* name = data.GetCString();
result = Directory::Rename(namespc, name,
DartUtils::GetNativeStringArgument(args, 2));
if (!result) {
// Errors must be caught before TypedDataScope data is destroyed.
os_error.Reload();
}
}
if (result) {
Dart_SetBooleanReturnValue(args, true);
} else {
Dart_SetReturnValue(args, DartUtils::NewDartOSError(&os_error));
}
}
void FUNCTION_NAME(Directory_FillWithDirectoryListing)(
Dart_NativeArguments args) {
Namespace* namespc = Namespace::GetNamespace(args, 0);
// The list that we should fill.
Dart_Handle results = Dart_GetNativeArgument(args, 1);
Dart_Handle path = Dart_GetNativeArgument(args, 2);
Dart_Handle dart_error;
const char* name;
{
TypedDataScope data(path);
ASSERT(data.type() == Dart_TypedData_kUint8);
// We need to release our typed data before creating SyncDirectoryListing
// since it allocates objects which require us to not be holding typed data
// that has been acquired.
name = data.GetScopedCString();
}
{
// Pass the list that should hold the directory listing to the
// SyncDirectoryListing object, which adds elements to it.
SyncDirectoryListing sync_listing(
results, namespc, name, DartUtils::GetNativeBooleanArgument(args, 3),
DartUtils::GetNativeBooleanArgument(args, 4));
Directory::List(&sync_listing);
dart_error = sync_listing.dart_error();
}
if (Dart_IsError(dart_error)) {
Dart_PropagateError(dart_error);
} else if (!Dart_IsNull(dart_error)) {
Dart_ThrowException(dart_error);
}
}
static const int kAsyncDirectoryListerFieldIndex = 0;
void FUNCTION_NAME(Directory_GetAsyncDirectoryListerPointer)(
Dart_NativeArguments args) {
AsyncDirectoryListing* listing;
Dart_Handle dart_this = ThrowIfError(Dart_GetNativeArgument(args, 0));
ASSERT(Dart_IsInstance(dart_this));
ThrowIfError(
Dart_GetNativeInstanceField(dart_this, kAsyncDirectoryListerFieldIndex,
reinterpret_cast<intptr_t*>(&listing)));
if (listing != NULL) {
intptr_t listing_pointer = reinterpret_cast<intptr_t>(listing);
// Increment the listing's reference count. This native should only be
// be called when we are about to send the AsyncDirectoryListing* to the
// IO service.
listing->Retain();
Dart_SetReturnValue(args, Dart_NewInteger(listing_pointer));
}
}
static void ReleaseListing(void* isolate_callback_data,
Dart_WeakPersistentHandle handle,
void* peer) {
AsyncDirectoryListing* listing =
reinterpret_cast<AsyncDirectoryListing*>(peer);
listing->Release();
}
void FUNCTION_NAME(Directory_SetAsyncDirectoryListerPointer)(
Dart_NativeArguments args) {
Dart_Handle dart_this = ThrowIfError(Dart_GetNativeArgument(args, 0));
intptr_t listing_pointer =
DartUtils::GetIntptrValue(Dart_GetNativeArgument(args, 1));
AsyncDirectoryListing* listing =
reinterpret_cast<AsyncDirectoryListing*>(listing_pointer);
Dart_NewWeakPersistentHandle(dart_this, reinterpret_cast<void*>(listing),
sizeof(*listing), ReleaseListing);
Dart_Handle result = Dart_SetNativeInstanceField(
dart_this, kAsyncDirectoryListerFieldIndex, listing_pointer);
ThrowIfError(result);
}
void Directory::SetSystemTemp(const char* path) {
if (system_temp_path_override_ != NULL) {
free(system_temp_path_override_);
system_temp_path_override_ = NULL;
}
if (path != NULL) {
system_temp_path_override_ = strdup(path);
}
}
static Namespace* CObjectToNamespacePointer(CObject* cobject) {
CObjectIntptr value(cobject);
return reinterpret_cast<Namespace*>(value.Value());
}
CObject* Directory::CreateRequest(const CObjectArray& request) {
if ((request.Length() < 1) || !request[0]->IsIntptr()) {
return CObject::IllegalArgumentError();
}
Namespace* namespc = CObjectToNamespacePointer(request[0]);
RefCntReleaseScope<Namespace> rs(namespc);
if ((request.Length() != 2) || !request[1]->IsUint8Array()) {
return CObject::IllegalArgumentError();
}
CObjectUint8Array path(request[1]);
return Directory::Create(namespc,
reinterpret_cast<const char*>(path.Buffer()))
? CObject::True()
: CObject::NewOSError();
}
CObject* Directory::DeleteRequest(const CObjectArray& request) {
if ((request.Length() < 1) || !request[0]->IsIntptr()) {
return CObject::IllegalArgumentError();
}
Namespace* namespc = CObjectToNamespacePointer(request[0]);
RefCntReleaseScope<Namespace> rs(namespc);
if ((request.Length() != 3) || !request[1]->IsUint8Array() ||
!request[2]->IsBool()) {
return CObject::IllegalArgumentError();
}
CObjectUint8Array path(request[1]);
CObjectBool recursive(request[2]);
return Directory::Delete(namespc,
reinterpret_cast<const char*>(path.Buffer()),
recursive.Value())
? CObject::True()
: CObject::NewOSError();
}
CObject* Directory::ExistsRequest(const CObjectArray& request) {
static const int kExists = 1;
static const int kDoesNotExist = 0;
if ((request.Length() < 1) || !request[0]->IsIntptr()) {
return CObject::IllegalArgumentError();
}
Namespace* namespc = CObjectToNamespacePointer(request[0]);
RefCntReleaseScope<Namespace> rs(namespc);
if ((request.Length() != 2) || !request[1]->IsUint8Array()) {
return CObject::IllegalArgumentError();
}
CObjectUint8Array path(request[1]);
Directory::ExistsResult result =
Directory::Exists(namespc, reinterpret_cast<const char*>(path.Buffer()));
if (result == Directory::EXISTS) {
return new CObjectInt32(CObject::NewInt32(kExists));
} else if (result == Directory::DOES_NOT_EXIST) {
return new CObjectInt32(CObject::NewInt32(kDoesNotExist));
} else {
return CObject::NewOSError();
}
}
CObject* Directory::CreateTempRequest(const CObjectArray& request) {
if ((request.Length() < 1) || !request[0]->IsIntptr()) {
return CObject::IllegalArgumentError();
}
Namespace* namespc = CObjectToNamespacePointer(request[0]);
RefCntReleaseScope<Namespace> rs(namespc);
if ((request.Length() != 2) || !request[1]->IsUint8Array()) {
return CObject::IllegalArgumentError();
}
CObjectUint8Array path(request[1]);
const char* result = Directory::CreateTemp(
namespc, reinterpret_cast<const char*>(path.Buffer()));
if (result == NULL) {
return CObject::NewOSError();
}
return new CObjectString(CObject::NewString(result));
}
static CObject* CreateIllegalArgumentError() {
// Respond with an illegal argument list error message.
CObjectArray* error = new CObjectArray(CObject::NewArray(3));
error->SetAt(0, new CObjectInt32(
CObject::NewInt32(AsyncDirectoryListing::kListError)));
error->SetAt(1, CObject::Null());
error->SetAt(2, CObject::IllegalArgumentError());
return error;
}
CObject* Directory::ListStartRequest(const CObjectArray& request) {
if ((request.Length() < 1) || !request[0]->IsIntptr()) {
return CreateIllegalArgumentError();
}
Namespace* namespc = CObjectToNamespacePointer(request[0]);
RefCntReleaseScope<Namespace> rs(namespc);
if ((request.Length() != 4) || !request[1]->IsUint8Array() ||
!request[2]->IsBool() || !request[3]->IsBool()) {
return CreateIllegalArgumentError();
}
CObjectUint8Array path(request[1]);
CObjectBool recursive(request[2]);
CObjectBool follow_links(request[3]);
AsyncDirectoryListing* dir_listing = new AsyncDirectoryListing(
namespc, reinterpret_cast<const char*>(path.Buffer()), recursive.Value(),
follow_links.Value());
if (dir_listing->error()) {
// Report error now, so we capture the correct OSError.
CObject* err = CObject::NewOSError();
dir_listing->Release();
CObjectArray* error = new CObjectArray(CObject::NewArray(3));
error->SetAt(0, new CObjectInt32(
CObject::NewInt32(AsyncDirectoryListing::kListError)));
error->SetAt(1, request[1]);
error->SetAt(2, err);
return error;
}
// TODO(ajohnsen): Consider returning the first few results.
return new CObjectIntptr(
CObject::NewIntptr(reinterpret_cast<intptr_t>(dir_listing)));
}
CObject* Directory::ListNextRequest(const CObjectArray& request) {
if ((request.Length() != 1) || !request[0]->IsIntptr()) {
return CreateIllegalArgumentError();
}
CObjectIntptr ptr(request[0]);
AsyncDirectoryListing* dir_listing =
reinterpret_cast<AsyncDirectoryListing*>(ptr.Value());
RefCntReleaseScope<AsyncDirectoryListing> rs(dir_listing);
if (dir_listing->IsEmpty()) {
return new CObjectArray(CObject::NewArray(0));
}
const int kArraySize = 128;
CObjectArray* response = new CObjectArray(CObject::NewArray(kArraySize));
dir_listing->SetArray(response, kArraySize);
Directory::List(dir_listing);
// In case the listing ended before it hit the buffer length, we need to
// override the array length.
response->AsApiCObject()->value.as_array.length = dir_listing->index();
return response;
}
CObject* Directory::ListStopRequest(const CObjectArray& request) {
if ((request.Length() != 1) || !request[0]->IsIntptr()) {
return CreateIllegalArgumentError();
}
CObjectIntptr ptr(request[0]);
AsyncDirectoryListing* dir_listing =
reinterpret_cast<AsyncDirectoryListing*>(ptr.Value());
RefCntReleaseScope<AsyncDirectoryListing> rs(dir_listing);
// We have retained a reference to the listing here. Therefore the listing's
// destructor can't be running. Since no further requests are dispatched by
// the Dart code after an async stop call, this PopAll() can't be racing
// with any other call on the listing. We don't do an extra Release(), and
// we don't delete the weak persistent handle. The file is closed here, but
// the memory for the listing will be cleaned up when the finalizer runs.
dir_listing->PopAll();
return new CObjectBool(CObject::Bool(true));
}
CObject* Directory::RenameRequest(const CObjectArray& request) {
if ((request.Length() < 1) || !request[0]->IsIntptr()) {
return CObject::IllegalArgumentError();
}
Namespace* namespc = CObjectToNamespacePointer(request[0]);
RefCntReleaseScope<Namespace> rs(namespc);
if ((request.Length() != 3) || !request[1]->IsUint8Array() ||
!request[2]->IsString()) {
return CObject::IllegalArgumentError();
}
CObjectUint8Array path(request[1]);
CObjectString new_path(request[2]);
return Directory::Rename(namespc,
reinterpret_cast<const char*>(path.Buffer()),
new_path.CString())
? CObject::True()
: CObject::NewOSError();
}
bool AsyncDirectoryListing::AddFileSystemEntityToResponse(Response type,
const char* arg) {
array_->SetAt(index_++, new CObjectInt32(CObject::NewInt32(type)));
if (arg != NULL) {
size_t len = strlen(arg);
Dart_CObject* io_buffer = CObject::NewIOBuffer(len);
uint8_t* data = io_buffer->value.as_external_typed_data.data;
memmove(reinterpret_cast<char*>(data), arg, len);
CObjectExternalUint8Array* external_array =
new CObjectExternalUint8Array(io_buffer);
array_->SetAt(index_++, external_array);
} else {
array_->SetAt(index_++, CObject::Null());
}
return index_ < length_;
}
bool AsyncDirectoryListing::HandleDirectory(const char* dir_name) {
return AddFileSystemEntityToResponse(kListDirectory, dir_name);
}
bool AsyncDirectoryListing::HandleFile(const char* file_name) {
return AddFileSystemEntityToResponse(kListFile, file_name);
}
bool AsyncDirectoryListing::HandleLink(const char* link_name) {
return AddFileSystemEntityToResponse(kListLink, link_name);
}
void AsyncDirectoryListing::HandleDone() {
AddFileSystemEntityToResponse(kListDone, NULL);
}
bool AsyncDirectoryListing::HandleError() {
CObject* err = CObject::NewOSError();
array_->SetAt(index_++, new CObjectInt32(CObject::NewInt32(kListError)));
CObjectArray* response = new CObjectArray(CObject::NewArray(3));
response->SetAt(0, new CObjectInt32(CObject::NewInt32(kListError)));
// Delay calling CurrentPath() until after CObject::NewOSError() in case
// CurrentPath() pollutes the OS error code.
response->SetAt(1, new CObjectString(CObject::NewString(
error() ? "Invalid path" : CurrentPath())));
response->SetAt(2, err);
array_->SetAt(index_++, response);
return index_ < length_;
}
bool SyncDirectoryListing::HandleDirectory(const char* dir_name) {
// Allocates a Uint8List for dir_name, and invokes the Directory.fromRawPath
// constructor. This avoids/delays interpreting the UTF-8 bytes in dir_name.
// Later, client code may either choose to access FileSystemEntity.path.
// FileSystemEntity.path will trigger UTF-8 decoding and return a path with
// non-UTF-8 characters replaced with U+FFFD.
size_t dir_name_length = strlen(dir_name);
uint8_t* buffer = NULL;
Dart_Handle dir_name_dart = IOBuffer::Allocate(dir_name_length, &buffer);
if (Dart_IsNull(dir_name_dart)) {
dart_error_ = DartUtils::NewDartOSError();
return false;
}
memmove(buffer, dir_name, dir_name_length);
Dart_Handle constructor_name = from_raw_path_string_;
Dart_Handle dir =
Dart_New(directory_type_, constructor_name, 1, &dir_name_dart);
Dart_Handle result = Dart_Invoke(results_, add_string_, 1, &dir);
if (Dart_IsError(result)) {
dart_error_ = result;
return false;
}
return true;
}
bool SyncDirectoryListing::HandleLink(const char* link_name) {
// Allocates a Uint8List for dir_name, and invokes the Directory.fromRawPath
// constructor. This avoids/delays interpreting the UTF-8 bytes in dir_name.
// Later, client code may either choose to access FileSystemEntity.path.
// FileSystemEntity.path will trigger UTF-8 decoding and return a path with
// non-UTF-8 characters replaced with U+FFFD.
size_t link_name_length = strlen(link_name);
uint8_t* buffer = NULL;
Dart_Handle link_name_dart = IOBuffer::Allocate(link_name_length, &buffer);
if (Dart_IsNull(link_name_dart)) {
dart_error_ = DartUtils::NewDartOSError();
return false;
}
memmove(buffer, link_name, link_name_length);
Dart_Handle constructor_name = from_raw_path_string_;
Dart_Handle link = Dart_New(link_type_, constructor_name, 1, &link_name_dart);
Dart_Handle result = Dart_Invoke(results_, add_string_, 1, &link);
if (Dart_IsError(result)) {
dart_error_ = result;
return false;
}
return true;
}
bool SyncDirectoryListing::HandleFile(const char* file_name) {
// Allocates a Uint8List for dir_name, and invokes the Directory.fromRawPath
// constructor. This avoids/delays interpreting the UTF-8 bytes in dir_name.
// Later, client code may either choose to access FileSystemEntity.path.
// FileSystemEntity.path will trigger UTF-8 decoding and return a path with
// non-UTF-8 characters replaced with U+FFFD.
size_t file_name_length = strlen(file_name);
uint8_t* buffer = NULL;
Dart_Handle file_name_dart = IOBuffer::Allocate(file_name_length, &buffer);
if (Dart_IsNull(file_name_dart)) {
dart_error_ = DartUtils::NewDartOSError();
return false;
}
memmove(buffer, file_name, file_name_length);
Dart_Handle constructor_name = from_raw_path_string_;
Dart_Handle file = Dart_New(file_type_, constructor_name, 1, &file_name_dart);
Dart_Handle result = Dart_Invoke(results_, add_string_, 1, &file);
if (Dart_IsError(result)) {
dart_error_ = result;
return false;
}
return true;
}
bool SyncDirectoryListing::HandleError() {
Dart_Handle dart_os_error = DartUtils::NewDartOSError();
Dart_Handle args[3];
args[0] = DartUtils::NewString("Directory listing failed");
args[1] = DartUtils::NewString(error() ? "Invalid path" : CurrentPath());
args[2] = dart_os_error;
dart_error_ = Dart_New(
DartUtils::GetDartType(DartUtils::kIOLibURL, "FileSystemException"),
Dart_Null(), 3, args);
return false;
}
static bool ListNext(DirectoryListing* listing) {
switch (listing->top()->Next(listing)) {
case kListFile:
return listing->HandleFile(listing->CurrentPath());
case kListLink:
return listing->HandleLink(listing->CurrentPath());
case kListDirectory:
if (listing->recursive()) {
listing->Push(new DirectoryListingEntry(listing->top()));
}
return listing->HandleDirectory(listing->CurrentPath());
case kListError:
return listing->HandleError();
case kListDone:
listing->Pop();
if (listing->IsEmpty()) {
listing->HandleDone();
return false;
} else {
return true;
}
default:
UNREACHABLE();
}
return false;
}
void Directory::List(DirectoryListing* listing) {
if (listing->error()) {
listing->HandleError();
listing->HandleDone();
} else {
while (ListNext(listing)) {
}
}
}
const char* Directory::Current(Namespace* namespc) {
return Namespace::GetCurrent(namespc);
}
bool Directory::SetCurrent(Namespace* namespc, const char* name) {
return Namespace::SetCurrent(namespc, name);
}
} // namespace bin
} // namespace dart
| 35.623824 | 80 | 0.705341 | [
"object"
] |
cb6fce627ad69de213459da65e0046c8f9480962 | 2,624 | hh | C++ | src/c++/lib/alignment/cppunit/testFragmentBuilder.hh | Illumina/Isaac4 | 0924fba8b467868da92e1c48323b15d7cbca17dd | [
"BSD-3-Clause"
] | 13 | 2018-02-09T22:59:39.000Z | 2021-11-29T06:33:22.000Z | src/c++/lib/alignment/cppunit/testFragmentBuilder.hh | Illumina/Isaac4 | 0924fba8b467868da92e1c48323b15d7cbca17dd | [
"BSD-3-Clause"
] | 17 | 2018-01-26T11:36:07.000Z | 2022-02-03T18:48:43.000Z | src/c++/lib/alignment/cppunit/testFragmentBuilder.hh | Illumina/Isaac4 | 0924fba8b467868da92e1c48323b15d7cbca17dd | [
"BSD-3-Clause"
] | 4 | 2018-10-19T20:00:00.000Z | 2020-10-29T14:44:06.000Z | /**
** Isaac Genome Alignment Software
** Copyright (c) 2010-2017 Illumina, Inc.
** All rights reserved.
**
** This software is provided under the terms and conditions of the
** GNU GENERAL PUBLIC LICENSE Version 3
**
** You should have received a copy of the GNU GENERAL PUBLIC LICENSE Version 3
** along with this program. If not, see
** <https://github.com/illumina/licenses/>.
**/
#ifndef iSAAC_ALIGNMENT_TEST_FRAGMENT_BUILDER_HH
#define iSAAC_ALIGNMENT_TEST_FRAGMENT_BUILDER_HH
#include <cppunit/extensions/HelperMacros.h>
#include <string>
#include <vector>
#include "alignment/templateBuilder/FragmentBuilder.hh"
#include "flowcell/ReadMetadata.hh"
#include "flowcell/Layout.hh"
class TestFragmentBuilder : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE( TestFragmentBuilder );
// CPPUNIT_TEST( testEmptyMatchList );
// CPPUNIT_TEST( testSingleSeed );
// CPPUNIT_TEST( testSeedOffset );
// CPPUNIT_TEST( testMultiSeed );
// CPPUNIT_TEST( testRepeats );
// CPPUNIT_TEST( testMismatches );
// CPPUNIT_TEST( testLeadingSoftClips );
// CPPUNIT_TEST( testTrailingSoftClips );
// CPPUNIT_TEST( testLeadingAndTrailingSoftClips );
CPPUNIT_TEST_SUITE_END();
private:
const isaac::flowcell::ReadMetadataList readMetadataList;
const isaac::flowcell::FlowcellLayoutList flowcells;
const isaac::reference::ContigList contigList;
const isaac::alignment::BclClusters bcl0;
const isaac::alignment::BclClusters bcl2;
const isaac::alignment::BclClusters bcl3;
const isaac::alignment::BclClusters bcl4l;
const isaac::alignment::BclClusters bcl4t;
const isaac::alignment::BclClusters bcl4lt;
const unsigned tile0;
const unsigned tile2;
const unsigned clusterId0;
const unsigned clusterId2;
isaac::alignment::Cluster cluster0;
isaac::alignment::Cluster cluster2;
isaac::alignment::Cluster cluster3;
isaac::alignment::Cluster cluster4l;
isaac::alignment::Cluster cluster4t;
isaac::alignment::Cluster cluster4lt;
std::vector<isaac::alignment::Match> matchList;
// auxiliary method for tests dedicated to a single seed on each read
void auxSingleSeed(const unsigned s0, const unsigned s1);
public:
TestFragmentBuilder();
void setUp();
void tearDown();
void testEmptyMatchList();
void testSingleSeed();
void testSeedOffset();
void testMultiSeed();
void testRepeats();
void testMismatches();
void testLeadingSoftClips();
void testTrailingSoftClips();
void testLeadingAndTrailingSoftClips();
};
#endif // #ifndef iSAAC_ALIGNMENT_TEST_FRAGMENT_BUILDER_HH
| 33.641026 | 79 | 0.73971 | [
"vector"
] |
cb7d97ae33cc4ac4d9c870437b742e1a20a27c25 | 2,908 | hpp | C++ | test/mettle/include/mettle/driver/log/child.hpp | Redchards/MiniDBMS | 1c7a3f63b46a934ae89184e3525c0754227c412b | [
"MIT"
] | 1 | 2017-05-12T21:22:13.000Z | 2017-05-12T21:22:13.000Z | test/mettle/include/mettle/driver/log/child.hpp | Redchards/MiniDBMS | 1c7a3f63b46a934ae89184e3525c0754227c412b | [
"MIT"
] | null | null | null | test/mettle/include/mettle/driver/log/child.hpp | Redchards/MiniDBMS | 1c7a3f63b46a934ae89184e3525c0754227c412b | [
"MIT"
] | 1 | 2017-12-02T14:42:02.000Z | 2017-12-02T14:42:02.000Z | #ifndef INC_METTLE_DRIVER_LOG_CHILD_HPP
#define INC_METTLE_DRIVER_LOG_CHILD_HPP
#include <cassert>
#include <ostream>
#include "../detail/bencode.hpp"
#include "core.hpp"
namespace mettle {
namespace log {
class child : public test_logger {
public:
child(std::ostream &out) : out(out) {}
void started_run() {
bencode::encode(out, bencode::dict_view{
{"event", "started_run"}
});
out.flush();
}
void ended_run() {
bencode::encode(out, bencode::dict_view{
{"event", "ended_run"}
});
out.flush();
}
void started_suite(const std::vector<std::string> &suites) {
bencode::encode(out, bencode::dict_view{
{"event", "started_suite"},
{"suites", wrap_suites(suites)}
});
out.flush();
}
void ended_suite(const std::vector<std::string> &suites) {
bencode::encode(out, bencode::dict_view{
{"event", "ended_suite"},
{"suites", wrap_suites(suites)}
});
out.flush();
}
void started_test(const test_name &test) {
bencode::encode(out, bencode::dict_view{
{"event", "started_test"},
{"test", wrap_test(test)}
});
out.flush();
}
void passed_test(const test_name &test, const test_output &output,
test_duration duration) {
bencode::encode(out, bencode::dict_view{
{"event", "passed_test"},
{"test", wrap_test(test)},
{"duration", duration.count()},
{"output", wrap_output(output)}
});
out.flush();
}
void failed_test(const test_name &test, const std::string &message,
const test_output &output, test_duration duration) {
bencode::encode(out, bencode::dict_view{
{"event", "failed_test"},
{"test", wrap_test(test)},
{"duration", duration.count()},
{"message", message},
{"output", wrap_output(output)}
});
out.flush();
}
void skipped_test(const test_name &test, const std::string &message) {
bencode::encode(out, bencode::dict_view{
{"event", "skipped_test"},
{"test", wrap_test(test)},
{"message", message}
});
out.flush();
}
private:
bencode::dict_view wrap_test(const test_name &test) {
return bencode::dict_view{
{"id", test.id},
{"suites", wrap_suites(test.suites)},
{"test", test.test}
};
}
bencode::dict_view wrap_output(const test_output &output) {
return bencode::dict_view{
{"stdout_log", output.stdout_log},
{"stderr_log", output.stderr_log}
};
}
bencode::list_view wrap_suites(const std::vector<std::string> &suites) {
bencode::list_view result;
for(auto &&i : suites)
result.push_back(i);
return result;
}
std::ostream &out;
};
}
} // namespace mettle
#endif
| 25.068966 | 76 | 0.577029 | [
"vector"
] |
cb7ea483bdb771827967957356e80d49fa1d51b8 | 692 | hpp | C++ | src/Core/Geometry/DCEL/Iterator/Vertex/VFIterator.hpp | sylvaindeker/Radium-Engine | 64164a258b3f7864c73a07c070e49b7138488d62 | [
"Apache-2.0"
] | 1 | 2018-04-16T13:55:45.000Z | 2018-04-16T13:55:45.000Z | src/Core/Geometry/DCEL/Iterator/Vertex/VFIterator.hpp | sylvaindeker/Radium-Engine | 64164a258b3f7864c73a07c070e49b7138488d62 | [
"Apache-2.0"
] | null | null | null | src/Core/Geometry/DCEL/Iterator/Vertex/VFIterator.hpp | sylvaindeker/Radium-Engine | 64164a258b3f7864c73a07c070e49b7138488d62 | [
"Apache-2.0"
] | null | null | null | #ifndef RADIUMENGINE_DCEL_VERTEX_FACE_ITERATOR_HPP
#define RADIUMENGINE_DCEL_VERTEX_FACE_ITERATOR_HPP
#include <Core/Geometry/DCEL/Iterator/Vertex/VertexIterator.hpp>
namespace Ra {
namespace Core {
class[[deprecated]] VFIterator : public VIterator<Face> {
public:
/// CONSTRUCTOR
VFIterator( Vertex_ptr & v );
VFIterator( const VFIterator& it ) = default;
/// DESTRUCTOR
~VFIterator();
/// LIST
inline FaceList list() const override;
/// OPERATOR
inline Face* operator->() const override;
};
} // namespace Core
} // namespace Ra
#include <Core/Geometry/DCEL/Iterator/Vertex/VFIterator.inl>
#endif // RADIUMENGINE_DCEL_VERTEX_FACE_ITERATOR_HPP
| 22.322581 | 64 | 0.729769 | [
"geometry"
] |
cb8102702286a46aaa8e66b5b8c65e5e65dc8288 | 4,212 | cpp | C++ | test/cppsim/test_state.cpp | 5c0t-qi/qulacs | 1c6c2f09616163eb92669cb7e9fb1ee78b7c2e42 | [
"MIT"
] | 1 | 2020-04-10T01:36:34.000Z | 2020-04-10T01:36:34.000Z | test/cppsim/test_state.cpp | 5c0t-qi/qulacs | 1c6c2f09616163eb92669cb7e9fb1ee78b7c2e42 | [
"MIT"
] | null | null | null | test/cppsim/test_state.cpp | 5c0t-qi/qulacs | 1c6c2f09616163eb92669cb7e9fb1ee78b7c2e42 | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include "../util/util.h"
#include <cppsim/state.hpp>
#include <cppsim/utility.hpp>
TEST(StateTest, GenerateAndRelease) {
UINT n = 10;
double eps = 1e-14;
QuantumState state(n);
ASSERT_EQ(state.qubit_count, n);
ASSERT_EQ(state.dim, 1ULL << n);
state.set_zero_state();
for (UINT i = 0; i < state.dim; ++i) {
if (i == 0) ASSERT_NEAR(abs(state.data_cpp()[i] - 1.), 0, eps);
else ASSERT_NEAR(abs(state.data_cpp()[i]), 0, eps);
}
Random random;
for (UINT repeat = 0; repeat < 10; ++repeat) {
ITYPE basis = random.int64()%state.dim;
state.set_computational_basis(basis);
for (UINT i = 0; i < state.dim; ++i) {
if (i == basis) ASSERT_NEAR(abs(state.data_cpp()[i] - 1.), 0, eps);
else ASSERT_NEAR(abs(state.data_cpp()[i]), 0, eps);
}
}
for (UINT repeat = 0; repeat < 10; ++repeat) {
state.set_Haar_random_state();
ASSERT_NEAR(state.get_squared_norm(),1.,eps);
}
}
TEST(StateTest, Sampling) {
UINT n = 10;
QuantumState state(n);
state.set_Haar_random_state();
state.set_computational_basis(100);
auto res1 = state.sampling(1024);
state.set_computational_basis(100);
auto res2 = state.sampling(1024);
}
TEST(StateTest, SetState) {
const double eps = 1e-10;
const UINT n = 10;
QuantumState state(n);
const ITYPE dim = 1ULL << n;
std::vector<std::complex<double>> state_vector(dim);
for (ITYPE i = 0; i < dim; ++i) {
double d = (double)i;
state_vector[i] = d + std::complex<double>(0, 1)*(d + 0.1);
}
state.load(state_vector);
for (ITYPE i = 0; i < dim; ++i) {
ASSERT_NEAR(state.data_cpp()[i].real(), state_vector[i].real(), eps);
ASSERT_NEAR(state.data_cpp()[i].imag(), state_vector[i].imag(), eps);
}
}
TEST(StateTest, GetMarginalProbability) {
const double eps = 1e-10;
const UINT n = 2;
const ITYPE dim = 1 << n;
QuantumState state(n);
state.set_Haar_random_state();
std::vector<double> probs;
for (ITYPE i = 0; i < dim; ++i) {
probs.push_back(pow(abs(state.data_cpp()[i]),2));
}
ASSERT_NEAR(state.get_marginal_probability({ 0,0 }), probs[0], eps);
ASSERT_NEAR(state.get_marginal_probability({ 1,0 }), probs[1], eps);
ASSERT_NEAR(state.get_marginal_probability({ 0,1 }), probs[2], eps);
ASSERT_NEAR(state.get_marginal_probability({ 1,1 }), probs[3], eps);
ASSERT_NEAR(state.get_marginal_probability({ 0,2 }), probs[0] + probs[2], eps);
ASSERT_NEAR(state.get_marginal_probability({ 1,2 }), probs[1] + probs[3], eps);
ASSERT_NEAR(state.get_marginal_probability({ 2,0 }), probs[0] + probs[1], eps);
ASSERT_NEAR(state.get_marginal_probability({ 2,1 }), probs[2] + probs[3], eps);
ASSERT_NEAR(state.get_marginal_probability({ 2,2 }), 1., eps);
}
TEST(StateTest, AddState) {
const double eps = 1e-10;
const UINT n = 10;
QuantumState state1(n);
QuantumState state2(n);
state1.set_Haar_random_state();
state2.set_Haar_random_state();
const ITYPE dim = 1ULL << n;
std::vector<std::complex<double>> state_vector1(dim);
std::vector<std::complex<double>> state_vector2(dim);
for (ITYPE i = 0; i < dim; ++i) {
state_vector1[i] = state1.data_cpp()[i];
state_vector2[i] = state2.data_cpp()[i];
}
state1.add_state(&state2);
for (ITYPE i = 0; i < dim; ++i) {
ASSERT_NEAR(state1.data_cpp()[i].real(), state_vector1[i].real() + state_vector2[i].real(), eps);
ASSERT_NEAR(state1.data_cpp()[i].imag(), state_vector1[i].imag() + state_vector2[i].imag(), eps);
ASSERT_NEAR(state2.data_cpp()[i].real(), state_vector2[i].real(), eps);
ASSERT_NEAR(state2.data_cpp()[i].imag(), state_vector2[i].imag(), eps);
}
}
TEST(StateTest, MultiplyCoef) {
const double eps = 1e-10;
const UINT n = 10;
const std::complex<double> coef(0.5, 0.2);
QuantumState state(n);
state.set_Haar_random_state();
const ITYPE dim = 1ULL << n;
std::vector<std::complex<double>> state_vector(dim);
for (ITYPE i = 0; i < dim; ++i) {
state_vector[i] = state.data_cpp()[i] * coef;
}
state.multiply_coef(coef);
for (ITYPE i = 0; i < dim; ++i) {
ASSERT_NEAR(state.data_cpp()[i].real(), state_vector[i].real(), eps);
ASSERT_NEAR(state.data_cpp()[i].imag(), state_vector[i].imag(), eps);
}
} | 33.165354 | 99 | 0.64886 | [
"vector"
] |
cb81bfc1e1484d74c20f5e2397c83735a5932556 | 185,036 | cpp | C++ | mysql-server/storage/ndb/src/ndbapi/NdbQueryOperation.cpp | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | mysql-server/storage/ndb/src/ndbapi/NdbQueryOperation.cpp | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | mysql-server/storage/ndb/src/ndbapi/NdbQueryOperation.cpp | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | /*
Copyright (c) 2011, 2020, Oracle and/or its affiliates.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is also distributed with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have included with MySQL.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <ndb_global.h>
#include <NdbDictionary.hpp>
#include <NdbIndexScanOperation.hpp>
#include "NdbQueryBuilder.hpp"
#include "NdbQueryOperation.hpp"
#include "API.hpp"
#include "NdbQueryBuilderImpl.hpp"
#include "NdbQueryOperationImpl.hpp"
#include "NdbInterpretedCode.hpp"
#include <signaldata/TcKeyReq.hpp>
#include <signaldata/TcKeyRef.hpp>
#include <signaldata/ScanTab.hpp>
#include <signaldata/QueryTree.hpp>
#include <signaldata/DbspjErr.hpp>
#include "AttributeHeader.hpp"
#include <Bitmask.hpp>
#if 0
#define DEBUG_CRASH() assert(false)
#else
#define DEBUG_CRASH()
#endif
/** To prevent compiler warnings about variables that are only used in asserts
* (when building optimized version).
*/
#define UNUSED(x) ((void)(x))
// To force usage of SCAN_NEXTREQ even for small scans resultsets:
// - '0' is default (production) value
// - '4' is normally a good value for testing batch related problems
static const int enforcedBatchSize = 0;
// Use double buffered ResultSets, may later change
// to be more adaptive based on query type
static const bool useDoubleBuffers = true;
/** Set to true to trace incoming signals.*/
static const bool traceSignals = false;
/* A 'void' index for a tuple in internal parent / child correlation structs .*/
static const Uint16 tupleNotFound = 0xffff;
/* Various error codes that are not specific to NdbQuery. */
static const int Err_TupleNotFound = 626;
static const int Err_FalsePredicate = 899;
static const int Err_MemoryAlloc = 4000;
static const int Err_SendFailed = 4002;
static const int Err_FunctionNotImplemented = 4003;
static const int Err_UnknownColumn = 4004;
static const int Err_ReceiveTimedOut = 4008;
static const int Err_NodeFailCausedAbort = 4028;
static const int Err_ParameterError = 4118;
static const int Err_SimpleDirtyReadFailed = 4119;
static const int Err_WrongFieldLength = 4209;
static const int Err_ReadTooMuch = 4257;
static const int Err_InvalidRangeNo = 4286;
static const int Err_DifferentTabForKeyRecAndAttrRec = 4287;
static const int Err_KeyIsNULL = 4316;
static const int Err_FinaliseNotCalled = 4519;
static const int Err_InterpretedCodeWrongTab = 4524;
enum
{
/**
* Set NdbQueryOperationImpl::m_parallelism to this value to indicate that
* scan parallelism should be adaptive.
*/
Parallelism_adaptive = 0xffff0000,
/**
* Set NdbQueryOperationImpl::m_parallelism to this value to indicate that
* all fragments should be scanned in parallel.
*/
Parallelism_max = 0xffff0001
};
/**
* A class for accessing the correlation data at the end of a tuple (for
* scan queries). These data have the following layout:
*
* Word 0: AttributeHeader
* Word 1, upper halfword: tuple id of parent tuple.
* Word 1, lower halfword: tuple id of this tuple.
* Word 2: Id of receiver for root operation (where the ancestor tuple of this
* tuple will go).
*
* Both tuple identifiers are unique within this batch of SPJ-worker results.
* With these identifiers, it is possible to relate a tuple to its parent and
* children. That way, results for child operations can be updated correctly
* when the application iterates over the results of the root scan operation.
*/
class TupleCorrelation
{
public:
static const Uint32 wordCount = 1;
explicit TupleCorrelation()
: m_correlation((tupleNotFound<<16) | tupleNotFound)
{}
/** Conversion to/from Uint32 to store/fetch from buffers */
explicit TupleCorrelation(Uint32 val)
: m_correlation(val)
{}
Uint32 toUint32() const
{ return m_correlation; }
Uint16 getTupleId() const
{ return m_correlation & 0xffff;}
Uint16 getParentTupleId() const
{ return m_correlation >> 16;}
private:
Uint32 m_correlation;
}; // class TupleCorrelation
class CorrelationData
{
public:
static const Uint32 wordCount = 3;
explicit CorrelationData(const Uint32* tupleData, Uint32 tupleLength):
m_corrPart(tupleData + tupleLength - wordCount)
{
assert(tupleLength >= wordCount);
assert(AttributeHeader(m_corrPart[0]).getAttributeId()
== AttributeHeader::CORR_FACTOR64);
assert(AttributeHeader(m_corrPart[0]).getByteSize() == 2*sizeof(Uint32));
assert(getTupleCorrelation().getTupleId()<tupleNotFound);
assert(getTupleCorrelation().getParentTupleId()<tupleNotFound);
}
Uint32 getRootReceiverId() const
{ return m_corrPart[2];}
const TupleCorrelation getTupleCorrelation() const
{ return TupleCorrelation(m_corrPart[1]); }
private:
const Uint32* const m_corrPart;
}; // class CorrelationData
/**
* The NdbWorker handles results produced by a request to a single SPJ instance.
*
* If 'MultiFragment' scan is requested, the NdbWorker handles root and
* related child rows from all fragments specified in the MultiFragment scan request.
*
* If a query has a scan operation as its root, then that scan will normally
* read from several fragments of its target table. Each such root fragment
* scan, along with any child lookup operations that are spawned from it,
* runs independently, in the sense that:
* - The API will know when it has received all data from a fragment for a
* given batch and all child operations spawned from it.
* - When one fragment is complete (for a batch) the API will make these data
* avaliable to the application, even if other fragments are not yet complete.
* - The tuple identifiers that are used for matching children with parents are
* only guaranteed to be unique within one batch of SPJ-worker results.
* Tuples derived from different worker result sets must thus be kept apart.
*
* This class manages the state of one such read operation, from one particular
* request to a SPJ block instance. If the root operation is a lookup,
* then there will be only one instance of this class.
*/
class NdbWorker {
public:
/** Build hash map for mapping from root receiver id to NdbWorker
* instance.*/
static void buildReceiverIdMap(NdbWorker* workers,
Uint32 noOfWorkers);
/** Find NdbWorker instance corresponding to a given root receiver id.*/
static NdbWorker* receiverIdLookup(NdbWorker* frags,
Uint32 noOfWorkers,
Uint32 receiverId);
explicit NdbWorker();
~NdbWorker();
/**
* Initialize object.
* @param query Enclosing query.
* @param workerNo This object manages state for reading from the
* workerNo'th worker result that the root operation accesses.
*/
void init(NdbQueryImpl& query, Uint32 workerNo);
static void clear(NdbWorker* frags, Uint32 noOfWorkers);
Uint32 getWorkerNo() const
{ return m_workerNo; }
/**
* Prepare for receiving another batch of results.
*/
void prepareNextReceiveSet();
bool hasRequestedMore() const;
/**
* Prepare for reading another batch of results.
*/
void grabNextResultSet(); // Need mutex lock
bool hasReceivedMore() const; // Need mutex lock
void setReceivedMore(); // Need mutex lock
void incrOutstandingResults(Int32 delta)
{
if (traceSignals) {
ndbout << "incrOutstandingResults: " << m_outstandingResults
<< ", with: " << delta
<< endl;
}
m_outstandingResults += delta;
assert(!(m_confReceived && m_outstandingResults<0));
}
void throwRemainingResults()
{
if (traceSignals) {
ndbout << "throwRemainingResults: " << m_outstandingResults
<< endl;
}
m_outstandingResults = 0;
m_confReceived = true;
postFetchRelease();
}
void setConfReceived(Uint32 tcPtrI);
/**
* The worker will read from a number of fragments of a table.
* This method checks if all results for the current batch has been
* received from this worker. This includes both results for the root
* operation and any child operations. Note that child operations may access
* other fragments.
*
* @return True if current batch is complete for this worker.
*/
bool isFragBatchComplete() const
{
assert(m_workerNo!=voidWorkerNo);
return m_confReceived && m_outstandingResults==0;
}
/**
* Get the result stream that handles results derived from this
* SPJ-worker for a particular operation.
* @param operationNo The id of the operation.
* @return The result stream for this worker.
*/
NdbResultStream& getResultStream(Uint32 operationNo) const;
NdbResultStream& getResultStream(const NdbQueryOperationImpl& op) const
{ return getResultStream(op.getQueryOperationDef().getOpNo()); }
Uint32 getReceiverId() const;
Uint32 getReceiverTcPtrI() const;
/**
* @return True if there are no more batches to be received for this worker.
*/
bool finalBatchReceived() const;
/**
* @return True if there are no more results from this worker (for
* the current batch).
*/
bool isEmpty() const;
/**
* This method is used for marking which streams belonging to this
* NdbWorker which has remaining batches for a sub scan
* instantiated from the current batch of its parent operation.
*
* moreMask: Set of streams which we may receive more result from
* in *next* batch.
* activeMask: Set of streams currently not returned their last row.
* (Will return 'more' in next or later REQuests)
*/
void setRemainingSubScans(Uint32 moreMask, Uint32 activeMask)
{
m_nextScans.assign(SpjTreeNodeMask::Size, &moreMask);
m_activeScans.assign(SpjTreeNodeMask::Size, &activeMask);
}
/** Release resources after last row has been returned */
void postFetchRelease();
private:
/** No copying.*/
NdbWorker(const NdbWorker&);
NdbWorker& operator=(const NdbWorker&);
STATIC_CONST(voidWorkerNo = 0xffffffff);
/** Enclosing query.*/
NdbQueryImpl* m_query;
/** Number of this worker result set as assigned by ::init().*/
Uint32 m_workerNo;
/** For processing results originating from worker (Array of).*/
NdbResultStream* m_resultStreams;
/**
* Number of requested (pre-)fetches which has either not completed
* from datanodes yet, or which are completed, but not consumed.
* (Which implies they are also counted in m_availResultSets)
*/
Uint32 m_pendingRequests;
/**
* Number of available 'm_pendingRequests' ( <= m_pendingRequests)
* which has been completely received. Will be made available
* for reading by calling ::grabNextResultSet()
*/
Uint32 m_availResultSets; // Need mutex
/**
* The number of outstanding TCKEYREF or TRANSID_AI messages to receive
* for the worker. This includes both messages related to the
* root operation and any descendant operation that was instantiated as
* a consequence of tuples found by the root operation.
* This number may temporarily be negative if e.g. TRANSID_AI arrives
* before SCAN_TABCONF.
*/
Int32 m_outstandingResults;
/**
* This is an array with one element for each fragment that the root
* operation accesses (i.e. one for a lookup, all for a table scan).
*
* Each element is true iff a SCAN_TABCONF (for that fragment) or
* TCKEYCONF message has been received
*/
bool m_confReceived;
/**
* A bitmask of operation id's which has been set up to receive more
* ResultSets by prepareNextReceiveSet().
*/
SpjTreeNodeMask m_preparedReceiveSet;
/**
* A bitmask of operation id's for which we will receive more
* ResultSets in a NEXTREQ.
* Note: This is the next set of op's to be prepared (before NEXTREQ)
* Note: Due to protocol legacy, only the uppermost scan op's in the branch
* getting new rows are set - However, all descendants will also get
* new ResultSets.
*/
SpjTreeNodeMask m_nextScans;
/**
* A bitmask of operation id's still being 'active' on the SPJ side.
* These will sooner or later return 'm_nextScans', but not necessarily
* in the next round. It follows from this that 'active' contains 'remaining'.
*/
SpjTreeNodeMask m_activeScans;
/**
* Used for implementing a hash map from root receiver ids to a
* NdbWorker instance. m_idMapHead is the index of the first
* NdbWorker in the m_workerNo'th hash bucket.
*/
int m_idMapHead;
/**
* Used for implementing a hash map from root receiver ids to a
* NdbWorker instance. m_idMapNext is the index of the next
* NdbWorker in the same hash bucket as this one.
*/
int m_idMapNext;
}; //NdbWorker
/**
* 'class NdbResultSet' is a helper for 'class NdbResultStream'.
* It manages the buffers which rows are received into and
* read from.
*/
class NdbResultSet
{
friend class NdbResultStream;
public:
explicit NdbResultSet();
void init(NdbQueryImpl& query,
Uint32 maxRows, Uint32 bufferSize);
void prepareReceive(NdbReceiver& receiver)
{
m_rowCount = 0;
receiver.prepareReceive(m_buffer);
}
Uint32 getRowCount() const
{ return m_rowCount; }
private:
/** No copying.*/
NdbResultSet(const NdbResultSet&);
NdbResultSet& operator=(const NdbResultSet&);
/** The buffers which we receive the results into */
NdbReceiverBuffer* m_buffer;
/** Array of TupleCorrelations for all rows in m_buffer */
TupleCorrelation* m_correlations;
/** The current #rows in 'm_buffer'.*/
Uint32 m_rowCount;
}; // class NdbResultSet
/**
* This class manages the subset of result data for one operation that is
* produced from one SPJ-worker. Note that the child result tuples
* may come from any fragment, but they all have initial ancestors from the
* root-fragment(s) scanned by the same SPJ-worker.
* For each operation there will thus be one NdbResultStream for each worker
* employed by this SPJ query (one in the case of lookups.)
* This class has an NdbReceiver object for processing tuples as well as
* structures for correlating child and parent tuples.
*/
class NdbResultStream {
public:
/**
* @param operation The operation for which we will receive results.
* @param worker the NdbWorker delivering the result to this 'stream.
*/
explicit NdbResultStream(NdbQueryOperationImpl& operation,
NdbWorker& worker);
~NdbResultStream();
/**
* Prepare for receiving first results.
*/
void prepare();
/** Prepare for receiving next batch of scan results, return nodes prepared */
SpjTreeNodeMask prepareNextReceiveSet();
NdbReceiver& getReceiver()
{ return m_receiver; }
const NdbReceiver& getReceiver() const
{ return m_receiver; }
const char* getCurrentRow()
{ return m_receiver.getCurrentRow(); }
/**
* Process an incomming tuple for this stream. Extract parent and own tuple
* ids and pass it on to m_receiver.
*
* @param ptr buffer holding tuple.
* @param len buffer length.
*/
void execTRANSID_AI(const Uint32 *ptr, Uint32 len,
TupleCorrelation correlation);
/**
* A complete batch has been received from the 'worker' delivering to NdbResultStream.
* Update whatever required before the appl. are allowed to navigate the result.
*/
void prepareResultSet(SpjTreeNodeMask expectingResults,
SpjTreeNodeMask stillActiveScans);
/**
* Navigate within the current ResultSet to resp. first and next row.
* For non-parent operations in the pushed query, navigation is with respect
* to any preceding parents which results in this ResultSet depends on.
* Returns either the tupleNo within TupleSet[] which we navigated to, or
* tupleNotFound().
*/
Uint16 firstResult();
Uint16 nextResult();
/**
* Returns true if last row matching the current parent tuple has been
* consumed.
*/
bool isEmpty() const
{ return m_iterState == Iter_finished; }
/**
* The internalOpNo is the identifier for this OpNo used in the
* 'matchingChild' logic in ::prepareResultSet().
*/
Uint32 getInternalOpNo() const
{ return m_internalOpNo; }
/**
* Returns true if this result stream holds the last batch of a sub scan.
* This means that it is the last batch of the scan that was instantiated
* from the current batch of its parent operation.
*/
bool isSubScanComplete(SpjTreeNodeMask remainingScans) const
{
return !remainingScans.get(m_internalOpNo);
}
bool isScanQuery() const
{ return (m_properties & Is_Scan_Query); }
bool isScanResult() const
{ return (m_properties & Is_Scan_Result); }
bool isInnerJoin() const
{ return (m_properties & Is_Inner_Join); }
bool isOuterJoin() const
{ return !(m_properties & Is_Inner_Join); }
bool isAntiJoin() const
{ return (m_properties & Is_Anti_Join); }
bool isFirstInner() const
{ return (m_properties & Is_First_Inner); }
bool useFirstMatch() const
{ return (m_properties & Is_First_Match); }
/** For debugging.*/
friend NdbOut& operator<<(NdbOut& out, const NdbResultStream&);
/**
* TupleSet contain two logically distinct set of information:
*
* - Child/Parent correlation set required to correlate
* child tuples with its parents. Child/Tuple pairs are indexed
* by tuple number which is the same as the order in which tuples
* appear in the NdbReceiver buffers.
*
* - A HashMap on 'm_parentId' used to locate tuples correlated
* to a parent tuple. Indexes by hashing the parentId such that:
* - [hash(parentId)].m_hash_head will then index the first
* TupleSet entry potential containing the parentId to locate.
* - .m_hash_next in the indexed TupleSet may index the next TupleSet
* to considder.
*
* Both the child/parent correlation set and the parentId HashMap has been
* folded into the same structure on order to reduce number of objects
* being dynamically allocated.
* As an advantage this results in an autoscaling of the hash bucket size .
*
* Structure is only present if 'isScanQuery'
*/
class TupleSet {
public:
// Tuple ids are unique within this batch and stream
Uint16 m_parentId; // Id of parent tuple which this tuple is correlated with
Uint16 m_tupleId; // Id of this tuple
Uint16 m_hash_head; // Index of first item in TupleSet[] matching a hashed parentId.
Uint16 m_hash_next; // 'next' index matching
/**
* m_matchingChild keep track of current and previous matches found for
* this tuple in the TupleSet:
*
* Bit 0 is the 'skip' bit for the current row. If set the row should be
* ignored when preparing the result sets and presenting the results rows
* through the API
*
* Note that there are no children with an m_internalOpNo of 0, so using
* bit-0 as a skip bit should not interfere with matching of child rows.
*
* The rest of the bits in m_matchingChild keep track of match history
* in previous result batches relating to this TupleSet. It has two usages,
* depending on whether it is an outer- or firstMatch-semi-join:
*
* outer-join:
* The aggregated set of (outer joined) nests which matched this tuple.
* (NULL-extensions excluded.) Only the bit representing the firstInner
* of the nest having a matching set of rows is set. Needed in order to
* decide when/if a NULL extension of the rows on this outer joined
* nest should be emitted or not.
*
* firstMatch semi-join:
* The aggregated set of treeNodes which has a previous match with tuple.
* Used to decide if a firstMatch had already been found for this tuple,
* such that further matches should be skipped.
*
* There is also a special skip-firstMatch usage of m_matchingChild, where
* all bits are set. (Also include the normal bit-0 skip). Using the normal
* interpretation of the bits, that translate into: All 31 firstMatch or
* outer-join children of the root matched, but skip the root tuple itself.
* That is an impossible contradiction of the join / firstMatch semantics,
* so this special all-set bit pattern could not happen elsewhere.
*
* Entering the skip-firstMatch mode will also overwrite any outer_join and
* firstMatch bits previously set. That is fine, as no further outer-join or
* firstMatch handling is relevant when skip-firstMatch has been set.
*/
SpjTreeNodeMask m_matchingChild;
explicit TupleSet() : m_hash_head(tupleNotFound)
{}
private:
/** No copying.*/
TupleSet(const TupleSet&);
TupleSet& operator=(const TupleSet&);
};
private:
/**
* This stream handles results derived from specified
* 'm_worker' creating partial SPJ results.
*/
const NdbWorker& m_worker;
/** Operation to which this resultStream belong.*/
NdbQueryOperationImpl& m_operation;
/** Cached internal OpNo, as retrieves from m_operation.getInternalOpNo() */
const Uint32 m_internalOpNo;
/** ResultStream for my parent operation, or nullptr if I am root */
const NdbResultStream* const m_parent;
/** Children of this operation.*/
Vector<NdbResultStream*> m_children;
/**
* The 'skipFirstInnerOpNo' is used as part of ::prepareResultSet()
* when there is a non-match for an outer-joined child. It will
* hold the internalOpNo of the NdbResultStream being either:
*
* 1) The first_inner of the (outer-joined) join_nest this
* NdbResultStream is a member of.
* --OR--
* 2) If this NdbResultStream is the first_inner itself, it
* will hold the first_inner of the join_nest we are embedded within
* ( -> or outer joined with...)
*
* Thus, in case an outer joined match is not found, *and* a NULL-extended
* result row should not be created, skipFirstInnerOpNo will then identify
* the first_inner of an join_nest where the entire nest will not match.
* prepareResultSet() use this to early-skip impossible matches.
*/
Uint32 m_skipFirstInnerOpNo;
/**
* The dependants node map contain those nodes depending on (the existence of)
* this internalOpNo. That includes all Op's in the same join nest *after*
* this op as well as all nodes in other join nests which are nested within
* the nest of this Op. In terms of QueryOperands that translates to:
* - All children of this op.
* - All Op's in branches referring this op as a firstUpper/Inner
*
* By convention this node itself is also contained in the dependants map
*/
const SpjTreeNodeMask m_dependants;
const enum properties
{
Is_Scan_Query = 0x01,
Is_Scan_Result = 0x02,
Is_Inner_Join = 0x10, // As opposed to outer join
Is_First_Match = 0x20, // Return FirstMatch only (semijoin)
Is_Anti_Join = 0x40,
Is_First_Inner = 0x80
} m_properties;
/** The receiver object that unpacks transid_AI messages.*/
NdbReceiver m_receiver;
/**
* ResultSets are received into and read from this stream,
* possibly doublebuffered,
*/
NdbResultSet m_resultSets[2];
Uint32 m_read; // We read from m_resultSets[m_read]
Uint32 m_recv; // We receive into m_resultSets[m_recv]
/** This is the state of the iterator used by firstResult(), nextResult().*/
enum
{
/** The first row has not been fetched yet.*/
Iter_notStarted,
/** Is iterating the ResultSet, (implies 'm_currentRow!=tupleNotFound').*/
Iter_started,
/** Last row for current ResultSet has been returned.*/
Iter_finished
} m_iterState;
/**
* Tuple id of the current tuple, or 'tupleNotFound'
* if Iter_notStarted or Iter_finished.
*/
Uint16 m_currentRow;
/** Max #rows which this stream may recieve in its TupleSet structures */
Uint32 m_maxRows;
/** TupleSet contains the correlation between parent/childs */
TupleSet* m_tupleSet;
void buildResultCorrelations();
Uint16 getTupleId(Uint16 tupleNo) const
{ return (m_tupleSet) ? m_tupleSet[tupleNo].m_tupleId : 0; }
Uint16 getCurrentTupleId() const
{ return (m_currentRow==tupleNotFound) ? tupleNotFound : getTupleId(m_currentRow); }
Uint16 findTupleWithParentId(Uint16 parentId) const;
Uint16 findNextTuple(Uint16 tupleNo) const;
/** Set/clear/check whether the specified tupleNo should become invisible */
void setSkipped(Uint16 tupleNo)
{ m_tupleSet[tupleNo].m_matchingChild.set(0U); }
void clearSkipped(Uint16 tupleNo)
{ m_tupleSet[tupleNo].m_matchingChild.clear(0U); }
bool isSkipped(Uint16 tupleNo) const
{ return m_tupleSet[tupleNo].m_matchingChild.get(0U); }
/**
* The skip methods above are a 'one time'-skip, where the tuples are
* skipped for this result batch only, and the skip recalculated for the
* next batch. For FirstMatch we need to skip the matched row for multiple
* batches, so we have a special variant for doing firstMatch-skip.
* (Also see comment for the 'm_matchingChild' member variable).
*
* Note that a firstMatch-skip also implies a 'normal' skip, but not the
* other way around.
*/
void setSkippedFirstMatch(Uint16 tupleNo)
{ m_tupleSet[tupleNo].m_matchingChild.set(); }
void clearSkippedFirstMatch(Uint16 tupleNo)
{ m_tupleSet[tupleNo].m_matchingChild.clear(); }
bool isSkippedFirstMatch(Uint16 tupleNo) const
{ return m_tupleSet[tupleNo].m_matchingChild.is_set(); }
/** No copying.*/
NdbResultStream(const NdbResultStream&);
NdbResultStream& operator=(const NdbResultStream&);
}; //class NdbResultStream
//////////////////////////////////////////////
///////// NdbBulkAllocator methods ///////////
//////////////////////////////////////////////
NdbBulkAllocator::NdbBulkAllocator(size_t objSize)
:m_objSize(objSize),
m_maxObjs(0),
m_buffer(NULL),
m_nextObjNo(0)
{}
int NdbBulkAllocator::init(Uint32 maxObjs)
{
assert(m_buffer == NULL);
m_maxObjs = maxObjs;
// Add check for buffer overrun.
m_buffer = new char[m_objSize*m_maxObjs+1];
if (unlikely(m_buffer == NULL))
{
return Err_MemoryAlloc;
}
m_buffer[m_maxObjs * m_objSize] = endMarker;
return 0;
}
void NdbBulkAllocator::reset(){
// Overrun check.
assert(m_buffer == NULL || m_buffer[m_maxObjs * m_objSize] == endMarker);
delete [] m_buffer;
m_buffer = NULL;
m_nextObjNo = 0;
m_maxObjs = 0;
}
void* NdbBulkAllocator::allocObjMem(Uint32 noOfObjs)
{
assert(m_nextObjNo + noOfObjs <= m_maxObjs);
void * const result = m_buffer+m_objSize*m_nextObjNo;
m_nextObjNo += noOfObjs;
return m_nextObjNo > m_maxObjs ? NULL : result;
}
///////////////////////////////////////////
///////// NdbResultSet methods ///////////
///////////////////////////////////////////
NdbResultSet::NdbResultSet() :
m_buffer(NULL),
m_correlations(NULL),
m_rowCount(0)
{}
void
NdbResultSet::init(NdbQueryImpl& query,
Uint32 maxRows,
Uint32 bufferSize)
{
{
NdbBulkAllocator& bufferAlloc = query.getRowBufferAlloc();
Uint32 *buffer = reinterpret_cast<Uint32*>(bufferAlloc.allocObjMem(bufferSize));
m_buffer = NdbReceiver::initReceiveBuffer(buffer, bufferSize, maxRows);
if (query.getQueryDef().isScanQuery())
{
m_correlations = reinterpret_cast<TupleCorrelation*>
(bufferAlloc.allocObjMem(maxRows*sizeof(TupleCorrelation)));
}
}
}
//////////////////////////////////////////////
///////// NdbResultStream methods ///////////
//////////////////////////////////////////////
NdbResultStream::NdbResultStream(NdbQueryOperationImpl& operation,
NdbWorker& worker)
:
m_worker(worker),
m_operation(operation),
m_internalOpNo(operation.getInternalOpNo()),
m_parent(operation.getParentOperation()
? &worker.getResultStream(*operation.getParentOperation())
: nullptr),
m_children(),
m_skipFirstInnerOpNo(~0U),
m_dependants(operation.getDependants()),
m_properties(
(enum properties)
((operation.getQueryDef().isScanQuery()
? Is_Scan_Query : 0)
| (operation.getQueryOperationDef().isScanOperation()
? Is_Scan_Result : 0)
// Note1: If an ancestor is a firstMatch-type, we only need to firstMatch this as well.
// Note2: FirstMatch is only relevant for scans (Both are optimizations only)
| ((operation.getQueryOperationDef().getMatchType() & NdbQueryOptions::MatchFirst ||
operation.getQueryOperationDef().hasFirstMatchAncestor()) &&
operation.getQueryOperationDef().isScanOperation()
? Is_First_Match : 0)
| (operation.getQueryOperationDef().getMatchType() & NdbQueryOptions::MatchNonNull
? Is_Inner_Join : 0)
| (operation.getQueryOperationDef().getMatchType() & NdbQueryOptions::MatchNullOnly
? Is_Anti_Join : 0)
// Is_first_Inner; if outer joined (with upper nest) and another firstInner
// than this 'operation' not specified
| ((operation.getQueryOperationDef().getMatchType() & NdbQueryOptions::MatchNonNull) == 0 &&
(operation.getQueryOperationDef().getFirstInner() == &operation.getQueryOperationDef() ||
operation.getQueryOperationDef().getFirstInner() == nullptr)
? Is_First_Inner : 0))),
m_receiver(operation.getQuery().getNdbTransaction().getNdb()),
m_resultSets(), m_read(0xffffffff), m_recv(0),
m_iterState(Iter_finished),
m_currentRow(tupleNotFound),
m_maxRows(0),
m_tupleSet(NULL)
{
if (m_parent != nullptr)
{
const int res = const_cast<NdbResultStream*>(m_parent)->m_children.push_back(this);
if (res != 0)
{
operation.getQuery().setErrorCode(Err_MemoryAlloc);
return;
}
if (isOuterJoin()) {
/**
* Outer joined scan child need to know the first inner of the
* join nest it is a member of. Used by prepareResultSet() to decide
* if/when a NULL extended row should be allowed for the outer join.
*/
const NdbQueryOperationDefImpl& queryOperationDef =
m_operation.getQueryOperationDef();
const NdbQueryOperationDefImpl* firstInEmbeddingNestDef =
queryOperationDef.getFirstInEmbeddingNest();
if (firstInEmbeddingNestDef == nullptr) {
m_skipFirstInnerOpNo = m_parent->getInternalOpNo();
} else {
if (firstInEmbeddingNestDef->getInternalOpNo() <= m_parent->getInternalOpNo()) {
// First is 'above' parent -> Is parent or an ancestor of 'this' stream
m_skipFirstInnerOpNo = m_parent->getInternalOpNo();
} else {
DBUG_ASSERT(!isScanResult() ||
firstInEmbeddingNestDef->getParentOperation() ==
queryOperationDef.getParentOperation());
m_skipFirstInnerOpNo = firstInEmbeddingNestDef->getInternalOpNo();
}
}
}
}
}
NdbResultStream::~NdbResultStream()
{
for (int i = static_cast<int>(m_maxRows)-1; i >= 0; i--)
{
m_tupleSet[i].~TupleSet();
}
}
void
NdbResultStream::prepare()
{
NdbQueryImpl &query = m_operation.getQuery();
const Uint32 resultBufferSize = m_operation.getResultBufferSize();
if (isScanQuery())
{
/* Parent / child correlation is only relevant for scan type queries
* Don't create a m_tupleSet with these correlation id's for lookups!
*/
const Uint32 fragsPerWorker = query.getFragsPerWorker();
m_maxRows = fragsPerWorker * m_operation.getMaxBatchRows();
m_tupleSet =
new (query.getTupleSetAlloc().allocObjMem(m_maxRows))
TupleSet[m_maxRows];
// Scan results may be double buffered
m_resultSets[0].init(query, m_maxRows, fragsPerWorker * resultBufferSize);
m_resultSets[1].init(query, m_maxRows, fragsPerWorker * resultBufferSize);
}
else
{
m_maxRows = 1;
m_resultSets[0].init(query, m_maxRows, resultBufferSize);
}
/* Alloc buffer for unpacked NdbRecord row */
const Uint32 rowSize = m_operation.getRowSize();
assert((rowSize % sizeof(Uint32)) == 0);
char *rowBuffer = reinterpret_cast<char*>(query.getRowBufferAlloc().allocObjMem(rowSize));
assert(rowBuffer != NULL);
m_receiver.init(NdbReceiver::NDB_QUERY_OPERATION, &m_operation);
m_receiver.do_setup_ndbrecord(
m_operation.getNdbRecord(),
rowBuffer,
false, /*read_range_no*/
false /*read_key_info*/);
} //NdbResultStream::prepare
/** Locate, and return 'tupleNo', of first tuple with specified parentId.
* parentId == tupleNotFound is use as a special value for iterating results
* from the root operation in the order which they was inserted by
* ::buildResultCorrelations()
*
* Position of 'currentRow' is *not* updated and should be modified by callee
* if it want to keep the new position.
*/
Uint16
NdbResultStream::findTupleWithParentId(Uint16 parentId) const
{
assert ((parentId==tupleNotFound) == (m_parent==NULL));
if (likely(m_resultSets[m_read].m_rowCount>0))
{
if (m_tupleSet==NULL)
{
assert (m_resultSets[m_read].m_rowCount <= 1);
return 0;
}
const Uint16 hash = (parentId % m_maxRows);
Uint16 currentRow = m_tupleSet[hash].m_hash_head;
while (currentRow != tupleNotFound)
{
assert(currentRow < m_maxRows);
if (!isSkipped(currentRow) &&
m_tupleSet[currentRow].m_parentId == parentId)
{
return currentRow;
}
currentRow = m_tupleSet[currentRow].m_hash_next;
}
}
return tupleNotFound;
} //NdbResultStream::findTupleWithParentId()
/** Locate, and return 'tupleNo', of next tuple with same parentId as currentRow
* Position of 'currentRow' is *not* updated and should be modified by callee
* if it want to keep the new position.
*/
Uint16
NdbResultStream::findNextTuple(Uint16 tupleNo) const
{
if (tupleNo!=tupleNotFound && m_tupleSet!=NULL)
{
assert(tupleNo < m_maxRows);
Uint16 parentId = m_tupleSet[tupleNo].m_parentId;
Uint16 nextRow = m_tupleSet[tupleNo].m_hash_next;
while (nextRow != tupleNotFound)
{
assert(nextRow < m_maxRows);
if (!isSkipped(nextRow) &&
m_tupleSet[nextRow].m_parentId == parentId)
{
return nextRow;
}
nextRow = m_tupleSet[nextRow].m_hash_next;
}
}
return tupleNotFound;
} //NdbResultStream::findNextTuple()
Uint16
NdbResultStream::firstResult()
{
Uint16 parentId = tupleNotFound;
if (m_parent!=NULL)
{
parentId = m_parent->getCurrentTupleId();
if (parentId == tupleNotFound)
{
m_currentRow = tupleNotFound;
m_iterState = Iter_finished;
return tupleNotFound;
}
}
if ((m_currentRow=findTupleWithParentId(parentId)) != tupleNotFound)
{
m_iterState = Iter_started;
const char *p = m_receiver.getRow(m_resultSets[m_read].m_buffer, m_currentRow);
assert(p != NULL); ((void)p);
return m_currentRow;
}
m_iterState = Iter_finished;
return tupleNotFound;
} //NdbResultStream::firstResult()
Uint16
NdbResultStream::nextResult()
{
// Fetch next row for this stream
if (m_currentRow != tupleNotFound &&
(m_currentRow=findNextTuple(m_currentRow)) != tupleNotFound)
{
m_iterState = Iter_started;
const char *p = m_receiver.getRow(m_resultSets[m_read].m_buffer, m_currentRow);
assert(p != NULL); ((void)p);
return m_currentRow;
}
m_iterState = Iter_finished;
return tupleNotFound;
} //NdbResultStream::nextResult()
/**
* Callback when a TRANSID_AI signal (receive row) is processed.
*/
void
NdbResultStream::execTRANSID_AI(const Uint32 *ptr, Uint32 len,
TupleCorrelation correlation)
{
NdbResultSet& receiveSet = m_resultSets[m_recv];
if (isScanQuery())
{
/**
* Store TupleCorrelation.
*/
receiveSet.m_correlations[receiveSet.m_rowCount] = correlation;
}
m_receiver.execTRANSID_AI(ptr, len);
receiveSet.m_rowCount++;
} // NdbResultStream::execTRANSID_AI()
/**
* Make preparation for another batch of results to be received.
* This NdbResultStream, and all its sibling will receive a batch
* of results from the datanodes.
*/
SpjTreeNodeMask
NdbResultStream::prepareNextReceiveSet()
{
SpjTreeNodeMask prepared;
if (isScanQuery()) // Doublebuffered ResultSet[] if isScanQuery()
{
m_recv = (m_recv+1) % 2; // Receive into next ResultSet
assert(m_recv != m_read);
}
m_resultSets[m_recv].prepareReceive(m_receiver);
prepared.set(getInternalOpNo());
/**
* If this stream will get new rows in the next batch, then so will
* all of its descendants.
*/
for (Uint32 childNo = 0; childNo < m_operation.getNoOfChildOperations();
childNo++)
{
NdbQueryOperationImpl& child = m_operation.getChildOperation(childNo);
prepared.bitOR(m_worker.getResultStream(child).prepareNextReceiveSet());
}
return prepared;
} //NdbResultStream::prepareNextReceiveSet
/**
* Make preparations for another batch of result to be read:
* - Advance to next NdbResultSet. (or reuse last)
* - Fill in parent/child result correlations in m_tupleSet[]
* for those getting a new ResulSet in this batch.
* - Apply inner/outer join filtering to remove non qualifying
* rows.
*/
void
NdbResultStream::prepareResultSet(const SpjTreeNodeMask expectingResults,
const SpjTreeNodeMask stillActive)
{
/**
* Prepare NdbResultSet for reading - either the next
* 'new' received from datanodes or reuse the last as has been
* determined by ::prepareNextReceiveSet()
*/
m_read = m_recv;
const NdbResultSet& readResult = m_resultSets[m_read];
if (m_tupleSet != nullptr &&
expectingResults.get(getInternalOpNo()))
{
buildResultCorrelations();
}
SpjTreeNodeMask firstMatchedNodes;
for (int childNo=m_children.size()-1; childNo>=0; childNo--)
{
NdbResultStream& childStream = *m_children[childNo];
if (expectingResults.overlaps(childStream.m_dependants))
{
// childStream got new result rows
childStream.prepareResultSet(expectingResults,stillActive);
}
// Collect set of treeNodes involved in a firstMatch
if (childStream.useFirstMatch())
{
firstMatchedNodes.bitOR(childStream.m_dependants);
}
}
// The 'highest order' child treeNode in expectingResults decides
// whether firstMatch elimination should be done in result set or not.
const uint firstInExpected = expectingResults.find_first();
// Prepare rows from the NdbQueryOperation's accessible now
if (m_tupleSet != nullptr)
{
const Uint32 thisOpId = getInternalOpNo();
const Uint32 rowCount = readResult.getRowCount();
for (Uint32 tupleNo=0; tupleNo < rowCount; tupleNo++)
{
/**
* FirstMatch handling: If this tupleNo already found a match from all
* tables, we skip it from further result processing:
*/
if (!firstMatchedNodes.isclear() && // Some childrens are firstmatch-semi-joins
m_tupleSet[tupleNo].m_matchingChild.contains(firstMatchedNodes))
{
// We have already found a match for (all of) our firstMatchedNodes.
// Should we skip potentially duplicates now? :
if (firstMatchedNodes.get(firstInExpected))
{
// Got a new set of firstMatch'ed rows, starting with semi-joined tables.
// Skip parent rows which already had its 'firstMatch'
if (unlikely(traceSignals)) {
ndbout << "prepareResultSet, useFirstMatch"
<< ", seen matches -> skip tupleNo"
<< ", opNo: " << thisOpId
<< ", row: " << tupleNo
<< endl;
}
// Done with this tupleNo
setSkippedFirstMatch(tupleNo);
continue; // Skip further processing of this row
}
else if (!firstMatchedNodes.overlaps(expectingResults))
{
// No semi joined tables affected by the 'expecting'.
// Do nothing, except keeping 'isSkipped' if already set.
if (unlikely(traceSignals)) {
ndbout << "prepareResultSet, 'expecting' doesn't overlaps FirstMatchNodes"
<< ", opNo: " << thisOpId
<< ", row: " << tupleNo
<< ", isSkipped?: " << isSkippedFirstMatch(tupleNo)
<< endl;
}
if (isSkippedFirstMatch(tupleNo)) // Already had a firstMatch
continue; // Keep skipping it
}
else
{
// Set of new children rows start with a full-join. Thus, the
// firstMatch handling is reset as part of preparing the new
// joined result set.
if (unlikely(traceSignals)) {
ndbout << "prepareResultSet, Join-useFirstMatch"
<< ", cleared 'hadMatching'-> un-skip"
<< ", opNo: " << thisOpId
<< ", row: " << tupleNo
<< endl;
}
clearSkippedFirstMatch(tupleNo);
}
} // FirstMatch
/**
* For each children; try to locate a matching row for tupleNo.
* Note down in hasMatchingChild when matching children are
* (not) found. We try to break out of the child-loop as soon
* as possible when we can conclude that a join-match is not
* possible. In such cases the thisOpNo-bit in hasMatchingChild
* is cleared in order to signal a 'skip' of this tupleNo.
*
* We can always 'skip' if the join-type is an InnerJoin.
* Else we use 'm_skipFirstInnerOpNo' to decide if an early 'skip'
* is possible or not.
*
* In addition there is extra logic for outer joins to decide
* if a NULL extended row should be made visible or not.
*/
SpjTreeNodeMask hasMatchingChild; // Collected Join match properties
hasMatchingChild.set(); // Assume a match
const Uint16 tupleId = getTupleId(tupleNo);
for (int childNo=m_children.size()-1; childNo>=0; childNo--)
{
const NdbResultStream& childStream = *m_children[childNo];
const Uint32 childId = childStream.getInternalOpNo();
/**
* Check for a matching child row(s). A 'skipFirstInnerOpNo'
* could possibly already have concluded the join-nest to be
* a non-match, and cleared our hasMatchingChild-bit.
*/
const bool childMatched = hasMatchingChild.get(childId)
? (childStream.findTupleWithParentId(tupleId) != tupleNotFound)
: false; // A previous (inner joined) Op already decided 'no-match'
if (unlikely(traceSignals)) {
const char *const state = (childMatched) ?"MATCHED" :"NO MATCH";
ndbout << "prepareResultSet, " << state
<< ", opNo: " << thisOpId
<< ", row: " << tupleNo
<< ", child: " << childId
<< endl;
}
if (childMatched == false) // Didn't match
{
hasMatchingChild.clear(childId);
if (childStream.isInnerJoin())
{
hasMatchingChild.clear(thisOpId); // Skip this tupleNo
break;
}
}
if (childStream.isOuterJoin())
{
if (childMatched == true)
{
// Found a match for this outer joined child,
// remember that to avoid later NULL extensions
m_tupleSet[tupleNo].m_matchingChild.set(childId);
if (unlikely(traceSignals)) {
ndbout << "prepareResultSet, isOuterJoin"
<< ", matched 'innerNest'"
<< ", opNo: " << thisOpId
<< ", row: " << tupleNo
<< ", child: " << childId
<< endl;
}
if (childStream.isAntiJoin()) {
hasMatchingChild.clear(thisOpId); // Skip this tupleNo
break;
}
}
/**
* Else: No matching children found from 'childId'. Now we may either
* create a NULL-extended row for the outer join(s), or keep looking
* for matches in later batches.
*
* A NULL-extended row should be created if:
* 1) This child is the firstInner in this outer-joined_nest, and
* 2) There are no more unfetched result rows from any of the
* outer-joined tables, or descendants of these.
* 3) A previous join-match had not been found
*/
else if (childStream.isFirstInner() && // 1)
!stillActive.overlaps(childStream.m_dependants) && // 2)
!m_tupleSet[tupleNo].m_matchingChild.get(childId)) // 3)
{
/**
* NULL-extend join-nest:
*
* No previous match found and no more rows expected.
* The NULL-extended row itself is created by the mysql server.
* All we have to do here is to treat the childId row as a
* 'match', such that and ancestor rows depending on it are
* allowed to be returned as well.
*/
hasMatchingChild.set(childId);
DBUG_ASSERT(hasMatchingChild.get(thisOpId));
if (unlikely(traceSignals)) {
const char *reason =
childStream.isAntiJoin() ?"(antijoin match)" :"(never matched)";
ndbout << "prepareResultSet, isOuterJoin"
<< ", NULL-extend, " << reason
<< ", opNo: " << thisOpId
<< ", row: " << tupleNo
<< ", child: " << childId
<< endl;
}
}
else
{
/**
* This is a non-match, without a NULL-extended join-nest (yet).
* Entire join-nest then becomes a match-failure itself.
* Handle this by 'un-matching' the firstInner of the join-nest.
*/
const Uint32 skipFirstInnerOpNo = childStream.m_skipFirstInnerOpNo;
DBUG_ASSERT(skipFirstInnerOpNo != ~0U);
hasMatchingChild.clear(skipFirstInnerOpNo); // Un-match join-nest
if (likely(skipFirstInnerOpNo == thisOpId)) {
/**
* firstInner in child's join-nest is thisOpId. 'un-matching'
* it also allowes us to conclude that thisOpNo is a 'skip'.
*/
if (unlikely(traceSignals)) {
ndbout << "prepareResultSet, isOuterJoin, ('child' is firstInner)"
<< " -> Skip it"
<< endl;
}
break; // Skip further child matching against this tupleNo
} else if (unlikely(traceSignals)) {
/**
* Join-nests has a first-inner being a sibling of (same parent as)
* this childStream. Can not skip yet, but was un-matched above
* such that we detect it as a failed-match when processed later.
*/
ndbout << "prepareResultSet, isOuterJoin (has firstInnerSibling)"
<< ", un-match firstInner: " << skipFirstInnerOpNo
<< endl;
}
}
} //if (isOuterJoin())
} //for (childNo..)
/**
* If some 'required' descendants of tupleNo didnt 'Match' (possibly with
* a NULL-row), the 'thisOpId' bit would have been cleared when checking
* the descendant Op's above. This tuple then needs to be skipped for now.
* May still be included in later result batches though, with a new set
* of descendants' row either matching or allowing NULL extensions.
*/
if (!hasMatchingChild.get(thisOpId))
{
// Persist the decission to skip this tupleNo
setSkipped(tupleNo);
}
else // tupleNo is part of (intermediate) results
{
clearSkipped(tupleNo);
/**
* When we get here we know that all children matched, including the
* 'firstMatchedNodes' (which are possibly a 0-mask if none 'useFirstMatch')
* Anyway we note down that a potential firstmatch has been found.
*/
m_tupleSet[tupleNo].m_matchingChild.bitOR(firstMatchedNodes);
}
} //for (tupleNo..)
} //if (m_tupleSet ..)
// Set current position 'before first'
m_iterState = Iter_notStarted;
m_currentRow = tupleNotFound;
} // NdbResultStream::prepareResultSet()
/**
* Fill m_tupleSet[] with correlation data between parent
* and child tuples. The 'TupleCorrelation' is stored
* in an array of TupleCorrelations in each ResultSet
* by execTRANSID_AI().
*
* NOTE: In order to reduce work done when holding the
* transporter mutex, the 'TupleCorrelation' is only stored
* in the buffer when it arrives. Later (here) we build the
* correlation hashMap immediately before we prepare to
* read the NdbResultSet.
*/
void
NdbResultStream::buildResultCorrelations()
{
const NdbResultSet& readResult = m_resultSets[m_read];
//if (m_tupleSet!=NULL)
{
/* Clear the hashmap structures */
for (Uint32 i=0; i<m_maxRows; i++)
{
m_tupleSet[i].m_hash_head = tupleNotFound;
}
/* Rebuild correlation & hashmap from 'readResult' */
for (Uint32 tupleNo=0; tupleNo<readResult.m_rowCount; tupleNo++)
{
const Uint16 tupleId = readResult.m_correlations[tupleNo].getTupleId();
const Uint16 parentId = (m_parent!=NULL)
? readResult.m_correlations[tupleNo].getParentTupleId()
: tupleNotFound;
m_tupleSet[tupleNo].m_parentId = parentId;
m_tupleSet[tupleNo].m_tupleId = tupleId;
m_tupleSet[tupleNo].m_matchingChild.clear();
/* Insert into parentId-hashmap */
const Uint16 hash = (parentId % m_maxRows);
if (m_parent==NULL)
{
/* Root stream: Insert sequentially in hash_next to make it
* possible to use ::findTupleWithParentId() and ::findNextTuple()
* to navigate even the root operation.
*/
/* Link into m_hash_next in order to let ::findNextTuple() navigate correctly */
if (tupleNo==0)
m_tupleSet[hash].m_hash_head = tupleNo;
else
m_tupleSet[tupleNo-1].m_hash_next = tupleNo;
m_tupleSet[tupleNo].m_hash_next = tupleNotFound;
}
else
{
/* Insert parentId in HashMap */
m_tupleSet[tupleNo].m_hash_next = m_tupleSet[hash].m_hash_head;
m_tupleSet[hash].m_hash_head = tupleNo;
}
}
}
} // NdbResultStream::buildResultCorrelations
/////////////////////////////////////
//////// NdbWorker methods /////////
/////////////////////////////////////
void NdbWorker::buildReceiverIdMap(NdbWorker* workers,
Uint32 noOfWorkers)
{
for (Uint32 workerNo = 0; workerNo < noOfWorkers; workerNo++)
{
const Uint32 receiverId = workers[workerNo].getReceiverId();
/**
* For reasons unknow, NdbObjectIdMap shifts ids two bits to the left,
* so we must do the opposite to get a good hash distribution.
*/
assert((receiverId & 0x3) == 0);
const int hash =
(receiverId >> 2) % noOfWorkers;
workers[workerNo].m_idMapNext = workers[hash].m_idMapHead;
workers[hash].m_idMapHead = workerNo;
}
}
//static
NdbWorker*
NdbWorker::receiverIdLookup(NdbWorker* workers,
Uint32 noOfWorkers,
Uint32 receiverId)
{
/**
* For reasons unknow, NdbObjectIdMap shifts ids two bits to the left,
* so we must do the opposite to get a good hash distribution.
*/
assert((receiverId & 0x3) == 0);
const int hash = (receiverId >> 2) % noOfWorkers;
int current = workers[hash].m_idMapHead;
assert(current < static_cast<int>(noOfWorkers));
while (current >= 0 && workers[current].getReceiverId() != receiverId)
{
current = workers[current].m_idMapNext;
assert(current < static_cast<int>(noOfWorkers));
}
if (unlikely (current < 0))
{
return NULL;
}
else
{
return &workers[current];
}
}
NdbWorker::NdbWorker():
m_query(NULL),
m_workerNo(voidWorkerNo),
m_resultStreams(NULL),
m_pendingRequests(0),
m_availResultSets(0),
m_outstandingResults(0),
m_confReceived(false),
m_preparedReceiveSet(),
m_nextScans(),
m_activeScans(),
m_idMapHead(-1),
m_idMapNext(-1)
{
m_nextScans.set();
}
NdbWorker::~NdbWorker()
{
assert(m_resultStreams==NULL);
}
void NdbWorker::init(NdbQueryImpl& query, Uint32 workerNo)
{
assert(m_workerNo==voidWorkerNo);
m_query = &query;
m_workerNo = workerNo;
m_resultStreams = reinterpret_cast<NdbResultStream*>
(query.getResultStreamAlloc().allocObjMem(query.getNoOfOperations()));
assert(m_resultStreams!=NULL);
for (unsigned opNo=0; opNo<query.getNoOfOperations(); opNo++)
{
NdbQueryOperationImpl& op = query.getQueryOperation(opNo);
new (&m_resultStreams[opNo]) NdbResultStream(op,*this);
m_resultStreams[opNo].prepare();
}
}
/**
* Release what we want need anymore after last available row has been
* returned from datanodes.
*/
void
NdbWorker::postFetchRelease()
{
if (m_resultStreams != NULL)
{
for (unsigned opNo=0; opNo<m_query->getNoOfOperations(); opNo++)
{
m_resultStreams[opNo].~NdbResultStream();
}
}
/**
* Don't 'delete' the object as it was in-place constructed from
* ResultStreamAlloc'ed memory. Memory is released by
* ResultStreamAlloc::reset().
*/
m_resultStreams = NULL;
}
NdbResultStream&
NdbWorker::getResultStream(Uint32 operationNo) const
{
assert(m_resultStreams);
return m_resultStreams[operationNo];
}
/**
* Throw any pending ResultSets from specified workers[]
*/
//static
void NdbWorker::clear(NdbWorker* workers, Uint32 noOfWorkers)
{
if (workers != NULL)
{
for (Uint32 workerNo = 0; workerNo < noOfWorkers; workerNo++)
{
workers[workerNo].m_pendingRequests = 0;
workers[workerNo].m_availResultSets = 0;
}
}
}
/**
* Check if there has been requested more ResultSets from
* this worker which has not been consumed yet.
* (This is also a candicate check for ::hasReceivedMore())
*/
bool NdbWorker::hasRequestedMore() const
{
return (m_pendingRequests > 0);
}
/**
* Signal that another complete ResultSet is available from
* this worker.
* Need mutex lock as 'm_availResultSets' is accesed both from
* receiver and application thread.
*/
void NdbWorker::setReceivedMore() // Need mutex
{
assert(m_availResultSets==0);
m_availResultSets++;
}
/**
* Check if another ResultSets has been received and is available
* for reading. It will be given to the application thread when it
* call ::grabNextResultSet().
* Need mutex lock as 'm_availResultSets' is accesed both from
* receiver and application thread.
*/
bool NdbWorker::hasReceivedMore() const // Need mutex
{
return (m_availResultSets > 0);
}
void NdbWorker::prepareNextReceiveSet()
{
assert(m_workerNo!=voidWorkerNo);
assert(m_outstandingResults == 0);
m_preparedReceiveSet.clear();
for (unsigned opNo=0; opNo<m_query->getNoOfOperations(); opNo++)
{
NdbResultStream& resultStream = getResultStream(opNo);
if (!resultStream.isSubScanComplete(m_nextScans))
{
/**
* Reset resultStream and all its descendants, since all these
* streams will get a new set of rows in the next batch.
*/
m_preparedReceiveSet.bitOR(resultStream.prepareNextReceiveSet());
}
}
m_confReceived = false;
m_pendingRequests++;
}
/**
* Let the application thread takes ownership of an available
* ResultSet, prepare it for reading first row.
* Need mutex lock as 'm_availResultSets' is accesed both from
* receiver and application thread.
*/
void NdbWorker::grabNextResultSet() // Need mutex
{
assert(m_availResultSets>0);
m_availResultSets--;
assert(m_pendingRequests>0);
m_pendingRequests--;
NdbResultStream& rootStream = getResultStream(0);
rootStream.prepareResultSet(m_preparedReceiveSet, m_activeScans);
/* Position at the first (sorted?) row available from this worker.
*/
rootStream.firstResult();
}
void NdbWorker::setConfReceived(Uint32 tcPtrI)
{
/* For a query with a lookup root, there may be more than one TCKEYCONF
message. For a scan, there should only be one SCAN_TABCONF per
worker result set.
*/
assert(!getResultStream(0).isScanQuery() || !m_confReceived);
getResultStream(0).getReceiver().m_tcPtrI = tcPtrI;
m_confReceived = true;
}
bool NdbWorker::finalBatchReceived() const
{
return m_confReceived && getReceiverTcPtrI()==RNIL;
}
bool NdbWorker::isEmpty() const
{
return getResultStream(0).isEmpty();
}
/**
* SPJ requests are identified by the receiver-id of the
* *root* ResultStream for each NdbWorker. Furthermore
* a NEXTREQ use the tcPtrI saved in this ResultStream to
* identify the 'cursor' to restart.
*
* We provide some convenient accessors for fetching this info
*/
Uint32 NdbWorker::getReceiverId() const
{
return getResultStream(0).getReceiver().getId();
}
Uint32 NdbWorker::getReceiverTcPtrI() const
{
return getResultStream(0).getReceiver().m_tcPtrI;
}
///////////////////////////////////////////
///////// NdbQuery API methods ///////////
///////////////////////////////////////////
NdbQuery::NdbQuery(NdbQueryImpl& impl):
m_impl(impl)
{}
NdbQuery::~NdbQuery()
{}
Uint32
NdbQuery::getNoOfOperations() const
{
return m_impl.getNoOfOperations();
}
NdbQueryOperation*
NdbQuery::getQueryOperation(Uint32 index) const
{
return &m_impl.getQueryOperation(index).getInterface();
}
NdbQueryOperation*
NdbQuery::getQueryOperation(const char* ident) const
{
NdbQueryOperationImpl* op = m_impl.getQueryOperation(ident);
return (op) ? &op->getInterface() : NULL;
}
Uint32
NdbQuery::getNoOfParameters() const
{
return m_impl.getNoOfParameters();
}
const NdbParamOperand*
NdbQuery::getParameter(const char* name) const
{
return m_impl.getParameter(name);
}
const NdbParamOperand*
NdbQuery::getParameter(Uint32 num) const
{
return m_impl.getParameter(num);
}
int
NdbQuery::setBound(const NdbRecord *keyRecord,
const NdbIndexScanOperation::IndexBound *bound)
{
const int error = m_impl.setBound(keyRecord,bound);
if (unlikely(error)) {
m_impl.setErrorCode(error);
return -1;
} else {
return 0;
}
}
NdbQuery::NextResultOutcome
NdbQuery::nextResult(bool fetchAllowed, bool forceSend)
{
return m_impl.nextResult(fetchAllowed, forceSend);
}
void
NdbQuery::close(bool forceSend)
{
m_impl.close(forceSend);
}
NdbTransaction*
NdbQuery::getNdbTransaction() const
{
return &m_impl.getNdbTransaction();
}
const NdbError&
NdbQuery::getNdbError() const {
return m_impl.getNdbError();
}
int NdbQuery::isPrunable(bool& prunable) const
{
return m_impl.isPrunable(prunable);
}
NdbQueryOperation::NdbQueryOperation(NdbQueryOperationImpl& impl)
:m_impl(impl)
{}
NdbQueryOperation::~NdbQueryOperation()
{}
Uint32
NdbQueryOperation::getNoOfParentOperations() const
{
return m_impl.getNoOfParentOperations();
}
NdbQueryOperation*
NdbQueryOperation::getParentOperation(Uint32 i) const
{
return &m_impl.getParentOperation(i).getInterface();
}
Uint32
NdbQueryOperation::getNoOfChildOperations() const
{
return m_impl.getNoOfChildOperations();
}
NdbQueryOperation*
NdbQueryOperation::getChildOperation(Uint32 i) const
{
return &m_impl.getChildOperation(i).getInterface();
}
const NdbQueryOperationDef&
NdbQueryOperation::getQueryOperationDef() const
{
return m_impl.getQueryOperationDef().getInterface();
}
NdbQuery&
NdbQueryOperation::getQuery() const {
return m_impl.getQuery().getInterface();
}
NdbRecAttr*
NdbQueryOperation::getValue(const char* anAttrName,
char* resultBuffer)
{
return m_impl.getValue(anAttrName, resultBuffer);
}
NdbRecAttr*
NdbQueryOperation::getValue(Uint32 anAttrId,
char* resultBuffer)
{
return m_impl.getValue(anAttrId, resultBuffer);
}
NdbRecAttr*
NdbQueryOperation::getValue(const NdbDictionary::Column* column,
char* resultBuffer)
{
if (unlikely(column==NULL)) {
m_impl.getQuery().setErrorCode(QRY_REQ_ARG_IS_NULL);
return NULL;
}
return m_impl.getValue(NdbColumnImpl::getImpl(*column), resultBuffer);
}
int
NdbQueryOperation::setResultRowBuf (
const NdbRecord *rec,
char* resBuffer,
const unsigned char* result_mask)
{
if (unlikely(rec==0 || resBuffer==0)) {
m_impl.getQuery().setErrorCode(QRY_REQ_ARG_IS_NULL);
return -1;
}
return m_impl.setResultRowBuf(rec, resBuffer, result_mask);
}
int
NdbQueryOperation::setResultRowRef (
const NdbRecord* rec,
const char* & bufRef,
const unsigned char* result_mask)
{
return m_impl.setResultRowRef(rec, bufRef, result_mask);
}
int
NdbQueryOperation::setOrdering(NdbQueryOptions::ScanOrdering ordering)
{
return m_impl.setOrdering(ordering);
}
NdbQueryOptions::ScanOrdering
NdbQueryOperation::getOrdering() const
{
return m_impl.getOrdering();
}
int NdbQueryOperation::setParallelism(Uint32 parallelism){
return m_impl.setParallelism(parallelism);
}
int NdbQueryOperation::setMaxParallelism(){
return m_impl.setMaxParallelism();
}
int NdbQueryOperation::setAdaptiveParallelism(){
return m_impl.setAdaptiveParallelism();
}
int NdbQueryOperation::setBatchSize(Uint32 batchSize){
return m_impl.setBatchSize(batchSize);
}
int NdbQueryOperation::setInterpretedCode(const NdbInterpretedCode& code) const
{
return m_impl.setInterpretedCode(code);
}
NdbQuery::NextResultOutcome
NdbQueryOperation::firstResult()
{
return m_impl.firstResult();
}
NdbQuery::NextResultOutcome
NdbQueryOperation::nextResult(bool fetchAllowed, bool forceSend)
{
return m_impl.nextResult(fetchAllowed, forceSend);
}
bool
NdbQueryOperation::isRowNULL() const
{
return m_impl.isRowNULL();
}
bool
NdbQueryOperation::isRowChanged() const
{
return m_impl.isRowChanged();
}
/////////////////////////////////////////////////
///////// NdbQueryParamValue methods ///////////
/////////////////////////////////////////////////
enum Type
{
Type_NULL,
Type_raw, // Raw data formated according to bound Column format.
Type_raw_shrink, // As Type_raw, except short VarChar has to be shrinked.
Type_string, // '\0' terminated C-type string, char/varchar data only
Type_Uint16,
Type_Uint32,
Type_Uint64,
Type_Double
};
NdbQueryParamValue::NdbQueryParamValue(Uint16 val) : m_type(Type_Uint16)
{ m_value.uint16 = val; }
NdbQueryParamValue::NdbQueryParamValue(Uint32 val) : m_type(Type_Uint32)
{ m_value.uint32 = val; }
NdbQueryParamValue::NdbQueryParamValue(Uint64 val) : m_type(Type_Uint64)
{ m_value.uint64 = val; }
NdbQueryParamValue::NdbQueryParamValue(double val) : m_type(Type_Double)
{ m_value.dbl = val; }
// C-type string, terminated by '\0'
NdbQueryParamValue::NdbQueryParamValue(const char* val) : m_type(Type_string)
{ m_value.string = val; }
// Raw data
NdbQueryParamValue::NdbQueryParamValue(const void* val, bool shrinkVarChar)
: m_type(shrinkVarChar ? Type_raw_shrink : Type_raw)
{ m_value.raw = val; }
// NULL-value, also used as optional end marker
NdbQueryParamValue::NdbQueryParamValue() : m_type(Type_NULL)
{}
int
NdbQueryParamValue::serializeValue(const class NdbColumnImpl& column,
Uint32Buffer& dst,
Uint32& len,
bool& isNull) const
{
const Uint32 maxSize = column.getSizeInBytes();
isNull = false;
// Start at (32-bit) word boundary.
dst.skipRestOfWord();
// Fetch parameter value and length.
// Rudimentary typecheck of paramvalue: At least length should be as expected:
// - Extend with more types if required
// - Considder to add simple type conversion, ex: Int64 -> Int32
// - Or
// -- Represent all exact numeric as Int64 and convert to 'smaller' int
// -- Represent all floats as Double and convert to smaller floats
//
switch(m_type)
{
case Type_NULL:
isNull = true;
len = 0;
break;
case Type_Uint16:
if (unlikely(column.getType() != NdbDictionary::Column::Smallint &&
column.getType() != NdbDictionary::Column::Smallunsigned))
return QRY_PARAMETER_HAS_WRONG_TYPE;
len = static_cast<Uint32>(sizeof(m_value.uint16));
DBUG_ASSERT(len == maxSize);
dst.appendBytes(&m_value.uint16, len);
break;
case Type_Uint32:
if (unlikely(column.getType() != NdbDictionary::Column::Int &&
column.getType() != NdbDictionary::Column::Unsigned))
return QRY_PARAMETER_HAS_WRONG_TYPE;
len = static_cast<Uint32>(sizeof(m_value.uint32));
DBUG_ASSERT(len == maxSize);
dst.appendBytes(&m_value.uint32, len);
break;
case Type_Uint64:
if (unlikely(column.getType() != NdbDictionary::Column::Bigint &&
column.getType() != NdbDictionary::Column::Bigunsigned))
return QRY_PARAMETER_HAS_WRONG_TYPE;
len = static_cast<Uint32>(sizeof(m_value.uint64));
DBUG_ASSERT(len == maxSize);
dst.appendBytes(&m_value.uint64, len);
break;
case Type_Double:
if (unlikely(column.getType() != NdbDictionary::Column::Double))
return QRY_PARAMETER_HAS_WRONG_TYPE;
len = static_cast<Uint32>(sizeof(m_value.dbl));
DBUG_ASSERT(len == maxSize);
dst.appendBytes(&m_value.dbl, len);
break;
case Type_string:
if (unlikely(column.getType() != NdbDictionary::Column::Char &&
column.getType() != NdbDictionary::Column::Varchar &&
column.getType() != NdbDictionary::Column::Longvarchar))
return QRY_PARAMETER_HAS_WRONG_TYPE;
{
len = static_cast<Uint32>(strlen(m_value.string));
if (unlikely(len > maxSize))
return QRY_CHAR_PARAMETER_TRUNCATED;
dst.appendBytes(m_value.string, len);
}
break;
case Type_raw:
// 'Raw' data is readily formated according to the bound column
if (likely(column.m_arrayType == NDB_ARRAYTYPE_FIXED))
{
len = maxSize;
dst.appendBytes(m_value.raw, maxSize);
}
else if (column.m_arrayType == NDB_ARRAYTYPE_SHORT_VAR)
{
len = 1+*((Uint8*)(m_value.raw));
DBUG_ASSERT(column.getType() == NdbDictionary::Column::Varchar ||
column.getType() == NdbDictionary::Column::Varbinary);
if (unlikely(len > 1+static_cast<Uint32>(column.getLength())))
return QRY_CHAR_PARAMETER_TRUNCATED;
dst.appendBytes(m_value.raw, len);
}
else if (column.m_arrayType == NDB_ARRAYTYPE_MEDIUM_VAR)
{
len = 2+uint2korr((Uint8*)m_value.raw);
DBUG_ASSERT(column.getType() == NdbDictionary::Column::Longvarchar ||
column.getType() == NdbDictionary::Column::Longvarbinary);
if (unlikely(len > 2+static_cast<Uint32>(column.getLength())))
return QRY_CHAR_PARAMETER_TRUNCATED;
dst.appendBytes(m_value.raw, len);
}
else
{
DBUG_ASSERT(0);
}
break;
case Type_raw_shrink:
// Only short VarChar can be shrinked
if (unlikely(column.m_arrayType != NDB_ARRAYTYPE_SHORT_VAR))
return QRY_PARAMETER_HAS_WRONG_TYPE;
DBUG_ASSERT(column.getType() == NdbDictionary::Column::Varchar ||
column.getType() == NdbDictionary::Column::Varbinary);
{
// Convert from two-byte to one-byte length field.
len = 1+uint2korr((Uint8*)m_value.raw);
assert(len <= 0x100);
if (unlikely(len > 1+static_cast<Uint32>(column.getLength())))
return QRY_CHAR_PARAMETER_TRUNCATED;
const Uint8 shortLen = static_cast<Uint8>(len-1);
dst.appendBytes(&shortLen, 1);
dst.appendBytes(((Uint8*)m_value.raw)+2, shortLen);
}
break;
default:
assert(false);
}
if (unlikely(dst.isMemoryExhausted())) {
return Err_MemoryAlloc;
}
return 0;
} // NdbQueryParamValue::serializeValue
///////////////////////////////////////////
///////// NdbQueryImpl methods ///////////
///////////////////////////////////////////
NdbQueryImpl::NdbQueryImpl(NdbTransaction& trans,
const NdbQueryDefImpl& queryDef):
m_interface(*this),
m_state(Initial),
m_tcState(Inactive),
m_next(NULL),
m_queryDef(&queryDef),
m_error(),
m_errorReceived(0),
m_transaction(trans),
m_scanTransaction(NULL),
m_operations(0),
m_countOperations(0),
m_globalCursor(0),
m_pendingWorkers(0),
m_workerCount(0),
m_fragsPerWorker(0),
m_workers(NULL),
m_applFrags(),
m_finalWorkers(0),
m_num_bounds(0),
m_shortestBound(0xffffffff),
m_attrInfo(),
m_keyInfo(),
m_startIndicator(false),
m_commitIndicator(false),
m_prunability(Prune_No),
m_pruneHashVal(0),
m_operationAlloc(sizeof(NdbQueryOperationImpl)),
m_tupleSetAlloc(sizeof(NdbResultStream::TupleSet)),
m_resultStreamAlloc(sizeof(NdbResultStream)),
m_pointerAlloc(sizeof(void*)),
m_rowBufferAlloc(sizeof(char))
{
// Allocate memory for all m_operations[] in a single chunk
m_countOperations = queryDef.getNoOfOperations();
const int error = m_operationAlloc.init(m_countOperations);
if (unlikely(error != 0))
{
setErrorCode(error);
return;
}
m_operations = reinterpret_cast<NdbQueryOperationImpl*>
(m_operationAlloc.allocObjMem(m_countOperations));
// Then; use placement new to construct each individual
// NdbQueryOperationImpl object in m_operations
for (Uint32 i=0; i<m_countOperations; ++i)
{
const NdbQueryOperationDefImpl& def = queryDef.getQueryOperation(i);
new(&m_operations[i]) NdbQueryOperationImpl(*this, def);
// Failed to create NdbQueryOperationImpl object.
if (m_error.code != 0)
{
// Destroy those objects that we have already constructed.
for (int j = static_cast<int>(i)-1; j>= 0; j--)
{
m_operations[j].~NdbQueryOperationImpl();
}
m_operations = NULL;
return;
}
}
// Serialized QueryTree definition is first part of ATTRINFO.
m_attrInfo.append(queryDef.getSerialized());
}
NdbQueryImpl::~NdbQueryImpl()
{
/** BEWARE:
* Don't refer NdbQueryDef or NdbQueryOperationDefs after
* NdbQuery::close() as at this stage the appliaction is
* allowed to destruct the Def's.
*/
assert(m_state==Closed);
assert(m_workers==NULL);
// NOTE: m_operations[] was allocated as a single memory chunk with
// placement new construction of each operation.
// Requires explicit call to d'tor of each operation before memory is free'ed.
if (m_operations != NULL) {
for (int i=m_countOperations-1; i>=0; --i)
{ m_operations[i].~NdbQueryOperationImpl();
}
m_operations = NULL;
}
m_state = Destructed;
}
void
NdbQueryImpl::postFetchRelease()
{
if (m_workers != NULL)
{
for (unsigned i=0; i<m_workerCount; i++)
{
m_workers[i].postFetchRelease();
}
}
if (m_operations != NULL)
{
for (unsigned i=0; i<m_countOperations; i++)
{
m_operations[i].postFetchRelease();
}
}
delete[] m_workers;
m_workers = NULL;
m_rowBufferAlloc.reset();
m_tupleSetAlloc.reset();
m_resultStreamAlloc.reset();
}
//static
NdbQueryImpl*
NdbQueryImpl::buildQuery(NdbTransaction& trans,
const NdbQueryDefImpl& queryDef)
{
assert(queryDef.getNoOfOperations() > 0);
NdbQueryImpl* const query = new NdbQueryImpl(trans, queryDef);
if (unlikely(query==NULL)) {
trans.setOperationErrorCodeAbort(Err_MemoryAlloc);
return NULL;
}
if (unlikely(query->m_error.code != 0))
{
// Transaction error code set already.
query->release();
return NULL;
}
assert(query->m_state==Initial);
return query;
}
/** Assign supplied parameter values to the parameter placeholders
* Created when the query was defined.
* Values are *copied* into this NdbQueryImpl object:
* Memory location used as source for parameter values don't have
* to be valid after this assignment.
*/
int
NdbQueryImpl::assignParameters(const NdbQueryParamValue paramValues[])
{
/**
* Immediately build the serialized parameter representation in order
* to avoid storing param values elsewhere until query is executed.
* Also calculates prunable property, and possibly its hashValue.
*/
// Build explicit key/filter/bounds for root operation, possibly refering paramValues
const int error = getRoot().prepareKeyInfo(m_keyInfo, paramValues);
if (unlikely(error != 0))
{
setErrorCode(error);
return -1;
}
// Serialize parameter values for the other (non-root) operations
// (No need to serialize for root (i==0) as root key is part of keyInfo above)
for (Uint32 i=1; i<getNoOfOperations(); ++i)
{
if (getQueryDef().getQueryOperation(i).getNoOfParameters() > 0)
{
const int error = getQueryOperation(i).serializeParams(paramValues);
if (unlikely(error != 0))
{
setErrorCode(error);
return -1;
}
}
}
assert(m_state<Defined);
m_state = Defined;
return 0;
} // NdbQueryImpl::assignParameters
static int
insert_bound(Uint32Buffer& keyInfo, const NdbRecord *key_record,
Uint32 column_index,
const char *row,
Uint32 bound_type)
{
char buf[NdbRecord::Attr::SHRINK_VARCHAR_BUFFSIZE];
const NdbRecord::Attr *column= &key_record->columns[column_index];
bool is_null= column->is_null(row);
Uint32 len= 0;
const void *aValue= row+column->offset;
if (!is_null)
{
bool len_ok;
/* Support for special mysqld varchar format in keys. */
if (column->flags & NdbRecord::IsMysqldShrinkVarchar)
{
len_ok= column->shrink_varchar(row, len, buf);
aValue= buf;
}
else
{
len_ok= column->get_var_length(row, len);
}
if (!len_ok) {
return Err_WrongFieldLength;
}
}
AttributeHeader ah(column->index_attrId, len);
keyInfo.append(bound_type);
keyInfo.append(ah.m_value);
keyInfo.appendBytes(aValue,len);
return 0;
}
int
NdbQueryImpl::setBound(const NdbRecord *key_record,
const NdbIndexScanOperation::IndexBound *bound)
{
m_prunability = Prune_Unknown;
if (unlikely(key_record == NULL || bound==NULL))
return QRY_REQ_ARG_IS_NULL;
if (unlikely(getRoot().getQueryOperationDef().getType()
!= NdbQueryOperationDef::OrderedIndexScan))
{
return QRY_WRONG_OPERATION_TYPE;
}
assert(m_state >= Defined);
if (m_state != Defined)
{
return QRY_ILLEGAL_STATE;
}
int startPos = m_keyInfo.getSize();
// We don't handle both NdbQueryIndexBound defined in ::scanIndex()
// in combination with a later ::setBound(NdbIndexScanOperation::IndexBound)
//assert (m_bound.lowKeys==0 && m_bound.highKeys==0);
if (unlikely(bound->range_no != m_num_bounds ||
bound->range_no > NdbIndexScanOperation::MaxRangeNo))
{
// setErrorCodeAbort(4286);
return Err_InvalidRangeNo;
}
Uint32 key_count= bound->low_key_count;
Uint32 common_key_count= key_count;
if (key_count < bound->high_key_count)
key_count= bound->high_key_count;
else
common_key_count= bound->high_key_count;
if (m_shortestBound > common_key_count)
{
m_shortestBound = common_key_count;
}
/* Has the user supplied an open range (no bounds)? */
const bool openRange= ((bound->low_key == NULL || bound->low_key_count == 0) &&
(bound->high_key == NULL || bound->high_key_count == 0));
if (likely(!openRange))
{
/* If low and high key pointers are the same and key counts are
* the same, we send as an Eq bound to save bandwidth.
* This will not send an EQ bound if :
* - Different numbers of high and low keys are EQ
* - High and low keys are EQ, but use different ptrs
*/
const bool isEqRange=
(bound->low_key == bound->high_key) &&
(bound->low_key_count == bound->high_key_count) &&
(bound->low_inclusive && bound->high_inclusive); // Does this matter?
if (isEqRange)
{
/* Using BoundEQ will result in bound being sent only once */
for (unsigned j= 0; j<key_count; j++)
{
const int error=
insert_bound(m_keyInfo, key_record, key_record->key_indexes[j],
bound->low_key, NdbIndexScanOperation::BoundEQ);
if (unlikely(error))
return error;
}
}
else
{
/* Distinct upper and lower bounds, must specify them independently */
/* Note : Protocol allows individual columns to be specified as EQ
* or some prefix of columns. This is not currently supported from
* NDBAPI.
*/
for (unsigned j= 0; j<key_count; j++)
{
Uint32 bound_type;
/* If key is part of lower bound */
if (bound->low_key && j<bound->low_key_count)
{
/* Inclusive if defined, or matching rows can include this value */
bound_type= bound->low_inclusive || j+1 < bound->low_key_count ?
NdbIndexScanOperation::BoundLE : NdbIndexScanOperation::BoundLT;
const int error=
insert_bound(m_keyInfo, key_record, key_record->key_indexes[j],
bound->low_key, bound_type);
if (unlikely(error))
return error;
}
/* If key is part of upper bound */
if (bound->high_key && j<bound->high_key_count)
{
/* Inclusive if defined, or matching rows can include this value */
bound_type= bound->high_inclusive || j+1 < bound->high_key_count ?
NdbIndexScanOperation::BoundGE : NdbIndexScanOperation::BoundGT;
const int error=
insert_bound(m_keyInfo, key_record, key_record->key_indexes[j],
bound->high_key, bound_type);
if (unlikely(error))
return error;
}
}
}
}
else
{
/* Open range - all rows must be returned.
* To encode this, we'll request all rows where the first
* key column value is >= NULL
*/
AttributeHeader ah(0, 0);
m_keyInfo.append(NdbIndexScanOperation::BoundLE);
m_keyInfo.append(ah.m_value);
}
Uint32 length = m_keyInfo.getSize()-startPos;
if (unlikely(m_keyInfo.isMemoryExhausted())) {
return Err_MemoryAlloc;
} else if (unlikely(length > 0xFFFF)) {
return QRY_DEFINITION_TOO_LARGE; // Query definition too large.
} else if (likely(length > 0)) {
m_keyInfo.put(startPos, m_keyInfo.get(startPos) | (length << 16) | (bound->range_no << 4));
}
#ifdef TRACE_SERIALIZATION
ndbout << "Serialized KEYINFO w/ bounds for indexScan root : ";
for (Uint32 i = startPos; i < m_keyInfo.getSize(); i++) {
char buf[12];
sprintf(buf, "%.8x", m_keyInfo.get(i));
ndbout << buf << " ";
}
ndbout << endl;
#endif
m_num_bounds++;
return 0;
} // NdbQueryImpl::setBound()
Uint32
NdbQueryImpl::getNoOfOperations() const
{
return m_countOperations;
}
Uint32
NdbQueryImpl::getNoOfLeafOperations() const
{
return getQueryOperation(Uint32(0)).getNoOfLeafOperations();
}
NdbQueryOperationImpl&
NdbQueryImpl::getQueryOperation(Uint32 index) const
{
assert(index<m_countOperations);
return m_operations[index];
}
NdbQueryOperationImpl*
NdbQueryImpl::getQueryOperation(const char* ident) const
{
for(Uint32 i = 0; i<m_countOperations; i++){
if(strcmp(m_operations[i].getQueryOperationDef().getName(), ident) == 0){
return &m_operations[i];
}
}
return NULL;
}
Uint32
NdbQueryImpl::getNoOfParameters() const
{
return 0; // FIXME
}
const NdbParamOperand*
NdbQueryImpl::getParameter(const char* name) const
{
return NULL; // FIXME
}
const NdbParamOperand*
NdbQueryImpl::getParameter(Uint32 num) const
{
return NULL; // FIXME
}
/**
* NdbQueryImpl::nextResult() - The 'global' cursor on the query results
*
* Will itterate and fetch results for all combinations of results from the NdbOperations
* which this query consists of. Except for the root operations which will follow any
* optinal ScanOrdering, we have no control of the ordering which the results from the
* QueryOperations appear in.
*/
NdbQuery::NextResultOutcome
NdbQueryImpl::nextResult(bool fetchAllowed, bool forceSend)
{
if (unlikely(m_state < Executing || m_state >= Closed)) {
assert (m_state >= Initial && m_state < Destructed);
if (m_state == Failed)
setErrorCode(QRY_IN_ERROR_STATE);
else
setErrorCode(QRY_ILLEGAL_STATE);
DEBUG_CRASH();
return NdbQuery::NextResult_error;
}
assert (m_globalCursor < getNoOfOperations());
while (m_state != EndOfData) // Or likely: return when 'gotRow'
{
NdbQuery::NextResultOutcome res =
getQueryOperation(m_globalCursor).nextResult(fetchAllowed,forceSend);
if (unlikely(res == NdbQuery::NextResult_error))
return res;
else if (res == NdbQuery::NextResult_scanComplete)
{
if (m_globalCursor == 0) // Completed reading all results from root
break;
m_globalCursor--; // Get 'next' from ancestor
}
else if (res == NdbQuery::NextResult_gotRow)
{
// Position to 'firstResult()' for all childs.
// Update m_globalCursor to itterate from last operation with results next time
//
for (uint child=m_globalCursor+1; child<getNoOfOperations(); child++)
{
res = getQueryOperation(child).firstResult();
if (unlikely(res == NdbQuery::NextResult_error))
return res;
else if (res == NdbQuery::NextResult_gotRow)
m_globalCursor = child;
}
return NdbQuery::NextResult_gotRow;
}
else
{
assert (res == NdbQuery::NextResult_bufferEmpty);
return res;
}
}
assert (m_state == EndOfData);
return NdbQuery::NextResult_scanComplete;
} //NdbQueryImpl::nextResult()
/**
* Local cursor component which implements the special case of 'next' on the
* root operation of entire NdbQuery. In addition to fetch 'next' result from
* the root operation, we should also retrieve more results from the datanodes
* if required and allowed.
*/
NdbQuery::NextResultOutcome
NdbQueryImpl::nextRootResult(bool fetchAllowed, bool forceSend)
{
/* To minimize lock contention, each query has the separate NdbWorker
* container 'm_applFrags'. m_applFrags is only accessed by the application
* thread, so it is safe to use it without locks.
*/
while (m_state != EndOfData) // Or likely: return when 'gotRow' or error
{
const NdbWorker* worker = m_applFrags.getCurrent();
if (unlikely(worker==NULL))
{
/* m_applFrags is empty, so we cannot get more results without
* possibly blocking.
*
* ::awaitMoreResults() will either copy worker results that are already
* complete (under mutex protection), or block until data
* previously requested arrives.
*/
const FetchResult fetchResult = awaitMoreResults(forceSend);
switch (fetchResult) {
case FetchResult_ok: // OK - got data wo/ error
assert(m_state != Failed);
worker = m_applFrags.getCurrent();
assert (worker!=NULL);
break;
case FetchResult_noMoreData: // No data, no error
assert(m_state != Failed);
assert (m_applFrags.getCurrent()==NULL);
getRoot().nullifyResult();
m_state = EndOfData;
postFetchRelease();
return NdbQuery::NextResult_scanComplete;
case FetchResult_noMoreCache: // No cached data, no error
assert(m_state != Failed);
assert (m_applFrags.getCurrent()==NULL);
getRoot().nullifyResult();
if (fetchAllowed)
{
break; // ::sendFetchMore() may request more results
}
return NdbQuery::NextResult_bufferEmpty;
case FetchResult_gotError: // Error in 'm_error.code'
assert (m_error.code != 0);
return NdbQuery::NextResult_error;
default:
assert(false);
}
}
else
{
worker->getResultStream(0).nextResult(); // Consume current
m_applFrags.reorganize(); // Calculate new current
// ::reorganize(). may update 'current' worker.
worker = m_applFrags.getCurrent();
}
/**
* If allowed to request more rows from datanodes, we do this asynch
* and request more rows as soon as we have consumed all rows from a
* SPJ-worker. ::awaitMoreResults() may eventually block and wait for
* these when required.
*/
if (fetchAllowed)
{
// Ask for a new batch if we emptied some.
NdbWorker** workers;
const Uint32 cnt = m_applFrags.getFetchMore(workers);
if (cnt > 0 && sendFetchMore(workers, cnt, forceSend) != 0)
{
return NdbQuery::NextResult_error;
}
}
if (worker!=NULL)
{
getRoot().fetchRow(worker->getResultStream(0));
return NdbQuery::NextResult_gotRow;
}
} // m_state != EndOfData
assert (m_state == EndOfData);
return NdbQuery::NextResult_scanComplete;
} //NdbQueryImpl::nextRootResult()
/**
* Wait for more scan results which already has been REQuested to arrive.
* @return 0 if some rows did arrive, a negative value if there are errors (in m_error.code),
* and 1 of there are no more rows to receive.
*/
NdbQueryImpl::FetchResult
NdbQueryImpl::awaitMoreResults(bool forceSend)
{
assert(m_applFrags.getCurrent() == NULL);
/* Check if there are any more completed fragments available.*/
if (getQueryDef().isScanQuery())
{
assert (m_scanTransaction);
assert (m_state==Executing);
NdbImpl* const ndb = m_transaction.getNdb()->theImpl;
{
/* This part needs to be done under mutex due to synchronization with
* receiver thread.
*/
PollGuard poll_guard(*ndb);
/* There may be pending (asynchronous received, mutex protected) errors
* from TC / datanodes. Propogate these into m_error.code in 'API space'.
*/
while (likely(!hasReceivedError()))
{
/* Scan m_workers (under mutex protection) for workers
* which has delivered a complete batch. Add these to m_applFrags.
*/
m_applFrags.prepareMoreResults(m_workers,m_workerCount);
if (m_applFrags.getCurrent() != NULL)
{
return FetchResult_ok;
}
/* There are no more available worker results available without
* first waiting for more to be received from the datanodes
*/
if (m_pendingWorkers == 0)
{
// 'No more *pending* results', ::sendFetchMore() may make more available
return (m_finalWorkers < getWorkerCount()) ? FetchResult_noMoreCache
: FetchResult_noMoreData;
}
const Uint32 timeout = ndb->get_waitfor_timeout();
const Uint32 nodeId = m_transaction.getConnectedNodeId();
const Uint32 seq = m_transaction.theNodeSequence;
/* More results are on the way, so we wait for them.*/
const FetchResult waitResult = static_cast<FetchResult>
(poll_guard.wait_scan(3*timeout,
nodeId,
forceSend));
if (ndb->getNodeSequence(nodeId) != seq)
setFetchTerminated(Err_NodeFailCausedAbort,false);
else if (likely(waitResult == FetchResult_ok))
continue;
else if (waitResult == FetchResult_timeOut)
setFetchTerminated(Err_ReceiveTimedOut,false);
else
setFetchTerminated(Err_NodeFailCausedAbort,false);
assert (m_state != Failed);
} // while(!hasReceivedError())
} // Terminates scope of 'PollGuard'
// Fall through only if ::hasReceivedError()
assert (m_error.code);
return FetchResult_gotError;
}
else // is a Lookup query
{
/* The root operation is a lookup. Lookups are guaranteed to be complete
* before NdbTransaction::execute() returns. Therefore we do not set
* the lock, because we know that the signal receiver thread will not
* be accessing m_workers at this time.
*/
m_applFrags.prepareMoreResults(m_workers,m_workerCount);
if (m_applFrags.getCurrent() != NULL)
{
return FetchResult_ok;
}
/* Getting here means that either:
* - No results was returned (TCKEYREF)
* - There was no matching row for an inner join.
* - or, the application called nextResult() twice for a lookup query.
*/
assert(m_pendingWorkers == 0);
assert(m_finalWorkers == getWorkerCount());
return FetchResult_noMoreData;
} // if(getQueryDef().isScanQuery())
} //NdbQueryImpl::awaitMoreResults
/*
::handleBatchComplete() is intended to be called when receiving signals only.
The PollGuard mutex is then set and the shared 'm_pendingWorkers' and
'm_finalWorkers' can safely be updated and ::setReceivedMore() signaled.
returns: 'true' when application thread should be resumed.
*/
bool
NdbQueryImpl::handleBatchComplete(NdbWorker& worker)
{
if (traceSignals) {
ndbout << "NdbQueryImpl::handleBatchComplete"
<< ", from workerNo=" << worker.getWorkerNo()
<< ", pendingWorkers=" << (m_pendingWorkers-1)
<< ", finalWorkers=" << m_finalWorkers
<< endl;
}
assert(worker.isFragBatchComplete());
/* May received SPJ results after a SCANREF() (timeout?)
* terminated the scan. We are about to close this query,
* and didn't expect any more data - ignore it!
*/
if (likely(m_errorReceived == 0))
{
assert(m_pendingWorkers > 0); // Check against underflow.
assert(m_pendingWorkers <= m_workerCount); // .... and overflow
m_pendingWorkers--;
if (worker.finalBatchReceived())
{
m_finalWorkers++;
assert(m_finalWorkers <= m_workerCount);
}
/* When application thread ::awaitMoreResults() it will later be
* added to m_applFrags under mutex protection.
*/
worker.setReceivedMore();
return true;
}
else if (!getQueryDef().isScanQuery()) // A failed lookup query
{
/**
* A lookup query will retrieve the rows as part of ::execute().
* -> Error must be visible through API before we return control
* to the application.
*/
setErrorCode(m_errorReceived);
return true;
}
return false;
} // NdbQueryImpl::handleBatchComplete
int
NdbQueryImpl::close(bool forceSend)
{
int res = 0;
assert (m_state >= Initial && m_state < Destructed);
if (m_state != Closed)
{
if (m_tcState != Inactive)
{
/* We have started a scan, but we have not yet received the last batch
* from all SPJ-workers. We must therefore close the scan to release
* the scan context at TC/SPJ.*/
res = closeTcCursor(forceSend);
}
// Throw any pending results
NdbWorker::clear(m_workers,m_workerCount);
m_applFrags.clear();
Ndb* const ndb = m_transaction.getNdb();
if (m_scanTransaction != NULL)
{
assert (m_state != Closed);
assert (m_scanTransaction->m_scanningQuery == this);
m_scanTransaction->m_scanningQuery = NULL;
ndb->closeTransaction(m_scanTransaction);
ndb->theRemainingStartTransactions--; // Compensate; m_scanTransaction was not a real Txn
m_scanTransaction = NULL;
}
postFetchRelease();
m_state = Closed; // Even if it was previously 'Failed' it is closed now!
}
/** BEWARE:
* Don't refer NdbQueryDef or its NdbQueryOperationDefs after ::close()
* as the application is allowed to destruct the Def's after this point.
*/
m_queryDef= NULL;
return res;
} //NdbQueryImpl::close
void
NdbQueryImpl::release()
{
assert (m_state >= Initial && m_state < Destructed);
if (m_state != Closed) {
close(true); // Ignore any errors, explicit ::close() first if errors are of interest
}
delete this;
}
void
NdbQueryImpl::setErrorCode(int aErrorCode)
{
assert (aErrorCode!=0);
m_error.code = aErrorCode;
m_transaction.theErrorLine = 0;
m_transaction.theErrorOperation = NULL;
switch(aErrorCode)
{
// Not realy an error. A root lookup found no match.
case Err_TupleNotFound:
// Simple or dirty read failed due to node failure. Transaction will be aborted.
case Err_SimpleDirtyReadFailed:
m_transaction.setOperationErrorCode(aErrorCode);
break;
// For any other error, abort the transaction.
default:
m_state = Failed;
m_transaction.setOperationErrorCodeAbort(aErrorCode);
break;
}
}
/*
* ::setFetchTerminated() Should only be called with mutex locked.
* Register result fetching as completed (possibly prematurely, w/ errorCode).
*/
void
NdbQueryImpl::setFetchTerminated(int errorCode, bool needClose)
{
assert(m_finalWorkers < getWorkerCount());
if (!needClose)
{
m_finalWorkers = getWorkerCount();
}
if (errorCode!=0)
{
m_errorReceived = errorCode;
}
m_pendingWorkers = 0;
} // NdbQueryImpl::setFetchTerminated()
/* There may be pending (asynchronous received, mutex protected) errors
* from TC / datanodes. Propogate these into 'API space'.
* ::hasReceivedError() Should only be called with mutex locked
*/
bool
NdbQueryImpl::hasReceivedError()
{
if (unlikely(m_errorReceived))
{
setErrorCode(m_errorReceived);
return true;
}
return false;
} // NdbQueryImpl::hasReceivedError
bool
NdbQueryImpl::execTCKEYCONF()
{
if (traceSignals) {
ndbout << "NdbQueryImpl::execTCKEYCONF()" << endl;
}
assert(!getQueryDef().isScanQuery());
NdbWorker& worker = m_workers[0];
// We will get 1 + #leaf-nodes TCKEYCONF for a lookup...
worker.setConfReceived(RNIL);
worker.incrOutstandingResults(-1);
bool ret = false;
if (worker.isFragBatchComplete())
{
ret = handleBatchComplete(worker);
}
if (traceSignals) {
ndbout << "NdbQueryImpl::execTCKEYCONF(): returns:" << ret
<< ", m_pendingWorkers=" << m_pendingWorkers
<< ", rootStream= {" << worker.getResultStream(0) << "}"
<< endl;
}
return ret;
} // NdbQueryImpl::execTCKEYCONF
void
NdbQueryImpl::execCLOSE_SCAN_REP(int errorCode, bool needClose)
{
if (traceSignals)
{
ndbout << "NdbQueryImpl::execCLOSE_SCAN_REP()" << endl;
}
setFetchTerminated(errorCode,needClose);
}
int
NdbQueryImpl::prepareSend()
{
if (unlikely(m_state != Defined)) {
assert (m_state >= Initial && m_state < Destructed);
if (m_state == Failed)
setErrorCode(QRY_IN_ERROR_STATE);
else
setErrorCode(QRY_ILLEGAL_STATE);
DEBUG_CRASH();
return -1;
}
// Determine execution parameters 'batch size'.
// May be user specified (TODO), and/or, limited/specified by config values
//
Uint32 rootFragments;
if (getQueryDef().isScanQuery())
{
const NdbQueryOperationImpl &rootOp = getRoot();
const NdbDictionary::Table &rootTable = rootOp.getQueryOperationDef().getTable();
rootFragments = rootTable.getFragmentCount();
/* For the first batch, we read from all fragments for both ordered
* and unordered scans.*/
if (getQueryOperation(0U).m_parallelism != Parallelism_max)
{
assert(getQueryOperation(0U).m_parallelism != Parallelism_adaptive);
rootFragments = MIN(rootFragments, getQueryOperation(0U).m_parallelism);
}
bool pruned = false;
const int error = isPrunable(pruned);
if (unlikely(error != 0))
{
setErrorCode(error);
return -1;
}
/**
* A 'pruned scan' will only be sent to the single fragment identified
* by the partition key.
*/
if (pruned)
{
// Scan pruned to single fragment
rootFragments = 1;
m_fragsPerWorker = 1;
}
else if (rootOp.getOrdering() != NdbQueryOptions::ScanOrdering_unordered)
{
// Merge-sort need one result set from each fragment
m_fragsPerWorker = 1;
}
else if (!ndbd_spj_multifrag_scan(m_transaction.getNdb()->getMinDbNodeVersion()))
{
// 'MultiFragment' not supported by all datanodes, partially upgraded?
m_fragsPerWorker = 1;
}
else
{
NdbNodeBitmask dataNodes;
Uint32 cnt = 0;
// Count number of nodes 'rootTable' is distributed over.
for (Uint32 i = 0; i<rootFragments; i++)
{
Uint32 nodes[1];
const Uint32 res = rootTable.getFragmentNodes(i, nodes, NDB_ARRAY_SIZE(nodes));
assert(res>0); (void)res;
{
if (!dataNodes.get(nodes[0]))
{
dataNodes.set(nodes[0]);
cnt++;
}
}
}
assert((rootFragments % cnt) == 0);
m_fragsPerWorker = rootFragments / cnt;
}
/** Scan operations need a own sub-transaction object associated with each
* query.
*/
Ndb* const ndb = m_transaction.getNdb();
ndb->theRemainingStartTransactions++; // Compensate; does not start a real Txn
NdbTransaction *scanTxn = ndb->hupp(&m_transaction);
if (scanTxn==NULL) {
ndb->theRemainingStartTransactions--;
m_transaction.setOperationErrorCodeAbort(ndb->getNdbError().code);
return -1;
}
scanTxn->theMagicNumber = 0x37412619;
scanTxn->m_scanningQuery = this;
this->m_scanTransaction = scanTxn;
}
else // Lookup query
{
rootFragments = 1;
m_fragsPerWorker = 1;
}
m_workerCount = rootFragments / m_fragsPerWorker;
assert(m_workerCount > 0);
int error = m_resultStreamAlloc.init(m_workerCount * getNoOfOperations());
if (error != 0)
{
setErrorCode(error);
return -1;
}
// Allocate space for ptrs to NdbResultStream and NdbWorker objects.
error = m_pointerAlloc.init(m_workerCount *
(OrderedFragSet::pointersPerWorker));
if (error != 0)
{
setErrorCode(error);
return -1;
}
// Some preparation for later batchsize calculations pr. (sub) scan
getRoot().calculateBatchedRows(NULL);
getRoot().setBatchedRows(1);
/**
* Calculate total amount of row buffer space for all operations and
* fragments.
*/
Uint32 totalBuffSize = 0;
for (Uint32 opNo = 0; opNo < getNoOfOperations(); opNo++)
{
const NdbQueryOperationImpl& op = getQueryOperation(opNo);
// Add space for batchBuffer & m_correlations
Uint32 opBuffSize = op.getResultBufferSize();
if (getQueryDef().isScanQuery())
{
opBuffSize += (sizeof(TupleCorrelation) * op.getMaxBatchRows());
opBuffSize *= 2; // Scans are double buffered
}
opBuffSize += op.getRowSize(); // Unpacked row from buffers
totalBuffSize += opBuffSize;
}
m_rowBufferAlloc.init(rootFragments * totalBuffSize);
if (getQueryDef().isScanQuery())
{
Uint32 totalRows = 0;
for (Uint32 i = 0; i<getNoOfOperations(); i++)
{
totalRows += getQueryOperation(i).getMaxBatchRows();
}
error = m_tupleSetAlloc.init(2 * rootFragments * totalRows);
if (unlikely(error != 0))
{
setErrorCode(error);
return -1;
}
}
/**
* Allocate and initialize SPJ-worker state objects.
* Will also cause a ResultStream object containing a
* NdbReceiver to be constructed for each operation in QueryTree
*/
m_workers = new NdbWorker[m_workerCount];
if (m_workers == NULL)
{
setErrorCode(Err_MemoryAlloc);
return -1;
}
for (Uint32 i = 0; i<m_workerCount; i++)
{
m_workers[i].init(*this, i); // Set worker number.
}
const Uint32Buffer &queryTree = getQueryDef().getSerialized();
const QueryNode *queryNode = (const QueryNode*)queryTree.addr(1);
// Fill in parameters (into ATTRINFO) for QueryTree.
for (Uint32 i = 0; i < m_countOperations; i++) {
const int error = m_operations[i].prepareAttrInfo(m_attrInfo, queryNode);
if (unlikely(error))
{
setErrorCode(error);
return -1;
}
}
if (unlikely(m_attrInfo.isMemoryExhausted() || m_keyInfo.isMemoryExhausted())) {
setErrorCode(Err_MemoryAlloc);
return -1;
}
if (unlikely(m_attrInfo.getSize() > ScanTabReq::MaxTotalAttrInfo ||
m_keyInfo.getSize() > ScanTabReq::MaxTotalAttrInfo)) {
setErrorCode(Err_ReadTooMuch); // TODO: find a more suitable errorcode,
return -1;
}
// Setup m_applStreams and m_fullStreams for receiving results
const NdbRecord* keyRec = NULL;
if(getRoot().getQueryOperationDef().getIndex()!=NULL)
{
/* keyRec is needed for comparing records when doing ordered index scans.*/
keyRec = getRoot().getQueryOperationDef().getIndex()->getDefaultRecord();
assert(keyRec!=NULL);
}
m_applFrags.prepare(m_pointerAlloc,
getRoot().getOrdering(),
m_workerCount,
keyRec,
getRoot().m_ndbRecord);
if (getQueryDef().isScanQuery())
{
NdbWorker::buildReceiverIdMap(m_workers, m_workerCount);
}
#ifdef TRACE_SERIALIZATION
ndbout << "Serialized ATTRINFO : ";
for(Uint32 i = 0; i < m_attrInfo.getSize(); i++){
char buf[12];
sprintf(buf, "%.8x", m_attrInfo.get(i));
ndbout << buf << " ";
}
ndbout << endl;
#endif
assert (m_pendingWorkers==0);
m_state = Prepared;
return 0;
} // NdbQueryImpl::prepareSend
/** This iterator is used for inserting a sequence of receiver ids
* for the initial batch of a scan into a section via a GenericSectionPtr.*/
class InitialReceiverIdIterator: public GenericSectionIterator
{
public:
InitialReceiverIdIterator(NdbWorker workers[],
Uint32 workerCount)
:m_workers(workers),
m_workerCount(workerCount),
m_workerNo(0)
{}
~InitialReceiverIdIterator() override {}
/**
* Get next batch of receiver ids.
* @param sz This will be set to the number of receiver ids that have been
* put in the buffer (0 if end has been reached.)
* @return Array of receiver ids (or NULL if end reached.
*/
const Uint32* getNextWords(Uint32& sz) override;
void reset() override
{ m_workerNo = 0;}
private:
/**
* Size of internal receiver id buffer. This value is arbitrary, but
* a larger buffer would mean fewer calls to getNextWords(), possibly
* improving efficiency.
*/
static const Uint32 bufSize = 16;
/** Set of SPJ workers which we want to itterate receiver ids for.*/
const NdbWorker* const m_workers;
const Uint32 m_workerCount;
/**
* The next SPJ-worker to be processed. (Range for 0 to no of workers.)
*/
Uint32 m_workerNo;
/** Buffer for storing one batch of receiver ids.*/
Uint32 m_receiverIds[bufSize];
};
const Uint32* InitialReceiverIdIterator::getNextWords(Uint32& sz)
{
/**
* For the initial batch, we want to retrieve one batch from each worker
* whether it is a sorted scan or not.
*/
if (m_workerNo >= m_workerCount)
{
sz = 0;
return NULL;
}
else
{
Uint32 cnt = 0;
while (cnt < bufSize && m_workerNo < m_workerCount)
{
m_receiverIds[cnt] = m_workers[m_workerNo].getReceiverId();
cnt++;
m_workerNo++;
}
sz = cnt;
return m_receiverIds;
}
}
/** This iterator is used for inserting a sequence of 'TcPtrI'
* for a NEXTREQ to a single or multiple SPJ-workers via a GenericSectionPtr.*/
class FetchMoreTcIdIterator: public GenericSectionIterator
{
public:
FetchMoreTcIdIterator(NdbWorker* workers[],
Uint32 cnt)
: m_workers(workers),
m_workerCount(cnt),
m_currWorkerNo(0)
{}
~FetchMoreTcIdIterator() override {}
/**
* Get next batch of receiver ids.
* @param sz This will be set to the number of receiver ids that have been
* put in the buffer (0 if end has been reached.)
* @return Array of receiver ids (or NULL if end reached.
*/
const Uint32* getNextWords(Uint32& sz) override;
void reset() override
{ m_currWorkerNo = 0;}
private:
/**
* Size of internal receiver id buffer. This value is arbitrary, but
* a larger buffer would mean fewer calls to getNextWords(), possibly
* improving efficiency.
*/
static const Uint32 bufSize = 16;
/** Set of SPJ workers which we want to itterate TcPtrI ids for.*/
NdbWorker** const m_workers;
const Uint32 m_workerCount;
/** The next worker to be processed. (Range for 0 to no of workers.)
*/
Uint32 m_currWorkerNo;
/** Buffer for storing one batch of receiver ids.*/
Uint32 m_receiverIds[bufSize];
};
const Uint32* FetchMoreTcIdIterator::getNextWords(Uint32& sz)
{
/**
* For the initial batch, we want to retrieve one batch from each worker
* whether it is a sorted scan or not.
*/
if (m_currWorkerNo >= m_workerCount)
{
sz = 0;
return NULL;
}
else
{
Uint32 cnt = 0;
while (cnt < bufSize && m_currWorkerNo < m_workerCount)
{
m_receiverIds[cnt] = m_workers[m_currWorkerNo]->getReceiverTcPtrI();
cnt++;
m_currWorkerNo++;
}
sz = cnt;
return m_receiverIds;
}
}
/******************************************************************************
int doSend() Send serialized queryTree and parameters encapsulated in
either a SCAN_TABREQ or TCKEYREQ to TC.
NOTE: The TransporterFacade mutex is already set by callee.
Return Value: Return >0 : send was succesful, returns number of signals sent
Return -1: In all other case.
Parameters: nodeId: Receiving processor node
Remark: Send a TCKEYREQ or SCAN_TABREQ (long) signal depending of
the query being either a lookup or scan type.
KEYINFO and ATTRINFO are included as part of the long signal
******************************************************************************/
int
NdbQueryImpl::doSend(int nodeId, bool lastFlag)
{
if (unlikely(m_state != Prepared)) {
assert (m_state >= Initial && m_state < Destructed);
if (m_state == Failed)
setErrorCode(QRY_IN_ERROR_STATE);
else
setErrorCode(QRY_ILLEGAL_STATE);
DEBUG_CRASH();
return -1;
}
Ndb& ndb = *m_transaction.getNdb();
NdbImpl * impl = ndb.theImpl;
const NdbQueryOperationImpl& root = getRoot();
const NdbQueryOperationDefImpl& rootDef = root.getQueryOperationDef();
const NdbTableImpl* const rootTable = rootDef.getIndex()
? rootDef.getIndex()->getIndexTable()
: &rootDef.getTable();
Uint32 tTableId = rootTable->m_id;
Uint32 tSchemaVersion = rootTable->m_version;
for (Uint32 i=0; i<m_workerCount; i++)
{
m_workers[i].prepareNextReceiveSet();
}
if (rootDef.isScanOperation())
{
Uint32 scan_flags = 0; // TODO: Specify with ScanOptions::SO_SCANFLAGS
// The number of acc-scans are limited therefore use tup-scans instead.
bool tupScan = (scan_flags & NdbScanOperation::SF_TupScan) || true;
#if defined(VM_TRACE)
if (ndb.theImpl->forceAccTableScans)
{
tupScan = false;
}
#endif
bool rangeScan = false;
/* Handle IndexScan specifics */
if ( (int) rootTable->m_indexType ==
(int) NdbDictionary::Index::OrderedIndex )
{
rangeScan = true;
tupScan = false;
}
const Uint32 descending =
root.getOrdering()==NdbQueryOptions::ScanOrdering_descending ? 1 : 0;
assert(descending==0 || (int) rootTable->m_indexType ==
(int) NdbDictionary::Index::OrderedIndex);
assert (root.getMaxBatchRows() > 0);
NdbApiSignal tSignal(&ndb);
tSignal.setSignal(GSN_SCAN_TABREQ, refToBlock(m_scanTransaction->m_tcRef));
ScanTabReq * const scanTabReq = CAST_PTR(ScanTabReq, tSignal.getDataPtrSend());
Uint32 reqInfo = 0;
const Uint64 transId = m_scanTransaction->getTransactionId();
scanTabReq->apiConnectPtr = m_scanTransaction->theTCConPtr;
scanTabReq->buddyConPtr = m_scanTransaction->theBuddyConPtr; // 'buddy' refers 'real-transaction'->theTCConPtr
scanTabReq->spare = 0; // Unused in later protocoll versions
scanTabReq->tableId = tTableId;
scanTabReq->tableSchemaVersion = tSchemaVersion;
scanTabReq->storedProcId = 0xFFFF;
scanTabReq->transId1 = (Uint32) transId;
scanTabReq->transId2 = (Uint32) (transId >> 32);
Uint32 batchRows = root.getMaxBatchRows();
const Uint32 batchByteSize = root.getMaxBatchBytes();
/**
* Check if query is a sorted scan-scan.
* Ordering can then only be guarented by restricting
* parent batch to contain single rows.
* (Child scans will have 'normal' batch size).
*
* Note that this solved the problem only for the 'v1'
* version of SPJ requests, and parameter. The v2 protocol
* introduced 'batch_size_rows' as part of the parameter,
* which took precedence over the batch size set in ScanTabReq.
* This resulted in giving not-sorted results even though
* sort order was requested. This is now fixed by setting a
* 'SFP_SORTED_ORDER' flag in the ScanFragParameter
* instead of hacking the batch size on the client side.
*/
if (root.getOrdering() != NdbQueryOptions::ScanOrdering_unordered &&
getQueryDef().getQueryType() == NdbQueryDef::MultiScanQuery)
{
batchRows = 1;
}
ScanTabReq::setScanBatch(reqInfo, batchRows);
scanTabReq->batch_byte_size = batchByteSize;
scanTabReq->first_batch_size = batchRows;
if (m_fragsPerWorker > 1)
{
ScanTabReq::setMultiFragFlag(reqInfo, 1);
}
ScanTabReq::setViaSPJFlag(reqInfo, 1);
ScanTabReq::setPassAllConfsFlag(reqInfo, 1);
ScanTabReq::setRangeScanFlag(reqInfo, rangeScan);
ScanTabReq::setDescendingFlag(reqInfo, descending);
ScanTabReq::setTupScanFlag(reqInfo, tupScan);
ScanTabReq::setNoDiskFlag(reqInfo, !root.diskInUserProjection());
ScanTabReq::setExtendedConf(reqInfo, 1);
// Assume LockMode LM_ReadCommited, set related lock flags
ScanTabReq::setLockMode(reqInfo, false); // not exclusive
ScanTabReq::setHoldLockFlag(reqInfo, false);
ScanTabReq::setReadCommittedFlag(reqInfo, true);
// m_keyInfo = (scan_flags & NdbScanOperation::SF_KeyInfo) ? 1 : 0;
// If scan is pruned, use optional 'distributionKey' to hold hashvalue
if (m_prunability == Prune_Yes)
{
// printf("Build pruned SCANREQ, w/ hashValue:%d\n", hashValue);
ScanTabReq::setDistributionKeyFlag(reqInfo, 1);
scanTabReq->distributionKey= m_pruneHashVal;
tSignal.setLength(ScanTabReq::StaticLength + 1);
} else {
tSignal.setLength(ScanTabReq::StaticLength);
}
scanTabReq->requestInfo = reqInfo;
/**
* Then send the signal:
*
* SCANTABREQ always has 2 mandatory sections and an optional
* third section
* Section 0 : List of receiver Ids NDBAPI has allocated
* for the scan
* Section 1 : ATTRINFO section
* Section 2 : Optional KEYINFO section
*/
GenericSectionPtr secs[3];
InitialReceiverIdIterator receiverIdIter(m_workers, m_workerCount);
LinearSectionIterator attrInfoIter(m_attrInfo.addr(), m_attrInfo.getSize());
LinearSectionIterator keyInfoIter(m_keyInfo.addr(), m_keyInfo.getSize());
secs[0].sectionIter= &receiverIdIter;
secs[0].sz= m_workerCount;
secs[1].sectionIter= &attrInfoIter;
secs[1].sz= m_attrInfo.getSize();
Uint32 numSections= 2;
if (m_keyInfo.getSize() > 0)
{
secs[2].sectionIter= &keyInfoIter;
secs[2].sz= m_keyInfo.getSize();
numSections= 3;
}
/* Send Fragmented as SCAN_TABREQ can be large */
const int res = impl->sendFragmentedSignal(&tSignal, nodeId, secs, numSections);
if (unlikely(res == -1))
{
setErrorCode(Err_SendFailed); // Error: 'Send to NDB failed'
return FetchResult_sendFail;
}
m_tcState = Active;
} else { // Lookup query
NdbApiSignal tSignal(&ndb);
tSignal.setSignal(GSN_TCKEYREQ, refToBlock(m_transaction.m_tcRef));
TcKeyReq * const tcKeyReq = CAST_PTR(TcKeyReq, tSignal.getDataPtrSend());
const Uint64 transId = m_transaction.getTransactionId();
tcKeyReq->apiConnectPtr = m_transaction.theTCConPtr;
tcKeyReq->apiOperationPtr = root.getIdOfReceiver();
tcKeyReq->tableId = tTableId;
tcKeyReq->tableSchemaVersion = tSchemaVersion;
tcKeyReq->transId1 = (Uint32) transId;
tcKeyReq->transId2 = (Uint32) (transId >> 32);
Uint32 attrLen = 0;
tcKeyReq->setAttrinfoLen(attrLen, 0); // Not required for long signals.
tcKeyReq->attrLen = attrLen;
Uint32 reqInfo = 0;
Uint32 interpretedFlag= root.hasInterpretedCode() &&
rootDef.getType() == NdbQueryOperationDef::PrimaryKeyAccess;
TcKeyReq::setOperationType(reqInfo, NdbOperation::ReadRequest);
TcKeyReq::setViaSPJFlag(reqInfo, true);
TcKeyReq::setKeyLength(reqInfo, 0); // This is a long signal
TcKeyReq::setAIInTcKeyReq(reqInfo, 0); // Not needed
TcKeyReq::setInterpretedFlag(reqInfo, interpretedFlag);
TcKeyReq::setStartFlag(reqInfo, m_startIndicator);
TcKeyReq::setExecuteFlag(reqInfo, lastFlag);
TcKeyReq::setNoDiskFlag(reqInfo, !root.diskInUserProjection());
TcKeyReq::setAbortOption(reqInfo, NdbOperation::AO_IgnoreError);
TcKeyReq::setDirtyFlag(reqInfo, true);
TcKeyReq::setSimpleFlag(reqInfo, true);
TcKeyReq::setCommitFlag(reqInfo, m_commitIndicator);
tcKeyReq->requestInfo = reqInfo;
tSignal.setLength(TcKeyReq::StaticLength);
/****
// Unused optional part located after TcKeyReq::StaticLength
tcKeyReq->scanInfo = 0;
tcKeyReq->distrGroupHashValue = 0;
tcKeyReq->distributionKeySize = 0;
tcKeyReq->storedProcId = 0xFFFF;
***/
/**** TODO ... maybe - from NdbOperation::prepareSendNdbRecord(AbortOption ao)
Uint8 abortOption= (ao == DefaultAbortOption) ?
(Uint8) m_abortOption : (Uint8) ao;
m_abortOption= theSimpleIndicator && theOperationType==ReadRequest ?
(Uint8) AO_IgnoreError : (Uint8) abortOption;
TcKeyReq::setAbortOption(reqInfo, m_abortOption);
TcKeyReq::setCommitFlag(tcKeyReq->requestInfo, theCommitIndicator);
*****/
LinearSectionPtr secs[2];
secs[TcKeyReq::KeyInfoSectionNum].p= m_keyInfo.addr();
secs[TcKeyReq::KeyInfoSectionNum].sz= m_keyInfo.getSize();
Uint32 numSections= 1;
if (m_attrInfo.getSize() > 0)
{
secs[TcKeyReq::AttrInfoSectionNum].p= m_attrInfo.addr();
secs[TcKeyReq::AttrInfoSectionNum].sz= m_attrInfo.getSize();
numSections= 2;
}
int res = 0;
const Uint32 long_sections_size = m_keyInfo.getSize() + m_attrInfo.getSize();
const Uint32 nodeVersion = impl->getNodeNdbVersion(nodeId);
if (long_sections_size <= NDB_MAX_LONG_SECTIONS_SIZE)
{
res = impl->sendSignal(&tSignal, nodeId, secs, numSections);
}
else if (ndbd_frag_tckeyreq(nodeVersion))
{
res = impl->sendFragmentedSignal(&tSignal, nodeId, secs, numSections);
}
else
{
/* It should not be possible to see a table definition that supports
* big rows unless all data nodes that are started also can handle it.
*/
require(ndbd_frag_tckeyreq(nodeVersion));
}
if (unlikely(res == -1))
{
setErrorCode(Err_SendFailed); // Error: 'Send to NDB failed'
return FetchResult_sendFail;
}
m_transaction.OpSent();
m_workers[0].incrOutstandingResults(1 + getNoOfOperations() +
getNoOfLeafOperations());
} // if
assert (m_pendingWorkers==0);
m_pendingWorkers = m_workerCount;
// Shrink memory footprint by removing structures not required after ::execute()
m_keyInfo.releaseExtend();
m_attrInfo.releaseExtend();
// TODO: Release m_interpretedCode now?
/* Todo : Consider calling NdbOperation::postExecuteRelease()
* Ideally it should be called outside TP mutex, so not added
* here yet
*/
m_state = Executing;
return 1;
} // NdbQueryImpl::doSend()
/******************************************************************************
int sendFetchMore() - Fetch another scan batch, optionaly closing the scan
Request another batch of rows to be retrieved from the scan.
Return Value: 0 if send succeeded, -1 otherwise.
Parameters: emptyFrag: Root frgament for which to ask for another batch.
Remark:
******************************************************************************/
int
NdbQueryImpl::sendFetchMore(NdbWorker* workers[],
Uint32 cnt,
bool forceSend)
{
assert(getQueryDef().isScanQuery());
for (Uint32 i=0; i<cnt; i++)
{
NdbWorker* worker = workers[i];
assert(worker->isFragBatchComplete());
assert(!worker->finalBatchReceived());
worker->prepareNextReceiveSet();
}
Ndb& ndb = *getNdbTransaction().getNdb();
NdbApiSignal tSignal(&ndb);
tSignal.setSignal(GSN_SCAN_NEXTREQ, refToBlock(m_scanTransaction->m_tcRef));
ScanNextReq * const scanNextReq =
CAST_PTR(ScanNextReq, tSignal.getDataPtrSend());
assert (m_scanTransaction);
const Uint64 transId = m_scanTransaction->getTransactionId();
scanNextReq->apiConnectPtr = m_scanTransaction->theTCConPtr;
scanNextReq->stopScan = 0;
scanNextReq->transId1 = (Uint32) transId;
scanNextReq->transId2 = (Uint32) (transId >> 32);
tSignal.setLength(ScanNextReq::SignalLength);
FetchMoreTcIdIterator receiverIdIter(workers, cnt);
GenericSectionPtr secs[1];
secs[ScanNextReq::ReceiverIdsSectionNum].sectionIter = &receiverIdIter;
secs[ScanNextReq::ReceiverIdsSectionNum].sz = cnt;
NdbImpl * impl = ndb.theImpl;
Uint32 nodeId = m_transaction.getConnectedNodeId();
Uint32 seq = m_transaction.theNodeSequence;
/* This part needs to be done under mutex due to synchronization with
* receiver thread.
*/
PollGuard poll_guard(* impl);
if (unlikely(hasReceivedError()))
{
// Errors arrived inbetween ::await released mutex, and sendFetchMore grabbed it
return -1;
}
if (impl->getNodeSequence(nodeId) != seq ||
impl->sendSignal(&tSignal, nodeId, secs, 1) != 0)
{
setErrorCode(Err_NodeFailCausedAbort);
return -1;
}
impl->do_forceSend(forceSend);
m_pendingWorkers += cnt;
assert(m_pendingWorkers <= getWorkerCount());
return 0;
} // NdbQueryImpl::sendFetchMore()
int
NdbQueryImpl::closeTcCursor(bool forceSend)
{
assert (getQueryDef().isScanQuery());
NdbImpl* const ndb = m_transaction.getNdb()->theImpl;
const Uint32 timeout = ndb->get_waitfor_timeout();
const Uint32 nodeId = m_transaction.getConnectedNodeId();
const Uint32 seq = m_transaction.theNodeSequence;
/* This part needs to be done under mutex due to synchronization with
* receiver thread.
*/
PollGuard poll_guard(*ndb);
if (unlikely(ndb->getNodeSequence(nodeId) != seq))
{
setErrorCode(Err_NodeFailCausedAbort);
return -1; // Transporter disconnected and reconnected, no need to close
}
/* Wait for outstanding scan results from current batch fetch */
while (m_pendingWorkers > 0)
{
const FetchResult result = static_cast<FetchResult>
(poll_guard.wait_scan(3*timeout, nodeId, forceSend));
if (unlikely(ndb->getNodeSequence(nodeId) != seq))
setFetchTerminated(Err_NodeFailCausedAbort,false);
else if (unlikely(result != FetchResult_ok))
{
if (result == FetchResult_timeOut)
setFetchTerminated(Err_ReceiveTimedOut,false);
else
setFetchTerminated(Err_NodeFailCausedAbort,false);
}
if (hasReceivedError())
{
break;
}
} // while
assert(m_pendingWorkers==0);
NdbWorker::clear(m_workers,m_workerCount);
m_errorReceived = 0; // Clear errors caused by previous fetching
m_error.code = 0;
if (m_finalWorkers < getWorkerCount()) // TC has an open scan cursor.
{
/* Send SCAN_NEXTREQ(close) */
const int error = sendClose(m_transaction.getConnectedNodeId());
if (unlikely(error))
return error;
assert(m_finalWorkers+m_pendingWorkers==getWorkerCount());
/* Wait for close to be confirmed: */
while (m_pendingWorkers > 0)
{
const FetchResult result = static_cast<FetchResult>
(poll_guard.wait_scan(3*timeout, nodeId, forceSend));
if (unlikely(ndb->getNodeSequence(nodeId) != seq))
setFetchTerminated(Err_NodeFailCausedAbort,false);
else if (unlikely(result != FetchResult_ok))
{
if (result == FetchResult_timeOut)
setFetchTerminated(Err_ReceiveTimedOut,false);
else
setFetchTerminated(Err_NodeFailCausedAbort,false);
}
if (hasReceivedError())
{
break;
}
} // while
} // if
return 0;
} //NdbQueryImpl::closeTcCursor
/*
* This method is called with the PollGuard mutex held on the transporter.
*/
int
NdbQueryImpl::sendClose(int nodeId)
{
assert(m_finalWorkers < getWorkerCount());
m_pendingWorkers = getWorkerCount() - m_finalWorkers;
Ndb& ndb = *m_transaction.getNdb();
NdbApiSignal tSignal(&ndb);
tSignal.setSignal(GSN_SCAN_NEXTREQ, refToBlock(m_scanTransaction->m_tcRef));
ScanNextReq * const scanNextReq = CAST_PTR(ScanNextReq, tSignal.getDataPtrSend());
assert (m_scanTransaction);
const Uint64 transId = m_scanTransaction->getTransactionId();
scanNextReq->apiConnectPtr = m_scanTransaction->theTCConPtr;
scanNextReq->stopScan = true;
scanNextReq->transId1 = (Uint32) transId;
scanNextReq->transId2 = (Uint32) (transId >> 32);
tSignal.setLength(ScanNextReq::SignalLength);
NdbImpl * impl = ndb.theImpl;
return impl->sendSignal(&tSignal, nodeId);
} // NdbQueryImpl::sendClose()
int NdbQueryImpl::isPrunable(bool& prunable)
{
if (m_prunability == Prune_Unknown)
{
const int error = getRoot().getQueryOperationDef()
.checkPrunable(m_keyInfo, m_shortestBound, prunable, m_pruneHashVal);
if (unlikely(error != 0))
{
prunable = false;
setErrorCode(error);
return -1;
}
m_prunability = prunable ? Prune_Yes : Prune_No;
}
prunable = (m_prunability == Prune_Yes);
return 0;
}
/****************
* NdbQueryImpl::OrderedFragSet methods.
***************/
NdbQueryImpl::OrderedFragSet::OrderedFragSet():
m_capacity(0),
m_activeWorkerCount(0),
m_fetchMoreWorkerCount(0),
m_finalResultReceivedCount(0),
m_finalResultConsumedCount(0),
m_ordering(NdbQueryOptions::ScanOrdering_void),
m_keyRecord(NULL),
m_resultRecord(NULL),
m_activeWorkers(NULL),
m_fetchMoreWorkers(NULL)
{
}
NdbQueryImpl::OrderedFragSet::~OrderedFragSet()
{
m_activeWorkers = NULL;
m_fetchMoreWorkers = NULL;
}
void NdbQueryImpl::OrderedFragSet::clear()
{
m_activeWorkerCount = 0;
m_fetchMoreWorkerCount = 0;
}
void
NdbQueryImpl::OrderedFragSet::prepare(NdbBulkAllocator& allocator,
NdbQueryOptions::ScanOrdering ordering,
int capacity,
const NdbRecord* keyRecord,
const NdbRecord* resultRecord)
{
assert(m_activeWorkers==NULL);
assert(m_capacity==0);
assert(ordering!=NdbQueryOptions::ScanOrdering_void);
if (capacity > 0)
{
m_capacity = capacity;
m_activeWorkers =
reinterpret_cast<NdbWorker**>(allocator.allocObjMem(capacity));
memset(m_activeWorkers, 0, capacity * sizeof(NdbWorker*));
m_fetchMoreWorkers =
reinterpret_cast<NdbWorker**>(allocator.allocObjMem(capacity));
memset(m_fetchMoreWorkers, 0, capacity * sizeof(NdbWorker*));
}
m_ordering = ordering;
m_keyRecord = keyRecord;
m_resultRecord = resultRecord;
} // OrderedFragSet::prepare()
/**
* Get current NdbWorker which to return results from.
* Logic relies on that ::reorganize() is called whenever the current
* NdbWorker is advanced to next result. This will eliminate
* empty NdbWorkers from the OrderedFragSet object
*/
NdbWorker*
NdbQueryImpl::OrderedFragSet::getCurrent() const
{
if (m_ordering!=NdbQueryOptions::ScanOrdering_unordered)
{
/**
* Must have tuples for each (non-completed) worker when doing ordered
* scan.
*/
if (unlikely(m_activeWorkerCount+m_finalResultConsumedCount < m_capacity))
{
return NULL;
}
}
if (unlikely(m_activeWorkerCount==0))
{
return NULL;
}
else
{
assert(!m_activeWorkers[m_activeWorkerCount-1]->isEmpty());
return m_activeWorkers[m_activeWorkerCount-1];
}
} // OrderedFragSet::getCurrent()
/**
* Keep the set of worker results ordered, both with respect to
* specified ScanOrdering, and such that NdbWorkers which become
* empty are removed from m_activeWorkers[].
* Thus, ::getCurrent() should be as lightweight as possible and only has
* to return the 'next' available from array wo/ doing any housekeeping.
*/
void
NdbQueryImpl::OrderedFragSet::reorganize()
{
assert(m_activeWorkerCount > 0);
NdbWorker* const worker = m_activeWorkers[m_activeWorkerCount-1];
// Remove the current worker if the batch has been emptied.
if (worker->isEmpty())
{
/**
* MT-note: Although ::finalBatchReceived() normally requires mutex,
* its safe to call it here wo/ mutex as:
*
* - 'not hasRequestedMore()' guaranty that there can't be any
* receiver thread simultaneously accessing the mutex protected members.
* - As this worker has already been added to (the mutex protected)
* class OrderedFragSet, we know that the mutex has been
* previously set for this 'frag'. This would have resolved
* any cache coherency problems related to mt'ed access to
* 'worker->finalBatchReceived()'.
*/
if (!worker->hasRequestedMore() && worker->finalBatchReceived())
{
assert(m_finalResultReceivedCount > m_finalResultConsumedCount);
m_finalResultConsumedCount++;
}
/**
* Without doublebuffering we can't 'fetchMore' from workers until
* the current ResultSet has been consumed by application.
* (Compared to how ::prepareMoreResults() immediately 'fetchMore')
*/
else if (!useDoubleBuffers)
{
m_fetchMoreWorkers[m_fetchMoreWorkerCount++] = worker;
}
m_activeWorkerCount--;
}
// Reorder worker results if add'ed nonEmpty worker to a sorted scan.
else if (m_ordering!=NdbQueryOptions::ScanOrdering_unordered)
{
/**
* This is a sorted scan. There are more data to be read from
* m_activeWorkers[m_activeWorkerCount-1]. Move it to its proper place.
*
* Use binary search to find the largest record that is smaller than or
* equal to m_activeWorkers[m_activeWorkerCount-1].
*/
int first = 0;
int last = m_activeWorkerCount-1;
int middle = (first+last)/2;
while (first<last)
{
assert(middle<m_activeWorkerCount);
const int cmpRes = compare(*worker, *m_activeWorkers[middle]);
if (cmpRes < 0)
{
first = middle + 1;
}
else if (cmpRes == 0)
{
last = first = middle;
}
else
{
last = middle;
}
middle = (first+last)/2;
}
// Move into correct sorted position
if (middle < m_activeWorkerCount-1)
{
assert(compare(*worker, *m_activeWorkers[middle]) >= 0);
memmove(m_activeWorkers+middle+1,
m_activeWorkers+middle,
(m_activeWorkerCount - middle - 1) * sizeof(NdbWorker*));
m_activeWorkers[middle] = worker;
}
assert(verifySortOrder());
}
assert(m_activeWorkerCount+m_finalResultConsumedCount <= m_capacity);
assert(m_fetchMoreWorkerCount+m_finalResultReceivedCount <= m_capacity);
} // OrderedFragSet::reorganize()
void
NdbQueryImpl::OrderedFragSet::add(NdbWorker& worker)
{
assert(m_activeWorkerCount+m_finalResultConsumedCount < m_capacity);
m_activeWorkers[m_activeWorkerCount++] = &worker; // Add avail worker
reorganize(); // Move into position
} // OrderedFragSet::add()
/**
* Scan workers[] for fragments which has received a ResultSet batch.
* Add these to m_applFrags (Require mutex protection)
*/
void
NdbQueryImpl::OrderedFragSet::prepareMoreResults(NdbWorker workers[], Uint32 cnt)
{
for (Uint32 workerNo = 0; workerNo < cnt; workerNo++)
{
NdbWorker& worker = workers[workerNo];
if (worker.isEmpty() && // Current ResultSet is empty
worker.hasReceivedMore()) // Another ResultSet is available
{
if (worker.finalBatchReceived())
{
m_finalResultReceivedCount++;
}
/**
* When doublebuffered fetch is active:
* Received worker results is a candidates for immediate prefetch.
*/
else if (useDoubleBuffers)
{
m_fetchMoreWorkers[m_fetchMoreWorkerCount++] = &worker;
} // useDoubleBuffers
worker.grabNextResultSet(); // Get new ResultSet.
add(worker); // Make avail. to appl. thread
}
} // for all 'workers[]'
assert(m_activeWorkerCount+m_finalResultConsumedCount <= m_capacity);
assert(m_fetchMoreWorkerCount+m_finalResultReceivedCount <= m_capacity);
} // OrderedFragSet::prepareMoreResults()
/**
* Determine if a ::sendFetchMore() should be requested at this point.
*/
Uint32
NdbQueryImpl::OrderedFragSet::getFetchMore(NdbWorker** &workers)
{
/**
* Decides (pre-)fetch strategy:
*
* 1) No doublebuffered ResultSets: Immediately request prefetch.
* (This is fetches related to 'isEmpty' fragments)
* 2) If ordered ResultSets; Immediately request prefetch.
* (Need rows from all fragments to do sort-merge)
* 3) When unordered, reduce #NEXTREQs to TC by avoid prefetch
* until there are pending request to all datanodes having more
* ResultSets
*/
if (m_fetchMoreWorkerCount > 0 &&
(!useDoubleBuffers || //1)
m_ordering != NdbQueryOptions::ScanOrdering_unordered || //2)
m_fetchMoreWorkerCount+m_finalResultReceivedCount >= m_capacity)) //3)
{
const int cnt = m_fetchMoreWorkerCount;
workers = m_fetchMoreWorkers;
m_fetchMoreWorkerCount = 0;
return cnt;
}
return 0;
}
bool
NdbQueryImpl::OrderedFragSet::verifySortOrder() const
{
for (int i = 0; i<m_activeWorkerCount-1; i++)
{
if (compare(*m_activeWorkers[i], *m_activeWorkers[i+1]) < 0)
{
assert(false);
return false;
}
}
return true;
}
/**
* Compare frags such that f1<f2 if f1 is empty but f2 is not.
* - Othewise compare record contents.
* @return negative if frag1<frag2, 0 if frag1 == frag2, otherwise positive.
*/
int
NdbQueryImpl::OrderedFragSet::compare(const NdbWorker& worker1,
const NdbWorker& worker2) const
{
assert(m_ordering!=NdbQueryOptions::ScanOrdering_unordered);
/* f1<f2 if f1 is empty but f2 is not.*/
if (worker1.isEmpty())
{
if (!worker2.isEmpty())
{
return -1;
}
else
{
return 0;
}
}
/* Neither stream is empty so we must compare records.*/
return compare_ndbrecord(&worker1.getResultStream(0).getReceiver(),
&worker2.getResultStream(0).getReceiver(),
m_keyRecord,
m_resultRecord,
m_ordering
== NdbQueryOptions::ScanOrdering_descending,
false);
}
////////////////////////////////////////////////////
///////// NdbQueryOperationImpl methods ///////////
////////////////////////////////////////////////////
NdbQueryOperationImpl::NdbQueryOperationImpl(
NdbQueryImpl& queryImpl,
const NdbQueryOperationDefImpl& def):
m_interface(*this),
m_magic(MAGIC),
m_queryImpl(queryImpl),
m_operationDef(def),
m_parent(NULL),
m_children(0),
m_dependants(0),
m_params(),
m_resultBuffer(NULL),
m_resultRef(NULL),
m_isRowNull(true),
m_ndbRecord(NULL),
m_read_mask(NULL),
m_firstRecAttr(NULL),
m_lastRecAttr(NULL),
m_ordering(NdbQueryOptions::ScanOrdering_unordered),
m_interpretedCode(NULL),
m_diskInUserProjection(false),
m_parallelism(def.getOpNo() == 0
? Parallelism_max : Parallelism_adaptive),
m_rowSize(0xffffffff),
m_maxBatchRows(0),
m_maxBatchBytes(0),
m_resultBufferSize(0)
{
if (m_children.expand(def.getNoOfChildOperations()))
{
// Memory allocation during Vector::expand() failed.
queryImpl.setErrorCode(Err_MemoryAlloc);
return;
}
// Fill in operations parent refs, and append it as child of its parent
const NdbQueryOperationDefImpl* parent = def.getParentOperation();
if (parent != NULL)
{
const Uint32 ix = parent->getOpNo();
assert (ix < def.getOpNo());
m_parent = &m_queryImpl.getQueryOperation(ix);
const int res = m_parent->m_children.push_back(this);
UNUSED(res);
/**
Enough memory should have been allocated when creating
m_parent->m_children, so res!=0 should never happen.
*/
assert(res == 0);
}
// Register the extra 'out of branch' (!isChildOf()) dependencies.
// If we are not an ancestor of the 'first' treeNode of the join-nest
// we are embedded within, we need to added to 'm_dependants' as
// such an 'out of branch' dependant for this 'first_inner'
const NdbQueryOperationDefImpl* firstInEmbeddingNestDef =
def.getFirstInEmbeddingNest();
if (firstInEmbeddingNestDef != nullptr &&
!def.isChildOf(firstInEmbeddingNestDef))
{
const Uint32 ix = firstInEmbeddingNestDef->getOpNo();
NdbQueryOperationImpl* firstInEmbeddingNest =
&m_queryImpl.getQueryOperation(ix);
const int res = firstInEmbeddingNest->m_dependants.push_back(this);
if (res != 0)
{
queryImpl.setErrorCode(Err_MemoryAlloc);
return;
}
}
if (def.getType()==NdbQueryOperationDef::OrderedIndexScan)
{
const NdbQueryOptions::ScanOrdering defOrdering =
static_cast<const NdbQueryIndexScanOperationDefImpl&>(def).getOrdering();
if (defOrdering != NdbQueryOptions::ScanOrdering_void)
{
// Use value from definition, if one was set.
m_ordering = defOrdering;
}
}
}
NdbQueryOperationImpl::~NdbQueryOperationImpl()
{
/**
* We expect ::postFetchRelease to have deleted fetch related structures when fetch completed.
* Either by fetching through last row, or calling ::close() which forcefully terminates fetch
*/
assert (m_firstRecAttr == NULL);
assert (m_interpretedCode == NULL);
} //NdbQueryOperationImpl::~NdbQueryOperationImpl()
/**
* Release what we want need anymore after last available row has been
* returned from datanodes.
*/
void
NdbQueryOperationImpl::postFetchRelease()
{
Ndb* const ndb = m_queryImpl.getNdbTransaction().getNdb();
NdbRecAttr* recAttr = m_firstRecAttr;
while (recAttr != NULL) {
NdbRecAttr* saveRecAttr = recAttr;
recAttr = recAttr->next();
ndb->releaseRecAttr(saveRecAttr);
}
m_firstRecAttr = NULL;
// Set API exposed info to indicate NULL-row
m_isRowNull = true;
if (m_resultRef!=NULL) {
*m_resultRef = NULL;
}
// TODO: Consider if interpretedCode can be deleted imm. after ::doSend
delete m_interpretedCode;
m_interpretedCode = NULL;
} //NdbQueryOperationImpl::postFetchRelease()
Uint32
NdbQueryOperationImpl::getNoOfParentOperations() const
{
return (m_parent) ? 1 : 0;
}
NdbQueryOperationImpl&
NdbQueryOperationImpl::getParentOperation(Uint32 i) const
{
assert(i==0 && m_parent!=NULL);
return *m_parent;
}
NdbQueryOperationImpl*
NdbQueryOperationImpl::getParentOperation() const
{
return m_parent;
}
Uint32
NdbQueryOperationImpl::getNoOfChildOperations() const
{
return m_children.size();
}
NdbQueryOperationImpl&
NdbQueryOperationImpl::getChildOperation(Uint32 i) const
{
return *m_children[i];
}
Int32 NdbQueryOperationImpl::getNoOfDescendantOperations() const
{
Int32 children = 0;
for (unsigned i = 0; i < getNoOfChildOperations(); i++)
children += 1 + getChildOperation(i).getNoOfDescendantOperations();
return children;
}
SpjTreeNodeMask
NdbQueryOperationImpl::getDependants() const
{
SpjTreeNodeMask dependants;
dependants.set(getInternalOpNo());
for (unsigned i = 0; i < m_children.size(); i++)
{
dependants.bitOR(m_children[i]->getDependants());
}
// Add extra dependants in sub-branches not being children
for (unsigned i = 0; i < m_dependants.size(); i++)
{
dependants.bitOR(m_dependants[i]->getDependants());
}
return dependants;
}
Uint32
NdbQueryOperationImpl::getNoOfLeafOperations() const
{
if (getNoOfChildOperations() == 0)
{
return 1;
}
else
{
Uint32 sum = 0;
for (unsigned i = 0; i < getNoOfChildOperations(); i++)
sum += getChildOperation(i).getNoOfLeafOperations();
return sum;
}
}
NdbRecAttr*
NdbQueryOperationImpl::getValue(
const char* anAttrName,
char* resultBuffer)
{
if (unlikely(anAttrName == NULL)) {
getQuery().setErrorCode(QRY_REQ_ARG_IS_NULL);
return NULL;
}
const NdbColumnImpl* const column
= m_operationDef.getTable().getColumn(anAttrName);
if(unlikely(column==NULL)){
getQuery().setErrorCode(Err_UnknownColumn);
return NULL;
} else {
return getValue(*column, resultBuffer);
}
}
NdbRecAttr*
NdbQueryOperationImpl::getValue(
Uint32 anAttrId,
char* resultBuffer)
{
const NdbColumnImpl* const column
= m_operationDef.getTable().getColumn(anAttrId);
if(unlikely(column==NULL)){
getQuery().setErrorCode(Err_UnknownColumn);
return NULL;
} else {
return getValue(*column, resultBuffer);
}
}
NdbRecAttr*
NdbQueryOperationImpl::getValue(
const NdbColumnImpl& column,
char* resultBuffer)
{
if (unlikely(getQuery().m_state != NdbQueryImpl::Defined)) {
int state = getQuery().m_state;
assert (state >= NdbQueryImpl::Initial && state < NdbQueryImpl::Destructed);
if (state == NdbQueryImpl::Failed)
getQuery().setErrorCode(QRY_IN_ERROR_STATE);
else
getQuery().setErrorCode(QRY_ILLEGAL_STATE);
DEBUG_CRASH();
return NULL;
}
Ndb* const ndb = getQuery().getNdbTransaction().getNdb();
NdbRecAttr* const recAttr = ndb->getRecAttr();
if(unlikely(recAttr == NULL)) {
getQuery().setErrorCode(Err_MemoryAlloc);
return NULL;
}
if(unlikely(recAttr->setup(&column, resultBuffer))) {
ndb->releaseRecAttr(recAttr);
getQuery().setErrorCode(Err_MemoryAlloc);
return NULL;
}
// Append to tail of list.
if(m_firstRecAttr == NULL){
m_firstRecAttr = recAttr;
}else{
m_lastRecAttr->next(recAttr);
}
m_lastRecAttr = recAttr;
assert(recAttr->next()==NULL);
return recAttr;
}
int
NdbQueryOperationImpl::setResultRowBuf (
const NdbRecord *rec,
char* resBuffer,
const unsigned char* result_mask)
{
if (unlikely(rec==0)) {
getQuery().setErrorCode(QRY_REQ_ARG_IS_NULL);
return -1;
}
if (unlikely(getQuery().m_state != NdbQueryImpl::Defined)) {
int state = getQuery().m_state;
assert (state >= NdbQueryImpl::Initial && state < NdbQueryImpl::Destructed);
if (state == NdbQueryImpl::Failed)
getQuery().setErrorCode(QRY_IN_ERROR_STATE);
else
getQuery().setErrorCode(QRY_ILLEGAL_STATE);
DEBUG_CRASH();
return -1;
}
if (rec->tableId !=
static_cast<Uint32>(m_operationDef.getTable().getTableId())){
/* The key_record and attribute_record in primary key operation do not
belong to the same table.*/
getQuery().setErrorCode(Err_DifferentTabForKeyRecAndAttrRec);
return -1;
}
if (unlikely(m_ndbRecord != NULL)) {
getQuery().setErrorCode(QRY_RESULT_ROW_ALREADY_DEFINED);
return -1;
}
m_ndbRecord = rec;
m_read_mask = result_mask;
m_resultBuffer = resBuffer;
return 0;
}
int
NdbQueryOperationImpl::setResultRowRef (
const NdbRecord* rec,
const char* & bufRef,
const unsigned char* result_mask)
{
m_resultRef = &bufRef;
*m_resultRef = NULL; // No result row yet
return setResultRowBuf(rec, NULL, result_mask);
}
NdbQuery::NextResultOutcome
NdbQueryOperationImpl::firstResult()
{
if (unlikely(getQuery().m_state < NdbQueryImpl::Executing ||
getQuery().m_state >= NdbQueryImpl::Closed)) {
int state = getQuery().m_state;
assert (state >= NdbQueryImpl::Initial && state < NdbQueryImpl::Destructed);
if (state == NdbQueryImpl::Failed)
getQuery().setErrorCode(QRY_IN_ERROR_STATE);
else
getQuery().setErrorCode(QRY_ILLEGAL_STATE);
DEBUG_CRASH();
return NdbQuery::NextResult_error;
}
const NdbWorker* worker;
#if 0 // TODO ::firstResult() on root operation is unused, incomplete & untested
if (unlikely(getParentOperation()==NULL))
{
// Reset *all* ResultStreams, optionaly order them, and find new current among them
for( Uint32 i = 0; i<m_queryImpl.getRootFragCount(); i++)
{
m_resultStreams[i]->firstResult();
}
worker = m_queryImpl.m_applFrags.reorganize();
assert(worker==NULL || worker==m_queryImpl.m_applFrags.getCurrent());
}
else
#endif
{
assert(getParentOperation()!=NULL); // TODO, See above
worker = m_queryImpl.m_applFrags.getCurrent();
}
if (worker != NULL)
{
NdbResultStream& resultStream = worker->getResultStream(*this);
if (resultStream.firstResult() != tupleNotFound)
{
fetchRow(resultStream);
return NdbQuery::NextResult_gotRow;
}
}
nullifyResult();
return NdbQuery::NextResult_scanComplete;
} //NdbQueryOperationImpl::firstResult()
NdbQuery::NextResultOutcome
NdbQueryOperationImpl::nextResult(bool fetchAllowed, bool forceSend)
{
if (unlikely(getQuery().m_state < NdbQueryImpl::Executing ||
getQuery().m_state >= NdbQueryImpl::Closed)) {
int state = getQuery().m_state;
assert (state >= NdbQueryImpl::Initial && state < NdbQueryImpl::Destructed);
if (state == NdbQueryImpl::Failed)
getQuery().setErrorCode(QRY_IN_ERROR_STATE);
else
getQuery().setErrorCode(QRY_ILLEGAL_STATE);
DEBUG_CRASH();
return NdbQuery::NextResult_error;
}
if (this == &getRoot())
{
return m_queryImpl.nextRootResult(fetchAllowed,forceSend);
}
/**
* 'next' will never be able to return anything for a lookup operation.
* NOTE: This is a pure optimization shortcut!
*/
else if (m_operationDef.isScanOperation())
{
const NdbWorker* worker = m_queryImpl.m_applFrags.getCurrent();
if (worker!=NULL)
{
NdbResultStream& resultStream = worker->getResultStream(*this);
if (resultStream.nextResult() != tupleNotFound)
{
fetchRow(resultStream);
return NdbQuery::NextResult_gotRow;
}
}
}
nullifyResult();
return NdbQuery::NextResult_scanComplete;
} //NdbQueryOperationImpl::nextResult()
void
NdbQueryOperationImpl::fetchRow(NdbResultStream& resultStream)
{
const char* buff = resultStream.getCurrentRow();
assert(buff!=NULL || (m_firstRecAttr==NULL && m_ndbRecord==NULL));
m_isRowNull = false;
if (m_firstRecAttr != NULL)
{
// Retrieve any RecAttr (getValues()) for current row
const int retVal = resultStream.getReceiver().get_AttrValues(m_firstRecAttr);
assert(retVal==0); ((void)retVal);
}
if (m_ndbRecord != NULL)
{
if (m_resultRef!=NULL)
{
// Set application pointer to point into internal buffer.
*m_resultRef = buff;
}
else
{
assert(m_resultBuffer!=NULL);
// Copy result to buffer supplied by application.
memcpy(m_resultBuffer, buff, m_ndbRecord->m_row_size);
}
}
} // NdbQueryOperationImpl::fetchRow
void
NdbQueryOperationImpl::nullifyResult()
{
if (!m_isRowNull)
{
/* This operation gave no result for the current row.*/
m_isRowNull = true;
if (m_resultRef!=NULL)
{
// Set the pointer supplied by the application to NULL.
*m_resultRef = NULL;
}
/* We should not give any results for the descendants either.*/
for (Uint32 i = 0; i<getNoOfChildOperations(); i++)
{
getChildOperation(i).nullifyResult();
}
}
} // NdbQueryOperationImpl::nullifyResult
bool
NdbQueryOperationImpl::isRowNULL() const
{
return m_isRowNull;
}
bool
NdbQueryOperationImpl::isRowChanged() const
{
// FIXME: Need to be implemented as scan linked with scan is now implemented.
return true;
}
static bool isSetInMask(const unsigned char* mask, int bitNo)
{
return mask[bitNo>>3] & 1<<(bitNo&7);
}
int
NdbQueryOperationImpl::serializeProject(Uint32Buffer& attrInfo)
{
Uint32 startPos = attrInfo.getSize();
attrInfo.append(0U); // Temp write firste 'length' word, update later
/**
* If the columns in the projections are specified as
* in NdbRecord format, attrId are assumed to be ordered ascending.
* In this form the projection spec. can be packed as
* a single bitmap.
*/
if (m_ndbRecord != NULL) {
Bitmask<MAXNROFATTRIBUTESINWORDS> readMask;
Uint32 requestedCols= 0;
Uint32 maxAttrId= 0;
for (Uint32 i= 0; i<m_ndbRecord->noOfColumns; i++)
{
const NdbRecord::Attr* const col= &m_ndbRecord->columns[i];
Uint32 attrId= col->attrId;
if (m_read_mask == NULL || isSetInMask(m_read_mask, i))
{ if (attrId > maxAttrId)
maxAttrId= attrId;
readMask.set(attrId);
requestedCols++;
const NdbColumnImpl* const column = getQueryOperationDef().getTable()
.getColumn(col->column_no);
if (column->getStorageType() == NDB_STORAGETYPE_DISK)
{
m_diskInUserProjection = true;
}
}
}
// Test for special case, get all columns:
if (requestedCols == (unsigned)m_operationDef.getTable().getNoOfColumns()) {
Uint32 ah;
AttributeHeader::init(&ah, AttributeHeader::READ_ALL, requestedCols);
attrInfo.append(ah);
} else if (requestedCols > 0) {
/* Serialize projection as a bitmap.*/
const Uint32 wordCount = 1+maxAttrId/32; // Size of mask.
Uint32* dst = attrInfo.alloc(wordCount+1);
AttributeHeader::init(dst,
AttributeHeader::READ_PACKED, 4*wordCount);
memcpy(dst+1, &readMask, 4*wordCount);
}
} // if (m_ndbRecord...)
/** Projection is specified in RecAttr format.
* This may also be combined with the NdbRecord format.
*/
const NdbRecAttr* recAttr = m_firstRecAttr;
/* Serialize projection as a list of Attribute id's.*/
while (recAttr) {
Uint32 ah;
AttributeHeader::init(&ah,
recAttr->attrId(),
0);
attrInfo.append(ah);
if (recAttr->getColumn()->getStorageType() == NDB_STORAGETYPE_DISK)
{
m_diskInUserProjection = true;
}
recAttr = recAttr->next();
}
const bool withCorrelation = getQueryDef().isScanQuery();
if (withCorrelation) {
Uint32 ah;
AttributeHeader::init(&ah, AttributeHeader::CORR_FACTOR64, 0);
attrInfo.append(ah);
}
// Size of projection in words.
Uint32 length = attrInfo.getSize() - startPos - 1 ;
attrInfo.put(startPos, length);
return 0;
} // NdbQueryOperationImpl::serializeProject
int NdbQueryOperationImpl::serializeParams(const NdbQueryParamValue* paramValues)
{
if (unlikely(paramValues == NULL))
{
return QRY_REQ_ARG_IS_NULL;
}
const NdbQueryOperationDefImpl& def = getQueryOperationDef();
for (Uint32 i=0; i<def.getNoOfParameters(); i++)
{
const NdbParamOperandImpl& paramDef = def.getParameter(i);
const NdbQueryParamValue& paramValue = paramValues[paramDef.getParamIx()];
/**
* Add parameter value to serialized data.
* Each value has a Uint32 length field (in bytes), followed by
* the actuall value. Allocation is in Uint32 units with unused bytes
* zero padded.
**/
const Uint32 oldSize = m_params.getSize();
m_params.append(0); // Place holder for length.
bool null;
Uint32 len;
const int error =
paramValue.serializeValue(*paramDef.getColumn(), m_params, len, null);
if (unlikely(error))
return error;
if (unlikely(null))
return Err_KeyIsNULL;
if(unlikely(m_params.isMemoryExhausted())){
return Err_MemoryAlloc;
}
// Back patch length field.
m_params.put(oldSize, len);
}
return 0;
} // NdbQueryOperationImpl::serializeParams
Uint32
NdbQueryOperationImpl
::calculateBatchedRows(const NdbQueryOperationImpl* closestScan)
{
const NdbQueryOperationImpl* myClosestScan;
if (m_operationDef.isScanOperation())
{
myClosestScan = this;
}
else
{
myClosestScan = closestScan;
}
Uint32 maxBatchRows = 0;
if (myClosestScan != NULL)
{
// To force usage of SCAN_NEXTREQ even for small scans resultsets
if (DBUG_EVALUATE_IF("max_4rows_in_spj_batches", true, false))
{
m_maxBatchRows = 4;
}
else if (DBUG_EVALUATE_IF("max_64rows_in_spj_batches", true, false))
{
m_maxBatchRows = 64;
}
else if (enforcedBatchSize)
{
m_maxBatchRows = enforcedBatchSize;
}
const Ndb& ndb = *getQuery().getNdbTransaction().getNdb();
/**
* For each batch, a lookup operation must be able to receive as many rows
* as the closest ancestor scan operation.
* We must thus make sure that we do not set a batch size for the scan
* that exceeds what any of its scan descendants can use.
*
* Ignore calculated 'batchByteSize'
* here - Recalculated when building signal after max-batchRows has been
* determined.
*/
const Uint32 rootFragments
= getRoot().getQueryOperationDef().getTable().getFragmentCount();
Uint32 batchByteSize;
/**
* myClosestScan->m_maxBatchRows may be zero to indicate that we
* should use default values, or non-zero if the application had an
* explicit preference.
* ::calculate_batch_size() will then use the configured 'batchSize'
* values to set, or cap, #rows / #bytes in batch for *each fragment*.
*/
maxBatchRows = myClosestScan->m_maxBatchRows;
NdbReceiver::calculate_batch_size(* ndb.theImpl,
getRoot().m_parallelism == Parallelism_max
? rootFragments
: getRoot().m_parallelism,
maxBatchRows,
batchByteSize);
assert(maxBatchRows > 0);
assert(maxBatchRows <= batchByteSize);
/**
* There is a 12-bit implementation limit of how large
* the 'parent-row-correlation-id' may be. Thus, if rows
* from this scan may be 'parents', we have to
* reduce number of rows retrieved in each batch.
*/
if (m_children.size() > 0) //Is a 'parent'
{
static const Uint32 max_batch_size_rows = 0x1000;
const Uint32 fragsPerWorker = getQuery().m_fragsPerWorker;
maxBatchRows = MIN(maxBatchRows, max_batch_size_rows/fragsPerWorker);
}
}
// Find the largest value that is acceptable to all lookup descendants.
for (Uint32 i = 0; i < m_children.size(); i++)
{
const Uint32 childMaxBatchRows =
m_children[i]->calculateBatchedRows(myClosestScan);
maxBatchRows = MIN(maxBatchRows, childMaxBatchRows);
}
if (m_operationDef.isScanOperation())
{
// Use this value for current op and all lookup descendants.
m_maxBatchRows = maxBatchRows;
// Return max(Unit32) to avoid interfering with batch size calculation
// for parent.
return 0xffffffff;
}
else
{
return maxBatchRows;
}
} // NdbQueryOperationImpl::calculateBatchedRows
void
NdbQueryOperationImpl::setBatchedRows(Uint32 batchedRows)
{
if (!m_operationDef.isScanOperation())
{
/** Lookup operations should handle the same number of rows as
* the closest scan ancestor.
*/
m_maxBatchRows = batchedRows;
}
for (Uint32 i = 0; i < m_children.size(); i++)
{
m_children[i]->setBatchedRows(m_maxBatchRows);
}
}
int
NdbQueryOperationImpl::prepareAttrInfo(Uint32Buffer& attrInfo,
const QueryNode*& queryNode)
{
const NdbQueryOperationDefImpl& def = getQueryOperationDef();
/**
* Serialize parameters refered by this NdbQueryOperation.
* Params for the complete NdbQuery is collected in a single
* serializedParams chunk. Each operations params are
* proceeded by 'length' for this operation.
*/
if (def.getType() == NdbQueryOperationDef::UniqueIndexAccess)
{
// Reserve memory for LookupParameters, fill in contents later when
// 'length' and 'requestInfo' has been calculated.
Uint32 startPos = attrInfo.getSize();
attrInfo.alloc(QN_LookupParameters::NodeSize);
Uint32 requestInfo = 0;
if (m_params.getSize() > 0)
{
// parameter values has been serialized as part of NdbTransaction::createQuery()
// Only need to append it to rest of the serialized arguments
requestInfo |= DABits::PI_KEY_PARAMS;
attrInfo.append(m_params);
}
QN_LookupParameters* param = reinterpret_cast<QN_LookupParameters*>(attrInfo.addr(startPos));
if (unlikely(param==NULL))
return Err_MemoryAlloc;
param->requestInfo = requestInfo;
param->resultData = getIdOfReceiver();
Uint32 length = attrInfo.getSize() - startPos;
if (unlikely(length > 0xFFFF)) {
return QRY_DEFINITION_TOO_LARGE; //Query definition too large.
}
QueryNodeParameters::setOpLen(param->len,
QueryNodeParameters::QN_LOOKUP,
length);
#ifdef __TRACE_SERIALIZATION
ndbout << "Serialized params for index node "
<< getInternalOpNo()-1 << " : ";
for(Uint32 i = startPos; i < attrInfo.getSize(); i++){
char buf[12];
sprintf(buf, "%.8x", attrInfo.get(i));
ndbout << buf << " ";
}
ndbout << endl;
#endif
queryNode = QueryNode::nextQueryNode(queryNode);
} // if (UniqueIndexAccess ...
// Reserve memory for LookupParameters, fill in contents later when
// 'length' and 'requestInfo' has been calculated.
Uint32 startPos = attrInfo.getSize();
Uint32 requestInfo = 0;
/**
* Create QueryNodeParameters type matching each QueryNode.
*/
const Uint32 type = QueryNode::getOpType(queryNode->len);
const QueryNodeParameters::OpType paramType = (QueryNodeParameters::OpType)type;
switch (paramType)
{
case QueryNodeParameters::QN_LOOKUP:
assert(!def.isScanOperation());
attrInfo.alloc(QN_LookupParameters::NodeSize);
break;
case QueryNodeParameters::QN_SCAN_FRAG:
assert(def.isScanOperation());
attrInfo.alloc(QN_ScanFragParameters::NodeSize);
break;
case QueryNodeParameters::QN_SCAN_INDEX_v1:
assert(def.isScanOperation() && def.getOpNo()>0);
attrInfo.alloc(QN_ScanIndexParameters_v1::NodeSize);
break;
case QueryNodeParameters::QN_SCAN_FRAG_v1:
assert(def.isScanOperation() && def.getOpNo()==0);
attrInfo.alloc(QN_ScanFragParameters_v1::NodeSize);
break;
default:
assert(false);
}
// SPJ block assume PARAMS to be supplied before ATTR_LIST
if (m_params.getSize() > 0 &&
def.getType() != NdbQueryOperationDef::UniqueIndexAccess)
{
// parameter values has been serialized as part of NdbTransaction::createQuery()
// Only need to append it to rest of the serialized arguments
requestInfo |= DABits::PI_KEY_PARAMS;
attrInfo.append(m_params);
}
if (hasInterpretedCode())
{
requestInfo |= DABits::PI_ATTR_INTERPRET;
const int error= prepareInterpretedCode(attrInfo);
if (unlikely(error))
{
return error;
}
}
if (m_ndbRecord==NULL && m_firstRecAttr==NULL)
{
// Leaf operations with empty projections are not supported.
if (getNoOfChildOperations() == 0)
{
return QRY_EMPTY_PROJECTION;
}
}
else
{
requestInfo |= DABits::PI_ATTR_LIST;
const int error = serializeProject(attrInfo);
if (unlikely(error)) {
return error;
}
}
if (diskInUserProjection())
{
requestInfo |= DABits::PI_DISK_ATTR;
}
Uint32 length = attrInfo.getSize() - startPos;
if (unlikely(length > 0xFFFF)) {
return QRY_DEFINITION_TOO_LARGE; //Query definition too large.
}
switch (paramType)
{
case QueryNodeParameters::QN_LOOKUP:
{
QN_LookupParameters* param = reinterpret_cast<QN_LookupParameters*>(attrInfo.addr(startPos));
if (unlikely(param==NULL))
return Err_MemoryAlloc;
param->requestInfo = requestInfo;
param->resultData = getIdOfReceiver();
QueryNodeParameters::setOpLen(param->len, paramType, length);
break;
}
case QueryNodeParameters::QN_SCAN_FRAG:
{
QN_ScanFragParameters* param =
reinterpret_cast<QN_ScanFragParameters*>(attrInfo.addr(startPos));
if (unlikely(param==NULL))
return Err_MemoryAlloc;
const Uint32 fragsPerWorker = getQuery().m_fragsPerWorker;
const Uint32 batchRows = getMaxBatchRows()*fragsPerWorker;
const Uint32 batchByteSize = getMaxBatchBytes()*fragsPerWorker;
assert(batchRows <= batchByteSize);
assert(m_parallelism == Parallelism_max ||
m_parallelism == Parallelism_adaptive);
if (m_parallelism == Parallelism_max)
{
requestInfo |= QN_ScanFragParameters::SFP_PARALLEL;
}
if (def.hasParamInPruneKey())
{
requestInfo |= QN_ScanFragParameters::SFP_PRUNE_PARAMS;
}
if (getOrdering() != NdbQueryOptions::ScanOrdering_unordered)
{
requestInfo |= QN_ScanFragParameters::SFP_SORTED_ORDER;
// Only supported for root yet.
DBUG_ASSERT(this == &getRoot());
}
param->requestInfo = requestInfo;
param->resultData = getIdOfReceiver();
param->batch_size_rows = batchRows;
param->batch_size_bytes = batchByteSize;
param->unused0 = 0; //Future
param->unused1 = 0;
param->unused2 = 0;
QueryNodeParameters::setOpLen(param->len, paramType, length);
break;
}
// Check deprecated QueryNode types last:
case QueryNodeParameters::QN_SCAN_INDEX_v1: //Deprecated
{
QN_ScanIndexParameters_v1* param =
reinterpret_cast<QN_ScanIndexParameters_v1*>(attrInfo.addr(startPos));
if (unlikely(param==NULL))
return Err_MemoryAlloc;
assert(m_parallelism == Parallelism_max ||
m_parallelism == Parallelism_adaptive);
if (m_parallelism == Parallelism_max)
{
requestInfo |= QN_ScanIndexParameters_v1::SIP_PARALLEL;
}
if (def.hasParamInPruneKey())
{
requestInfo |= QN_ScanIndexParameters_v1::SIP_PRUNE_PARAMS;
}
param->requestInfo = requestInfo;
// Get Batch sizes, assert that both values fit in param->batchSize.
const Uint32 batchRows = getMaxBatchRows();
const Uint32 batchByteSize = getMaxBatchBytes();
assert(batchRows < (1<<QN_ScanIndexParameters_v1::BatchRowBits));
assert(batchByteSize < (1 << (sizeof param->batchSize * 8
- QN_ScanIndexParameters_v1::BatchRowBits)));
param->batchSize = (batchByteSize << QN_ScanIndexParameters_v1::BatchRowBits)
| batchRows;
param->resultData = getIdOfReceiver();
QueryNodeParameters::setOpLen(param->len, paramType, length);
break;
}
case QueryNodeParameters::QN_SCAN_FRAG_v1: //Deprecated
{
assert(paramType == QueryNodeParameters::QN_SCAN_FRAG_v1);
QN_ScanFragParameters_v1* param =
reinterpret_cast<QN_ScanFragParameters_v1*>(attrInfo.addr(startPos));
if (unlikely(param==NULL))
return Err_MemoryAlloc;
param->requestInfo = requestInfo;
param->resultData = getIdOfReceiver();
QueryNodeParameters::setOpLen(param->len, paramType, length);
break;
}
default:
assert(false);
}
#ifdef __TRACE_SERIALIZATION
ndbout << "Serialized params for node "
<< getInternalOpNo() << " : ";
for(Uint32 i = startPos; i < attrInfo.getSize(); i++){
char buf[12];
sprintf(buf, "%.8x", attrInfo.get(i));
ndbout << buf << " ";
}
ndbout << endl;
#endif
// Parameter values was appended to AttrInfo, shrink param buffer
// to reduce memory footprint.
m_params.releaseExtend();
queryNode = QueryNode::nextQueryNode(queryNode);
return 0;
} // NdbQueryOperationImpl::prepareAttrInfo
int
NdbQueryOperationImpl::prepareKeyInfo(
Uint32Buffer& keyInfo,
const NdbQueryParamValue* actualParam)
{
assert(this == &getRoot()); // Should only be called for root operation.
#ifdef TRACE_SERIALIZATION
int startPos = keyInfo.getSize();
#endif
const NdbQueryOperationDefImpl::IndexBound* bounds = m_operationDef.getBounds();
if (bounds)
{
const int error = prepareIndexKeyInfo(keyInfo, bounds, actualParam);
if (unlikely(error))
return error;
}
const NdbQueryOperandImpl* const* keys = m_operationDef.getKeyOperands();
if (keys)
{
const int error = prepareLookupKeyInfo(keyInfo, keys, actualParam);
if (unlikely(error))
return error;
}
if (unlikely(keyInfo.isMemoryExhausted())) {
return Err_MemoryAlloc;
}
#ifdef TRACE_SERIALIZATION
ndbout << "Serialized KEYINFO for NdbQuery root : ";
for (Uint32 i = startPos; i < keyInfo.getSize(); i++) {
char buf[12];
sprintf(buf, "%.8x", keyInfo.get(i));
ndbout << buf << " ";
}
ndbout << endl;
#endif
return 0;
} // NdbQueryOperationImpl::prepareKeyInfo
/**
* Convert constant operand into sequence of words that may be sent to data
* nodes.
* @param constOp Operand to convert.
* @param buffer Destination buffer.
* @param len Will be set to length in bytes.
* @return 0 if ok, otherwise error code.
*/
static int
serializeConstOp(const NdbConstOperandImpl& constOp,
Uint32Buffer& buffer,
Uint32& len)
{
// Check that column->shrink_varchar() not specified, only used by mySQL
// assert (!(column->flags & NdbDictionary::RecMysqldShrinkVarchar));
buffer.skipRestOfWord();
len = constOp.getSizeInBytes();
Uint8 shortLen[2];
switch (constOp.getColumn()->getArrayType()) {
case NdbDictionary::Column::ArrayTypeFixed:
buffer.appendBytes(constOp.getAddr(), len);
break;
case NdbDictionary::Column::ArrayTypeShortVar:
// Such errors should have been caught in convert2ColumnType().
assert(len <= 0xFF);
shortLen[0] = (unsigned char)len;
buffer.appendBytes(shortLen, 1);
buffer.appendBytes(constOp.getAddr(), len);
len+=1;
break;
case NdbDictionary::Column::ArrayTypeMediumVar:
// Such errors should have been caught in convert2ColumnType().
assert(len <= 0xFFFF);
shortLen[0] = (unsigned char)(len & 0xFF);
shortLen[1] = (unsigned char)(len >> 8);
buffer.appendBytes(shortLen, 2);
buffer.appendBytes(constOp.getAddr(), len);
len+=2;
break;
default:
assert(false);
}
if (unlikely(buffer.isMemoryExhausted())) {
return Err_MemoryAlloc;
}
return 0;
} // static serializeConstOp
static int
appendBound(Uint32Buffer& keyInfo,
NdbIndexScanOperation::BoundType type, const NdbQueryOperandImpl* bound,
const NdbQueryParamValue* actualParam)
{
Uint32 len = 0;
keyInfo.append(type);
const Uint32 oldSize = keyInfo.getSize();
keyInfo.append(0); // Place holder for AttributeHeader
switch(bound->getKind()){
case NdbQueryOperandImpl::Const:
{
const NdbConstOperandImpl& constOp =
static_cast<const NdbConstOperandImpl&>(*bound);
const int error = serializeConstOp(constOp, keyInfo, len);
if (unlikely(error))
return error;
break;
}
case NdbQueryOperandImpl::Param:
{
const NdbParamOperandImpl* const paramOp
= static_cast<const NdbParamOperandImpl*>(bound);
const int paramNo = paramOp->getParamIx();
assert(actualParam != NULL);
bool null;
const int error =
actualParam[paramNo].serializeValue(*paramOp->getColumn(), keyInfo,
len, null);
if (unlikely(error))
return error;
if (unlikely(null))
return Err_KeyIsNULL;
break;
}
case NdbQueryOperandImpl::Linked: // Root operation cannot have linked operands.
default:
assert(false);
}
// Back patch attribute header.
keyInfo.put(oldSize,
AttributeHeader(bound->getColumn()->m_attrId, len).m_value);
return 0;
} // static appendBound()
int
NdbQueryOperationImpl::prepareIndexKeyInfo(
Uint32Buffer& keyInfo,
const NdbQueryOperationDefImpl::IndexBound* bounds,
const NdbQueryParamValue* actualParam)
{
int startPos = keyInfo.getSize();
if (bounds->lowKeys==0 && bounds->highKeys==0) // No Bounds defined
return 0;
const unsigned key_count =
(bounds->lowKeys >= bounds->highKeys) ? bounds->lowKeys : bounds->highKeys;
for (unsigned keyNo = 0; keyNo < key_count; keyNo++)
{
NdbIndexScanOperation::BoundType bound_type;
/* If upper and lower limit is equal, a single BoundEQ is sufficient */
if (keyNo < bounds->lowKeys &&
keyNo < bounds->highKeys &&
bounds->low[keyNo] == bounds->high[keyNo])
{
/* Inclusive if defined, or matching rows can include this value */
bound_type= NdbIndexScanOperation::BoundEQ;
int error = appendBound(keyInfo, bound_type, bounds->low[keyNo], actualParam);
if (unlikely(error))
return error;
} else {
/* If key is part of lower bound */
if (keyNo < bounds->lowKeys)
{
/* Inclusive if defined, or matching rows can include this value */
bound_type= bounds->lowIncl || keyNo+1 < bounds->lowKeys ?
NdbIndexScanOperation::BoundLE : NdbIndexScanOperation::BoundLT;
int error = appendBound(keyInfo, bound_type, bounds->low[keyNo], actualParam);
if (unlikely(error))
return error;
}
/* If key is part of upper bound */
if (keyNo < bounds->highKeys)
{
/* Inclusive if defined, or matching rows can include this value */
bound_type= bounds->highIncl || keyNo+1 < bounds->highKeys ?
NdbIndexScanOperation::BoundGE : NdbIndexScanOperation::BoundGT;
int error = appendBound(keyInfo, bound_type, bounds->high[keyNo], actualParam);
if (unlikely(error))
return error;
}
}
}
Uint32 length = keyInfo.getSize()-startPos;
if (unlikely(keyInfo.isMemoryExhausted())) {
return Err_MemoryAlloc;
} else if (unlikely(length > 0xFFFF)) {
return QRY_DEFINITION_TOO_LARGE; // Query definition too large.
} else if (likely(length > 0)) {
keyInfo.put(startPos, keyInfo.get(startPos) | (length << 16));
}
m_queryImpl.m_shortestBound =(bounds->lowKeys <= bounds->highKeys) ? bounds->lowKeys : bounds->highKeys;
return 0;
} // NdbQueryOperationImpl::prepareIndexKeyInfo
int
NdbQueryOperationImpl::prepareLookupKeyInfo(
Uint32Buffer& keyInfo,
const NdbQueryOperandImpl* const keys[],
const NdbQueryParamValue* actualParam)
{
const int keyCount = m_operationDef.getIndex()!=NULL ?
static_cast<int>(m_operationDef.getIndex()->getNoOfColumns()) :
m_operationDef.getTable().getNoOfPrimaryKeys();
for (int keyNo = 0; keyNo<keyCount; keyNo++)
{
Uint32 dummy;
switch(keys[keyNo]->getKind()){
case NdbQueryOperandImpl::Const:
{
const NdbConstOperandImpl* const constOp
= static_cast<const NdbConstOperandImpl*>(keys[keyNo]);
const int error =
serializeConstOp(*constOp, keyInfo, dummy);
if (unlikely(error))
return error;
break;
}
case NdbQueryOperandImpl::Param:
{
const NdbParamOperandImpl* const paramOp
= static_cast<const NdbParamOperandImpl*>(keys[keyNo]);
int paramNo = paramOp->getParamIx();
assert(actualParam != NULL);
bool null;
const int error =
actualParam[paramNo].serializeValue(*paramOp->getColumn(), keyInfo,
dummy, null);
if (unlikely(error))
return error;
if (unlikely(null))
return Err_KeyIsNULL;
break;
}
case NdbQueryOperandImpl::Linked: // Root operation cannot have linked operands.
default:
assert(false);
}
}
if (unlikely(keyInfo.isMemoryExhausted())) {
return Err_MemoryAlloc;
}
return 0;
} // NdbQueryOperationImpl::prepareLookupKeyInfo
bool
NdbQueryOperationImpl::execTRANSID_AI(const Uint32* ptr, Uint32 len)
{
TupleCorrelation tupleCorrelation;
NdbWorker* worker = m_queryImpl.m_workers;
if (getQueryDef().isScanQuery())
{
const CorrelationData correlData(ptr, len);
const Uint32 receiverId = correlData.getRootReceiverId();
/** receiverId holds the Id of the receiver of the corresponding stream
* of the root operation. We can thus find the correct worker
* number.
*/
worker = NdbWorker::receiverIdLookup(m_queryImpl.m_workers,
m_queryImpl.getWorkerCount(),
receiverId);
if (unlikely(worker == NULL))
{
assert(false);
return false;
}
// Extract tuple correlation.
tupleCorrelation = correlData.getTupleCorrelation();
len -= CorrelationData::wordCount;
}
if (traceSignals) {
ndbout << "NdbQueryOperationImpl::execTRANSID_AI()"
<< ", from workerNo=" << worker->getWorkerNo()
<< ", operation no: " << getQueryOperationDef().getInternalOpNo()
<< endl;
}
// Process result values.
worker->getResultStream(*this).execTRANSID_AI(ptr, len, tupleCorrelation);
worker->incrOutstandingResults(-1);
bool ret = false;
if (worker->isFragBatchComplete())
{
ret = m_queryImpl.handleBatchComplete(*worker);
}
if (false && traceSignals) {
ndbout << "NdbQueryOperationImpl::execTRANSID_AI(): returns:" << ret
<< ", *this=" << *this << endl;
}
return ret;
} //NdbQueryOperationImpl::execTRANSID_AI
bool
NdbQueryOperationImpl::execTCKEYREF(const NdbApiSignal* aSignal)
{
if (traceSignals) {
ndbout << "NdbQueryOperationImpl::execTCKEYREF()" << endl;
}
/* The SPJ block does not forward TCKEYREFs for trees with scan roots.*/
assert(!getQueryDef().isScanQuery());
const TcKeyRef* ref = CAST_CONSTPTR(TcKeyRef, aSignal->getDataPtr());
if (!getQuery().m_transaction.checkState_TransId(ref->transId))
{
#ifdef NDB_NO_DROPPED_SIGNAL
abort();
#endif
return false;
}
// Suppress 'TupleNotFound' status for child operations.
if (&getRoot() == this ||
ref->errorCode != static_cast<Uint32>(Err_TupleNotFound))
{
if (aSignal->getLength() == TcKeyRef::SignalLength)
{
// Signal may contain additional error data
getQuery().m_error.details = (char *)UintPtr(ref->errorData);
}
getQuery().setFetchTerminated(ref->errorCode,false);
}
NdbWorker& worker = getQuery().m_workers[0];
/**
* Error may be either a 'soft' or a 'hard' error.
* 'Soft error' are regarded 'informational', and we are
* allowed to continue execution of the query. A 'hard error'
* will terminate query, close comminication, and further
* incomming signals to this NdbReceiver will be discarded.
*/
switch (ref->errorCode)
{
case Err_TupleNotFound: // 'Soft error' : Row not found
case Err_FalsePredicate: // 'Soft error' : Interpreter_exit_nok
{
/**
* Need to update 'outstanding' count:
* Compensate for children results not produced.
* (doSend() assumed all child results to be materialized)
*/
Uint32 cnt = 1; // self
cnt += getNoOfDescendantOperations();
if (getNoOfChildOperations() > 0)
{
cnt += getNoOfLeafOperations();
}
worker.incrOutstandingResults(- Int32(cnt));
break;
}
default: // 'Hard error':
worker.throwRemainingResults(); // Terminate receive -> complete
}
bool ret = false;
if (worker.isFragBatchComplete())
{
ret = m_queryImpl.handleBatchComplete(worker);
}
if (traceSignals) {
ndbout << "NdbQueryOperationImpl::execTCKEYREF(): returns:" << ret
<< ", *this=" << *this << endl;
}
return ret;
} //NdbQueryOperationImpl::execTCKEYREF
bool
NdbQueryOperationImpl::execSCAN_TABCONF(Uint32 tcPtrI,
Uint32 rowCount,
Uint32 moreMask,
Uint32 activeMask,
const NdbReceiver* receiver)
{
assert((tcPtrI==RNIL && moreMask==0) ||
(tcPtrI!=RNIL && moreMask!=0));
assert(checkMagicNumber());
// For now, only the root operation may be a scan.
assert(&getRoot() == this);
assert(m_operationDef.isScanOperation());
NdbWorker* worker =
NdbWorker::receiverIdLookup(m_queryImpl.m_workers,
m_queryImpl.getWorkerCount(),
receiver->getId());
if (unlikely(worker == NULL))
{
assert(false);
return false;
}
if(traceSignals){
ndbout << "NdbQueryOperationImpl::execSCAN_TABCONF"
<< " from workerNo=" << worker->getWorkerNo()
<< " rows " << rowCount
<< " moreMask: H'" << hex << moreMask
<< " activeMask: H'" << hex << activeMask
<< " tcPtrI " << tcPtrI
<< endl;
}
DBUG_ASSERT(moreMask!=0 || activeMask==0);
// Prepare for SCAN_NEXTREQ, tcPtrI==RNIL, moreMask==0 -> EOF
worker->setConfReceived(tcPtrI);
worker->setRemainingSubScans(moreMask,activeMask);
worker->incrOutstandingResults(rowCount);
bool ret = false;
if (worker->isFragBatchComplete())
{
/* This fragment is now complete */
ret = m_queryImpl.handleBatchComplete(*worker);
}
if (false && traceSignals) {
ndbout << "NdbQueryOperationImpl::execSCAN_TABCONF():, returns:" << ret
<< ", tcPtrI=" << tcPtrI << " rowCount=" << rowCount
<< " *this=" << *this << endl;
}
return ret;
} //NdbQueryOperationImpl::execSCAN_TABCONF
int
NdbQueryOperationImpl::setOrdering(NdbQueryOptions::ScanOrdering ordering)
{
if (getQueryOperationDef().getType() != NdbQueryOperationDef::OrderedIndexScan)
{
getQuery().setErrorCode(QRY_WRONG_OPERATION_TYPE);
return -1;
}
if (m_parallelism != Parallelism_max)
{
getQuery().setErrorCode(QRY_SEQUENTIAL_SCAN_SORTED);
return -1;
}
if(static_cast<const NdbQueryIndexScanOperationDefImpl&>
(getQueryOperationDef())
.getOrdering() != NdbQueryOptions::ScanOrdering_void)
{
getQuery().setErrorCode(QRY_SCAN_ORDER_ALREADY_SET);
return -1;
}
m_ordering = ordering;
return 0;
} // NdbQueryOperationImpl::setOrdering()
int NdbQueryOperationImpl::setInterpretedCode(const NdbInterpretedCode& code)
{
if (code.m_instructions_length == 0)
{
return 0;
}
const NdbTableImpl& table = getQueryOperationDef().getTable();
// Check if operation and interpreter code use the same table
if (unlikely(table.getTableId() != code.getTable()->getTableId()
|| table_version_major(table.getObjectVersion()) !=
table_version_major(code.getTable()->getObjectVersion())))
{
getQuery().setErrorCode(Err_InterpretedCodeWrongTab);
return -1;
}
if (unlikely((code.m_flags & NdbInterpretedCode::Finalised)
== 0))
{
// NdbInterpretedCode::finalise() not called.
getQuery().setErrorCode(Err_FinaliseNotCalled);
return -1;
}
// Allocate an interpreted code object if we do not have one already.
if (likely(m_interpretedCode == NULL))
{
m_interpretedCode = new NdbInterpretedCode();
if (unlikely(m_interpretedCode==NULL))
{
getQuery().setErrorCode(Err_MemoryAlloc);
return -1;
}
}
/*
* Make a deep copy, such that 'code' can be destroyed when this method
* returns.
*/
const int error = m_interpretedCode->copy(code);
if (unlikely(error))
{
getQuery().setErrorCode(error);
return -1;
}
return 0;
} // NdbQueryOperationImpl::setInterpretedCode()
int NdbQueryOperationImpl::setParallelism(Uint32 parallelism){
if (!getQueryOperationDef().isScanOperation())
{
getQuery().setErrorCode(QRY_WRONG_OPERATION_TYPE);
return -1;
}
else if (getOrdering() == NdbQueryOptions::ScanOrdering_ascending ||
getOrdering() == NdbQueryOptions::ScanOrdering_descending)
{
getQuery().setErrorCode(QRY_SEQUENTIAL_SCAN_SORTED);
return -1;
}
else if (getQueryOperationDef().getOpNo() > 0)
{
getQuery().setErrorCode(Err_FunctionNotImplemented);
return -1;
}
else if (parallelism < 1 || parallelism > NDB_PARTITION_MASK)
{
getQuery().setErrorCode(Err_ParameterError);
return -1;
}
m_parallelism = parallelism;
return 0;
}
int NdbQueryOperationImpl::setMaxParallelism(){
if (!getQueryOperationDef().isScanOperation())
{
getQuery().setErrorCode(QRY_WRONG_OPERATION_TYPE);
return -1;
}
m_parallelism = Parallelism_max;
return 0;
}
int NdbQueryOperationImpl::setAdaptiveParallelism(){
if (!getQueryOperationDef().isScanOperation())
{
getQuery().setErrorCode(QRY_WRONG_OPERATION_TYPE);
return -1;
}
else if (getQueryOperationDef().getOpNo() == 0)
{
getQuery().setErrorCode(Err_FunctionNotImplemented);
return -1;
}
m_parallelism = Parallelism_adaptive;
return 0;
}
int NdbQueryOperationImpl::setBatchSize(Uint32 batchSize){
if (!getQueryOperationDef().isScanOperation())
{
getQuery().setErrorCode(QRY_WRONG_OPERATION_TYPE);
return -1;
}
if (this != &getRoot() &&
batchSize < getQueryOperationDef().getTable().getFragmentCount())
{
/** Each SPJ block instance will scan each fragment, so the batch size
* cannot be smaller than the number of fragments.*/
getQuery().setErrorCode(QRY_BATCH_SIZE_TOO_SMALL);
return -1;
}
m_maxBatchRows = batchSize;
return 0;
}
bool
NdbQueryOperationImpl::hasInterpretedCode() const
{
return (m_interpretedCode && m_interpretedCode->m_instructions_length > 0) ||
(getQueryOperationDef().getInterpretedCode() != NULL);
} // NdbQueryOperationImpl::hasInterpretedCode
int
NdbQueryOperationImpl::prepareInterpretedCode(Uint32Buffer& attrInfo) const
{
const NdbInterpretedCode* interpretedCode =
(m_interpretedCode && m_interpretedCode->m_instructions_length > 0)
? m_interpretedCode
: getQueryOperationDef().getInterpretedCode();
// There should be no subroutines in a filter.
assert(interpretedCode->m_first_sub_instruction_pos==0);
assert(interpretedCode->m_instructions_length > 0);
assert(interpretedCode->m_instructions_length <= 0xffff);
// Allocate space for program and length field.
Uint32* const buffer =
attrInfo.alloc(1+interpretedCode->m_instructions_length);
if(unlikely(buffer==NULL))
{
return Err_MemoryAlloc;
}
buffer[0] = interpretedCode->m_instructions_length;
memcpy(buffer+1,
interpretedCode->m_buffer,
interpretedCode->m_instructions_length * sizeof(Uint32));
return 0;
} // NdbQueryOperationImpl::prepareInterpretedCode
Uint32
NdbQueryOperationImpl::getIdOfReceiver() const
{
const NdbWorker& worker = m_queryImpl.m_workers[0];
return worker.getResultStream(*this).getReceiver().getId();
}
Uint32 NdbQueryOperationImpl::getRowSize() const
{
// Check if row size has been computed yet.
if (m_rowSize == 0xffffffff)
{
m_rowSize =
NdbReceiver::ndbrecord_rowsize(m_ndbRecord, false);
}
return m_rowSize;
}
Uint32 NdbQueryOperationImpl::getMaxBatchBytes() const
{
// Check if batch buffer size has been computed yet.
if (m_maxBatchBytes == 0)
{
Uint32 batchRows = getMaxBatchRows();
Uint32 batchByteSize = 0;
Uint32 batchFrags = getQuery().m_fragsPerWorker;
// Set together with 'm_resultBufferSize'
assert(m_resultBufferSize == 0);
const Uint32 rootFragments
= getRoot().getQueryOperationDef().getTable().getFragmentCount();
if (m_operationDef.isScanOperation())
{
const Ndb* const ndb = getQuery().getNdbTransaction().getNdb();
const Uint32 parallelism = rootFragments;
NdbReceiver::calculate_batch_size(* ndb->theImpl,
parallelism,
batchRows,
batchByteSize);
assert(batchRows == getMaxBatchRows());
/**
* When LQH reads a scan batch, the size of the batch is limited
* both to a maximal number of rows and a maximal number of bytes.
* The latter limit is interpreted such that the batch ends when the
* limit has been exceeded. Consequently, the buffer must be able to
* hold max_no_of_bytes plus one extra row. In addition, when the
* SPJ block executes a (pushed) child scan operation, it scans a
* number of fragments (possibly all) in parallel, and divides the
* row and byte limits by the number of parallel fragments.
* Consequently, a child scan operation may return max_no_of_bytes,
* plus one extra row for each fragment.
*/
if (getParentOperation() != NULL)
{
batchFrags = rootFragments;
}
else
{
batchFrags = 1;
}
}
AttributeMask readMask;
if (m_ndbRecord != NULL)
{
m_ndbRecord->copyMask(readMask.rep.data, m_read_mask);
}
const bool withCorrelation = getQueryDef().isScanQuery();
m_maxBatchBytes = batchByteSize;
NdbReceiver::result_bufsize(m_ndbRecord,
readMask.rep.data,
m_firstRecAttr,
0, false, //No 'key_size' and 'read_range'
withCorrelation,
batchFrags,
batchRows,
m_maxBatchBytes,
m_resultBufferSize);
}
return m_maxBatchBytes;
}
Uint32 NdbQueryOperationImpl::getResultBufferSize() const
{
(void)getMaxBatchBytes(); //Force calculation if required
return m_resultBufferSize;
}
/** For debugging.*/
NdbOut& operator<<(NdbOut& out, const NdbQueryOperationImpl& op)
{
out << "[ this: " << &op
<< " m_magic: " << op.m_magic;
out << " op.operationDef.getOpNo()"
<< op.m_operationDef.getOpNo();
if (op.getParentOperation()){
out << " m_parent: " << op.getParentOperation();
}
for(unsigned int i = 0; i<op.getNoOfChildOperations(); i++){
out << " m_children[" << i << "]: " << &op.getChildOperation(i);
}
out << " m_queryImpl: " << &op.m_queryImpl;
out << " m_operationDef: " << &op.m_operationDef;
out << " m_isRowNull " << op.m_isRowNull;
out << " ]";
return out;
}
NdbOut& operator<<(NdbOut& out, const NdbResultStream& stream)
{
out << " received rows: " << stream.m_resultSets[stream.m_recv].getRowCount();
return out;
}
// Compiler settings require explicit instantiation.
template class Vector<NdbQueryOperationImpl*>;
| 30.885662 | 114 | 0.663098 | [
"object",
"vector"
] |
cb87cc22a70540cd0dea75c39d9ab83353d91480 | 1,833 | cpp | C++ | lib/c++/search.cpp | tetsuzawa/algorithm | 556c229c6df8787a118498eab3848b53fb57ebd0 | [
"MIT"
] | null | null | null | lib/c++/search.cpp | tetsuzawa/algorithm | 556c229c6df8787a118498eab3848b53fb57ebd0 | [
"MIT"
] | null | null | null | lib/c++/search.cpp | tetsuzawa/algorithm | 556c229c6df8787a118498eab3848b53fb57ebd0 | [
"MIT"
] | null | null | null | /* ------------------- 二分探索 ------------------- */
vector<int> a = {1, 14, 32, 51, 51, 51, 243, 419, 750, 910};
bool isOK(int index, int key) {
if (a[index] >= key)
return true;
else
return false;
}
int binary_search(int key) {
int ng = -1;
int ok = (int)a.size();
while (abs(ok - ng) > 1) {
int mid = (ok + ng) / 2;
if (isOK(mid, key))
ok = mid;
else
ng = mid;
}
/* left は条件を満たさない最大の値、right は条件を満たす最小の値になっている */
return ok;
}
/* ------------------- 二分探索 ------------------- */
/* ------------------- 幅優先探索 ------------------- */
// 各座標に格納したい情報を構造体にする
// 今回はX座標,Y座標,深さ(距離)を記述している
struct Corr {
int x;
int y;
int depth;
};
queue<Corr> q;
int bfs(vector<vector<int>> grid) {
// 既に探索の場所を1,探索していなかったら0を格納する配列
vector<vector<int>> ispassed(grid.size(), vector<int>(grid[0].size(), false));
// このような記述をしておくと,この後のfor文が綺麗にかける
int dx[8] = {1, 0, -1, 0};
int dy[8] = {0, 1, 0, -1};
while (!q.empty()) {
Corr now = q.front();
q.pop();
/*
今いる座標は(x,y)=(now.x, now.y)で,深さ(距離)はnow.depthである
ここで,今いる座標がゴール(探索対象)なのか判定する
*/
for (int i = 0; i < 4; i++) {
int nextx = now.x + dx[i];
int nexty = now.y + dy[i];
// 次に探索する場所のX座標がはみ出した時
if (nextx >= grid[0].size()) continue;
if (nextx < 0) continue;
// 次に探索する場所のY座標がはみ出した時
if (nexty >= grid.size()) continue;
if (nexty < 0) continue;
// 次に探索する場所が既に探索済みの場合
if (ispass[nexty][nextx]) continue;
ispass[nexty][nextx] = true;
Corr next = {nextx, nexty, now.depth + 1};
q.push(next);
}
}
}
/* ------------------- 幅優先探索 ------------------- */ | 25.458333 | 82 | 0.445717 | [
"vector"
] |
cb8e1fa581b24a0dbb1a58309ecb43e8331ac397 | 812 | inl | C++ | TAO/orbsvcs/orbsvcs/SSLIOP/SSLIOP_Connection_Handler.inl | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 36 | 2015-01-10T07:27:33.000Z | 2022-03-07T03:32:08.000Z | TAO/orbsvcs/orbsvcs/SSLIOP/SSLIOP_Connection_Handler.inl | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 2 | 2018-08-13T07:30:51.000Z | 2019-02-25T03:04:31.000Z | TAO/orbsvcs/orbsvcs/SSLIOP/SSLIOP_Connection_Handler.inl | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 38 | 2015-01-08T14:12:06.000Z | 2022-01-19T08:33:00.000Z | // -*- C++ -*-
//
// $Id: SSLIOP_Connection_Handler.inl 73791 2006-07-27 20:54:56Z wotte $
TAO_BEGIN_VERSIONED_NAMESPACE_DECL
ACE_INLINE
TAO::SSLIOP::State_Guard::State_Guard (
TAO::SSLIOP::Connection_Handler *handler,
int &result)
: handler_ (handler),
previous_current_impl_ (0),
current_impl_ (),
setup_done_ (false)
{
// Set up the SSLIOP::Current object.
result = this->handler_->setup_ssl_state (this->previous_current_impl_,
&(this->current_impl_),
this->setup_done_);
}
ACE_INLINE
TAO::SSLIOP::State_Guard::~State_Guard (void)
{
this->handler_->teardown_ssl_state (this->previous_current_impl_,
this->setup_done_);
}
TAO_END_VERSIONED_NAMESPACE_DECL
| 27.066667 | 73 | 0.624384 | [
"object"
] |
cb926278f9250d3abc3c1e7146826c8922f7afb5 | 7,436 | cpp | C++ | Tests/UnitTests/BVH3Tests.cpp | Snowapril/CubbyFlow | ba7808f62c3dd3cd01a3950f54f7f3c086f89df6 | [
"MIT"
] | null | null | null | Tests/UnitTests/BVH3Tests.cpp | Snowapril/CubbyFlow | ba7808f62c3dd3cd01a3950f54f7f3c086f89df6 | [
"MIT"
] | null | null | null | Tests/UnitTests/BVH3Tests.cpp | Snowapril/CubbyFlow | ba7808f62c3dd3cd01a3950f54f7f3c086f89df6 | [
"MIT"
] | null | null | null | #include "UnitTestsUtils.hpp"
#include "pch.hpp"
#include <Core/Geometry/BVH.hpp>
using namespace CubbyFlow;
TEST(BVH3, Constructors)
{
BVH3<Vector3D> bvh;
EXPECT_EQ(bvh.begin(), bvh.end());
}
TEST(BVH3, BasicGetters)
{
BVH3<Vector3D> bvh;
Array1<Vector3D> points{ Vector3D{ 0, 0, 0 }, Vector3D{ 1, 1, 1 } };
Array1<BoundingBox3D> bounds{ points.Length() };
size_t i = 0;
BoundingBox3D rootBounds;
std::generate(bounds.begin(), bounds.end(), [&]() {
const auto c = points[i++];
BoundingBox3D box{ c, c };
box.Expand(0.1);
rootBounds.Merge(box);
return box;
});
bvh.Build(points, bounds);
EXPECT_EQ(2u, bvh.NumberOfItems());
EXPECT_VECTOR3_EQ(points[0], bvh.Item(0));
EXPECT_VECTOR3_EQ(points[1], bvh.Item(1));
EXPECT_EQ(3u, bvh.NumberOfNodes());
EXPECT_EQ(1u, bvh.Children(0).first);
EXPECT_EQ(2u, bvh.Children(0).second);
EXPECT_FALSE(bvh.IsLeaf(0));
EXPECT_TRUE(bvh.IsLeaf(1));
EXPECT_TRUE(bvh.IsLeaf(2));
EXPECT_BOUNDING_BOX3_EQ(rootBounds, bvh.NodeBound(0));
EXPECT_BOUNDING_BOX3_EQ(bounds[0], bvh.NodeBound(1));
EXPECT_BOUNDING_BOX3_EQ(bounds[1], bvh.NodeBound(2));
EXPECT_EQ(bvh.end(), bvh.ItemOfNode(0));
EXPECT_EQ(bvh.begin(), bvh.ItemOfNode(1));
EXPECT_EQ(bvh.begin() + 1, bvh.ItemOfNode(2));
}
TEST(BVH3, Nearest)
{
BVH3<Vector3D> bvh;
auto distanceFunc = [](const Vector3D& a, const Vector3D& b) {
return a.DistanceTo(b);
};
size_t numSamples = GetNumberOfSamplePoints3();
Array1<Vector3D> points;
size_t i = 0;
const Vector3D* samplePoints = GetSamplePoints3();
for (size_t j = 0; j < numSamples; ++j)
{
points.Append(samplePoints[j]);
}
Array1<BoundingBox3D> bounds(points.Length());
std::generate(bounds.begin(), bounds.end(), [&]() {
auto c = points[i++];
BoundingBox3D box(c, c);
box.Expand(0.1);
return box;
});
bvh.Build(points, bounds);
Vector3D testPt(0.5, 0.5, 0.5);
auto nearest = bvh.Nearest(testPt, distanceFunc);
ptrdiff_t answerIdx = 0;
double bestDist = testPt.DistanceTo(points[answerIdx]);
for (i = 1; i < numSamples; ++i)
{
double dist = testPt.DistanceTo(GetSamplePoints3()[i]);
if (dist < bestDist)
{
bestDist = dist;
answerIdx = i;
}
}
EXPECT_EQ(answerIdx, nearest.item - &bvh.Item(0));
}
TEST(BVH3, BBoxIntersects)
{
BVH3<Vector3D> bvh;
auto overlapsFunc = [](const Vector3D& pt, const BoundingBox3D& bbox) {
BoundingBox3D box(pt, pt);
box.Expand(0.1);
return bbox.Overlaps(box);
};
size_t numSamples = GetNumberOfSamplePoints3();
Array1<Vector3D> points;
size_t i = 0;
const Vector3D* samplePoints = GetSamplePoints3();
for (size_t j = 0; j < numSamples; ++j)
{
points.Append(samplePoints[j]);
}
Array1<BoundingBox3D> bounds(points.Length());
std::generate(bounds.begin(), bounds.end(), [&]() {
auto c = points[i++];
BoundingBox3D box(c, c);
box.Expand(0.1);
return box;
});
bvh.Build(points, bounds);
BoundingBox3D testBox({ 0.25, 0.15, 0.3 }, { 0.5, 0.6, 0.4 });
bool hasOverlaps = false;
for (i = 0; i < numSamples; ++i)
{
hasOverlaps |= overlapsFunc(GetSamplePoints3()[i], testBox);
}
EXPECT_EQ(hasOverlaps, bvh.Intersects(testBox, overlapsFunc));
BoundingBox3D testBox2({ 0.3, 0.2, 0.1 }, { 0.6, 0.5, 0.4 });
hasOverlaps = false;
for (i = 0; i < numSamples; ++i)
{
hasOverlaps |= overlapsFunc(GetSamplePoints3()[i], testBox2);
}
EXPECT_EQ(hasOverlaps, bvh.Intersects(testBox2, overlapsFunc));
}
TEST(BVH3, RayIntersects)
{
BVH3<BoundingBox3D> bvh;
auto intersectsFunc = [](const BoundingBox3D& a, const Ray3D& ray) {
return a.Intersects(ray);
};
size_t numSamples = GetNumberOfSamplePoints3();
Array1<BoundingBox3D> items(numSamples / 2);
size_t i = 0;
std::generate(items.begin(), items.end(), [&]() {
auto c = GetSamplePoints3()[i++];
BoundingBox3D box(c, c);
box.Expand(0.1);
return box;
});
bvh.Build(items, items);
for (i = 0; i < numSamples / 2; ++i)
{
Ray3D ray(GetSampleDirs3()[i + numSamples / 2],
GetSampleDirs3()[i + numSamples / 2]);
// ad-hoc search
bool ansInts = false;
for (size_t j = 0; j < numSamples / 2; ++j)
{
if (intersectsFunc(items[j], ray))
{
ansInts = true;
break;
}
}
// bvh search
bool octInts = bvh.Intersects(ray, intersectsFunc);
EXPECT_EQ(ansInts, octInts);
}
}
TEST(BVH3, ClosestIntersection)
{
BVH3<BoundingBox3D> bvh;
auto intersectsFunc = [](const BoundingBox3D& a, const Ray3D& ray) {
auto bboxResult = a.ClosestIntersection(ray);
if (bboxResult.isIntersecting)
{
return bboxResult.near;
}
else
{
return std::numeric_limits<double>::max();
}
};
size_t numSamples = GetNumberOfSamplePoints3();
Array1<BoundingBox3D> items(numSamples / 2);
size_t i = 0;
std::generate(items.begin(), items.end(), [&]() {
auto c = GetSamplePoints3()[i++];
BoundingBox3D box(c, c);
box.Expand(0.1);
return box;
});
bvh.Build(items, items);
for (i = 0; i < numSamples / 2; ++i)
{
Ray3D ray(GetSamplePoints3()[i + numSamples / 2],
GetSampleDirs3()[i + numSamples / 2]);
// ad-hoc search
ClosestIntersectionQueryResult3<BoundingBox3D> ansInts;
for (size_t j = 0; j < numSamples / 2; ++j)
{
double dist = intersectsFunc(items[j], ray);
if (dist < ansInts.distance)
{
ansInts.distance = dist;
ansInts.item = &bvh.Item(j);
}
}
// bvh search
auto bvhInts = bvh.ClosestIntersection(ray, intersectsFunc);
EXPECT_DOUBLE_EQ(ansInts.distance, bvhInts.distance);
EXPECT_EQ(ansInts.item, bvhInts.item);
}
}
TEST(BVH3, ForEachOverlappingItems)
{
BVH3<Vector3D> bvh;
auto overlapsFunc = [](const Vector3D& pt, const BoundingBox3D& bbox) {
return bbox.Contains(pt);
};
size_t numSamples = GetNumberOfSamplePoints3();
Array1<Vector3D> points;
size_t i = 0;
const Vector3D* samplePoints = GetSamplePoints3();
for (size_t j = 0; j < numSamples; ++j)
{
points.Append(samplePoints[j]);
}
Array1<BoundingBox3D> bounds(points.Length());
std::generate(bounds.begin(), bounds.end(), [&]() {
auto c = points[i++];
BoundingBox3D box(c, c);
box.Expand(0.1);
return box;
});
bvh.Build(points, bounds);
BoundingBox3D testBox({ 0.3, 0.2, 0.1 }, { 0.6, 0.5, 0.4 });
size_t numOverlaps = 0;
for (i = 0; i < numSamples; ++i)
{
numOverlaps += overlapsFunc(GetSamplePoints3()[i], testBox);
}
size_t measured = 0;
bvh.ForEachIntersectingItem(testBox, overlapsFunc, [&](const Vector3D& pt) {
EXPECT_TRUE(overlapsFunc(pt, testBox));
++measured;
});
EXPECT_EQ(numOverlaps, measured);
} | 24.541254 | 80 | 0.579209 | [
"geometry"
] |
ed832adbf2b8108a962d33ee7f50629d1a8ef8b2 | 29,573 | cpp | C++ | src/mongo/db/s/sharding_state.cpp | tychoish/mongo | 0c695aa1e879af482dc3aea4768dbda223ff4592 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/s/sharding_state.cpp | tychoish/mongo | 0c695aa1e879af482dc3aea4768dbda223ff4592 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/s/sharding_state.cpp | tychoish/mongo | 0c695aa1e879af482dc3aea4768dbda223ff4592 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2015 MongoDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects
* for all of the code used other than as permitted herein. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you do not
* wish to do so, delete this exception statement from your version. If you
* delete this exception statement from all source files in the program,
* then also delete it in the license file.
*/
#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kSharding
#include "mongo/platform/basic.h"
#include "mongo/db/s/sharding_state.h"
#include "mongo/client/remote_command_targeter_factory_impl.h"
#include "mongo/db/client.h"
#include "mongo/db/concurrency/lock_state.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/s/collection_metadata.h"
#include "mongo/db/s/metadata_loader.h"
#include "mongo/db/s/sharded_connection_info.h"
#include "mongo/s/catalog/catalog_manager.h"
#include "mongo/s/catalog/type_chunk.h"
#include "mongo/s/client/shard_registry.h"
#include "mongo/s/chunk_version.h"
#include "mongo/s/grid.h"
#include "mongo/s/sharding_initialization.h"
#include "mongo/util/log.h"
#include "mongo/util/mongoutils/str.h"
#include "mongo/util/net/sock.h"
namespace mongo {
using std::shared_ptr;
using std::string;
using std::vector;
namespace {
const auto getShardingState = ServiceContext::declareDecoration<ShardingState>();
enum class VersionChoice { Local, Remote, Unknown };
/**
* Compares a remotely-loaded version (remoteVersion) to the latest local version of a collection
* (localVersion) and returns which one is the newest.
*
* Because it isn't clear during epoch changes which epoch is newer, the local version before the
* reload occurred, 'prevLocalVersion', is used to determine whether the remote epoch is definitely
* newer, or we're not sure.
*/
VersionChoice chooseNewestVersion(ChunkVersion prevLocalVersion,
ChunkVersion localVersion,
ChunkVersion remoteVersion) {
OID prevEpoch = prevLocalVersion.epoch();
OID localEpoch = localVersion.epoch();
OID remoteEpoch = remoteVersion.epoch();
// Everything changed in-flight, so we need to try again
if (prevEpoch != localEpoch && localEpoch != remoteEpoch) {
return VersionChoice::Unknown;
}
// We're in the same (zero) epoch as the latest metadata, nothing to do
if (localEpoch == remoteEpoch && !remoteEpoch.isSet()) {
return VersionChoice::Local;
}
// We're in the same (non-zero) epoch as the latest metadata, so increment the version
if (localEpoch == remoteEpoch && remoteEpoch.isSet()) {
// Use the newer version if possible
if (localVersion < remoteVersion) {
return VersionChoice::Remote;
} else {
return VersionChoice::Local;
}
}
// We're now sure we're installing a new epoch and the epoch didn't change during reload
dassert(prevEpoch == localEpoch && localEpoch != remoteEpoch);
return VersionChoice::Remote;
}
} // namespace
bool isMongos() {
return false;
}
ShardingState::ShardingState()
: _enabled(false),
_configServerTickets(3 /* max number of concurrent config server refresh threads */) {}
ShardingState::~ShardingState() = default;
ShardingState* ShardingState::get(ServiceContext* serviceContext) {
return &getShardingState(serviceContext);
}
ShardingState* ShardingState::get(OperationContext* operationContext) {
return ShardingState::get(operationContext->getServiceContext());
}
bool ShardingState::enabled() {
stdx::lock_guard<stdx::mutex> lk(_mutex);
return _enabled;
}
string ShardingState::getConfigServer(OperationContext* txn) {
stdx::lock_guard<stdx::mutex> lk(_mutex);
invariant(_enabled);
return grid.shardRegistry()->getConfigServerConnectionString().toString();
}
string ShardingState::getShardName() {
stdx::lock_guard<stdx::mutex> lk(_mutex);
invariant(_enabled);
return _shardName;
}
void ShardingState::initialize(const string& server) {
uassert(18509,
"Unable to obtain host name during sharding initialization.",
!getHostName().empty());
stdx::lock_guard<stdx::mutex> lk(_mutex);
if (_enabled) {
// TODO: Do we need to throw exception if the config servers have changed from what we
// already have in place? How do we test for that?
return;
}
ShardedConnectionInfo::addHook();
ConnectionString configServerCS = uassertStatusOK(ConnectionString::parse(server));
uassertStatusOK(initializeGlobalShardingState(configServerCS));
_enabled = true;
}
void ShardingState::setShardName(const string& name) {
const string clientAddr = cc().clientAddress(true);
stdx::lock_guard<stdx::mutex> lk(_mutex);
if (_shardName.empty()) {
// TODO SERVER-2299 remotely verify the name is sound w.r.t IPs
_shardName = name;
log() << "remote client " << clientAddr << " initialized this host as shard " << name;
return;
}
if (_shardName != name) {
const string message = str::stream()
<< "remote client " << clientAddr << " tried to initialize this host as shard " << name
<< ", but shard name was previously initialized as " << _shardName;
warning() << message;
uassertStatusOK({ErrorCodes::AlreadyInitialized, message});
}
}
void ShardingState::clearCollectionMetadata() {
stdx::lock_guard<stdx::mutex> lk(_mutex);
_collMetadata.clear();
}
// TODO we shouldn't need three ways for checking the version. Fix this.
bool ShardingState::hasVersion(const string& ns) {
stdx::lock_guard<stdx::mutex> lk(_mutex);
CollectionMetadataMap::const_iterator it = _collMetadata.find(ns);
return it != _collMetadata.end();
}
ChunkVersion ShardingState::getVersion(const string& ns) {
stdx::lock_guard<stdx::mutex> lk(_mutex);
CollectionMetadataMap::const_iterator it = _collMetadata.find(ns);
if (it != _collMetadata.end()) {
shared_ptr<CollectionMetadata> p = it->second;
return p->getShardVersion();
} else {
return ChunkVersion(0, 0, OID());
}
}
void ShardingState::donateChunk(OperationContext* txn,
const string& ns,
const BSONObj& min,
const BSONObj& max,
ChunkVersion version) {
invariant(txn->lockState()->isCollectionLockedForMode(ns, MODE_X));
stdx::lock_guard<stdx::mutex> lk(_mutex);
CollectionMetadataMap::const_iterator it = _collMetadata.find(ns);
verify(it != _collMetadata.end());
shared_ptr<CollectionMetadata> p = it->second;
// empty shards should have version 0
version = (p->getNumChunks() > 1) ? version : ChunkVersion(0, 0, p->getCollVersion().epoch());
ChunkType chunk;
chunk.setMin(min);
chunk.setMax(max);
string errMsg;
shared_ptr<CollectionMetadata> cloned(p->cloneMigrate(chunk, version, &errMsg));
// uassert to match old behavior, TODO: report errors w/o throwing
uassert(16855, errMsg, NULL != cloned.get());
// TODO: a bit dangerous to have two different zero-version states - no-metadata and
// no-version
_collMetadata[ns] = cloned;
}
void ShardingState::undoDonateChunk(OperationContext* txn,
const string& ns,
shared_ptr<CollectionMetadata> prevMetadata) {
invariant(txn->lockState()->isCollectionLockedForMode(ns, MODE_X));
stdx::lock_guard<stdx::mutex> lk(_mutex);
log() << "ShardingState::undoDonateChunk acquired _mutex";
CollectionMetadataMap::iterator it = _collMetadata.find(ns);
verify(it != _collMetadata.end());
it->second = prevMetadata;
}
bool ShardingState::notePending(OperationContext* txn,
const string& ns,
const BSONObj& min,
const BSONObj& max,
const OID& epoch,
string* errMsg) {
invariant(txn->lockState()->isCollectionLockedForMode(ns, MODE_X));
stdx::lock_guard<stdx::mutex> lk(_mutex);
CollectionMetadataMap::const_iterator it = _collMetadata.find(ns);
if (it == _collMetadata.end()) {
*errMsg = str::stream() << "could not note chunk "
<< "[" << min << "," << max << ")"
<< " as pending because the local metadata for " << ns
<< " has changed";
return false;
}
shared_ptr<CollectionMetadata> metadata = it->second;
// This can currently happen because drops aren't synchronized with in-migrations
// The idea for checking this here is that in the future we shouldn't have this problem
if (metadata->getCollVersion().epoch() != epoch) {
*errMsg = str::stream() << "could not note chunk "
<< "[" << min << "," << max << ")"
<< " as pending because the epoch for " << ns
<< " has changed from " << epoch << " to "
<< metadata->getCollVersion().epoch();
return false;
}
ChunkType chunk;
chunk.setMin(min);
chunk.setMax(max);
shared_ptr<CollectionMetadata> cloned(metadata->clonePlusPending(chunk, errMsg));
if (!cloned)
return false;
_collMetadata[ns] = cloned;
return true;
}
bool ShardingState::forgetPending(OperationContext* txn,
const string& ns,
const BSONObj& min,
const BSONObj& max,
const OID& epoch,
string* errMsg) {
invariant(txn->lockState()->isCollectionLockedForMode(ns, MODE_X));
stdx::lock_guard<stdx::mutex> lk(_mutex);
CollectionMetadataMap::const_iterator it = _collMetadata.find(ns);
if (it == _collMetadata.end()) {
*errMsg = str::stream() << "no need to forget pending chunk "
<< "[" << min << "," << max << ")"
<< " because the local metadata for " << ns << " has changed";
return false;
}
shared_ptr<CollectionMetadata> metadata = it->second;
// This can currently happen because drops aren't synchronized with in-migrations
// The idea for checking this here is that in the future we shouldn't have this problem
if (metadata->getCollVersion().epoch() != epoch) {
*errMsg = str::stream() << "no need to forget pending chunk "
<< "[" << min << "," << max << ")"
<< " because the epoch for " << ns << " has changed from " << epoch
<< " to " << metadata->getCollVersion().epoch();
return false;
}
ChunkType chunk;
chunk.setMin(min);
chunk.setMax(max);
shared_ptr<CollectionMetadata> cloned(metadata->cloneMinusPending(chunk, errMsg));
if (!cloned)
return false;
_collMetadata[ns] = cloned;
return true;
}
void ShardingState::splitChunk(OperationContext* txn,
const string& ns,
const BSONObj& min,
const BSONObj& max,
const vector<BSONObj>& splitKeys,
ChunkVersion version) {
invariant(txn->lockState()->isCollectionLockedForMode(ns, MODE_X));
stdx::lock_guard<stdx::mutex> lk(_mutex);
CollectionMetadataMap::const_iterator it = _collMetadata.find(ns);
verify(it != _collMetadata.end());
ChunkType chunk;
chunk.setMin(min);
chunk.setMax(max);
string errMsg;
shared_ptr<CollectionMetadata> cloned(
it->second->cloneSplit(chunk, splitKeys, version, &errMsg));
// uassert to match old behavior, TODO: report errors w/o throwing
uassert(16857, errMsg, NULL != cloned.get());
_collMetadata[ns] = cloned;
}
void ShardingState::mergeChunks(OperationContext* txn,
const string& ns,
const BSONObj& minKey,
const BSONObj& maxKey,
ChunkVersion mergedVersion) {
invariant(txn->lockState()->isCollectionLockedForMode(ns, MODE_X));
stdx::lock_guard<stdx::mutex> lk(_mutex);
CollectionMetadataMap::const_iterator it = _collMetadata.find(ns);
verify(it != _collMetadata.end());
string errMsg;
shared_ptr<CollectionMetadata> cloned(
it->second->cloneMerge(minKey, maxKey, mergedVersion, &errMsg));
// uassert to match old behavior, TODO: report errors w/o throwing
uassert(17004, errMsg, NULL != cloned.get());
_collMetadata[ns] = cloned;
}
bool ShardingState::inCriticalMigrateSection() {
return _migrationSourceManager.getInCriticalSection();
}
bool ShardingState::waitTillNotInCriticalSection(int maxSecondsToWait) {
return _migrationSourceManager.waitTillNotInCriticalSection(maxSecondsToWait);
}
void ShardingState::resetMetadata(const string& ns) {
stdx::lock_guard<stdx::mutex> lk(_mutex);
warning() << "resetting metadata for " << ns << ", this should only be used in testing";
_collMetadata.erase(ns);
}
Status ShardingState::refreshMetadataIfNeeded(OperationContext* txn,
const string& ns,
const ChunkVersion& reqShardVersion,
ChunkVersion* latestShardVersion) {
// The _configServerTickets serializes this process such that only a small number of threads
// can try to refresh at the same time.
LOG(2) << "metadata refresh requested for " << ns << " at shard version " << reqShardVersion;
//
// Queuing of refresh requests starts here when remote reload is needed. This may take time.
// TODO: Explicitly expose the queuing discipline.
//
_configServerTickets.waitForTicket();
TicketHolderReleaser needTicketFrom(&_configServerTickets);
//
// Fast path - check if the requested version is at a higher version than the current
// metadata version or a different epoch before verifying against config server.
//
shared_ptr<CollectionMetadata> storedMetadata;
{
stdx::lock_guard<stdx::mutex> lk(_mutex);
CollectionMetadataMap::iterator it = _collMetadata.find(ns);
if (it != _collMetadata.end())
storedMetadata = it->second;
}
ChunkVersion storedShardVersion;
if (storedMetadata)
storedShardVersion = storedMetadata->getShardVersion();
*latestShardVersion = storedShardVersion;
if (storedShardVersion >= reqShardVersion &&
storedShardVersion.epoch() == reqShardVersion.epoch()) {
// Don't need to remotely reload if we're in the same epoch with a >= version
return Status::OK();
}
//
// Slow path - remotely reload
//
// Cases:
// A) Initial config load and/or secondary take-over.
// B) Migration TO this shard finished, notified by mongos.
// C) Dropping a collection, notified (currently) by mongos.
// D) Stale client wants to reload metadata with a different *epoch*, so we aren't sure.
if (storedShardVersion.epoch() != reqShardVersion.epoch()) {
// Need to remotely reload if our epochs aren't the same, to verify
LOG(1) << "metadata change requested for " << ns << ", from shard version "
<< storedShardVersion << " to " << reqShardVersion
<< ", need to verify with config server";
} else {
// Need to remotely reload since our epochs aren't the same but our version is greater
LOG(1) << "metadata version update requested for " << ns << ", from shard version "
<< storedShardVersion << " to " << reqShardVersion
<< ", need to verify with config server";
}
return doRefreshMetadata(txn, ns, reqShardVersion, true, latestShardVersion);
}
Status ShardingState::refreshMetadataNow(OperationContext* txn,
const string& ns,
ChunkVersion* latestShardVersion) {
return doRefreshMetadata(txn, ns, ChunkVersion(0, 0, OID()), false, latestShardVersion);
}
Status ShardingState::doRefreshMetadata(OperationContext* txn,
const string& ns,
const ChunkVersion& reqShardVersion,
bool useRequestedVersion,
ChunkVersion* latestShardVersion) {
// The idea here is that we're going to reload the metadata from the config server, but
// we need to do so outside any locks. When we get our result back, if the current metadata
// has changed, we may not be able to install the new metadata.
//
// Get the initial metadata
// No DBLock is needed since the metadata is expected to change during reload.
//
shared_ptr<CollectionMetadata> beforeMetadata;
{
stdx::lock_guard<stdx::mutex> lk(_mutex);
// We can't reload if sharding is not enabled - i.e. without a config server location
if (!_enabled) {
string errMsg = str::stream() << "cannot refresh metadata for " << ns
<< " before sharding has been enabled";
warning() << errMsg;
return Status(ErrorCodes::NotYetInitialized, errMsg);
}
// We also can't reload if a shard name has not yet been set.
if (_shardName.empty()) {
string errMsg = str::stream() << "cannot refresh metadata for " << ns
<< " before shard name has been set";
warning() << errMsg;
return Status(ErrorCodes::NotYetInitialized, errMsg);
}
CollectionMetadataMap::iterator it = _collMetadata.find(ns);
if (it != _collMetadata.end()) {
beforeMetadata = it->second;
}
}
ChunkVersion beforeShardVersion;
ChunkVersion beforeCollVersion;
if (beforeMetadata) {
beforeShardVersion = beforeMetadata->getShardVersion();
beforeCollVersion = beforeMetadata->getCollVersion();
}
*latestShardVersion = beforeShardVersion;
//
// Determine whether we need to diff or fully reload
//
bool fullReload = false;
if (!beforeMetadata) {
// We don't have any metadata to reload from
fullReload = true;
} else if (useRequestedVersion && reqShardVersion.epoch() != beforeShardVersion.epoch()) {
// It's not useful to use the metadata as a base because we think the epoch will differ
fullReload = true;
}
//
// Load the metadata from the remote server, start construction
//
LOG(0) << "remotely refreshing metadata for " << ns
<< (useRequestedVersion
? string(" with requested shard version ") + reqShardVersion.toString()
: "")
<< (fullReload ? ", current shard version is " : " based on current shard version ")
<< beforeShardVersion << ", current metadata version is " << beforeCollVersion;
string errMsg;
MetadataLoader mdLoader;
shared_ptr<CollectionMetadata> remoteMetadata(std::make_shared<CollectionMetadata>());
Timer refreshTimer;
long long refreshMillis;
{
Status status = mdLoader.makeCollectionMetadata(grid.catalogManager(txn),
ns,
getShardName(),
fullReload ? NULL : beforeMetadata.get(),
remoteMetadata.get());
refreshMillis = refreshTimer.millis();
if (status.code() == ErrorCodes::NamespaceNotFound) {
remoteMetadata.reset();
} else if (!status.isOK()) {
warning() << "could not remotely refresh metadata for " << ns
<< causedBy(status.reason());
return status;
}
}
ChunkVersion remoteShardVersion;
ChunkVersion remoteCollVersion;
if (remoteMetadata) {
remoteShardVersion = remoteMetadata->getShardVersion();
remoteCollVersion = remoteMetadata->getCollVersion();
}
//
// Get ready to install loaded metadata if needed
//
shared_ptr<CollectionMetadata> afterMetadata;
ChunkVersion afterShardVersion;
ChunkVersion afterCollVersion;
VersionChoice choice;
// If we choose to install the new metadata, this describes the kind of install
enum InstallType {
InstallType_New,
InstallType_Update,
InstallType_Replace,
InstallType_Drop,
InstallType_None
} installType = InstallType_None; // compiler complains otherwise
{
// Exclusive collection lock needed since we're now potentially changing the metadata,
// and don't want reads/writes to be ongoing.
ScopedTransaction transaction(txn, MODE_IX);
Lock::DBLock dbLock(txn->lockState(), nsToDatabaseSubstring(ns), MODE_IX);
Lock::CollectionLock collLock(txn->lockState(), ns, MODE_X);
//
// Get the metadata now that the load has completed
//
stdx::lock_guard<stdx::mutex> lk(_mutex);
// Don't reload if our config server has changed or sharding is no longer enabled
if (!_enabled) {
string errMsg = str::stream() << "could not refresh metadata for " << ns
<< ", sharding is no longer enabled";
warning() << errMsg;
return Status(ErrorCodes::NotYetInitialized, errMsg);
}
CollectionMetadataMap::iterator it = _collMetadata.find(ns);
if (it != _collMetadata.end())
afterMetadata = it->second;
if (afterMetadata) {
afterShardVersion = afterMetadata->getShardVersion();
afterCollVersion = afterMetadata->getCollVersion();
}
*latestShardVersion = afterShardVersion;
//
// Resolve newer pending chunks with the remote metadata, finish construction
//
Status status = mdLoader.promotePendingChunks(afterMetadata.get(), remoteMetadata.get());
if (!status.isOK()) {
warning() << "remote metadata for " << ns
<< " is inconsistent with current pending chunks"
<< causedBy(status.reason());
return status;
}
//
// Compare the 'before', 'after', and 'remote' versions/epochs and choose newest
// Zero-epochs (sentinel value for "dropped" collections), are tested by
// !epoch.isSet().
//
choice = chooseNewestVersion(beforeCollVersion, afterCollVersion, remoteCollVersion);
if (choice == VersionChoice::Remote) {
dassert(!remoteCollVersion.epoch().isSet() || remoteShardVersion >= beforeShardVersion);
if (!afterCollVersion.epoch().isSet()) {
// First metadata load
installType = InstallType_New;
dassert(it == _collMetadata.end());
_collMetadata.insert(make_pair(ns, remoteMetadata));
} else if (remoteCollVersion.epoch().isSet() &&
remoteCollVersion.epoch() == afterCollVersion.epoch()) {
// Update to existing metadata
installType = InstallType_Update;
// Invariant: If CollMetadata was not found, version should be have been 0.
dassert(it != _collMetadata.end());
it->second = remoteMetadata;
} else if (remoteCollVersion.epoch().isSet()) {
// New epoch detected, replacing metadata
installType = InstallType_Replace;
// Invariant: If CollMetadata was not found, version should be have been 0.
dassert(it != _collMetadata.end());
it->second = remoteMetadata;
} else {
dassert(!remoteCollVersion.epoch().isSet());
// Drop detected
installType = InstallType_Drop;
_collMetadata.erase(it);
}
*latestShardVersion = remoteShardVersion;
}
}
// End _mutex
// End DBWrite
//
// Do messaging based on what happened above
//
string localShardVersionMsg = beforeShardVersion.epoch() == afterShardVersion.epoch()
? afterShardVersion.toString()
: beforeShardVersion.toString() + " / " + afterShardVersion.toString();
if (choice == VersionChoice::Unknown) {
string errMsg = str::stream()
<< "need to retry loading metadata for " << ns
<< ", collection may have been dropped or recreated during load"
<< " (loaded shard version : " << remoteShardVersion.toString()
<< ", stored shard versions : " << localShardVersionMsg << ", took " << refreshMillis
<< "ms)";
warning() << errMsg;
return Status(ErrorCodes::RemoteChangeDetected, errMsg);
}
if (choice == VersionChoice::Local) {
LOG(0) << "metadata of collection " << ns
<< " already up to date (shard version : " << afterShardVersion.toString()
<< ", took " << refreshMillis << "ms)";
return Status::OK();
}
dassert(choice == VersionChoice::Remote);
switch (installType) {
case InstallType_New:
LOG(0) << "collection " << ns << " was previously unsharded"
<< ", new metadata loaded with shard version " << remoteShardVersion;
break;
case InstallType_Update:
LOG(0) << "updating metadata for " << ns << " from shard version "
<< localShardVersionMsg << " to shard version " << remoteShardVersion;
break;
case InstallType_Replace:
LOG(0) << "replacing metadata for " << ns << " at shard version "
<< localShardVersionMsg << " with a new epoch (shard version "
<< remoteShardVersion << ")";
break;
case InstallType_Drop:
LOG(0) << "dropping metadata for " << ns << " at shard version " << localShardVersionMsg
<< ", took " << refreshMillis << "ms";
break;
default:
verify(false);
break;
}
if (installType != InstallType_Drop) {
LOG(0) << "collection version was loaded at version " << remoteCollVersion << ", took "
<< refreshMillis << "ms";
}
return Status::OK();
}
void ShardingState::appendInfo(OperationContext* txn, BSONObjBuilder& builder) {
stdx::lock_guard<stdx::mutex> lk(_mutex);
builder.appendBool("enabled", _enabled);
if (!_enabled) {
return;
}
builder.append("configServer",
grid.shardRegistry()->getConfigServerConnectionString().toString());
builder.append("shardName", _shardName);
BSONObjBuilder versionB(builder.subobjStart("versions"));
for (CollectionMetadataMap::const_iterator it = _collMetadata.begin();
it != _collMetadata.end();
++it) {
shared_ptr<CollectionMetadata> metadata = it->second;
versionB.appendTimestamp(it->first, metadata->getShardVersion().toLong());
}
versionB.done();
}
bool ShardingState::needCollectionMetadata(Client* client, const string& ns) const {
if (!_enabled)
return false;
if (!ShardedConnectionInfo::get(client, false))
return false;
return true;
}
shared_ptr<CollectionMetadata> ShardingState::getCollectionMetadata(const string& ns) {
stdx::lock_guard<stdx::mutex> lk(_mutex);
CollectionMetadataMap::const_iterator it = _collMetadata.find(ns);
if (it == _collMetadata.end()) {
return shared_ptr<CollectionMetadata>();
} else {
return it->second;
}
}
} // namespace mongo
| 37.058897 | 100 | 0.613161 | [
"vector"
] |
ed83c30a8e03616127a0dff7cd9a03614b5373d8 | 8,989 | cc | C++ | RecoEgamma/EgammaElectronAlgos/src/PixelHitMatcher.cc | IzaakWN/cmssw | 07492d201be64e1c8ed8877c627d72f1d99c1f48 | [
"Apache-2.0"
] | 1 | 2021-04-13T13:26:16.000Z | 2021-04-13T13:26:16.000Z | RecoEgamma/EgammaElectronAlgos/src/PixelHitMatcher.cc | IzaakWN/cmssw | 07492d201be64e1c8ed8877c627d72f1d99c1f48 | [
"Apache-2.0"
] | null | null | null | RecoEgamma/EgammaElectronAlgos/src/PixelHitMatcher.cc | IzaakWN/cmssw | 07492d201be64e1c8ed8877c627d72f1d99c1f48 | [
"Apache-2.0"
] | null | null | null | #include "RecoEgamma/EgammaElectronAlgos/interface/PixelHitMatcher.h"
#include "RecoEgamma/EgammaElectronAlgos/interface/ElectronUtilities.h"
#include "TrackingTools/PatternTools/interface/TrajectoryMeasurement.h"
#include "TrackingTools/DetLayers/interface/DetLayer.h"
#include "TrackingTools/MeasurementDet/interface/LayerMeasurements.h"
#include "RecoTracker/MeasurementDet/interface/MeasurementTracker.h"
#include "RecoTracker/MeasurementDet/interface/MeasurementTrackerEvent.h"
#include "DataFormats/DetId/interface/DetId.h"
#include "DataFormats/GeometryCommonDetAlgo/interface/PerpendicularBoundPlaneBuilder.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include <typeinfo>
#include <bitset>
using namespace reco;
using namespace std;
PixelHitMatcher::PixelHitMatcher(float phi1min,
float phi1max,
float phi2minB,
float phi2maxB,
float phi2minF,
float phi2maxF,
float z2minB,
float z2maxB,
float r2minF,
float r2maxF,
float rMinI,
float rMaxI,
bool useRecoVertex)
: //zmin1 and zmax1 are dummy at this moment, set from beamspot later
meas1stBLayer(phi1min, phi1max, 0., 0.),
meas2ndBLayer(phi2minB, phi2maxB, z2minB, z2maxB),
meas1stFLayer(phi1min, phi1max, 0., 0.),
meas2ndFLayer(phi2minF, phi2maxF, r2minF, r2maxF),
prop1stLayer(nullptr),
prop2ndLayer(nullptr),
useRecoVertex_(useRecoVertex) {
meas1stFLayer.setRRangeI(rMinI, rMaxI);
meas2ndFLayer.setRRangeI(rMinI, rMaxI);
}
void PixelHitMatcher::set1stLayer(float dummyphi1min, float dummyphi1max) {
meas1stBLayer.setPhiRange(dummyphi1min, dummyphi1max);
meas1stFLayer.setPhiRange(dummyphi1min, dummyphi1max);
}
void PixelHitMatcher::set1stLayerZRange(float zmin1, float zmax1) {
meas1stBLayer.setZRange(zmin1, zmax1);
meas1stFLayer.setRRange(zmin1, zmax1);
}
void PixelHitMatcher::set2ndLayer(float dummyphi2minB, float dummyphi2maxB, float dummyphi2minF, float dummyphi2maxF) {
meas2ndBLayer.setPhiRange(dummyphi2minB, dummyphi2maxB);
meas2ndFLayer.setPhiRange(dummyphi2minF, dummyphi2maxF);
}
void PixelHitMatcher::setES(const MagneticField *magField, const TrackerGeometry *trackerGeometry) {
theMagField = magField;
theTrackerGeometry = trackerGeometry;
float mass = .000511; // electron propagation
prop1stLayer = std::make_unique<PropagatorWithMaterial>(oppositeToMomentum, mass, theMagField);
prop2ndLayer = std::make_unique<PropagatorWithMaterial>(alongMomentum, mass, theMagField);
}
std::vector<SeedWithInfo> PixelHitMatcher::operator()(const std::vector<const TrajectorySeedCollection *> &seedsV,
const GlobalPoint &xmeas,
const GlobalPoint &vprim,
float energy,
int charge) const {
auto xmeas_r = xmeas.perp();
const float phicut = std::cos(2.5);
FreeTrajectoryState fts = FTSFromVertexToPointFactory::get(*theMagField, xmeas, vprim, energy, charge);
PerpendicularBoundPlaneBuilder bpb;
TrajectoryStateOnSurface tsos(fts, *bpb(fts.position(), fts.momentum()));
std::vector<SeedWithInfo> result;
unsigned int allSeedsSize = 0;
for (auto const sc : seedsV)
allSeedsSize += sc->size();
std::unordered_map<std::pair<const GeomDet *, GlobalPoint>, TrajectoryStateOnSurface> mapTsos2Fast;
mapTsos2Fast.reserve(allSeedsSize);
auto ndets = theTrackerGeometry->dets().size();
int iTsos[ndets];
for (auto &i : iTsos)
i = -1;
std::vector<TrajectoryStateOnSurface> vTsos;
vTsos.reserve(allSeedsSize);
for (const auto seeds : seedsV) {
for (const auto &seed : *seeds) {
std::vector<GlobalPoint> hitGpMap;
if (seed.nHits() > 9) {
edm::LogWarning("GsfElectronAlgo|UnexpectedSeed") << "We cannot deal with seeds having more than 9 hits.";
continue;
}
const TrajectorySeed::range &hits = seed.recHits();
// cache the global points
for (auto it = hits.first; it != hits.second; ++it) {
hitGpMap.emplace_back(it->globalPosition());
}
//iterate on the hits
auto he = hits.second - 1;
for (auto it1 = hits.first; it1 < he; ++it1) {
if (!it1->isValid())
continue;
auto idx1 = std::distance(hits.first, it1);
const DetId id1 = it1->geographicalId();
const GeomDet *geomdet1 = it1->det();
auto ix1 = geomdet1->gdetIndex();
/* VI: this generates regression (other cut is just in phi). in my opinion it is safe and makes sense
auto away = geomdet1->position().basicVector().dot(xmeas.basicVector()) <0;
if (away) continue;
*/
const GlobalPoint &hit1Pos = hitGpMap[idx1];
auto dt = hit1Pos.x() * xmeas.x() + hit1Pos.y() * xmeas.y();
if (dt < 0)
continue;
if (dt < phicut * (xmeas_r * hit1Pos.perp()))
continue;
if (iTsos[ix1] < 0) {
iTsos[ix1] = vTsos.size();
vTsos.push_back(prop1stLayer->propagate(tsos, geomdet1->surface()));
}
auto tsos1 = &vTsos[iTsos[ix1]];
if (!tsos1->isValid())
continue;
std::pair<bool, double> est = (id1.subdetId() % 2 ? meas1stBLayer.estimate(vprim, *tsos1, hit1Pos)
: meas1stFLayer.estimate(vprim, *tsos1, hit1Pos));
if (!est.first)
continue;
EleRelPointPair pp1(hit1Pos, tsos1->globalParameters().position(), vprim);
const math::XYZPoint relHit1Pos(hit1Pos - vprim), relTSOSPos(tsos1->globalParameters().position() - vprim);
const int subDet1 = id1.subdetId();
const float dRz1 = (id1.subdetId() % 2 ? pp1.dZ() : pp1.dPerp());
const float dPhi1 = pp1.dPhi();
// setup our vertex
double zVertex;
if (!useRecoVertex_) {
// we don't know the z vertex position, get it from linear extrapolation
// compute the z vertex from the cluster point and the found pixel hit
const double pxHit1z = hit1Pos.z();
const double pxHit1x = hit1Pos.x();
const double pxHit1y = hit1Pos.y();
const double r1diff =
std::sqrt((pxHit1x - vprim.x()) * (pxHit1x - vprim.x()) + (pxHit1y - vprim.y()) * (pxHit1y - vprim.y()));
const double r2diff =
std::sqrt((xmeas.x() - pxHit1x) * (xmeas.x() - pxHit1x) + (xmeas.y() - pxHit1y) * (xmeas.y() - pxHit1y));
zVertex = pxHit1z - r1diff * (xmeas.z() - pxHit1z) / r2diff;
} else {
// here use rather the reco vertex z position
zVertex = vprim.z();
}
GlobalPoint vertex(vprim.x(), vprim.y(), zVertex);
FreeTrajectoryState fts2 = FTSFromVertexToPointFactory::get(*theMagField, hit1Pos, vertex, energy, charge);
// now find the matching hit
for (auto it2 = it1 + 1; it2 != hits.second; ++it2) {
if (!it2->isValid())
continue;
auto idx2 = std::distance(hits.first, it2);
const DetId id2 = it2->geographicalId();
const GeomDet *geomdet2 = it2->det();
const std::pair<const GeomDet *, GlobalPoint> det_key(geomdet2, hit1Pos);
const TrajectoryStateOnSurface *tsos2;
auto tsos2_itr = mapTsos2Fast.find(det_key);
if (tsos2_itr != mapTsos2Fast.end()) {
tsos2 = &(tsos2_itr->second);
} else {
auto empl_result = mapTsos2Fast.emplace(det_key, prop2ndLayer->propagate(fts2, geomdet2->surface()));
tsos2 = &(empl_result.first->second);
}
if (!tsos2->isValid())
continue;
const GlobalPoint &hit2Pos = hitGpMap[idx2];
std::pair<bool, double> est2 = (id2.subdetId() % 2 ? meas2ndBLayer.estimate(vertex, *tsos2, hit2Pos)
: meas2ndFLayer.estimate(vertex, *tsos2, hit2Pos));
if (est2.first) {
EleRelPointPair pp2(hit2Pos, tsos2->globalParameters().position(), vertex);
const int subDet2 = id2.subdetId();
const float dRz2 = (subDet2 % 2 == 1) ? pp2.dZ() : pp2.dPerp();
const float dPhi2 = pp2.dPhi();
const unsigned char hitsMask = (1 << idx1) | (1 << idx2);
result.push_back({seed, hitsMask, subDet2, dRz2, dPhi2, subDet1, dRz1, dPhi1});
}
} // inner loop on hits
} // outer loop on hits
} // loop on seeds
} //loop on vector of seeds
return result;
}
| 43.84878 | 119 | 0.605518 | [
"vector"
] |
ed8f452872f3056b80f7e6216d4e916f9c8fc1f1 | 1,007 | cpp | C++ | Source/PrefabricatorRuntime/Private/PrefabricatorRuntimeModule.cpp | meso-unimpressed/prefabricator-ue4 | afbe11d85e3cd3fa212fd1b4507e27e0fc64e956 | [
"MIT"
] | 280 | 2019-01-02T17:14:41.000Z | 2022-03-28T07:40:18.000Z | Source/PrefabricatorRuntime/Private/PrefabricatorRuntimeModule.cpp | meso-unimpressed/prefabricator-ue4 | afbe11d85e3cd3fa212fd1b4507e27e0fc64e956 | [
"MIT"
] | 39 | 2019-01-07T04:33:10.000Z | 2022-01-22T00:16:48.000Z | Source/PrefabricatorRuntime/Private/PrefabricatorRuntimeModule.cpp | meso-unimpressed/prefabricator-ue4 | afbe11d85e3cd3fa212fd1b4507e27e0fc64e956 | [
"MIT"
] | 66 | 2019-01-02T20:09:39.000Z | 2022-03-28T07:47:51.000Z | //$ Copyright 2015-21, Code Respawn Technologies Pvt Ltd - All Rights Reserved $//
#include "PrefabricatorRuntimeModule.h"
#include "Prefab/PrefabTools.h"
#include "Utils/PrefabricatorService.h"
class FPrefabricatorRuntime : public IPrefabricatorRuntime
{
/** IModuleInterface implementation */
virtual void StartupModule() override;
virtual void ShutdownModule() override;
};
IMPLEMENT_MODULE(FPrefabricatorRuntime, PrefabricatorRuntime)
void FPrefabricatorRuntime::StartupModule()
{
// Set the runtime prefabricator service
// Set this only if it is null (the editor might have set the editor service, and if so, we won't override it)
if (!FPrefabricatorService::Get().IsValid()) {
FPrefabricatorService::Set(MakeShareable(new FPrefabricatorRuntimeService));
}
FGlobalPrefabInstanceTemplates::_CreateSingleton();
}
void FPrefabricatorRuntime::ShutdownModule()
{
// Clear the service object
FPrefabricatorService::Set(nullptr);
FGlobalPrefabInstanceTemplates::_ReleaseSingleton();
}
| 27.216216 | 111 | 0.789474 | [
"object"
] |
ed8fea8f9563f4eb9cabb2f26d3e8fe1f5c54ddc | 2,381 | cpp | C++ | main.cpp | ruslancheboxary/julia | 67ce6f92a0b656c414571a92c8dad298e0e7b127 | [
"Apache-2.0"
] | null | null | null | main.cpp | ruslancheboxary/julia | 67ce6f92a0b656c414571a92c8dad298e0e7b127 | [
"Apache-2.0"
] | null | null | null | main.cpp | ruslancheboxary/julia | 67ce6f92a0b656c414571a92c8dad298e0e7b127 | [
"Apache-2.0"
] | null | null | null | #include "mainwindow.h"
#include <QApplication>
#include <iostream>
#include <cstdlib>
#include <math.h>
#include <vector>
#include <stdarg.h>
#include <iostream>
#include <thread>
#include "ssr.h"
#ifdef LANG_RU
/**
* Глобальные переменные массивов в куче
*/
#endif
#ifdef LANG_EN
/**
* Global variables arrays in heap
*/
#endif
#define NUMBER_FRAMES 3
#define SIZE_FRAME 3
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
//w.show();
//Инициализация
int noise=0;
int framesAP[10]={3,3,0};
int frames[3][3]= {
{1, 0, 0} ,
{0, 1, 0} ,
{0, 0, 1}
};
bool changesMask[3][3];
//Выполнение
//Init system of search regularities
SSR * ssr=new SSR;
//Поиск изменений от подмассива к подмасссиву
ssr->compareInsideArray((int *)&frames[0],(bool *) &changesMask[0],noise,0,framesAP,SSR::isParallelOpenMP
,false /*isDebugInfo*/,true /*isMeasureTime*/,true /*bool isMeasureAvgTime*/);
ssr->compareInsideArrayOpenMP((int *)&frames[0],(bool *) &changesMask[0],noise,0,framesAP,SSR::isParallelOpenMP
,false /*isDebugInfo*/,true /*isMeasureTime*/,true /*bool isMeasureAvgTime*/);
typedef std::vector<int> container;
typedef container::iterator iter;
container v(100, 1);
auto worker = [] (iter begin, iter end) {
for(auto it = begin; it != end; ++it) {
*it *= 2;
}
};
// serial
worker(std::begin(v), std::end(v));
std::cout << std::accumulate(std::begin(v), std::end(v), 0) << std::endl; // 200
// parallel
std::vector<std::thread> threads(8);
const int grainsize = v.size() / 8;
auto work_iter = std::begin(v);
for(auto it = std::begin(threads); it != std::end(threads) - 1; ++it) {
*it = std::thread(worker, work_iter, work_iter + grainsize);
work_iter += grainsize;
}
threads.back() = std::thread(worker, work_iter, std::end(v));
for(auto&& i : threads) {
i.join();
}
std::cout << std::accumulate(std::begin(v), std::end(v), 0) << std::endl; // 400
//Поиск закономерностей
//ssr.searchRepeatCharsAndFragmentsInArray<int>(&frames[0][0],&changesMask[0][0],noise,framesAP,SSR::isParallelOpenMP
// ,true /*isDebugInfo*/,true /*isMeasureTime*/,true /*bool isMeasureAvgTime*/);
//return a.exec();
return 0;
}
| 24.802083 | 121 | 0.611088 | [
"vector"
] |
ed9082cf59a543f498f4876e6bdea19df02f28f3 | 16,054 | cpp | C++ | BuildModel/src/regmeshpcd.cpp | gopi231091/Object-Pose-Estimation | 11726fd008447fed3947c893d959b5acb9fd339e | [
"BSD-2-Clause"
] | 4 | 2019-02-19T18:55:35.000Z | 2021-10-10T22:20:18.000Z | BuildModel/src/regmeshpcd.cpp | gopi231091/Object-Pose-Estimation | 11726fd008447fed3947c893d959b5acb9fd339e | [
"BSD-2-Clause"
] | null | null | null | BuildModel/src/regmeshpcd.cpp | gopi231091/Object-Pose-Estimation | 11726fd008447fed3947c893d959b5acb9fd339e | [
"BSD-2-Clause"
] | 4 | 2019-09-06T01:52:41.000Z | 2020-04-03T09:40:11.000Z | #include "../include/regmeshpcd.h"
RegMeshPcd::RegMeshPcd()
{
}
//function to get ICP aligned pointcloud using single ICP
pcl::PointCloud<PointTReg>::Ptr RegMeshPcd::getIcp ( pcl::PointCloud<PointTReg>::Ptr p_cloudSource,
pcl::PointCloud<PointTReg>::Ptr p_cloudTarget,
float p_maxCorrDist, float p_ransacStatOutThresh, int p_maxIterations ){
//cloud to store the result
pcl::PointCloud<PointTReg>::Ptr cloudAligned (new pcl::PointCloud<PointTReg> );
//create icp object
pcl::IterativeClosestPoint<PointTReg, PointTReg> icp;
// Set the input source and target
icp.setInputSource ( p_cloudSource );
icp.setInputTarget ( p_cloudTarget );
// Set the max correspondence distance , correspondences with higher distances will be ignored
icp.setMaxCorrespondenceDistance ( p_maxCorrDist );
// set the ransac outlier rejection threshold
icp.setRANSACOutlierRejectionThreshold( p_ransacStatOutThresh );
// Set the maximum number of iterations (criterion 1)
icp.setMaximumIterations ( p_maxIterations );
// Set the transformation epsilon (criterion 2)
icp.setTransformationEpsilon (1e-16);
// Set the euclidean distance difference epsilon (criterion 3)
//icp.setEuclideanFitnessEpsilon (1);
// Perform the alignment
icp.align ( *cloudAligned );
std::cout << "ICP converged with score: " << icp.getFitnessScore() << std::endl;
return cloudAligned;
}
pcl::PointCloud<PointTReg>::Ptr RegMeshPcd::getIcp2 ( pcl::PointCloud<PointTReg>::Ptr p_cloudSource,
pcl::PointCloud<PointTReg>::Ptr p_cloudTarget,
float p_maxCorrDist1, float p_ransacStatOutThresh1, int p_maxIterations1,
float p_maxCorrDist2, float p_ransacStatOutThresh2, int p_maxIterations2){
//cloud to store outputs
pcl::PointCloud<PointTReg>::Ptr cloudAlign1 ( new pcl::PointCloud<PointTReg> );
pcl::PointCloud<PointTReg>::Ptr cloudAlign2 ( new pcl::PointCloud<PointTReg> );
cloudAlign1 = getIcp( p_cloudSource, p_cloudTarget, p_maxCorrDist1, p_ransacStatOutThresh1, p_maxIterations1);
cloudAlign2 = getIcp( cloudAlign1, p_cloudTarget, p_maxCorrDist2, p_ransacStatOutThresh2, p_maxIterations2);
return cloudAlign2;
}
//function to get ICP aligned pointcloud using ICPwithNormals
pcl::PointCloud<PointTReg>::Ptr RegMeshPcd::getIcpNormal ( pcl::PointCloud<PointTReg>::Ptr p_cloudSource,
pcl::PointCloud<PointTReg>::Ptr p_cloudTarget,
float p_maxCorrDist, float p_ransacStatOutThresh, int p_maxIterations ){
//clouds to store intermediate results
pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr cloudSourceWithNormal ( new pcl::PointCloud<pcl::PointXYZRGBNormal> );
pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr cloudTargetWithNormal ( new pcl::PointCloud<pcl::PointXYZRGBNormal> );
pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr cloudIcpNormal ( new pcl::PointCloud<pcl::PointXYZRGBNormal> );
pcl::PointCloud<PointTReg>::Ptr cloudAligned ( new pcl::PointCloud<PointTReg> );
//Normal Estimation
pcl::NormalEstimation<PointTReg, pcl::PointXYZRGBNormal> normEst;
//create kd tree for search
pcl::search::KdTree<PointTReg>::Ptr kdtree ( new pcl::search::KdTree<PointTReg> );
//set parameters
normEst.setSearchMethod( kdtree );
normEst.setKSearch( 12 );
//computer noramls for Source
normEst.setInputCloud( p_cloudSource );
normEst.compute( *cloudSourceWithNormal );
pcl::copyPointCloud( *p_cloudSource, *cloudSourceWithNormal );
//compute normals for target
normEst.setInputCloud( p_cloudTarget );
normEst.compute( *cloudTargetWithNormal );
pcl::copyPointCloud( *p_cloudTarget, *cloudTargetWithNormal );
// //Initial alignmernt
// pcl::PointCloud<pcl::FPFHSignature33>::Ptr sourceCloudFeatures;
// // FPFH Descriptor for Source
// pcl::FPFHEstimation<PointTReg, pcl::PointXYZRGBNormal, pcl::FPFHSignature33> fpfhEstimation;
// fpfhEstimation.setInputCloud( p_cloudSource );
// fpfhEstimation.setRadiusSearch( 0.02 );
// fpfhEstimation.setInputNormals( cloudSourceWithNormal );
// sourceCloudFeatures = pcl::PointCloud<pcl::FPFHSignature33>::Ptr ( new pcl::PointCloud<pcl::FPFHSignature33> );
// fpfhEstimation.compute( *sourceCloudFeatures );
// pcl::PointCloud<pcl::FPFHSignature33>::Ptr targetCloudFeatures;
// // FPFH Descriptor for target
// fpfhEstimation.setInputCloud( p_cloudTarget );
// fpfhEstimation.setRadiusSearch( 0.02 );
// fpfhEstimation.setInputNormals( cloudTargetWithNormal );
// targetCloudFeatures = pcl::PointCloud<pcl::FPFHSignature33>::Ptr ( new pcl::PointCloud<pcl::FPFHSignature33> );
// fpfhEstimation.compute( *targetCloudFeatures );
// //Sample Consensus Initail Alignment
// pcl::PointCloud<PointTReg>::Ptr result ( new pcl::PointCloud<PointTReg> );
// pcl::SampleConsensusInitialAlignment<PointTReg, PointTReg, pcl::FPFHSignature33> sacia;
// sacia.setInputSource( p_cloudSource );
// sacia.setInputTarget( p_cloudTarget );
// sacia.setSourceFeatures( sourceCloudFeatures );
// sacia.setTargetFeatures( targetCloudFeatures );
// sacia.setMaximumIterations( 1000 );
// sacia.setMaxCorrespondenceDistance( 0.1 );
// sacia.setMinSampleDistance( 0.001f );
// sacia.align( *result );
// Eigen::Matrix4f pose = sacia.getFinalTransformation();
// std::cout << "SCA_IA converged with score: " << sacia.getFitnessScore(0.05) << std::endl;
// pcl::PointCloud<PointTReg>::Ptr alignedCloud ( new pcl::PointCloud<PointTReg> );
// pcl::transformPointCloud( *p_cloudSource, *alignedCloud, pose);
// //computer noramls for New Source
// cloudSourceWithNormal.reset( new pcl::PointCloud<pcl::PointXYZRGBNormal> );
// normEst.setInputCloud( alignedCloud );
// normEst.compute( *cloudSourceWithNormal );
// pcl::copyPointCloud( *alignedCloud, *cloudSourceWithNormal );
//Final alignment
// Correspodndence estimation
pcl::CorrespondencesPtr correspondences ( new pcl::Correspondences );
//correspondence_estimation_noraml_shooting
pcl::registration::CorrespondenceEstimationNormalShooting<pcl::PointXYZRGBNormal, pcl::PointXYZRGBNormal, pcl::PointXYZRGBNormal>::Ptr corrEstNormShoot ( new pcl::registration::CorrespondenceEstimationNormalShooting<pcl::PointXYZRGBNormal, pcl::PointXYZRGBNormal, pcl::PointXYZRGBNormal> );
corrEstNormShoot->setInputSource( cloudSourceWithNormal );
corrEstNormShoot->setSourceNormals( cloudSourceWithNormal );
corrEstNormShoot->setInputTarget( cloudTargetWithNormal );
corrEstNormShoot->setKSearch( 20 );
corrEstNormShoot->determineCorrespondences( *correspondences, p_maxCorrDist );
// Correspondence Rejection
pcl::CorrespondencesPtr correspondencesFiltered ( new pcl::Correspondences );
//correpondence_rejection_surface_normal
pcl::registration::CorrespondenceRejectorSurfaceNormal::Ptr corrRejSurNorm (new pcl::registration::CorrespondenceRejectorSurfaceNormal );
corrRejSurNorm->initializeDataContainer<pcl::PointXYZRGBNormal, pcl::PointXYZRGBNormal>();
const pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr cloudSourceWithNormalConstPtr = cloudSourceWithNormal;
corrRejSurNorm->setInputSource<pcl::PointXYZRGBNormal>(cloudSourceWithNormalConstPtr);
corrRejSurNorm->setInputNormals<pcl::PointXYZRGBNormal, pcl::PointXYZRGBNormal>(cloudSourceWithNormalConstPtr);
const pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr cloudTargetWithNormalConstPtr = cloudTargetWithNormal;
corrRejSurNorm->setInputTarget<pcl::PointXYZRGBNormal>(cloudTargetWithNormalConstPtr);
corrRejSurNorm->setTargetNormals<pcl::PointXYZRGBNormal, pcl::PointXYZRGBNormal>(cloudTargetWithNormalConstPtr);
corrRejSurNorm->setThreshold( corrRejThreshNormAngle );
corrRejSurNorm->getRemainingCorrespondences( *correspondences, *correspondencesFiltered );
//transformation_estimation_point_to-plane
pcl::registration::TransformationEstimationPointToPlane<pcl::PointXYZRGBNormal, pcl::PointXYZRGBNormal>::Ptr transfEstpointToPlane ( new pcl::registration::TransformationEstimationPointToPlane<pcl::PointXYZRGBNormal, pcl::PointXYZRGBNormal> );
//ICP With Normals
pcl::IterativeClosestPointWithNormals<pcl::PointXYZRGBNormal, pcl::PointXYZRGBNormal> icpNorm;
// Set the input source and target
icpNorm.setInputSource ( cloudSourceWithNormal );
icpNorm.setInputTarget ( cloudTargetWithNormal );
// Set the max correspondence distance , correspondences with higher distances will be ignored
//icpNorm.setMaxCorrespondenceDistance ( p_maxCorrDist );
// set the ransac outlier rejection threshold
//icpNorm.setRANSACOutlierRejectionThreshold( p_ransacStatOutThresh );
// Set the maximum number of iterations (criterion 1)
icpNorm.setMaximumIterations ( p_maxIterations );
// Set the transformation epsilon (criterion 2)
icpNorm.setTransformationEpsilon (1e-8);
icpNorm.setEuclideanFitnessEpsilon(1e-8);
//set correspondence estimation
icpNorm.setCorrespondenceEstimation( corrEstNormShoot );
//set Rejectors
icpNorm.addCorrespondenceRejector( corrRejSurNorm );
//set transofrmation estimation
icpNorm.setTransformationEstimation( transfEstpointToPlane );
// Perform the alignment
icpNorm.align ( *cloudIcpNormal );
std::cout << "ICP converged with score: " << icpNorm.getFitnessScore() << std::endl;
//get the final transformation and transform the source cloud
Eigen::Matrix4f transformIcpNormal = icpNorm.getFinalTransformation();
pcl::transformPointCloud( *p_cloudSource, *cloudAligned, transformIcpNormal );
return cloudAligned;
}
//function to register pointclouds using ICPs
pcl::PointCloud<PointTReg>::Ptr RegMeshPcd::registerPointClouds ( std::vector<pcl::PointCloud<PointTReg>::Ptr> & cloudVector, float maxCorrDist, float corrRejThresh, int maxIter ){
//clouds to store intermediate results
pcl::PointCloud<PointTReg>::Ptr cloudSource ( new pcl::PointCloud<PointTReg> );
pcl::PointCloud<PointTReg>::Ptr cloudTarget ( new pcl::PointCloud<PointTReg> );
pcl::PointCloud<PointTReg>::Ptr cloudSourceDs ( new pcl::PointCloud<PointTReg> );
pcl::PointCloud<PointTReg>::Ptr cloudTargetDs ( new pcl::PointCloud<PointTReg> );
pcl::PointCloud<PointTReg>::Ptr cloudTemp ( new pcl::PointCloud<PointTReg> );
pcl::PointCloud<PointTReg>::Ptr cloudAlignedIcp ( new pcl::PointCloud<PointTReg> );
pcl::PointCloud<PointTReg>::Ptr cloudAlignedIcpOutRem ( new pcl::PointCloud<PointTReg> );
pcl::PointCloud<PointTReg>::Ptr cloudAlignedIcpOutRemSmooth ( new pcl::PointCloud<PointTReg> );
//set parameters for ICP
float maxCorrDist1 = 0.05, ransacStatOutThresh1 = 0.01; int maxIterations1 = 80;
float maxCorrDist2 = 0.005, ransacStatOutThresh2 = 0.02; int maxIterations2 = 500;
float voxelGridLeafSize = 0.001, outlierRemovalThresh = 5.5;
corrRejThreshNormAngle = corrRejThresh;
//start the ICP between pointclouds
cloudTemp = cloudVector[0]; //make first cloud as cloud source using a temp cloud
//create objet for ProcessingPcd class to use its functions
ProcessingPcd processingPcd;
//loop for all clouds
for (int i = 0; i < cloudVector.size()-1; i++){
std::cout << "ICP between frame " << i << " and " << i+1 << std::endl;
//assign source and target clouds
cloudSource = cloudTemp;
cloudTarget = cloudVector[i+1];
//downsample both the clouds
//cloudSourceDs = processingPcd.getDownSampled( cloudSource, voxelGridLeafSize );
//cloudTargetDs = processingPcd.getDownSampled( cloudTarget, voxelGridLeafSize );
//invoke ICP and align two clouds //three variants // choose the best one
//cloudAlignedIcp = getIcp( cloudSourceDs, cloudTargetDs, maxCorrDist1, ransacStatOutThresh1, maxIterations1 );
//cloudAlignedIcp = getIcp2( cloudSourceDs, cloudTargetDs, maxCorrDist1, ransacStatOutThresh1, maxIterations1, maxCorrDist2, ransacStatOutThresh2, maxIterations2 );
cloudAlignedIcp = getIcpNormal( cloudSource, cloudTarget, maxCorrDist, ransacStatOutThresh2, maxIter );
//combine two aligned pointclouds
*cloudAlignedIcp += *cloudTarget;
//remove outliers if any in aligned cloud
*cloudTemp = *cloudAlignedIcp;
//cloudTemp = processingPcd.getOutlierRemove( cloudAlignedIcp, outlierRemovalThresh );
}
//smooth overall aligned pointcloud
*cloudAlignedIcpOutRem = *cloudTemp;
//cloudAlignedIcpOutRemSmooth = processingPcd.getSmooth( cloudAlignedIcpOutRem, 0.02 );
//cloudAlignedIcpOutRem = processingPcd.getOutlierRemove( cloudTemp, outlierRemovalThresh );
return cloudAlignedIcpOutRem;
}
pcl::PolygonMesh RegMeshPcd::generateMesh( pcl::PointCloud<pcl::PointXYZ>::Ptr p_cloud )
{
pcl::MovingLeastSquares<pcl::PointXYZ, pcl::PointXYZ> mls; //upsampling object
//UpSampling using MLS VoxelGrid Dilation
mls.setInputCloud (p_cloud);
mls.setSearchRadius (0.03);
mls.setPolynomialFit (true);
mls.setPolynomialOrder (4);
mls.setUpsamplingMethod (pcl::MovingLeastSquares<pcl::PointXYZ, pcl::PointXYZ>::VOXEL_GRID_DILATION);
//mls.setUpsamplingRadius (0.005);
//mls.setUpsamplingStepSize (0.003);
mls.setDilationVoxelSize(0.002);
pcl::PointCloud<pcl::PointXYZ>::Ptr cloudSmoothed (new pcl::PointCloud<pcl::PointXYZ>);
mls.process (*cloudSmoothed);
//Normal Estimation
pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> normEst;
pcl::PointCloud<pcl::Normal>::Ptr cloudNormals (new pcl::PointCloud<pcl::Normal>);
pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ>);
tree->setInputCloud (cloudSmoothed);
normEst.setInputCloud (cloudSmoothed);
normEst.setSearchMethod (tree);
normEst.setKSearch (20);
normEst.compute (*cloudNormals);
//* normals should not contain the point normals + surface curvatures
// Concatenate the XYZ and normal fields*
pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr cloudWithNormals (new pcl::PointCloud<pcl::PointXYZRGBNormal>);
pcl::concatenateFields (*cloudSmoothed, *cloudNormals, *cloudWithNormals);
// Create search tree*
pcl::search::KdTree<pcl::PointXYZRGBNormal>::Ptr tree2 (new pcl::search::KdTree<pcl::PointXYZRGBNormal>);
tree2->setInputCloud (cloudWithNormals);
boost::shared_ptr<pcl::PolygonMesh> triangles (new pcl::PolygonMesh);
//Greedy Projection Triangulation
pcl::GreedyProjectionTriangulation<pcl::PointXYZRGBNormal> gp3;
// Set typical values for the parameters
gp3.setMu (3);//3
gp3.setSearchRadius (0.025);
gp3.setMaximumNearestNeighbors (1200);
gp3.setMaximumSurfaceAngle(M_PI); // 45 degrees //2
gp3.setMinimumAngle(M_PI/36); // 10 degrees //5deg
gp3.setMaximumAngle(2*M_PI/3 + M_PI/6); // 120 degrees // 150 degrees
gp3.setNormalConsistency(true);
// Get result
gp3.setInputCloud (cloudWithNormals);
gp3.setSearchMethod (tree2);
gp3.reconstruct (*triangles);
std::vector<int> parts = gp3.getPartIDs();
std::vector<int> states = gp3.getPointStates();
//Laplacian Smoothing of mesh
pcl::PolygonMesh output;
pcl::MeshSmoothingLaplacianVTK vtk;
vtk.setInputMesh(triangles);
vtk.setNumIter(20000);
vtk.setConvergence(0.0001);
vtk.setRelaxationFactor(0.0001);
vtk.setFeatureEdgeSmoothing(true);
vtk.setFeatureAngle(M_PI/5);
vtk.setBoundarySmoothing(true);
vtk.process(output);
//pcl::io::saveVTKFile ("../3DModel/brickModelAxisAlignedOrigin.vtk", output);
return output;
}
| 46.668605 | 294 | 0.725053 | [
"mesh",
"object",
"vector",
"transform"
] |
ed944932472514aa10bf926229417868d3634e5c | 36,871 | cpp | C++ | maya/AbcExport/AbcWriteJob.cpp | matsbtegner/alembic | a714545ffeecf33b7eda52d12259210f4775a1ba | [
"MIT"
] | null | null | null | maya/AbcExport/AbcWriteJob.cpp | matsbtegner/alembic | a714545ffeecf33b7eda52d12259210f4775a1ba | [
"MIT"
] | null | null | null | maya/AbcExport/AbcWriteJob.cpp | matsbtegner/alembic | a714545ffeecf33b7eda52d12259210f4775a1ba | [
"MIT"
] | null | null | null | //-*****************************************************************************
//
// Copyright (c) 2009-2014,
// Sony Pictures Imageworks Inc. and
// Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd.
//
// 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 Sony Pictures Imageworks, nor
// Industrial Light & Magic, nor the names of their 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 "AbcWriteJob.h"
#ifdef ALEMBIC_WITH_HDF5
#include <Alembic/AbcCoreHDF5/All.h>
#endif
#include <Alembic/AbcCoreOgawa/All.h>
namespace
{
void hasDuplicates(const util::ShapeSet & dagPath, unsigned int stripDepth)
{
std::map<std::string, MDagPath> roots;
const util::ShapeSet::const_iterator end = dagPath.end();
for (util::ShapeSet::const_iterator it = dagPath.begin();
it != end; it++)
{
std::string fullName = it->fullPathName().asChar();
if (!fullName.empty() && fullName[0] == '|')
{
fullName = fullName.substr(1);
}
if (stripDepth > 0)
{
MString name = fullName.c_str();
fullName = util::stripNamespaces(name, stripDepth).asChar();
}
std::map<std::string, MDagPath>::iterator strIt =
roots.find(fullName);
if (strIt != roots.end())
{
std::string theError = "Conflicting root node names specified: ";
theError += it->fullPathName().asChar();
theError += " ";
theError += strIt->second.fullPathName().asChar();
if (stripDepth > 0)
{
theError += " with -stripNamespace specified.";
}
throw std::runtime_error(theError);
}
else
{
roots[fullName] = *it;
}
}
}
void addToString(std::string & str,
const std::string & name, unsigned int value)
{
if (value > 0)
{
std::stringstream ss;
ss << value;
str += name + std::string(" ") + ss.str() + std::string(" ");
}
}
void processCallback(std::string iCallback, bool isMelCallback,
double iFrame, const MBoundingBox & iBbox)
{
if (iCallback.empty())
return;
size_t pos = iCallback.find("#FRAME#");
if ( pos != std::string::npos )
{
std::stringstream sstrm;
sstrm.precision(std::numeric_limits<double>::digits10);
sstrm << iFrame;
std::string str = sstrm.str();
iCallback.replace(pos, 7, str);
}
pos = iCallback.find("#BOUNDS#");
if ( pos != std::string::npos )
{
std::stringstream sstrm;
sstrm.precision(std::numeric_limits<float>::digits10);
sstrm << " " << iBbox.min().x << " " << iBbox.min().y << " " <<
iBbox.min().z << " " << iBbox.max().x << " " <<
iBbox.max().y << " " <<iBbox.max().z;
std::string str = sstrm.str();
iCallback.replace(pos, 8, str);
}
pos = iCallback.find("#BOUNDSARRAY#");
if ( pos != std::string::npos )
{
std::stringstream sstrm;
sstrm.precision(std::numeric_limits<float>::digits10);
if (isMelCallback)
{
sstrm << " {";
}
else
{
sstrm << " [";
}
sstrm << iBbox.min().x << "," << iBbox.min().y << "," <<
iBbox.min().z << "," << iBbox.max().x << "," <<
iBbox.max().y << "," << iBbox.max().z;
if (isMelCallback)
{
sstrm << "} ";
}
else
{
sstrm << "] ";
}
std::string str = sstrm.str();
iCallback.replace(pos, 13, str);
}
if (isMelCallback)
MGlobal::executeCommand(iCallback.c_str(), true);
else
MGlobal::executePythonCommand(iCallback.c_str(), true);
}
}
AbcWriteJob::AbcWriteJob(const char * iFileName,
bool iAsOgawa,
std::set<double> & iTransFrames,
Alembic::AbcCoreAbstract::TimeSamplingPtr iTransTime,
std::set<double> & iShapeFrames,
Alembic::AbcCoreAbstract::TimeSamplingPtr iShapeTime,
const JobArgs & iArgs)
{
MStatus status;
mFileName = iFileName;
mAsOgawa = iAsOgawa;
mBoxIndex = 0;
mArgs = iArgs;
mShapeSamples = 1;
mTransSamples = 1;
if (mArgs.useSelectionList)
{
bool emptyDagPaths = mArgs.dagPaths.empty();
// get the active selection
MSelectionList activeList;
MGlobal::getActiveSelectionList(activeList);
mSList = activeList;
unsigned int selectionSize = activeList.length();
for (unsigned int index = 0; index < selectionSize; index ++)
{
MDagPath dagPath;
status = activeList.getDagPath(index, dagPath);
if (status == MS::kSuccess)
{
unsigned int length = dagPath.length();
while (--length)
{
dagPath.pop();
mSList.add(dagPath, MObject::kNullObj, true);
}
if (emptyDagPaths)
{
mArgs.dagPaths.insert(dagPath);
}
}
}
}
mTransFrames = iTransFrames;
mShapeFrames = iShapeFrames;
// only needed during creation of the transforms and shapes
mTransTime = iTransTime;
mTransTimeIndex = 0;
mShapeTime = iShapeTime;
mShapeTimeIndex = 0;
// should have at least 1 value
assert(!mTransFrames.empty() && !mShapeFrames.empty());
mFirstFrame = *(mTransFrames.begin());
std::set<double>::iterator last = mTransFrames.end();
last--;
mLastFrame = *last;
last = mShapeFrames.end();
last--;
double lastShapeFrame = *last;
if (lastShapeFrame > mLastFrame)
mLastFrame = lastShapeFrame;
}
MBoundingBox AbcWriteJob::getBoundingBox(double iFrame, const MMatrix & eMInvMat)
{
MStatus status;
MBoundingBox curBBox;
if (iFrame == mFirstFrame)
{
// Set up bbox shape map in the first frame.
// If we have a lot of transforms and shapes, we don't need to
// iterate them for each frame.
MItDag dagIter;
for (dagIter.reset(mCurDag); !dagIter.isDone(); dagIter.next())
{
MObject object = dagIter.currentItem();
MDagPath path;
dagIter.getPath(path);
// short-circuit if the selection flag is on but this node is not in the
// active selection
// MGlobal::isSelected(ob) doesn't work, because DG node and DAG node is
// not the same even if they refer to the same MObject
if (mArgs.useSelectionList && !mSList.hasItem(path))
{
dagIter.prune();
continue;
}
MFnDagNode dagNode(path, &status);
if (status == MS::kSuccess)
{
// check for riCurves flag for flattening all curve object to
// one curve group
MPlug riCurvesPlug = dagNode.findPlug("riCurves", true, &status);
if ( status == MS::kSuccess && riCurvesPlug.asBool() == true)
{
MBoundingBox box = dagNode.boundingBox();
box.transformUsing(path.exclusiveMatrix()*eMInvMat);
curBBox.expand(box);
// Prune this curve group
dagIter.prune();
// Save children paths
std::map< MDagPath, util::ShapeSet, util::cmpDag >::iterator iter =
mBBoxShapeMap.insert(std::make_pair(mCurDag, util::ShapeSet())).first;
if (iter != mBBoxShapeMap.end())
(*iter).second.insert(path);
}
else if (object.hasFn(MFn::kParticle)
|| object.hasFn(MFn::kMesh)
|| object.hasFn(MFn::kNurbsCurve)
|| object.hasFn(MFn::kNurbsSurface) )
{
if (util::isIntermediate(object))
continue;
MBoundingBox box = dagNode.boundingBox();
box.transformUsing(path.exclusiveMatrix()*eMInvMat);
curBBox.expand(box);
// Save children paths
std::map< MDagPath, util::ShapeSet, util::cmpDag >::iterator iter =
mBBoxShapeMap.insert(std::make_pair(mCurDag, util::ShapeSet())).first;
if (iter != mBBoxShapeMap.end())
(*iter).second.insert(path);
}
}
}
}
else
{
// We have already find out all the shapes for the dag path.
std::map< MDagPath, util::ShapeSet, util::cmpDag >::iterator iter =
mBBoxShapeMap.find(mCurDag);
if (iter != mBBoxShapeMap.end())
{
// Iterate through the saved paths to calculate the box.
util::ShapeSet& paths = (*iter).second;
for (util::ShapeSet::iterator pathIter = paths.begin();
pathIter != paths.end(); pathIter++)
{
MFnDagNode dagNode(*pathIter, &status);
if (status == MS::kSuccess)
{
MBoundingBox box = dagNode.boundingBox();
box.transformUsing((*pathIter).exclusiveMatrix()*eMInvMat);
curBBox.expand(box);
}
}
}
}
return curBBox;
}
bool AbcWriteJob::checkCurveGrp()
{
MItDag itDag(MItDag::kBreadthFirst, MFn::kNurbsCurve);
itDag.reset(mCurDag, MItDag::kBreadthFirst, MFn::kNurbsCurve);
bool init = false;
int degree = 0;
MFnNurbsCurve::Form form = MFnNurbsCurve::kInvalid;
for (; !itDag.isDone(); itDag.next())
{
MDagPath curvePath;
if (itDag.getPath(curvePath) == MS::kSuccess)
{
MObject curve = curvePath.node();
if (!util::isIntermediate(curve) && curve.hasFn(MFn::kNurbsCurve))
{
MFnNurbsCurve fn(curvePath);
if (!init)
{
degree = fn.degree();
form = fn.form();
init = true;
}
else
{
if (degree != fn.degree() || form != fn.form())
return false;
}
}
}
}
return true;
}
void AbcWriteJob::setup(double iFrame, MayaTransformWriterPtr iParent, GetMembersMap& gmMap)
{
MStatus status;
// short-circuit if selection flag is on but this node isn't actively
// selected
if (mArgs.useSelectionList && !mSList.hasItem(mCurDag))
return;
MObject ob = mCurDag.node();
// skip all intermediate nodes (and their children)
if (util::isIntermediate(ob))
{
return;
}
// skip nodes that aren't renderable (and their children)
if (mArgs.excludeInvisible && !util::isRenderable(ob))
{
return;
}
// look for riCurves flag for flattening all curve objects to a curve group
MFnDependencyNode fnDepNode(ob, &status);
MPlug riCurvesPlug = fnDepNode.findPlug("riCurves", true, &status);
bool riCurvesVal = riCurvesPlug.asBool();
bool writeOutAsGroup = false;
if (riCurvesVal)
{
writeOutAsGroup = checkCurveGrp();
if (writeOutAsGroup == false)
{
MString msg = "Curves have different degrees or close ";
msg += "states, not writing out as curve group";
MGlobal::displayWarning(msg);
}
}
if ( status == MS::kSuccess && riCurvesVal && writeOutAsGroup)
{
if( !mArgs.writeCurvesGroup )
{
return;
}
MayaNurbsCurveWriterPtr nurbsCurve;
if (iParent == NULL)
{
Alembic::Abc::OObject obj = mRoot.getTop();
nurbsCurve = MayaNurbsCurveWriterPtr(new MayaNurbsCurveWriter(
mCurDag, obj, mShapeTimeIndex, true, mArgs));
}
else
{
Alembic::Abc::OObject obj = iParent->getObject();
nurbsCurve = MayaNurbsCurveWriterPtr(new MayaNurbsCurveWriter(
mCurDag, obj, mShapeTimeIndex, true, mArgs));
}
if (nurbsCurve->isAnimated() && mShapeTimeIndex != 0)
{
mCurveList.push_back(nurbsCurve);
mStats.mCurveAnimNum++;
mStats.mCurveAnimCurves += nurbsCurve->getNumCurves();
mStats.mCurveAnimCVs += nurbsCurve->getNumCVs();
}
else
{
mStats.mCurveStaticNum++;
mStats.mCurveStaticCurves += nurbsCurve->getNumCurves();
mStats.mCurveStaticCVs += nurbsCurve->getNumCVs();
}
AttributesWriterPtr attrs = nurbsCurve->getAttrs();
if (mShapeTimeIndex != 0 && attrs->isAnimated())
mShapeAttrList.push_back(attrs);
}
else if (ob.hasFn(MFn::kTransform))
{
MayaTransformWriterPtr trans;
MFnTransform fnTrans(ob, &status);
if (status != MS::kSuccess)
{
MString msg = "Initialize transform node ";
msg += mCurDag.fullPathName();
msg += " failed, skipping.";
MGlobal::displayWarning(msg);
return;
}
// parented to the root case
if (iParent == NULL)
{
Alembic::Abc::OObject obj = mRoot.getTop();
trans = MayaTransformWriterPtr(new MayaTransformWriter(
obj, mCurDag, mTransTimeIndex, mArgs));
}
else
{
trans = MayaTransformWriterPtr(new MayaTransformWriter(
*iParent, mCurDag, mTransTimeIndex, mArgs));
}
if (trans->isAnimated() && mTransTimeIndex != 0)
{
mTransList.push_back(trans);
mStats.mTransAnimNum++;
}
else
{
mStats.mTransStaticNum++;
}
AttributesWriterPtr attrs = trans->getAttrs();
if (mTransTimeIndex != 0 && attrs->isAnimated())
mTransAttrList.push_back(attrs);
// loop through the children, making sure to push and pop them
// from the MDagPath
unsigned int numChild = mCurDag.childCount();
for (unsigned int i = 0; i < numChild; ++i)
{
if (mCurDag.push(mCurDag.child(i)) == MS::kSuccess)
{
setup(iFrame, trans, gmMap);
mCurDag.pop();
}
}
}
else if (ob.hasFn(MFn::kLocator))
{
if( !mArgs.writeLocators )
{
return;
}
MFnDependencyNode fnLocator(ob, & status);
if (status != MS::kSuccess)
{
MString msg = "Initialize locator node ";
msg += mCurDag.fullPathName();
msg += " failed, skipping.";
MGlobal::displayWarning(msg);
return;
}
if (iParent != NULL)
{
Alembic::Abc::OObject obj = iParent->getObject();
MayaLocatorWriterPtr locator(new MayaLocatorWriter(
mCurDag, obj, mShapeTimeIndex, mArgs));
if (locator->isAnimated() && mShapeTimeIndex != 0)
{
mLocatorList.push_back(locator);
mStats.mLocatorAnimNum++;
}
else
{
mStats.mLocatorStaticNum++;
}
AttributesWriterPtr attrs = locator->getAttrs();
if (mShapeTimeIndex != 0 && attrs->isAnimated())
mShapeAttrList.push_back(attrs);
}
else
{
MString err = "Can't translate ";
err += fnLocator.name() + " since it doesn't have a parent.";
MGlobal::displayError(err);
}
}
else if (ob.hasFn(MFn::kParticle))
{
if( !mArgs.writeParticles )
{
return;
}
MFnParticleSystem mFnParticle(ob, &status);
if (status != MS::kSuccess)
{
MString msg = "Initialize particle system ";
msg += mCurDag.fullPathName();
msg += " failed, skipping.";
MGlobal::displayWarning(msg);
return;
}
if (iParent != NULL)
{
Alembic::Abc::OObject obj = iParent->getObject();
MayaPointPrimitiveWriterPtr particle(new MayaPointPrimitiveWriter(
iFrame, mCurDag, obj, mShapeTimeIndex, mArgs));
if (particle->isAnimated() && mShapeTimeIndex != 0)
{
mPointList.push_back(particle);
mStats.mPointAnimNum++;
mStats.mPointAnimCVs += particle->getNumCVs();
}
else
{
mStats.mPointStaticNum++;
mStats.mPointStaticCVs += particle->getNumCVs();
}
AttributesWriterPtr attrs = particle->getAttrs();
if (mShapeTimeIndex != 0 && attrs->isAnimated())
mShapeAttrList.push_back(attrs);
}
else
{
MString err = "Can't translate ";
err += mFnParticle.name() + " since it doesn't have a parent.";
MGlobal::displayError(err);
}
}
else if (ob.hasFn(MFn::kMesh))
{
if( !mArgs.writeMeshes)
{
return;
}
MFnMesh fnMesh(ob, &status);
if (status != MS::kSuccess)
{
MString msg = "Initialize mesh node ";
msg += mCurDag.fullPathName();
msg += " failed, skipping.";
MGlobal::displayWarning(msg);
return;
}
if (iParent != NULL)
{
Alembic::Abc::OObject obj = iParent->getObject();
MayaMeshWriterPtr mesh(new MayaMeshWriter(mCurDag, obj,
mShapeTimeIndex, mArgs, gmMap));
if (mesh->isAnimated() && mShapeTimeIndex != 0)
{
mMeshList.push_back(mesh);
if (mesh->isSubD())
{
mStats.mSubDAnimNum++;
mStats.mSubDAnimCVs += mesh->getNumCVs();
mStats.mSubDAnimFaces += mesh->getNumFaces();
}
else
{
mStats.mPolyAnimNum++;
mStats.mPolyAnimCVs += mesh->getNumCVs();
mStats.mPolyAnimFaces += mesh->getNumFaces();
}
}
else
{
if (mesh->isSubD())
{
mStats.mSubDStaticNum++;
mStats.mSubDStaticCVs += mesh->getNumCVs();
mStats.mSubDStaticFaces += mesh->getNumFaces();
}
else
{
mStats.mPolyStaticNum++;
mStats.mPolyStaticCVs += mesh->getNumCVs();
mStats.mPolyStaticFaces += mesh->getNumFaces();
}
}
AttributesWriterPtr attrs = mesh->getAttrs();
if (mShapeTimeIndex != 0 && attrs->isAnimated())
mShapeAttrList.push_back(attrs);
}
else
{
MString err = "Can't translate ";
err += fnMesh.name() + " since it doesn't have a parent.";
MGlobal::displayError(err);
}
}
else if (ob.hasFn(MFn::kCamera))
{
if( !mArgs.writeCameras )
{
return;
}
MFnCamera fnCamera(ob, &status);
if (status != MS::kSuccess)
{
MString msg = "Initialize camera node ";
msg += mCurDag.fullPathName();
msg += " failed, skipping.";
MGlobal::displayWarning(msg);
return;
}
if (iParent != NULL)
{
Alembic::Abc::OObject obj = iParent->getObject();
MayaCameraWriterPtr camera(new MayaCameraWriter(
mCurDag, obj, mShapeTimeIndex, mArgs));
if (camera->isAnimated() && mShapeTimeIndex != 0)
{
mCameraList.push_back(camera);
mStats.mCameraAnimNum++;
}
else
mStats.mCameraStaticNum++;
AttributesWriterPtr attrs = camera->getAttrs();
if (mShapeTimeIndex != 0 && attrs->isAnimated())
mShapeAttrList.push_back(attrs);
}
else
{
MString err = "Can't translate ";
err += fnCamera.name() + " since it doesn't have a parent.";
MGlobal::displayError(err);
}
}
else if (ob.hasFn(MFn::kNurbsSurface))
{
if( !mArgs.writeNurbsSurfaces )
{
return;
}
MFnNurbsSurface fnNurbsSurface(ob, &status);
if (status != MS::kSuccess)
{
MString msg = "Initialize nurbs surface ";
msg += mCurDag.fullPathName();
msg += " failed, skipping.";
MGlobal::displayWarning(msg);
return;
}
if (iParent != NULL)
{
Alembic::Abc::OObject obj = iParent->getObject();
MayaNurbsSurfaceWriterPtr nurbsSurface(new MayaNurbsSurfaceWriter(
mCurDag, obj, mShapeTimeIndex, mArgs));
if (nurbsSurface->isAnimated() && mShapeTimeIndex != 0)
{
mNurbsList.push_back(nurbsSurface);
mStats.mNurbsAnimNum++;
mStats.mNurbsAnimCVs += nurbsSurface->getNumCVs();
}
else
{
mStats.mNurbsStaticNum++;
mStats.mNurbsStaticCVs += nurbsSurface->getNumCVs();
}
AttributesWriterPtr attrs = nurbsSurface->getAttrs();
if (mShapeTimeIndex != 0 && attrs->isAnimated())
mShapeAttrList.push_back(attrs);
}
else
{
MString err = "Can't translate ";
err += fnNurbsSurface.name() + " since it doesn't have a parent.";
MGlobal::displayError(err);
}
}
else if (ob.hasFn(MFn::kNurbsCurve))
{
if( !mArgs.writeNurbsCurves )
{
return;
}
MFnNurbsCurve fnNurbsCurve(ob, &status);
if (status != MS::kSuccess)
{
MString msg = "Initialize curve node ";
msg += mCurDag.fullPathName();
msg += " failed, skipping.";
MGlobal::displayWarning(msg);
return;
}
if (iParent != NULL)
{
Alembic::Abc::OObject obj = iParent->getObject();
MayaNurbsCurveWriterPtr nurbsCurve(new MayaNurbsCurveWriter(
mCurDag, obj, mShapeTimeIndex, false, mArgs));
if (nurbsCurve->isAnimated() && mShapeTimeIndex != 0)
{
mCurveList.push_back(nurbsCurve);
mStats.mCurveAnimNum++;
mStats.mCurveAnimCurves++;
mStats.mCurveAnimCVs += nurbsCurve->getNumCVs();
}
else
{
mStats.mCurveStaticNum++;
mStats.mCurveStaticCurves++;
mStats.mCurveStaticCVs += nurbsCurve->getNumCVs();
}
AttributesWriterPtr attrs = nurbsCurve->getAttrs();
if (mShapeTimeIndex != 0 && attrs->isAnimated())
mShapeAttrList.push_back(attrs);
}
else
{
MString err = "Can't translate ";
err += fnNurbsCurve.name() + " since it doesn't have a parent.";
MGlobal::displayError(err);
}
}
else
{
MString warn = mCurDag.fullPathName() + " is an unsupported type of ";
warn += ob.apiTypeStr();
MGlobal::displayWarning(warn);
}
}
AbcWriteJob::~AbcWriteJob()
{
}
bool AbcWriteJob::eval(double iFrame)
{
if (iFrame == mFirstFrame)
{
// check if the shortnames of any two nodes are the same
// if so, exit here
hasDuplicates(mArgs.dagPaths, mArgs.stripNamespace);
std::string appWriter = "Maya ";
appWriter += MGlobal::mayaVersion().asChar();
appWriter += " AbcExport v";
appWriter += ABCEXPORT_VERSION;
std::string userInfo = "Exported from: ";
userInfo += MFileIO::currentFile().asChar();
// these symbols can't be in the meta data
if (userInfo.find('=') != std::string::npos ||
userInfo.find(';') != std::string::npos)
{
userInfo = "";
}
#ifdef ALEMBIC_WITH_HDF5
if (mAsOgawa)
{
mRoot = CreateArchiveWithInfo(Alembic::AbcCoreOgawa::WriteArchive(),
mFileName, appWriter, userInfo,
Alembic::Abc::ErrorHandler::kThrowPolicy);
}
else
{
mRoot = CreateArchiveWithInfo(Alembic::AbcCoreHDF5::WriteArchive(),
mFileName, appWriter, userInfo,
Alembic::Abc::ErrorHandler::kThrowPolicy);
}
#else
// just write it out as Ogawa
mRoot = CreateArchiveWithInfo(Alembic::AbcCoreOgawa::WriteArchive(),
mFileName, appWriter, userInfo,
Alembic::Abc::ErrorHandler::kThrowPolicy);
#endif
mShapeTimeIndex = mRoot.addTimeSampling(*mShapeTime);
mTransTimeIndex = mRoot.addTimeSampling(*mTransTime);
mBoxProp = Alembic::AbcGeom::CreateOArchiveBounds(mRoot,
mTransTimeIndex);
if (!mRoot.valid())
{
std::string theError = "Unable to create abc file";
throw std::runtime_error(theError);
}
mArgs.setFirstAnimShape = (iFrame == *mShapeFrames.begin());
util::ShapeSet::const_iterator end = mArgs.dagPaths.end();
GetMembersMap gmMap;
for (util::ShapeSet::const_iterator it = mArgs.dagPaths.begin();
it != end; ++it)
{
mCurDag = *it;
setup(iFrame * util::spf(), MayaTransformWriterPtr(), gmMap);
}
perFrameCallback(iFrame);
}
else
{
std::set<double>::iterator checkFrame = mShapeFrames.find(iFrame);
bool foundShapeFrame = false;
if (checkFrame != mShapeFrames.end())
{
assert(mRoot != NULL);
foundShapeFrame = true;
mShapeSamples ++;
double curTime = iFrame * util::spf();
std::vector< MayaCameraWriterPtr >::iterator camIt, camEnd;
camEnd = mCameraList.end();
for (camIt = mCameraList.begin(); camIt != camEnd; camIt++)
{
(*camIt)->write();
}
std::vector< MayaMeshWriterPtr >::iterator meshIt, meshEnd;
meshEnd = mMeshList.end();
for (meshIt = mMeshList.begin(); meshIt != meshEnd; meshIt++)
{
(*meshIt)->write();
if ((*meshIt)->isSubD())
{
mStats.mSubDAnimCVs += (*meshIt)->getNumCVs();
}
else
{
mStats.mPolyAnimCVs += (*meshIt)->getNumCVs();
}
}
std::vector< MayaNurbsCurveWriterPtr >::iterator curveIt, curveEnd;
curveEnd = mCurveList.end();
for (curveIt = mCurveList.begin(); curveIt != curveEnd; curveIt++)
{
(*curveIt)->write();
mStats.mCurveAnimCVs += (*curveIt)->getNumCVs();
}
std::vector< MayaNurbsSurfaceWriterPtr >::iterator nurbsIt,nurbsEnd;
nurbsEnd = mNurbsList.end();
for (nurbsIt = mNurbsList.begin(); nurbsIt != nurbsEnd; nurbsIt++)
{
(*nurbsIt)->write();
mStats.mNurbsAnimCVs += (*nurbsIt)->getNumCVs();
}
std::vector< MayaLocatorWriterPtr >::iterator locIt, locEnd;
locEnd = mLocatorList.end();
for (locIt = mLocatorList.begin(); locIt != locEnd; locIt++)
{
(*locIt)->write();
}
std::vector< MayaPointPrimitiveWriterPtr >::iterator ptIt, ptEnd;
ptEnd = mPointList.end();
for (ptIt = mPointList.begin(); ptIt != ptEnd; ptIt++)
{
(*ptIt)->write(curTime);
mStats.mPointAnimCVs += (*ptIt)->getNumCVs();
}
std::vector< AttributesWriterPtr >::iterator sattrCur =
mShapeAttrList.begin();
std::vector< AttributesWriterPtr >::iterator sattrEnd =
mShapeAttrList.end();
for(; sattrCur != sattrEnd; sattrCur++)
{
(*sattrCur)->write();
}
}
checkFrame = mTransFrames.find(iFrame);
bool foundTransFrame = false;
if (checkFrame != mTransFrames.end())
{
assert(mRoot.valid());
foundTransFrame = true;
mTransSamples ++;
std::vector< MayaTransformWriterPtr >::iterator tcur =
mTransList.begin();
std::vector< MayaTransformWriterPtr >::iterator tend =
mTransList.end();
for (; tcur != tend; tcur++)
{
(*tcur)->write();
}
std::vector< AttributesWriterPtr >::iterator tattrCur =
mTransAttrList.begin();
std::vector< AttributesWriterPtr >::iterator tattrEnd =
mTransAttrList.end();
for(; tattrCur != tattrEnd; tattrCur++)
{
(*tattrCur)->write();
}
}
if (foundTransFrame || foundShapeFrame)
perFrameCallback(iFrame);
}
if (iFrame == mLastFrame)
{
postCallback(iFrame);
return true;
}
return false;
}
void AbcWriteJob::perFrameCallback(double iFrame)
{
MBoundingBox bbox;
util::ShapeSet::iterator it = mArgs.dagPaths.begin();
const util::ShapeSet::iterator end = mArgs.dagPaths.end();
for (; it != end; it ++)
{
mCurDag = *it;
MMatrix eMInvMat;
if (mArgs.worldSpace)
{
eMInvMat.setToIdentity();
}
else
{
eMInvMat = mCurDag.exclusiveMatrixInverse();
}
bbox.expand(getBoundingBox(iFrame, eMInvMat));
}
Alembic::Abc::V3d min(bbox.min().x, bbox.min().y, bbox.min().z);
Alembic::Abc::V3d max(bbox.max().x, bbox.max().y, bbox.max().z);
Alembic::Abc::Box3d b(min, max);
mBoxProp.set(b);
processCallback(mArgs.melPerFrameCallback, true, iFrame, bbox);
processCallback(mArgs.pythonPerFrameCallback, false, iFrame, bbox);
}
// write the frame ranges and statistic string on the root
// Also call the post callbacks
void AbcWriteJob::postCallback(double iFrame)
{
std::string statsStr = "";
addToString(statsStr, "SubDStaticNum", mStats.mSubDStaticNum);
addToString(statsStr, "SubDAnimNum", mStats.mSubDAnimNum);
addToString(statsStr, "SubDStaticCVs", mStats.mSubDStaticCVs);
addToString(statsStr, "SubDAnimCVs", mStats.mSubDAnimCVs);
addToString(statsStr, "SubDStaticFaces", mStats.mSubDStaticFaces);
addToString(statsStr, "SubDAnimFaces", mStats.mSubDAnimFaces);
addToString(statsStr, "PolyStaticNum", mStats.mPolyStaticNum);
addToString(statsStr, "PolyAnimNum", mStats.mPolyAnimNum);
addToString(statsStr, "PolyStaticCVs", mStats.mPolyStaticCVs);
addToString(statsStr, "PolyAnimCVs", mStats.mPolyAnimCVs);
addToString(statsStr, "PolyStaticFaces", mStats.mPolyStaticFaces);
addToString(statsStr, "PolyAnimFaces", mStats.mPolyAnimFaces);
addToString(statsStr, "CurveStaticNum", mStats.mCurveStaticNum);
addToString(statsStr, "CurveStaticCurves", mStats.mCurveStaticCurves);
addToString(statsStr, "CurveAnimNum", mStats.mCurveAnimNum);
addToString(statsStr, "CurveAnimCurves", mStats.mCurveAnimCurves);
addToString(statsStr, "CurveStaticCVs", mStats.mCurveStaticCVs);
addToString(statsStr, "CurveAnimCVs", mStats.mCurveAnimCVs);
addToString(statsStr, "PointStaticNum", mStats.mPointStaticNum);
addToString(statsStr, "PointAnimNum", mStats.mPointAnimNum);
addToString(statsStr, "PointStaticCVs", mStats.mPointStaticCVs);
addToString(statsStr, "PointAnimCVs", mStats.mPointAnimCVs);
addToString(statsStr, "NurbsStaticNum", mStats.mNurbsStaticNum);
addToString(statsStr, "NurbsAnimNum", mStats.mNurbsAnimNum);
addToString(statsStr, "NurbsStaticCVs", mStats.mNurbsStaticCVs);
addToString(statsStr, "NurbsAnimCVs", mStats.mNurbsAnimCVs);
addToString(statsStr, "TransStaticNum", mStats.mTransStaticNum);
addToString(statsStr, "TransAnimNum", mStats.mTransAnimNum);
addToString(statsStr, "LocatorStaticNum", mStats.mLocatorStaticNum);
addToString(statsStr, "LocatorAnimNum", mStats.mLocatorAnimNum);
addToString(statsStr, "CameraStaticNum", mStats.mCameraStaticNum);
addToString(statsStr, "CameraAnimNum", mStats.mCameraAnimNum);
if (statsStr.length() > 0)
{
Alembic::Abc::OStringProperty stats(mRoot.getTop().getProperties(),
"statistics");
stats.set(statsStr);
}
if (mTransTimeIndex != 0)
{
MString propName;
propName += static_cast<int>(mTransTimeIndex);
propName += ".samples";
Alembic::Abc::OUInt32Property samp(mRoot.getTop().getProperties(),
propName.asChar());
samp.set(mTransSamples);
}
if (mShapeTimeIndex != 0 && mShapeTimeIndex != mTransTimeIndex)
{
MString propName;
propName += static_cast<int>(mShapeTimeIndex);
propName += ".samples";
Alembic::Abc::OUInt32Property samp(mRoot.getTop().getProperties(),
propName.asChar());
samp.set(mShapeSamples);
}
MBoundingBox bbox;
if (mArgs.melPostCallback.find("#BOUNDS#") != std::string::npos ||
mArgs.pythonPostCallback.find("#BOUNDS#") != std::string::npos ||
mArgs.melPostCallback.find("#BOUNDSARRAY#") != std::string::npos ||
mArgs.pythonPostCallback.find("#BOUNDSARRAY#") != std::string::npos)
{
util::ShapeSet::const_iterator it = mArgs.dagPaths.begin();
const util::ShapeSet::const_iterator end = mArgs.dagPaths.end();
for (; it != end; it ++)
{
mCurDag = *it;
MMatrix eMInvMat;
if (mArgs.worldSpace)
{
eMInvMat.setToIdentity();
}
else
{
eMInvMat = mCurDag.exclusiveMatrixInverse();
}
bbox.expand(getBoundingBox(iFrame, eMInvMat));
}
}
processCallback(mArgs.melPostCallback, true, iFrame, bbox);
processCallback(mArgs.pythonPostCallback, false, iFrame, bbox);
}
| 32.745115 | 94 | 0.538336 | [
"mesh",
"object",
"shape",
"vector",
"transform"
] |
ed97760dac6d064402de0ab4ff08d4e4ef5ed28a | 946 | cpp | C++ | Codeforces/1099B.cpp | anubhawbhalotia/Competitive-Programming | 32d7003abf9af4999b3dfa78fe1df9022ebbf50b | [
"MIT"
] | null | null | null | Codeforces/1099B.cpp | anubhawbhalotia/Competitive-Programming | 32d7003abf9af4999b3dfa78fe1df9022ebbf50b | [
"MIT"
] | null | null | null | Codeforces/1099B.cpp | anubhawbhalotia/Competitive-Programming | 32d7003abf9af4999b3dfa78fe1df9022ebbf50b | [
"MIT"
] | 1 | 2020-05-20T18:36:31.000Z | 2020-05-20T18:36:31.000Z | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define S string
#define mp make_pair
#define pb push_back
#define lb lower_bound
#define ub upper_bound
//Anubhaw Bhalotia https://github.com/anubhawbhalotia
#define fi first
#define se second
#define f(i,s,n) for(long i=s;i<n;i++)
#define fe(i,s,n) for(long i=s;i<=n;i++)
#define fr(i,s,n) for(long i=s;i>n;i--)
#define fre(i,s,n) for(long i=s;i>=n;i--)
#define mod 998244353
typedef vector<int> vi;
typedef vector<long> vl;
typedef vector<ll> vll;
typedef pair<int,int> pii;
typedef pair<long,long> pll;
typedef pair<ll,ll> pllll;
typedef set<int> si;
typedef set<long> sl;
typedef set<ll> sll;
typedef multiset<int> msi;
typedef multiset<long> msl;
typedef multiset<ll> msll;
int main()
{
long n;
cin>>n;
long a=ceil(sqrt(n));
// cout<<a<<endl;
long b=a-1;
long c=(b*b)+(((a*a)-(b*b))/2);
// cout<<c<<endl;
if(n<=c)
cout<<(a*2)-1<<endl;
else
cout<<(a*2)<<endl;
} | 22 | 53 | 0.674419 | [
"vector"
] |
ed98818f0f47583eb9cbe4148763a16c5ba41ea4 | 644 | cpp | C++ | test/api/refinement_test.cpp | joergi-w/iGenVar | 6dfd3f9009dd435e86d838b973f1282b6e6e471c | [
"BSD-3-Clause"
] | 7 | 2019-11-18T14:34:03.000Z | 2022-03-13T22:29:40.000Z | test/api/refinement_test.cpp | joergi-w/iGenVar | 6dfd3f9009dd435e86d838b973f1282b6e6e471c | [
"BSD-3-Clause"
] | 174 | 2020-09-24T08:20:47.000Z | 2022-03-31T12:44:32.000Z | test/api/refinement_test.cpp | joergi-w/iGenVar | 6dfd3f9009dd435e86d838b973f1282b6e6e471c | [
"BSD-3-Clause"
] | 7 | 2019-11-18T14:34:13.000Z | 2021-11-19T02:59:32.000Z | #include "api_test.hpp"
// #include "modules/refinment/sViper_refinement_method.hpp" // for the sViper refinement method
/* -------- refinement methods tests -------- */
// TODO (irallia): these tests should be implemented when the associated refinement methods are implemented
// TEST(junction_detection, refinement_method_sViper)
// {
// testing::internal::CaptureStdout();
// std::vector<Junction> junctions{};
// std::vector<Cluster> resulting_clusters{};
// sViper_refinement_method(junctions, clusters);
// std::vector<Cluster> expected_clusters{};
// EXPECT_EQ(expected_clusters, resulting_clusters);
// }
| 32.2 | 107 | 0.71118 | [
"vector"
] |
ed98db938a59c4eaf8aaee683be92fcca3d41590 | 555 | cc | C++ | test/async_context.cc | LaudateCorpus1/node-addon-api | 744c8d2410af2e9e6c9abc3f19ea97fd686ca9c0 | [
"MIT"
] | 1,500 | 2017-05-23T06:54:02.000Z | 2022-03-31T07:28:40.000Z | test/async_context.cc | LaudateCorpus1/node-addon-api | 744c8d2410af2e9e6c9abc3f19ea97fd686ca9c0 | [
"MIT"
] | 1,024 | 2017-05-18T17:51:29.000Z | 2022-03-31T21:46:18.000Z | test/async_context.cc | LaudateCorpus1/node-addon-api | 744c8d2410af2e9e6c9abc3f19ea97fd686ca9c0 | [
"MIT"
] | 450 | 2017-06-01T20:25:04.000Z | 2022-03-31T09:34:27.000Z | #include "napi.h"
using namespace Napi;
namespace {
static void MakeCallback(const CallbackInfo& info) {
Function callback = info[0].As<Function>();
Object resource = info[1].As<Object>();
AsyncContext context(info.Env(), "async_context_test", resource);
callback.MakeCallback(
Object::New(info.Env()), std::initializer_list<napi_value>{}, context);
}
} // end anonymous namespace
Object InitAsyncContext(Env env) {
Object exports = Object::New(env);
exports["makeCallback"] = Function::New(env, MakeCallback);
return exports;
}
| 25.227273 | 77 | 0.713514 | [
"object"
] |
ed9e427c9c605cd3c80cdb61164cd477b95e4d3d | 205 | cc | C++ | src/model.cc | CS126SP20/naive-bayes-pyanda2 | d07b1b6c479ea8ca4ac5b07a23ad9a1e56f236f4 | [
"MIT"
] | null | null | null | src/model.cc | CS126SP20/naive-bayes-pyanda2 | d07b1b6c479ea8ca4ac5b07a23ad9a1e56f236f4 | [
"MIT"
] | null | null | null | src/model.cc | CS126SP20/naive-bayes-pyanda2 | d07b1b6c479ea8ca4ac5b07a23ad9a1e56f236f4 | [
"MIT"
] | null | null | null | // Copyright 2020 [Your Name]. All rights reserved.
#include <bayes/model.h>
#include <nlohmann/json.hpp>
namespace bayes {
void Model::CalcProbsForPixel(const char& pixel) {
}
} // namespace bayes
| 14.642857 | 51 | 0.712195 | [
"model"
] |
ed9e45cf944bce9549df0fe010e9446ca9d4598c | 396 | cpp | C++ | GuiTest/DumbGuiItem.cpp | jordsti/stigame | 6ac0ae737667b1c77da3ef5007f5c4a3a080045a | [
"MIT"
] | 8 | 2015-02-03T20:23:49.000Z | 2022-02-15T07:51:05.000Z | GuiTest/DumbGuiItem.cpp | jordsti/stigame | 6ac0ae737667b1c77da3ef5007f5c4a3a080045a | [
"MIT"
] | null | null | null | GuiTest/DumbGuiItem.cpp | jordsti/stigame | 6ac0ae737667b1c77da3ef5007f5c4a3a080045a | [
"MIT"
] | 2 | 2017-02-13T18:04:00.000Z | 2020-08-24T03:21:37.000Z | #include "DumbGuiItem.h"
DumbGuiItem::DumbGuiItem(std::string m_value) :
StiGame::Gui::Item("DumbGuiItem")
{
value = m_value;
}
DumbGuiItem::~DumbGuiItem()
{
}
void DumbGuiItem::setValue(std::string m_value)
{
value = m_value;
}
std::string DumbGuiItem::getValue(void)
{
return value;
}
StiGame::Surface* DumbGuiItem::render(void)
{
return new StiGame::Surface(1, 1);
}
| 14.142857 | 47 | 0.681818 | [
"render"
] |
eda4ebdd56a175aac4f1752839684af81aaa2b14 | 76,447 | cpp | C++ | src/draw.cpp | assasinwar9/Barony | c67c01de1168db1c5a2edad98b23cfff9f999187 | [
"FTL",
"Zlib",
"MIT"
] | 373 | 2016-06-28T06:56:46.000Z | 2022-03-23T02:32:54.000Z | src/draw.cpp | assasinwar9/Barony | c67c01de1168db1c5a2edad98b23cfff9f999187 | [
"FTL",
"Zlib",
"MIT"
] | 361 | 2016-07-06T19:09:25.000Z | 2022-03-26T14:14:19.000Z | src/draw.cpp | addictgamer/Barony | c67c01de1168db1c5a2edad98b23cfff9f999187 | [
"FTL",
"Zlib",
"MIT"
] | 129 | 2016-06-29T09:02:49.000Z | 2022-01-23T09:56:06.000Z | /*-------------------------------------------------------------------------------
BARONY
File: draw.cpp
Desc: contains all drawing code
Copyright 2013-2016 (c) Turning Wheel LLC, all rights reserved.
See LICENSE for details.
-------------------------------------------------------------------------------*/
#include "main.hpp"
#include "draw.hpp"
#include "files.hpp"
#include "hash.hpp"
#include "entity.hpp"
#include "player.hpp"
#include "magic/magic.hpp"
#ifndef NINTENDO
#include "editor.hpp"
#endif
#include "items.hpp"
/*-------------------------------------------------------------------------------
getPixel
gets the value of a pixel at the given x,y location in the given
SDL_Surface
-------------------------------------------------------------------------------*/
Uint32 getPixel(SDL_Surface* surface, int x, int y)
{
int bpp = surface->format->BytesPerPixel;
// Here p is the address to the pixel we want to retrieve
Uint8* p = (Uint8*)surface->pixels + y * surface->pitch + x * bpp;
switch (bpp)
{
case 1:
return *p;
break;
case 2:
return *(Uint16*)p;
break;
case 3:
if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
{
return p[0] << 16 | p[1] << 8 | p[2];
}
else
{
return p[0] | p[1] << 8 | p[2] << 16;
}
break;
case 4:
return *(Uint32*)p;
break;
default:
return 0; /* shouldn't happen, but avoids warnings */
}
}
/*-------------------------------------------------------------------------------
putPixel
sets the value of a pixel at the given x,y location in the given
SDL_Surface
-------------------------------------------------------------------------------*/
void putPixel(SDL_Surface* surface, int x, int y, Uint32 pixel)
{
int bpp = surface->format->BytesPerPixel;
// Here p is the address to the pixel we want to set
Uint8* p = (Uint8*)surface->pixels + y * surface->pitch + x * bpp;
switch (bpp)
{
case 1:
*p = pixel;
break;
case 2:
*(Uint16*)p = pixel;
break;
case 3:
if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
{
p[0] = (pixel >> 16) & 0xff;
p[1] = (pixel >> 8) & 0xff;
p[2] = pixel & 0xff;
}
else
{
p[0] = pixel & 0xff;
p[1] = (pixel >> 8) & 0xff;
p[2] = (pixel >> 16) & 0xff;
}
break;
case 4:
*(Uint32*)p = pixel;
break;
}
}
/*-------------------------------------------------------------------------------
flipSurface
flips the contents of an SDL_Surface horizontally, vertically, or both
-------------------------------------------------------------------------------*/
SDL_Surface* flipSurface( SDL_Surface* surface, int flags )
{
SDL_Surface* flipped = NULL;
Uint32 pixel;
int x, rx;
int y, ry;
// prepare surface for flipping
flipped = SDL_CreateRGBSurface( SDL_SWSURFACE, surface->w, surface->h, surface->format->BitsPerPixel, surface->format->Rmask, surface->format->Gmask, surface->format->Bmask, surface->format->Amask );
if ( SDL_MUSTLOCK( surface ) )
{
SDL_LockSurface( surface );
}
if ( SDL_MUSTLOCK( flipped ) )
{
SDL_LockSurface( flipped );
}
for ( x = 0, rx = flipped->w - 1; x < flipped->w; x++, rx-- )
{
for ( y = 0, ry = flipped->h - 1; y < flipped->h; y++, ry-- )
{
pixel = getPixel( surface, x, y );
// copy pixel
if ( ( flags & FLIP_VERTICAL ) && ( flags & FLIP_HORIZONTAL ) )
{
putPixel( flipped, rx, ry, pixel );
}
else if ( flags & FLIP_HORIZONTAL )
{
putPixel( flipped, rx, y, pixel );
}
else if ( flags & FLIP_VERTICAL )
{
putPixel( flipped, x, ry, pixel );
}
}
}
// restore image
if ( SDL_MUSTLOCK( surface ) )
{
SDL_UnlockSurface( surface );
}
if ( SDL_MUSTLOCK( flipped ) )
{
SDL_UnlockSurface( flipped );
}
return flipped;
}
/*-------------------------------------------------------------------------------
drawCircle
draws a circle in either an opengl or SDL context
-------------------------------------------------------------------------------*/
void drawCircle( int x, int y, real_t radius, Uint32 color, Uint8 alpha )
{
drawArc(x, y, radius, 0, 360, color, alpha);
}
/*-------------------------------------------------------------------------------
drawArc
draws an arc in either an opengl or SDL context
-------------------------------------------------------------------------------*/
void drawArc( int x, int y, real_t radius, real_t angle1, real_t angle2, Uint32 color, Uint8 alpha )
{
int c;
// update projection
glDisable(GL_DEPTH_TEST);
glDisable(GL_LIGHTING);
glMatrixMode(GL_PROJECTION);
glViewport(0, 0, xres, yres);
glLoadIdentity();
glOrtho(0, xres, 0, yres, -1, 1);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_BLEND);
// set line width
GLint lineWidth;
glGetIntegerv(GL_LINE_WIDTH, &lineWidth);
glLineWidth(2);
// draw line
glColor4f(((Uint8)(color >> mainsurface->format->Rshift)) / 255.f, ((Uint8)(color >> mainsurface->format->Gshift)) / 255.f, ((Uint8)(color >> mainsurface->format->Bshift)) / 255.f, alpha / 255.f);
glBindTexture(GL_TEXTURE_2D, 0);
glEnable(GL_LINE_SMOOTH);
glBegin(GL_LINE_STRIP);
for ( c = angle1; c <= angle2; c++)
{
float degInRad = c * PI / 180.f;
glVertex2f(x + ceil(cos(degInRad)*radius) + 1, yres - (y + ceil(sin(degInRad)*radius)));
}
glEnd();
glDisable(GL_LINE_SMOOTH);
// reset line width
glLineWidth(lineWidth);
}
/*-------------------------------------------------------------------------------
drawArcInvertedY, reversing the angle of direction in the y coordinate.
draws an arc in either an opengl or SDL context
-------------------------------------------------------------------------------*/
void drawArcInvertedY(int x, int y, real_t radius, real_t angle1, real_t angle2, Uint32 color, Uint8 alpha)
{
int c;
// update projection
glDisable(GL_DEPTH_TEST);
glDisable(GL_LIGHTING);
glMatrixMode(GL_PROJECTION);
glViewport(0, 0, xres, yres);
glLoadIdentity();
glOrtho(0, xres, 0, yres, -1, 1);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_BLEND);
// set line width
GLint lineWidth;
glGetIntegerv(GL_LINE_WIDTH, &lineWidth);
glLineWidth(2);
// draw line
glColor4f(((Uint8)(color >> mainsurface->format->Rshift)) / 255.f, ((Uint8)(color >> mainsurface->format->Gshift)) / 255.f, ((Uint8)(color >> mainsurface->format->Bshift)) / 255.f, alpha / 255.f);
glBindTexture(GL_TEXTURE_2D, 0);
glEnable(GL_LINE_SMOOTH);
glBegin(GL_LINE_STRIP);
for ( c = angle1; c <= angle2; c++ )
{
float degInRad = c * PI / 180.f;
glVertex2f(x + ceil(cos(degInRad)*radius) + 1, yres - (y - ceil(sin(degInRad)*radius)));
}
glEnd();
glDisable(GL_LINE_SMOOTH);
// reset line width
glLineWidth(lineWidth);
}
/*-------------------------------------------------------------------------------
drawLine
draws a line in either an opengl or SDL context
-------------------------------------------------------------------------------*/
void drawLine( int x1, int y1, int x2, int y2, Uint32 color, Uint8 alpha )
{
// update projection
glDisable(GL_DEPTH_TEST);
glDisable(GL_LIGHTING);
glMatrixMode(GL_PROJECTION);
glViewport(0, 0, xres, yres);
glLoadIdentity();
glOrtho(0, xres, 0, yres, -1, 1);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_BLEND);
// set line width
GLint lineWidth;
glGetIntegerv(GL_LINE_WIDTH, &lineWidth);
glLineWidth(2);
// draw line
glColor4f(((Uint8)(color >> mainsurface->format->Rshift)) / 255.f, ((Uint8)(color >> mainsurface->format->Gshift)) / 255.f, ((Uint8)(color >> mainsurface->format->Bshift)) / 255.f, alpha / 255.f);
glBindTexture(GL_TEXTURE_2D, 0);
glEnable(GL_LINE_SMOOTH);
glBegin(GL_LINES);
glVertex2f(x1 + 1, yres - y1);
glVertex2f(x2 + 1, yres - y2);
glEnd();
glDisable(GL_LINE_SMOOTH);
// reset line width
glLineWidth(lineWidth);
}
/*-------------------------------------------------------------------------------
drawRect
draws a rectangle in either an opengl or SDL context
-------------------------------------------------------------------------------*/
int drawRect( SDL_Rect* src, Uint32 color, Uint8 alpha )
{
SDL_Rect secondsrc;
// update projection
glDisable(GL_DEPTH_TEST);
glDisable(GL_LIGHTING);
glMatrixMode(GL_PROJECTION);
glViewport(0, 0, xres, yres);
glLoadIdentity();
glOrtho(0, xres, 0, yres, -1, 1);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_BLEND);
// for the use of the whole screen
if ( src == NULL )
{
secondsrc.x = 0;
secondsrc.y = 0;
secondsrc.w = xres;
secondsrc.h = yres;
src = &secondsrc;
}
// draw quad
glColor4f(((Uint8)(color >> mainsurface->format->Rshift)) / 255.f, ((Uint8)(color >> mainsurface->format->Gshift)) / 255.f, ((Uint8)(color >> mainsurface->format->Bshift)) / 255.f, alpha / 255.f);
glBindTexture(GL_TEXTURE_2D, 0);
glBegin(GL_QUADS);
glVertex2f(src->x, yres - src->y);
glVertex2f(src->x, yres - src->y - src->h);
glVertex2f(src->x + src->w, yres - src->y - src->h);
glVertex2f(src->x + src->w, yres - src->y);
glEnd();
return 0;
}
/*-------------------------------------------------------------------------------
drawBox
draws the border of a rectangle
-------------------------------------------------------------------------------*/
int drawBox(SDL_Rect* src, Uint32 color, Uint8 alpha)
{
drawLine(src->x, src->y, src->x + src->w, src->y, color, alpha); //Top.
drawLine(src->x, src->y, src->x, src->y + src->h, color, alpha); //Left.
drawLine(src->x + src->w, src->y, src->x + src->w, src->y + src->h, color, alpha); //Right.
drawLine(src->x, src->y + src->h, src->x + src->w, src->y + src->h, color, alpha); //Bottom.
return 0;
}
/*-------------------------------------------------------------------------------
drawGear
draws a gear (used for turning wheel splash)
-------------------------------------------------------------------------------*/
void drawGear(Sint16 x, Sint16 y, real_t size, Sint32 rotation)
{
Uint32 color;
int c;
Sint16 x1, y1, x2, y2;
color = SDL_MapRGB(mainsurface->format, 255, 127, 0);
for ( c = 0; c < 6; c++ )
{
drawArc(x, y, size, 0 + c * 60 + rotation, 30 + c * 60 + rotation, color, 255);
drawArc(x, y, (int)ceil(size * 1.33), 30 + c * 60 + 4 + rotation, 60 + c * 60 - 4 + rotation, color, 255);
x1 = ceil(size * cos((30 + c * 60 + rotation) * (PI / 180))) + x;
y1 = ceil(size * sin((30 + c * 60 + rotation) * (PI / 180))) + y;
x2 = ceil(size * cos((30 + c * 60 + 4 + rotation) * (PI / 180)) * 1.33) + x;
y2 = ceil(size * sin((30 + c * 60 + 4 + rotation) * (PI / 180)) * 1.33) + y;
drawLine(x1, y1, x2, y2, color, 255);
x1 = ceil(size * cos((60 + c * 60 + rotation) * (PI / 180))) + x;
y1 = ceil(size * sin((60 + c * 60 + rotation) * (PI / 180))) + y;
x2 = ceil(size * cos((60 + c * 60 - 4 + rotation) * (PI / 180)) * 1.33) + x;
y2 = ceil(size * sin((60 + c * 60 - 4 + rotation) * (PI / 180)) * 1.33) + y;
drawLine(x1, y1, x2, y2, color, 255);
}
color = SDL_MapRGBA(mainsurface->format, 191, 63, 0, 255);
drawCircle(x, y, size * .66, color, 255);
color = SDL_MapRGBA(mainsurface->format, 127, 0, 0, 255);
drawCircle(x, y, size * .25, color, 255);
}
/*-------------------------------------------------------------------------------
drawImageRotatedAlpha
blits an image in either an opengl or SDL context, rotating the image
relative to the screen and taking an alpha value
-------------------------------------------------------------------------------*/
void drawImageRotatedAlpha( SDL_Surface* image, SDL_Rect* src, SDL_Rect* pos, real_t angle, Uint8 alpha )
{
SDL_Rect secondsrc;
// update projection
glPushMatrix();
glDisable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glViewport(0, 0, xres, yres);
glLoadIdentity();
glOrtho(0, xres, 0, yres, -1, 1);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_BLEND);
glTranslatef(pos->x, yres - pos->y, 0);
glRotatef(-angle * 180 / PI, 0.f, 0.f, 1.f);
// for the use of a whole image
if ( src == NULL )
{
secondsrc.x = 0;
secondsrc.y = 0;
secondsrc.w = image->w;
secondsrc.h = image->h;
src = &secondsrc;
}
// draw a textured quad
glBindTexture(GL_TEXTURE_2D, texid[image->refcount]);
glColor4f(1, 1, 1, alpha / 255.1);
glBegin(GL_QUADS);
glTexCoord2f(1.0 * ((real_t)src->x / image->w), 1.0 * ((real_t)src->y / image->h));
glVertex2f(-src->w / 2, src->h / 2);
glTexCoord2f(1.0 * ((real_t)src->x / image->w), 1.0 * (((real_t)src->y + src->h) / image->h));
glVertex2f(-src->w / 2, -src->h / 2);
glTexCoord2f(1.0 * (((real_t)src->x + src->w) / image->w), 1.0 * (((real_t)src->y + src->h) / image->h));
glVertex2f(src->w / 2, -src->h / 2);
glTexCoord2f(1.0 * (((real_t)src->x + src->w) / image->w), 1.0 * ((real_t)src->y / image->h));
glVertex2f(src->w / 2, src->h / 2);
glEnd();
glPopMatrix();
glEnable(GL_DEPTH_TEST);
}
/*-------------------------------------------------------------------------------
drawImageColor
blits an image in either an opengl or SDL context while colorizing it
-------------------------------------------------------------------------------*/
void drawImageColor( SDL_Surface* image, SDL_Rect* src, SDL_Rect* pos, Uint32 color )
{
SDL_Rect secondsrc;
// update projection
glPushMatrix();
glDisable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glViewport(0, 0, xres, yres);
glLoadIdentity();
glOrtho(0, xres, 0, yres, -1, 1);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_BLEND);
// for the use of a whole image
if ( src == NULL )
{
secondsrc.x = 0;
secondsrc.y = 0;
secondsrc.w = image->w;
secondsrc.h = image->h;
src = &secondsrc;
}
// draw a textured quad
glBindTexture(GL_TEXTURE_2D, texid[image->refcount]);
real_t r = ((Uint8)(color >> mainsurface->format->Rshift)) / 255.f;
real_t g = ((Uint8)(color >> mainsurface->format->Gshift)) / 255.f;
real_t b = ((Uint8)(color >> mainsurface->format->Bshift)) / 255.f;
real_t a = ((Uint8)(color >> mainsurface->format->Ashift)) / 255.f;
glColor4f(r, g, b, a);
glPushMatrix();
glBegin(GL_QUADS);
glTexCoord2f(1.0 * ((real_t)src->x / image->w), 1.0 * ((real_t)src->y / image->h));
glVertex2f(pos->x, yres - pos->y);
glTexCoord2f(1.0 * ((real_t)src->x / image->w), 1.0 * (((real_t)src->y + src->h) / image->h));
glVertex2f(pos->x, yres - pos->y - src->h);
glTexCoord2f(1.0 * (((real_t)src->x + src->w) / image->w), 1.0 * (((real_t)src->y + src->h) / image->h));
glVertex2f(pos->x + src->w, yres - pos->y - src->h);
glTexCoord2f(1.0 * (((real_t)src->x + src->w) / image->w), 1.0 * ((real_t)src->y / image->h));
glVertex2f(pos->x + src->w, yres - pos->y);
glEnd();
glPopMatrix();
glEnable(GL_DEPTH_TEST);
}
/*-------------------------------------------------------------------------------
drawImageAlpha
blits an image in either an opengl or SDL context, taking an alpha value
-------------------------------------------------------------------------------*/
void drawImageAlpha( SDL_Surface* image, SDL_Rect* src, SDL_Rect* pos, Uint8 alpha )
{
SDL_Rect secondsrc;
// update projection
glPushMatrix();
glDisable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glViewport(0, 0, xres, yres);
glLoadIdentity();
glOrtho(0, xres, 0, yres, -1, 1);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_BLEND);
// for the use of a whole image
if ( src == NULL )
{
secondsrc.x = 0;
secondsrc.y = 0;
secondsrc.w = image->w;
secondsrc.h = image->h;
src = &secondsrc;
}
// draw a textured quad
glBindTexture(GL_TEXTURE_2D, texid[image->refcount]);
glColor4f(1, 1, 1, alpha / 255.1);
glPushMatrix();
glBegin(GL_QUADS);
glTexCoord2f(1.0 * ((real_t)src->x / image->w), 1.0 * ((real_t)src->y / image->h));
glVertex2f(pos->x, yres - pos->y);
glTexCoord2f(1.0 * ((real_t)src->x / image->w), 1.0 * (((real_t)src->y + src->h) / image->h));
glVertex2f(pos->x, yres - pos->y - src->h);
glTexCoord2f(1.0 * (((real_t)src->x + src->w) / image->w), 1.0 * (((real_t)src->y + src->h) / image->h));
glVertex2f(pos->x + src->w, yres - pos->y - src->h);
glTexCoord2f(1.0 * (((real_t)src->x + src->w) / image->w), 1.0 * ((real_t)src->y / image->h));
glVertex2f(pos->x + src->w, yres - pos->y);
glEnd();
glPopMatrix();
glEnable(GL_DEPTH_TEST);
}
/*-------------------------------------------------------------------------------
drawImage
blits an image in either an opengl or SDL context
-------------------------------------------------------------------------------*/
void drawImage( SDL_Surface* image, SDL_Rect* src, SDL_Rect* pos )
{
SDL_Rect secondsrc;
// update projection
glPushMatrix();
glDisable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glViewport(0, 0, xres, yres);
glLoadIdentity();
glOrtho(0, xres, 0, yres, -1, 1);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_BLEND);
// for the use of a whole image
if ( src == NULL )
{
secondsrc.x = 0;
secondsrc.y = 0;
secondsrc.w = image->w;
secondsrc.h = image->h;
src = &secondsrc;
}
// draw a textured quad
glBindTexture(GL_TEXTURE_2D, texid[image->refcount]);
glColor4f(1, 1, 1, 1);
glPushMatrix();
glBegin(GL_QUADS);
glTexCoord2f(1.0 * ((real_t)src->x / image->w), 1.0 * ((real_t)src->y / image->h));
glVertex2f(pos->x, yres - pos->y);
glTexCoord2f(1.0 * ((real_t)src->x / image->w), 1.0 * (((real_t)src->y + src->h) / image->h));
glVertex2f(pos->x, yres - pos->y - src->h);
glTexCoord2f(1.0 * (((real_t)src->x + src->w) / image->w), 1.0 * (((real_t)src->y + src->h) / image->h));
glVertex2f(pos->x + src->w, yres - pos->y - src->h);
glTexCoord2f(1.0 * (((real_t)src->x + src->w) / image->w), 1.0 * ((real_t)src->y / image->h));
glVertex2f(pos->x + src->w, yres - pos->y);
glEnd();
glPopMatrix();
glEnable(GL_DEPTH_TEST);
}
/*-------------------------------------------------------------------------------
drawImageRing
blits an image in either an opengl or SDL context into a 2d ring.
-------------------------------------------------------------------------------*/
void drawImageRing(SDL_Surface* image, SDL_Rect* src, int radius, int thickness, int segments, real_t angStart, real_t angEnd, Uint8 alpha)
{
SDL_Rect secondsrc;
// update projection
glPushMatrix();
glDisable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glViewport(0, 0, xres, yres);
glLoadIdentity();
glOrtho(0, xres, 0, yres, -1, 1);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_BLEND);
// for the use of a whole image
if ( src == NULL )
{
secondsrc.x = 0;
secondsrc.y = 0;
secondsrc.w = image->w;
secondsrc.h = image->h;
src = &secondsrc;
}
// draw a textured quad
glBindTexture(GL_TEXTURE_2D, texid[image->refcount]);
glColor4f(1, 1, 1, alpha / 255.f);
glPushMatrix();
double s;
real_t arcAngle = angStart;
int first = segments / 2;
real_t distance = std::round((angEnd - angStart) * segments / (2 * PI));
for ( int i = 0; i < first; ++i )
{
glBegin(GL_QUAD_STRIP);
for ( int j = 0; j <= static_cast<int>(distance); ++j )
{
s = i % first + 0.01;
arcAngle = ((j % segments) * 2 * PI / segments) + angStart; // angle of the line.
real_t arcx1 = (radius + thickness * cos(s * 2 * PI / first)) * cos(arcAngle);
real_t arcy1 = (radius + thickness * cos(s * 2 * PI / first)) * sin(arcAngle);
s = (i + 1) % first + 0.01;
real_t arcx2 = (radius + thickness * cos(s * 2 * PI / first)) * cos(arcAngle);
real_t arcy2 = (radius + thickness * cos(s * 2 * PI / first)) * sin(arcAngle);
//glTexCoord2f(1.f, 0.f);
glVertex2f(src->x + arcx1, yres - src->y + arcy1);
//glTexCoord2f(0.f, 1.f);
glVertex2f(src->x + arcx2, yres - src->y + arcy2);
//s = i % first + 0.01;
//arcAngle = (((j + 1) % segments) * 2 * PI / segments) + angStart; // angle of the line.
//real_t arcx3 = (radius + thickness * cos(s * 2 * PI / first)) * cos(arcAngle);
//real_t arcy3 = (radius + thickness * cos(s * 2 * PI / first)) * sin(arcAngle);
//s = (i + 1) % first + 0.01;
//real_t arcx4 = (radius + thickness * cos(s * 2 * PI / first)) * cos(arcAngle);
//real_t arcy4 = (radius + thickness * cos(s * 2 * PI / first)) * sin(arcAngle);
//std::vector<std::pair<real_t, real_t>> xycoords;
//xycoords.push_back(std::make_pair(arcx1, arcy1));
//xycoords.push_back(std::make_pair(arcx2, arcy2));
//xycoords.push_back(std::make_pair(arcx3, arcy3));
//xycoords.push_back(std::make_pair(arcx4, arcy4));
//std::sort(xycoords.begin(), xycoords.end());
//if ( xycoords.at(2).second < xycoords.at(3).second )
//{
// glTexCoord2f(1.f, 0.f);
// glVertex2f(xres / 2 + xycoords.at(2).first, yres / 2 + xycoords.at(2).second); // lower right.
// glTexCoord2f(1.f, 1.f);
// glVertex2f(xres / 2 + xycoords.at(3).first, yres / 2 + xycoords.at(3).second); // upper right.
//}
//else
//{
// glTexCoord2f(1.f, 0.f);
// glVertex2f(xres / 2 + xycoords.at(3).first, yres / 2 + xycoords.at(3).second); // lower right.
// glTexCoord2f(1.f, 1.f);
// glVertex2f(xres / 2 + xycoords.at(2).first, yres / 2 + xycoords.at(2).second); // upper right.
//}
//if ( xycoords.at(0).second < xycoords.at(1).second )
//{
// glTexCoord2f(0.f, 0.f);
// glVertex2f(xres / 2 + xycoords.at(0).first, yres / 2 + xycoords.at(0).second); // lower left.
// glTexCoord2f(0.f, 1.f);
// glVertex2f(xres / 2 + xycoords.at(1).first, yres / 2 + xycoords.at(1).second); // upper left.
//}
//else
//{
// glTexCoord2f(0.f, 0.f);
// glVertex2f(xres / 2 + xycoords.at(1).first, yres / 2 + xycoords.at(1).second); // lower left.
// glTexCoord2f(0.f, 1.f);
// glVertex2f(xres / 2 + xycoords.at(0).first, yres / 2 + xycoords.at(0).second); // upper left.
//}
//glVertex2f(xres / 2 + arcx3, yres / 2 + arcy3);
//glVertex2f(xres / 2 + arcx4, yres / 2 + arcy4);
}
glEnd();
}
glPopMatrix();
// debug lines
/*real_t x1 = xres / 2 + 300 * cos(angStart);
real_t y1 = yres / 2 - 300 * sin(angStart);
real_t x2 = xres / 2 + 300 * cos(angEnd);
real_t y2 = yres / 2 - 300 * sin(angEnd);
drawLine(xres / 2, yres / 2, x1, y1, 0xFFFFFFFF, 255);
drawLine(xres / 2, yres / 2, x2, y2, 0xFFFFFFFF, 255);*/
glEnable(GL_DEPTH_TEST);
}
/*-------------------------------------------------------------------------------
drawImageScaled
blits an image in either an opengl or SDL context, scaling it
-------------------------------------------------------------------------------*/
void drawImageScaled( SDL_Surface* image, SDL_Rect* src, SDL_Rect* pos )
{
SDL_Rect secondsrc;
if ( !image )
{
return;
}
// update projection
glPushMatrix();
glDisable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glViewport(0, 0, xres, yres);
glLoadIdentity();
glOrtho(0, xres, 0, yres, -1, 1);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_BLEND);
// for the use of a whole image
if ( src == NULL )
{
secondsrc.x = 0;
secondsrc.y = 0;
secondsrc.w = image->w;
secondsrc.h = image->h;
src = &secondsrc;
}
// draw a textured quad
glBindTexture(GL_TEXTURE_2D, texid[image->refcount]);
glColor4f(1, 1, 1, 1);
glPushMatrix();
glBegin(GL_QUADS);
glTexCoord2f(1.0 * ((real_t)src->x / image->w), 1.0 * ((real_t)src->y / image->h));
glVertex2f(pos->x, yres - pos->y);
glTexCoord2f(1.0 * ((real_t)src->x / image->w), 1.0 * (((real_t)src->y + src->h) / image->h));
glVertex2f(pos->x, yres - pos->y - pos->h);
//glVertex2f(pos->x, yres - pos->y - src->h);
glTexCoord2f(1.0 * (((real_t)src->x + src->w) / image->w), 1.0 * (((real_t)src->y + src->h) / image->h));
glVertex2f(pos->x + pos->w, yres - pos->y - pos->h);
//glVertex2f(pos->x + src->w, yres - pos->y - src->h);
glTexCoord2f(1.0 * (((real_t)src->x + src->w) / image->w), 1.0 * ((real_t)src->y / image->h));
//glVertex2f(pos->x + src->w, yres - pos->y);
glVertex2f(pos->x + pos->w, yres - pos->y);
//glTexCoord2f(0.f, 0.f);
//glVertex2f(pos->x, yres - pos->y);
//glTexCoord2f(0.f, 1.f);
//glVertex2f(pos->x, yres - pos->y - pos->h);
//glTexCoord2f(1.f, 1.f);
//glVertex2f(pos->x + pos->w, yres - pos->y - pos->h);
//glTexCoord2f(1.f, 0.f);
//glVertex2f(pos->x + pos->w, yres - pos->y);
glEnd();
glPopMatrix();
glEnable(GL_DEPTH_TEST);
}
/*-------------------------------------------------------------------------------
drawImageScaledPartial
blits an image in either an opengl or SDL context, scaling it
-------------------------------------------------------------------------------*/
void drawImageScaledPartial(SDL_Surface* image, SDL_Rect* src, SDL_Rect* pos, float percentY)
{
SDL_Rect secondsrc;
if ( !image )
{
return;
}
// update projection
glPushMatrix();
glDisable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glViewport(0, 0, xres, yres);
glLoadIdentity();
glOrtho(0, xres, 0, yres, -1, 1);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_BLEND);
// for the use of a whole image
if ( src == NULL )
{
secondsrc.x = 0;
secondsrc.y = 0;
secondsrc.w = image->w;
secondsrc.h = image->h;
src = &secondsrc;
}
// draw a textured quad
glBindTexture(GL_TEXTURE_2D, texid[image->refcount]);
glColor4f(1, 1, 1, 1);
glPushMatrix();
glBegin(GL_QUADS);
glTexCoord2f(0.f, 1.f - 1.f * percentY); // top left.
glVertex2f(pos->x, yres - pos->y - pos->h + pos->h * percentY);
glTexCoord2f(0.f, 1.f); // bottom left
glVertex2f(pos->x, yres - pos->y - pos->h);
glTexCoord2f(1.f, 1.f); // bottom right
glVertex2f(pos->x + pos->w, yres - pos->y - pos->h);
glTexCoord2f(1.f, 1.f - 1.f * percentY); // top right
glVertex2f(pos->x + pos->w, yres - pos->y - pos->h + pos->h * percentY);
glEnd();
glPopMatrix();
glEnable(GL_DEPTH_TEST);
// debug corners
//Uint32 color = SDL_MapRGB(mainsurface->format, 64, 255, 64); // green
//drawCircle(pos->x, pos->y + (pos->h - (pos->h * percentY)), 5, color, 255);
//color = SDL_MapRGB(mainsurface->format, 204, 121, 167); // pink
//drawCircle(pos->x, pos->y + pos->h, 5, color, 255);
//color = SDL_MapRGB(mainsurface->format, 86, 180, 233); // sky blue
//drawCircle(pos->x + pos->w, pos->y + pos->h, 5, color, 255);
//color = SDL_MapRGB(mainsurface->format, 240, 228, 66); // yellow
//drawCircle(pos->x + pos->w, pos->y + (pos->h - (pos->h * percentY)), 5, color, 255);
}
/*-------------------------------------------------------------------------------
drawImageScaledColor
blits an image in either an opengl or SDL context while colorizing and scaling it
-------------------------------------------------------------------------------*/
void drawImageScaledColor(SDL_Surface* image, SDL_Rect* src, SDL_Rect* pos, Uint32 color)
{
SDL_Rect secondsrc;
// update projection
glPushMatrix();
glDisable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glViewport(0, 0, xres, yres);
glLoadIdentity();
glOrtho(0, xres, 0, yres, -1, 1);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_BLEND);
// for the use of a whole image
if ( src == NULL )
{
secondsrc.x = 0;
secondsrc.y = 0;
secondsrc.w = image->w;
secondsrc.h = image->h;
src = &secondsrc;
}
// draw a textured quad
glBindTexture(GL_TEXTURE_2D, texid[image->refcount]);
real_t r = ((Uint8)(color >> mainsurface->format->Rshift)) / 255.f;
real_t g = ((Uint8)(color >> mainsurface->format->Gshift)) / 255.f;
real_t b = ((Uint8)(color >> mainsurface->format->Bshift)) / 255.f;
real_t a = ((Uint8)(color >> mainsurface->format->Ashift)) / 255.f;
glColor4f(r, g, b, a);
glPushMatrix();
glBegin(GL_QUADS);
glTexCoord2f(0.f, 0.f);
glVertex2f(pos->x, yres - pos->y);
glTexCoord2f(0.f, 1.f);
glVertex2f(pos->x, yres - pos->y - pos->h);
glTexCoord2f(1.f, 1.f);
glVertex2f(pos->x + pos->w, yres - pos->y - pos->h);
glTexCoord2f(1.f, 0.f);
glVertex2f(pos->x + pos->w, yres - pos->y);
glEnd();
glPopMatrix();
glEnable(GL_DEPTH_TEST);
}
/*-------------------------------------------------------------------------------
scaleSurface
Scales an SDL_Surface to the given width and height.
-------------------------------------------------------------------------------*/
SDL_Surface* scaleSurface(SDL_Surface* Surface, Uint16 Width, Uint16 Height)
{
Sint32 x, y, o_x, o_y;
if (!Surface || !Width || !Height)
{
return NULL;
}
SDL_Surface* _ret = SDL_CreateRGBSurface(Surface->flags, Width, Height, Surface->format->BitsPerPixel, Surface->format->Rmask, Surface->format->Gmask, Surface->format->Bmask, Surface->format->Amask);
real_t _stretch_factor_x = (real_t)Width / (real_t)Surface->w;
real_t _stretch_factor_y = (real_t)Height / (real_t)Surface->h;
for (y = 0; y < Surface->h; y++)
for (x = 0; x < Surface->w; x++)
for (o_y = 0; o_y < _stretch_factor_y; ++o_y)
for (o_x = 0; o_x < _stretch_factor_x; ++o_x)
{
putPixel(_ret, (Sint32)(_stretch_factor_x * x) + o_x, (Sint32)(_stretch_factor_y * y) + o_y, getPixel(Surface, x, y));
}
free(Surface);
return _ret;
}
/*-------------------------------------------------------------------------------
drawImageFancy
blits an image in either an opengl or SDL context, while coloring,
rotating, and scaling it
-------------------------------------------------------------------------------*/
void drawImageFancy( SDL_Surface* image, Uint32 color, real_t angle, SDL_Rect* src, SDL_Rect* pos )
{
SDL_Rect secondsrc;
if ( !image )
{
return;
}
// update projection
glPushMatrix();
glDisable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glViewport(0, 0, xres, yres);
glLoadIdentity();
glOrtho(0, xres, 0, yres, -1, 1);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_BLEND);
glTranslatef(pos->x, yres - pos->y, 0);
glRotatef(-angle * 180 / PI, 0.f, 0.f, 1.f);
// for the use of a whole image
if ( src == NULL )
{
secondsrc.x = 0;
secondsrc.y = 0;
secondsrc.w = image->w;
secondsrc.h = image->h;
src = &secondsrc;
}
// draw a textured quad
glBindTexture(GL_TEXTURE_2D, texid[image->refcount]);
real_t r = ((Uint8)(color >> mainsurface->format->Rshift)) / 255.f;
real_t g = ((Uint8)(color >> mainsurface->format->Gshift)) / 255.f;
real_t b = ((Uint8)(color >> mainsurface->format->Bshift)) / 255.f;
real_t a = ((Uint8)(color >> mainsurface->format->Ashift)) / 255.f;
glColor4f(r, g, b, a);
glPushMatrix();
glBegin(GL_QUADS);
glTexCoord2f(((real_t)src->x) / ((real_t)image->w), ((real_t)src->y) / ((real_t)image->h));
glVertex2f(0, 0);
glTexCoord2f(((real_t)src->x) / ((real_t)image->w), ((real_t)(src->y + src->h)) / ((real_t)image->h));
glVertex2f(0, -pos->h);
glTexCoord2f(((real_t)(src->x + src->w)) / ((real_t)image->w), ((real_t)(src->y + src->h)) / ((real_t)image->h));
glVertex2f(pos->w, -pos->h);
glTexCoord2f(((real_t)(src->x + src->w)) / ((real_t)image->w), ((real_t)src->y) / ((real_t)image->h));
glVertex2f(pos->w, 0);
glEnd();
glPopMatrix();
glEnable(GL_DEPTH_TEST);
}
/*-------------------------------------------------------------------------------
drawSky3D
Draws the sky as an image whose position depends upon the given camera
position
-------------------------------------------------------------------------------*/
void drawSky3D( view_t* camera, SDL_Surface* tex )
{
real_t screenfactor;
int skyx, skyy;
SDL_Rect dest;
SDL_Rect src;
// move the images differently depending upon the screen size
screenfactor = xres / 320.0;
// bitmap offsets
skyx = -camera->ang * ((320 * screenfactor) / (PI / 2.0));
skyy = (-114 * screenfactor - camera->vang);
src.x = -skyx;
src.y = -skyy;
src.w = (-skyx) + xres; // clip to the screen width
src.h = (-skyy) + yres; // clip to the screen height
dest.x = 0;
dest.y = 0;
dest.w = xres;
dest.h = yres;
drawImage(tex, &src, &dest);
// draw the part of the last part of the sky (only appears when angle > 270 deg.)
if ( skyx < -960 * screenfactor )
{
dest.x = 1280 * screenfactor + skyx;
dest.y = 0;
dest.w = xres;
dest.h = yres;
src.x = 0;
src.y = -skyy;
src.w = xres - (-skyx - 1280 * screenfactor);
src.h = src.y + yres;
drawImage(tex, &src, &dest);
}
}
/*-------------------------------------------------------------------------------
drawLayer / drawBackground / drawForeground
Draws the world tiles that are viewable at the given camera coordinates
-------------------------------------------------------------------------------*/
void drawLayer(long camx, long camy, int z, map_t* map)
{
long x, y;
long minx, miny, maxx, maxy;
int index;
SDL_Rect pos;
minx = std::max<long int>(camx >> TEXTUREPOWER, 0);
maxx = std::min<long int>((camx >> TEXTUREPOWER) + xres / TEXTURESIZE + 2, map->width); //TODO: Why are long int and unsigned int being compared?
miny = std::max<long int>(camy >> TEXTUREPOWER, 0);
maxy = std::min<long int>((camy >> TEXTUREPOWER) + yres / TEXTURESIZE + 2, map->height); //TODO: Why are long int and unsigned int being compared?
for ( y = miny; y < maxy; y++ )
{
for ( x = minx; x < maxx; x++ )
{
index = map->tiles[z + y * MAPLAYERS + x * MAPLAYERS * map->height];
if ( index > 0)
{
pos.x = (x << TEXTUREPOWER) - camx;
pos.y = (y << TEXTUREPOWER) - camy;
pos.w = TEXTURESIZE;
pos.h = TEXTURESIZE;
if ( index >= 0 && index < numtiles )
{
if ( tiles[index] != NULL )
{
drawImageScaled(tiles[index], NULL, &pos);
}
else
{
drawImageScaled(sprites[0], NULL, &pos);
}
}
else
{
drawImageScaled(sprites[0], NULL, &pos);
}
}
}
}
}
void drawBackground(long camx, long camy)
{
long z;
for ( z = 0; z < OBSTACLELAYER; z++ )
{
drawLayer(camx, camy, z, &map);
}
}
void drawForeground(long camx, long camy)
{
long z;
for ( z = OBSTACLELAYER; z < MAPLAYERS; z++ )
{
drawLayer(camx, camy, z, &map);
}
}
/*-------------------------------------------------------------------------------
drawClearBuffers
clears the screen and resets zbuffer and vismap
-------------------------------------------------------------------------------*/
void drawClearBuffers()
{
// empty video and input buffers
if ( zbuffer != NULL )
{
memset( zbuffer, 0, xres * yres * sizeof(real_t) );
}
if ( clickmap != NULL )
{
memset( clickmap, 0, xres * yres * sizeof(Entity*) );
}
if ( vismap != NULL )
{
int c, i = map.width * map.height;
for ( c = 0; c < i; c++ )
{
vismap[c] = false;
}
}
// clear the screen
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
drawRect(NULL, 0, 255);
}
/*-------------------------------------------------------------------------------
raycast
Performs raycasting from the given camera's position through the
environment to update minimap and vismap
-------------------------------------------------------------------------------*/
void raycast(view_t* camera, int mode, bool updateVismap)
{
long posx, posy;
real_t fracx, fracy;
long inx, iny, inx2, iny2;
real_t rx, ry;
real_t d, dstart, dend;
long sx;
real_t arx, ary;
long dincx, dincy;
real_t dval0, dval1;
Uint8 light;
Sint32 z;
bool zhit[MAPLAYERS], wallhit;
posx = floor(camera->x);
posy = floor(camera->y); // integer coordinates
fracx = camera->x - posx;
fracy = camera->y - posy; // fraction coordinates
real_t wfov = (fov * camera->winw / camera->winh) * PI / 180.f;
dstart = CLIPNEAR / 16.0;
// ray vector
rx = cos(camera->ang - wfov / 2.f);
ry = sin(camera->ang - wfov / 2.f);
if ( updateVismap && posx >= 0 && posy >= 0 && posx < map.width && posy < map.height )
{
vismap[posy + posx * map.height] = true;
}
for ( sx = 0; sx < camera->winw; sx++ ) // for every column of the screen
{
inx = posx;
iny = posy;
inx2 = inx;
iny2 = iny;
arx = 0;
if (rx)
{
arx = 1.0 / fabs(rx); // distance increments
}
ary = 0;
if (ry)
{
ary = 1.0 / fabs(ry);
}
// dval0=dend+1 is there to prevent infinite loops when ray is parallel to axis
dincx = 0;
dval0 = 1e32;
dincy = 0;
dval1 = 1e32;
// calculate integer coordinate increments
// x-axis:
if (rx < 0)
{
dincx = -1;
dval0 = fracx * arx;
}
else if (rx > 0)
{
dincx = 1;
dval0 = (1 - fracx) * arx;
}
// y-axis:
if (ry < 0)
{
dincy = -1;
dval1 = fracy * ary;
}
else if (ry > 0)
{
dincy = 1;
dval1 = (1 - fracy) * ary;
}
d = 0;
dend = CLIPFAR / 16;
do
{
inx2 = inx;
iny2 = iny;
// move the ray one square forward
if (dval1 > dval0)
{
inx += dincx;
d = dval0;
dval0 += arx;
}
else
{
iny += dincy;
d = dval1;
dval1 += ary;
}
if ( inx >= 0 && iny >= 0 && inx < map.width && iny < map.height )
{
if ( updateVismap )
{
vismap[iny + inx * map.height] = true;
}
for ( z = 0; z < MAPLAYERS; z++ )
{
zhit[z] = false;
if ( map.tiles[z + iny * MAPLAYERS + inx * MAPLAYERS * map.height] && d > dstart ) // hit something solid
{
zhit[z] = true;
// collect light information
if ( inx2 >= 0 && iny2 >= 0 && inx2 < map.width && iny2 < map.height )
{
if ( map.tiles[z + iny2 * MAPLAYERS + inx2 * MAPLAYERS * map.height] )
{
continue;
}
light = std::min(std::max(0, lightmap[iny2 + inx2 * map.height]), 255);
}
else
{
light = 128;
}
// update minimap
if ( mode == REALCOLORS )
if ( d < 16 && z == OBSTACLELAYER )
if ( light > 0 )
{
minimap[iny][inx] = 2; // wall space
}
}
else if ( z == OBSTACLELAYER && mode == REALCOLORS )
{
// update minimap to show empty region
if ( inx >= 0 && iny >= 0 && inx < map.width && iny < map.height )
{
light = std::min(std::max(0, lightmap[iny + inx * map.height]), 255);
}
else
{
light = 128;
}
if ( d < 16 )
{
if ( light > 0 && map.tiles[iny * MAPLAYERS + inx * MAPLAYERS * map.height] )
{
minimap[iny][inx] = 1; // walkable space
}
else if ( map.tiles[z + iny * MAPLAYERS + inx * MAPLAYERS * map.height] )
{
minimap[iny][inx] = 0; // no floor
}
}
}
}
wallhit = true;
for ( z = 0; z < MAPLAYERS; z++ )
if ( zhit[z] == false )
{
wallhit = false;
}
if ( wallhit == true )
{
break;
}
}
}
while (d < dend);
// new ray vector for next column
rx = cos(camera->ang - wfov / 2.f + (wfov / camera->winw) * sx);
ry = sin(camera->ang - wfov / 2.f + (wfov / camera->winw) * sx);
}
}
/*-------------------------------------------------------------------------------
drawEntities3D
Draws all entities in the level as either voxel models or sprites
-------------------------------------------------------------------------------*/
void drawEntities3D(view_t* camera, int mode)
{
node_t* node;
Entity* entity;
long x, y;
if ( map.entities->first == nullptr )
{
return;
}
glEnable(GL_SCISSOR_TEST);
glScissor(camera->winx, yres - camera->winh - camera->winy, camera->winw, camera->winh);
node_t* nextnode = nullptr;
for ( node = map.entities->first; node != nullptr; node = nextnode )
{
entity = (Entity*)node->element;
nextnode = node->next;
if ( node->next == nullptr && node->list == map.entities )
{
if ( map.worldUI->first )
{
// quick way to attach worldUI to the end of map.entities.
nextnode = map.worldUI->first;
}
}
if ( entity->flags[INVISIBLE] )
{
continue;
}
if ( entity->flags[UNCLICKABLE] && mode == ENTITYUIDS )
{
continue;
}
if ( entity->flags[GENIUS] )
{
// genius entities are not drawn when the camera is inside their bounding box
if ( camera->x >= (entity->x - entity->sizex) / 16 && camera->x <= (entity->x + entity->sizex) / 16 )
if ( camera->y >= (entity->y - entity->sizey) / 16 && camera->y <= (entity->y + entity->sizey) / 16 )
{
continue;
}
}
if ( entity->flags[OVERDRAW] && splitscreen )
{
// need to skip some HUD models in splitscreen.
int currentPlayerViewport = -1;
for ( int c = 0; c < MAXPLAYERS; ++c )
{
if ( &cameras[c] == camera )
{
currentPlayerViewport = c;
break;
}
}
if ( currentPlayerViewport >= 0 )
{
if ( entity->behavior == &actHudWeapon
|| entity->behavior == &actHudArm
|| entity->behavior == &actGib
|| entity->behavior == &actFlame )
{
// the gibs are from casting magic in the HUD
if ( entity->skill[11] != currentPlayerViewport )
{
continue;
}
}
else if ( entity->behavior == &actHudAdditional
|| entity->behavior == &actHudArrowModel
|| entity->behavior == &actHudShield
|| entity->behavior == &actLeftHandMagic
|| entity->behavior == &actRightHandMagic )
{
if ( entity->skill[2] != currentPlayerViewport )
{
continue;
}
}
}
}
x = entity->x / 16;
y = entity->y / 16;
if ( x >= 0 && y >= 0 && x < map.width && y < map.height )
{
if ( vismap[y + x * map.height] || entity->flags[OVERDRAW] || entity->monsterEntityRenderAsTelepath == 1 )
{
if ( entity->flags[SPRITE] == false )
{
glDrawVoxel(camera, entity, mode);
}
else
{
if ( entity->behavior == &actSpriteNametag )
{
int playersTag = playerEntityMatchesUid(entity->parent);
if ( playersTag >= 0 )
{
glDrawSpriteFromImage(camera, entity, stats[playersTag]->name, mode);
}
}
else if ( entity->behavior == &actSpriteWorldTooltip )
{
glDrawWorldUISprite(camera, entity, mode);
}
else
{
glDrawSprite(camera, entity, mode);
}
}
}
}
else
{
if ( entity->flags[SPRITE] == false )
{
glDrawVoxel(camera, entity, mode);
}
else if ( entity->behavior == &actSpriteWorldTooltip )
{
glDrawWorldUISprite(camera, entity, mode);
}
else
{
glDrawSprite(camera, entity, mode);
}
}
}
glDisable(GL_SCISSOR_TEST);
glScissor(0, 0, xres, yres);
}
/*-------------------------------------------------------------------------------
drawEntities2D
Draws all entities in the level as sprites while accounting for the given
camera coordinates
-------------------------------------------------------------------------------*/
void drawEntities2D(long camx, long camy)
{
node_t* node;
Entity* entity;
SDL_Rect pos, box;
int offsetx = 0;
int offsety = 0;
if ( map.entities->first == nullptr )
{
return;
}
// draw entities
for ( node = map.entities->first; node != nullptr; node = node->next )
{
entity = (Entity*)node->element;
if ( entity->flags[INVISIBLE] )
{
continue;
}
pos.x = entity->x * (TEXTURESIZE / 16) - camx;
pos.y = entity->y * (TEXTURESIZE / 16) - camy;
pos.w = TEXTURESIZE;
pos.h = TEXTURESIZE;
//ttfPrintText(ttf8, 100, 100, inputstr); debug any errant text input in editor
if ( entity->sprite >= 0 && entity->sprite < numsprites )
{
if ( sprites[entity->sprite] != nullptr )
{
if ( entity == selectedEntity[0] )
{
// draws a box around the sprite
box.w = TEXTURESIZE;
box.h = TEXTURESIZE;
box.x = pos.x;
box.y = pos.y;
drawRect(&box, SDL_MapRGB(mainsurface->format, 255, 0, 0), 255);
box.w = TEXTURESIZE - 2;
box.h = TEXTURESIZE - 2;
box.x = pos.x + 1;
box.y = pos.y + 1;
drawRect(&box, SDL_MapRGB(mainsurface->format, 0, 0, 255), 255);
}
// if item sprite and the item index is not 0 (NULL), or 1 (RANDOM)
if ( entity->sprite == 8 && entity->skill[10] > 1 )
{
// draw the item sprite in the editor layout
Item* tmpItem = newItem(static_cast<ItemType>(entity->skill[10] - 2), static_cast<Status>(0), 0, 0, 0, 0, nullptr);
drawImageScaled(itemSprite(tmpItem), nullptr, &pos);
free(tmpItem);
}
else if ( entity->sprite == 133 )
{
pos.y += sprites[entity->sprite]->h / 2;
pos.x += sprites[entity->sprite]->w / 2;
switch ( entity->signalInputDirection )
{
case 0:
drawImageRotatedAlpha(sprites[entity->sprite], nullptr, &pos, 0.f, 255);
break;
case 1:
drawImageRotatedAlpha(sprites[entity->sprite], nullptr, &pos, 3 * PI / 2, 255);
break;
case 2:
drawImageRotatedAlpha(sprites[entity->sprite], nullptr, &pos, PI, 255);
break;
case 3:
drawImageRotatedAlpha(sprites[entity->sprite], nullptr, &pos, PI / 2, 255);
break;
}
}
else
{
// draw sprite normally from sprites list
drawImageScaled(sprites[entity->sprite], nullptr, &pos);
}
}
else
{
if ( entity == selectedEntity[0] )
{
// draws a box around the sprite
box.w = TEXTURESIZE;
box.h = TEXTURESIZE;
box.x = pos.x;
box.y = pos.y;
drawRect(&box, SDL_MapRGB(mainsurface->format, 255, 0, 0), 255);
box.w = TEXTURESIZE - 2;
box.h = TEXTURESIZE - 2;
box.x = pos.x + 1;
box.y = pos.y + 1;
drawRect(&box, SDL_MapRGB(mainsurface->format, 0, 0, 255), 255);
}
drawImageScaled(sprites[0], nullptr, &pos);
}
}
else
{
if ( entity == selectedEntity[0] )
{
// draws a box around the sprite
box.w = TEXTURESIZE;
box.h = TEXTURESIZE;
box.x = pos.x;
box.y = pos.y;
drawRect(&box, SDL_MapRGB(mainsurface->format, 255, 0, 0), 255);
box.w = TEXTURESIZE - 2;
box.h = TEXTURESIZE - 2;
box.x = pos.x + 1;
box.y = pos.y + 1;
drawRect(&box, SDL_MapRGB(mainsurface->format, 0, 0, 255), 255);
}
drawImageScaled(sprites[0], nullptr, &pos);
}
}
// draw hover text for entities over the top of sprites.
for ( node = map.entities->first;
node != nullptr
#ifndef NINTENDO
&& (openwindow == 0
&& savewindow == 0)
#endif
;
node = node->next
)
{
entity = (Entity*)node->element;
if ( entity->flags[INVISIBLE] )
{
continue;
}
pos.x = entity->x * (TEXTURESIZE / 16) - camx;
pos.y = entity->y * (TEXTURESIZE / 16) - camy;
pos.w = TEXTURESIZE;
pos.h = TEXTURESIZE;
//ttfPrintText(ttf8, 100, 100, inputstr); debug any errant text input in editor
if ( entity->sprite >= 0 && entity->sprite < numsprites )
{
if ( sprites[entity->sprite] != nullptr )
{
if ( entity == selectedEntity[0] )
{
int spriteType = checkSpriteType(selectedEntity[0]->sprite);
char tmpStr[1024] = "";
char tmpStr2[1024] = "";
int padx = pos.x + 10;
int pady = pos.y - 40;
Uint32 color = SDL_MapRGB(mainsurface->format, 255, 255, 255);
Uint32 colorWhite = SDL_MapRGB(mainsurface->format, 255, 255, 255);
switch ( spriteType )
{
case 1: //monsters
pady += 10;
if ( entity->getStats() != nullptr ) {
strcpy(tmpStr, spriteEditorNameStrings[selectedEntity[0]->sprite]);
ttfPrintText(ttf8, padx, pady - 10, tmpStr);
snprintf(tmpStr, sizeof(entity->getStats()->name), "Name: %s", entity->getStats()->name);
ttfPrintText(ttf8, padx, pady, tmpStr);
snprintf(tmpStr, 10, "HP: %d", entity->getStats()->MAXHP);
ttfPrintText(ttf8, padx, pady + 10, tmpStr);
snprintf(tmpStr, 10, "Level: %d", entity->getStats()->LVL);
ttfPrintText(ttf8, padx, pady + 20, tmpStr);
}
break;
case 2: //chest
pady += 5;
strcpy(tmpStr, spriteEditorNameStrings[selectedEntity[0]->sprite]);
ttfPrintText(ttf8, padx, pady, tmpStr);
switch ( (int)entity->yaw )
{
case 0:
strcpy(tmpStr, "Facing: EAST");
break;
case 1:
strcpy(tmpStr, "Facing: SOUTH");
break;
case 2:
strcpy(tmpStr, "Facing: WEST");
break;
case 3:
strcpy(tmpStr, "Facing: NORTH");
break;
default:
strcpy(tmpStr, "Facing: Invalid");
break;
}
ttfPrintText(ttf8, padx, pady + 10, tmpStr);
switch ( entity->skill[9] )
{
case 0:
strcpy(tmpStr, "Type: Random");
break;
case 1:
strcpy(tmpStr, "Type: Garbage");
break;
case 2:
strcpy(tmpStr, "Type: Food");
break;
case 3:
strcpy(tmpStr, "Type: Jewelry");
break;
case 4:
strcpy(tmpStr, "Type: Equipment");
break;
case 5:
strcpy(tmpStr, "Type: Tools");
break;
case 6:
strcpy(tmpStr, "Type: Magical");
break;
case 7:
strcpy(tmpStr, "Type: Potions");
break;
case 8:
strcpy(tmpStr, "Type: Empty");
break;
default:
strcpy(tmpStr, "Type: Random");
break;
}
ttfPrintText(ttf8, padx, pady + 20, tmpStr);
break;
case 3: //Items
pady += 5;
strcpy(tmpStr, itemNameStrings[selectedEntity[0]->skill[10]]);
ttfPrintText(ttf8, padx, pady - 20, tmpStr);
color = SDL_MapRGB(mainsurface->format, 255, 255, 255);
pady += 2;
strcpy(tmpStr, "Status: ");
ttfPrintTextColor(ttf8, padx, pady - 10, colorWhite, 1, tmpStr);
switch ( (int)selectedEntity[0]->skill[11] )
{
case 1:
strcpy(tmpStr, "Broken");
color = SDL_MapRGB(mainsurface->format, 255, 0, 0);
break;
case 2:
strcpy(tmpStr, "Decrepit");
color = SDL_MapRGB(mainsurface->format, 200, 128, 0);
break;
case 3:
strcpy(tmpStr, "Worn");
color = SDL_MapRGB(mainsurface->format, 255, 255, 0);
break;
case 4:
strcpy(tmpStr, "Servicable");
color = SDL_MapRGB(mainsurface->format, 128, 200, 0);
break;
case 5:
strcpy(tmpStr, "Excellent");
color = SDL_MapRGB(mainsurface->format, 0, 255, 0);
break;
default:
strcpy(tmpStr, "?");
color = SDL_MapRGB(mainsurface->format, 0, 168, 255);
break;
}
ttfPrintTextColor(ttf8, padx + 56, pady - 10, color, 1, tmpStr);
strcpy(tmpStr, "Bless: ");
ttfPrintTextColor(ttf8, padx, pady, colorWhite, 1, tmpStr);
if ( selectedEntity[0]->skill[12] < 0 )
{
snprintf(tmpStr2, 10, "%d", selectedEntity[0]->skill[12]);
color = SDL_MapRGB(mainsurface->format, 255, 0, 0);
}
else if ( selectedEntity[0]->skill[12] == 0 )
{
snprintf(tmpStr2, 10, "%d", selectedEntity[0]->skill[12]);
color = SDL_MapRGB(mainsurface->format, 255, 255, 255);
}
else if ( selectedEntity[0]->skill[12] == 10 )
{
strcpy(tmpStr2, "?");
color = SDL_MapRGB(mainsurface->format, 0, 168, 255);
}
else
{
snprintf(tmpStr2, 10, "+%d", selectedEntity[0]->skill[12]);
color = SDL_MapRGB(mainsurface->format, 0, 255, 0);
}
ttfPrintTextColor(ttf8, padx + 48, pady, color, 1, tmpStr2);
strcpy(tmpStr, "Qty: ");
ttfPrintTextColor(ttf8, padx, pady + 10, colorWhite, 1, tmpStr);
snprintf(tmpStr2, 10, "%d", selectedEntity[0]->skill[13]);
ttfPrintTextColor(ttf8, padx + 32, pady + 10, colorWhite, 1, tmpStr2);
pady += 2;
strcpy(tmpStr, "Identified: ");
ttfPrintTextColor(ttf8, padx, pady + 20, colorWhite, 1, tmpStr);
if ( (int)selectedEntity[0]->skill[15] == 0 )
{
strcpy(tmpStr2, "No");
color = SDL_MapRGB(mainsurface->format, 255, 255, 0);
}
else if ( (int)selectedEntity[0]->skill[15] == 1 )
{
strcpy(tmpStr2, "Yes");
color = SDL_MapRGB(mainsurface->format, 0, 255, 0);
}
else
{
strcpy(tmpStr2, "?");
color = SDL_MapRGB(mainsurface->format, 0, 168, 255);
}
ttfPrintTextColor(ttf8, padx + 80, pady + 20, color, 1, tmpStr2);
break;
case 4: //summoning trap
pady += 5;
offsety = -40;
strcpy(tmpStr, spriteEditorNameStrings[selectedEntity[0]->sprite]);
ttfPrintText(ttf8, padx, pady + offsety, tmpStr);
offsety += 10;
strcpy(tmpStr, "Type: ");
offsetx = strlen(tmpStr) * 8 - 8;
ttfPrintTextColor(ttf8, padx, pady + offsety, colorWhite, 1, tmpStr);
strcpy(tmpStr2, monsterEditorNameStrings[entity->skill[0]]);
ttfPrintText(ttf8, padx + offsetx, pady + offsety, tmpStr2);
offsety += 10;
strcpy(tmpStr, "Qty: ");
offsetx = strlen(tmpStr) * 8 - 8;
ttfPrintTextColor(ttf8, padx, pady + offsety, colorWhite, 1, tmpStr);
snprintf(tmpStr2, 10, "%d", selectedEntity[0]->skill[1]);
ttfPrintText(ttf8, padx + offsetx, pady + offsety, tmpStr2);
offsety += 10;
strcpy(tmpStr, "Time: ");
offsetx = strlen(tmpStr) * 8 - 8;
ttfPrintTextColor(ttf8, padx, pady + offsety, colorWhite, 1, tmpStr);
snprintf(tmpStr2, 10, "%d", selectedEntity[0]->skill[2]);
ttfPrintText(ttf8, padx + offsetx, pady + offsety, tmpStr2);
offsety += 10;
strcpy(tmpStr, "Amount: ");
offsetx = strlen(tmpStr) * 8 - 8;
ttfPrintTextColor(ttf8, padx, pady + offsety, colorWhite, 1, tmpStr);
snprintf(tmpStr2, 10, "%d", selectedEntity[0]->skill[3]);
ttfPrintText(ttf8, padx + offsetx, pady + offsety, tmpStr2);
offsety += 10;
strcpy(tmpStr, "Power to: ");
offsetx = strlen(tmpStr) * 8 - 8;
ttfPrintTextColor(ttf8, padx, pady + offsety, colorWhite, 1, tmpStr);
if ( selectedEntity[0]->skill[4] == 1 )
{
strcpy(tmpStr2, "Spawn");
}
else
{
strcpy(tmpStr2, "Disable");
}
ttfPrintText(ttf8, padx + offsetx, pady + offsety, tmpStr2);
offsety += 10;
strcpy(tmpStr, "Stop Chance: ");
offsetx = strlen(tmpStr) * 8 - 8;
ttfPrintTextColor(ttf8, padx, pady + offsety, colorWhite, 1, tmpStr);
snprintf(tmpStr2, 10, "%d", selectedEntity[0]->skill[5]);
ttfPrintText(ttf8, padx + offsetx, pady + offsety, tmpStr2);
break;
case 5: //power crystal
pady += 5;
offsety = -20;
strcpy(tmpStr, spriteEditorNameStrings[selectedEntity[0]->sprite]);
ttfPrintText(ttf8, padx, pady + offsety, tmpStr);
offsety += 10;
strcpy(tmpStr, "Facing: ");
ttfPrintText(ttf8, padx, pady + offsety, tmpStr);
offsetx = strlen(tmpStr) * 8 - 8;
switch ( (int)entity->yaw )
{
case 0:
strcpy(tmpStr2, "EAST");
break;
case 1:
strcpy(tmpStr2, "SOUTH");
break;
case 2:
strcpy(tmpStr2, "WEST");
break;
case 3:
strcpy(tmpStr2, "NORTH");
break;
default:
strcpy(tmpStr2, "Invalid");
break;
}
ttfPrintText(ttf8, padx + offsetx, pady + offsety, tmpStr2);
offsety += 10;
strcpy(tmpStr, "Nodes: ");
offsetx = strlen(tmpStr) * 8 - 8;
ttfPrintTextColor(ttf8, padx, pady + offsety, colorWhite, 1, tmpStr);
snprintf(tmpStr2, 10, "%d", selectedEntity[0]->crystalNumElectricityNodes);
ttfPrintText(ttf8, padx + offsetx, pady + offsety, tmpStr2);
offsety += 10;
strcpy(tmpStr, "Rotation: ");
offsetx = strlen(tmpStr) * 8 - 8;
ttfPrintTextColor(ttf8, padx, pady + offsety, colorWhite, 1, tmpStr);
switch ( (int)entity->crystalTurnReverse )
{
case 0:
strcpy(tmpStr2, "Clockwise");
break;
case 1:
strcpy(tmpStr2, "Anti-Clockwise");
break;
default:
strcpy(tmpStr2, "Invalid");
break;
}
ttfPrintText(ttf8, padx + offsetx, pady + offsety, tmpStr2);
offsety += 10;
strcpy(tmpStr, "Spell to Activate: ");
offsetx = strlen(tmpStr) * 8 - 8;
ttfPrintTextColor(ttf8, padx, pady + offsety, colorWhite, 1, tmpStr);
switch ( (int)entity->crystalSpellToActivate )
{
case 0:
strcpy(tmpStr2, "No");
break;
case 1:
strcpy(tmpStr2, "Yes");
break;
default:
strcpy(tmpStr2, "Invalid");
break;
}
ttfPrintText(ttf8, padx + offsetx, pady + offsety, tmpStr2);
break;
case 16:
case 13:
{
char buf[256] = "";
int totalChars = 0;
for ( int i = (spriteType == 16 ? 4 : 8); i < 60; ++i )
{
if ( selectedEntity[0]->skill[i] != 0 && i != 28 ) // skill[28] is circuit status.
{
for ( int c = 0; c < 4; ++c )
{
if ( static_cast<char>((selectedEntity[0]->skill[i] >> (c * 8)) & 0xFF) == '\0'
&& i != 59 && selectedEntity[0]->skill[i + 1] != 0 )
{
// don't add '\0' termination unless the next skill slot is empty as we have more data to read.
}
else
{
buf[totalChars] = static_cast<char>((selectedEntity[0]->skill[i] >> (c * 8)) & 0xFF);
++totalChars;
}
}
}
}
if ( buf[totalChars] != '\0' )
{
buf[totalChars] = '\0';
}
int numLines = 0;
std::vector<std::string> lines;
lines.push_back(spriteEditorNameStrings[selectedEntity[0]->sprite]);
strncpy(tmpStr, buf, 48);
if ( strcmp(tmpStr, "") )
{
lines.push_back(tmpStr);
}
strncpy(tmpStr, buf + 48, 48);
if ( strcmp(tmpStr, "") )
{
lines.push_back(tmpStr);
}
strncpy(tmpStr, buf + 96, 48);
if ( strcmp(tmpStr, "") )
{
lines.push_back(tmpStr);
}
strncpy(tmpStr, buf + 144, 48);
if ( strcmp(tmpStr, "") )
{
lines.push_back(tmpStr);
}
strncpy(tmpStr, buf + 192, 48);
if ( strcmp(tmpStr, "") )
{
lines.push_back(tmpStr);
}
if ( lines.size() > 3 )
{
offsety -= (lines.size() - 2) * 5;
}
size_t longestLine = 0;
for ( auto it : lines )
{
longestLine = std::max(longestLine, strlen(it.c_str()));
}
SDL_Rect tooltip;
tooltip.x = padx + offsetx - 4;
tooltip.w = TTF8_WIDTH * longestLine + 8;
tooltip.y = pady + offsety - 4;
tooltip.h = lines.size() * TTF8_HEIGHT + 8;
if ( lines.size() > 1 )
{
drawTooltip(&tooltip);
}
for ( auto it : lines )
{
ttfPrintText(ttf8, padx + offsetx, pady + offsety, it.c_str());
offsety += 10;
}
}
break;
default:
strcpy(tmpStr, spriteEditorNameStrings[selectedEntity[0]->sprite]);
ttfPrintText(ttf8, padx, pady + 20, tmpStr);
break;
}
}
else if ( (omousex / TEXTURESIZE) * 32 == pos.x
&& (omousey / TEXTURESIZE) * 32 == pos.y
&& selectedEntity[0] == NULL
#ifndef NINTENDO
&& hovertext
#endif
)
{
// handle mouseover sprite name tooltip in main editor screen
int padx = pos.x + 10;
int pady = pos.y - 20;
int spriteType = checkSpriteType(entity->sprite);
//offsety = 0;
Stat* tmpStats = nullptr;
if ( spriteType == 1 )
{
tmpStats = entity->getStats();
if ( tmpStats != nullptr )
{
if ( strcmp(tmpStats->name, "") != 0 )
{
ttfPrintText(ttf8, padx, pady - offsety, tmpStats->name);
offsety += 10;
}
ttfPrintText(ttf8, padx, pady - offsety, spriteEditorNameStrings[entity->sprite]);
offsety += 10;
}
}
else if ( spriteType == 3 )
{
ttfPrintText(ttf8, padx, pady - offsety, itemNameStrings[entity->skill[10]]);
offsety += 10;
}
else
{
ttfPrintText(ttf8, padx, pady - offsety, spriteEditorNameStrings[entity->sprite]);
offsety += 10;
}
}
}
}
}
}
/*-------------------------------------------------------------------------------
drawGrid
Draws a white line grid for the tile map
-------------------------------------------------------------------------------*/
void drawGrid(long camx, long camy)
{
long x, y;
Uint32 color;
color = SDL_MapRGB(mainsurface->format, 127, 127, 127);
drawLine(-camx, (map.height << TEXTUREPOWER) - camy, (map.width << TEXTUREPOWER) - camx, (map.height << TEXTUREPOWER) - camy, color, 255);
drawLine((map.width << TEXTUREPOWER) - camx, -camy, (map.width << TEXTUREPOWER) - camx, (map.height << TEXTUREPOWER) - camy, color, 255);
for ( y = 0; y < map.height; y++ )
{
for ( x = 0; x < map.width; x++ )
{
drawLine((x << TEXTUREPOWER) - camx, (y << TEXTUREPOWER) - camy, ((x + 1) << TEXTUREPOWER) - camx, (y << TEXTUREPOWER) - camy, color, 255);
drawLine((x << TEXTUREPOWER) - camx, (y << TEXTUREPOWER) - camy, (x << TEXTUREPOWER) - camx, ((y + 1) << TEXTUREPOWER) - camy, color, 255);
}
}
}
/*-------------------------------------------------------------------------------
drawEditormap
Draws a minimap in the upper right corner of the screen to represent
the screen's position relative to the rest of the level
-------------------------------------------------------------------------------*/
void drawEditormap(long camx, long camy)
{
SDL_Rect src, osrc;
src.x = xres - 120;
src.y = 24;
src.w = 112;
src.h = 112;
drawRect(&src, SDL_MapRGB(mainsurface->format, 0, 0, 0), 255);
// initial box dimensions
src.x = (xres - 120) + (((real_t)camx / TEXTURESIZE) * 112.0) / map.width;
src.y = 24 + (((real_t)camy / TEXTURESIZE) * 112.0) / map.height;
src.w = (112.0 / map.width) * ((real_t)xres / TEXTURESIZE);
src.h = (112.0 / map.height) * ((real_t)yres / TEXTURESIZE);
// clip at left edge
if ( src.x < xres - 120 )
{
src.w -= (xres - 120) - src.x;
src.x = xres - 120;
}
// clip at right edge
if ( src.x + src.w > xres - 8 )
{
src.w = xres - 8 - src.x;
}
// clip at top edge
if ( src.y < 24 )
{
src.h -= 24 - src.y;
src.y = 24;
}
// clip at bottom edge
if ( src.y + src.h > 136 )
{
src.h = 136 - src.y;
}
osrc.x = src.x + 1;
osrc.y = src.y + 1;
osrc.w = src.w - 2;
osrc.h = src.h - 2;
drawRect(&src, SDL_MapRGB(mainsurface->format, 255, 255, 255), 255);
drawRect(&osrc, SDL_MapRGB(mainsurface->format, 0, 0, 0), 255);
}
/*-------------------------------------------------------------------------------
drawWindow / drawDepressed
Draws a rectangular box that fills the area inside the given screen
coordinates
-------------------------------------------------------------------------------*/
void drawWindow(int x1, int y1, int x2, int y2)
{
SDL_Rect src;
src.x = x1;
src.y = y1;
src.w = x2 - x1;
src.h = y2 - y1;
drawRect(&src, SDL_MapRGB(mainsurface->format, 160, 160, 192), 255);
src.x = x1 + 1;
src.y = y1 + 1;
src.w = x2 - x1 - 1;
src.h = y2 - y1 - 1;
drawRect(&src, SDL_MapRGB(mainsurface->format, 96, 96, 128), 255);
src.x = x1 + 1;
src.y = y1 + 1;
src.w = x2 - x1 - 2;
src.h = y2 - y1 - 2;
drawRect(&src, SDL_MapRGB(mainsurface->format, 128, 128, 160), 255);
}
void drawDepressed(int x1, int y1, int x2, int y2)
{
SDL_Rect src;
src.x = x1;
src.y = y1;
src.w = x2 - x1;
src.h = y2 - y1;
drawRect(&src, SDL_MapRGB(mainsurface->format, 96, 96, 128), 255);
src.x = x1 + 1;
src.y = y1 + 1;
src.w = x2 - x1 - 1;
src.h = y2 - y1 - 1;
drawRect(&src, SDL_MapRGB(mainsurface->format, 160, 160, 192), 255);
src.x = x1 + 1;
src.y = y1 + 1;
src.w = x2 - x1 - 2;
src.h = y2 - y1 - 2;
drawRect(&src, SDL_MapRGB(mainsurface->format, 128, 128, 160), 255);
}
void drawWindowFancy(int x1, int y1, int x2, int y2)
{
if (softwaremode)
{
// no fancy stuff in software mode
drawWindow(x1, y1, x2, y2);
return;
}
// update projection
glDisable(GL_DEPTH_TEST);
glDisable(GL_LIGHTING);
glMatrixMode(GL_PROJECTION);
glViewport(0, 0, xres, yres);
glLoadIdentity();
glOrtho(0, xres, 0, yres, -1, 1);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_BLEND);
// draw quads
glColor3f(.25, .25, .25);
glBindTexture(GL_TEXTURE_2D, 0);
glBegin(GL_QUADS);
glVertex2f(x1, yres - y1);
glVertex2f(x1, yres - y2);
glVertex2f(x2, yres - y2);
glVertex2f(x2, yres - y1);
glEnd();
glColor3f(.5, .5, .5);
glBindTexture(GL_TEXTURE_2D, 0);
glBegin(GL_QUADS);
glVertex2f(x1 + 1, yres - y1 - 1);
glVertex2f(x1 + 1, yres - y2 + 1);
glVertex2f(x2 - 1, yres - y2 + 1);
glVertex2f(x2 - 1, yres - y1 - 1);
glEnd();
glColor3f(.75, .75, .75);
glBindTexture(GL_TEXTURE_2D, texid[fancyWindow_bmp->refcount]); // wood texture
glBegin(GL_QUADS);
glTexCoord2f(0, 0);
glVertex2f(x1 + 2, yres - y1 - 2);
glTexCoord2f(0, (y2 - y1 - 4) / (real_t)tiles[30]->h);
glVertex2f(x1 + 2, yres - y2 + 2);
glTexCoord2f((x2 - x1 - 4) / (real_t)tiles[30]->w, (y2 - y1 - 4) / (real_t)tiles[30]->h);
glVertex2f(x2 - 2, yres - y2 + 2);
glTexCoord2f((x2 - x1 - 4) / (real_t)tiles[30]->w, 0);
glVertex2f(x2 - 2, yres - y1 - 2);
glEnd();
}
/*-------------------------------------------------------------------------------
ttfPrintText / ttfPrintTextColor
Prints an unformatted utf8 string to the screen, returning the width of
the message surface in pixels. ttfPrintTextColor() also takes a 32-bit
color argument
-------------------------------------------------------------------------------*/
SDL_Rect errorRect = { 0 };
SDL_Rect ttfPrintTextColor( TTF_Font* font, int x, int y, Uint32 color, bool outline, const char* str )
{
#ifdef NINTENDO
if (font == ttf8)
{
printTextFormattedColor(font8x8_bmp, x, y, color, const_cast<char*>(str));
}
if (font == ttf12)
{
printTextFormattedColor(font12x12_bmp, x, y, color, const_cast<char*>(str));
}
if (font == ttf16)
{
printTextFormattedColor(font16x16_bmp, x, y, color, const_cast<char*>(str));
}
return errorRect;
#endif
SDL_Rect pos = { x, y, 0, 0 };
SDL_Surface* surf;
int c;
if ( !str )
{
return errorRect;
}
char newStr[1024] = { 0 };
strcpy(newStr, str);
// tokenize string
for ( c = 0; c < strlen(newStr) + 1; c++ )
{
if ( newStr[c] == '\n' || newStr[c] == '\r' )
{
int offY = 0;
if ( newStr[c] == '\n' )
{
offY = getHeightOfFont(font);
}
newStr[c] = 0;
ttfPrintTextColor(font, x, y + offY, color, outline, (char*)&newStr[c + 1]);
break;
}
else if ( newStr[c] == 0 )
{
break;
}
}
if ( imgref > ttfTextCacheLimit )
{
// time to flush the cache.
imgref -= 6144;
for ( int i = 0; i < HASH_SIZE; ++i )
{
list_FreeAll(&ttfTextHash[i]);
}
printlog("notice: stored hash limit exceeded, clearing ttfTextHash...");
}
// retrieve text surface
if ( (surf = ttfTextHashRetrieve(ttfTextHash, newStr, font, outline)) == NULL )
{
// create the text outline surface
if ( outline )
{
if ( font == ttf8 )
{
TTF_SetFontOutline(font, 1);
}
else
{
TTF_SetFontOutline(font, 2);
}
SDL_Color sdlColorBlack = { 0, 0, 0, 255 };
surf = TTF_RenderUTF8_Blended(font, newStr, sdlColorBlack);
}
else
{
int w, h;
getSizeOfText(font, newStr, &w, &h);
if ( font == ttf8 )
{
surf = SDL_CreateRGBSurface(0, w + 2, h + 2,
mainsurface->format->BitsPerPixel,
mainsurface->format->Rmask,
mainsurface->format->Gmask,
mainsurface->format->Bmask,
mainsurface->format->Amask
);
}
else
{
surf = SDL_CreateRGBSurface(0, w + 4, h + 4,
mainsurface->format->BitsPerPixel,
mainsurface->format->Rmask,
mainsurface->format->Gmask,
mainsurface->format->Bmask,
mainsurface->format->Amask
);
}
}
if (!surf)
{
printlog("warning: failed to create the surface\n");
return errorRect;
}
// create the text surface
TTF_SetFontOutline(font, 0);
SDL_Color sdlColorWhite = { 255, 255, 255, 255 };
SDL_Surface* textSurf = TTF_RenderUTF8_Blended(font, newStr, sdlColorWhite);
// combine the surfaces
if ( font == ttf8 )
{
pos.x = 1;
pos.y = 1;
}
else
{
pos.x = 2;
pos.y = 2;
}
SDL_BlitSurface(textSurf, NULL, surf, &pos);
SDL_FreeSurface(textSurf);
// load the text outline surface as a GL texture
allsurfaces[imgref] = surf;
allsurfaces[imgref]->refcount = imgref;
glLoadTexture(allsurfaces[imgref], imgref);
imgref++;
// store the surface in the text surface cache
if ( !ttfTextHashStore(ttfTextHash, newStr, font, outline, surf) )
{
printlog("warning: failed to store text outline surface with imgref %d\n", imgref - 1);
}
}
// draw the text surface
if ( font == ttf8 )
{
pos.x = x;
pos.y = y - 3;
}
else
{
pos.x = x + 1;
pos.y = y - 4;
}
pos.w = surf->w;
pos.h = surf->h;
drawImageColor(surf, NULL, &pos, color);
pos.x = x;
pos.y = y;
return pos;
}
SDL_Rect ttfPrintText( TTF_Font* font, int x, int y, const char* str )
{
if ( !str )
{
return errorRect;
}
return ttfPrintTextColor(font, x, y, 0xFFFFFFFF, true, str);
}
/*-------------------------------------------------------------------------------
ttfPrintTextFormatted / ttfPrintTextFormattedColor
Prints a formatted utf8 string to the screen using
ttfPrintText / ttfPrintTextColor
-------------------------------------------------------------------------------*/
SDL_Rect ttfPrintTextFormattedColor( TTF_Font* font, int x, int y, Uint32 color, char const * const fmt, ... )
{
char str[1024] = { 0 };
if ( !fmt )
{
return errorRect;
}
// format the string
va_list argptr;
va_start( argptr, fmt );
vsnprintf( str, 1023, fmt, argptr );
va_end( argptr );
// print the text
return ttfPrintTextColor(font, x, y, color, true, str);
}
SDL_Rect ttfPrintTextFormatted( TTF_Font* font, int x, int y, char const * const fmt, ... )
{
char str[1024] = { 0 };
if ( !fmt )
{
return errorRect;
}
// format the string
va_list argptr;
va_start( argptr, fmt );
vsnprintf( str, 1023, fmt, argptr );
va_end( argptr );
// print the text
return ttfPrintTextColor(font, x, y, 0xFFFFFFFF, true, str);
}
/*-------------------------------------------------------------------------------
printText
Prints unformatted text to the screen using a font bitmap
-------------------------------------------------------------------------------*/
void printText( SDL_Surface* font_bmp, int x, int y, const char* str )
{
int c;
int numbytes;
SDL_Rect src, dest, odest;
if ( strlen(str) > 2048 )
{
printlog("error: buffer overflow in printText\n");
return;
}
// format the string
numbytes = strlen(str);
// define font dimensions
dest.x = x;
dest.y = y;
dest.w = font_bmp->w / 16;
src.w = font_bmp->w / 16;
dest.h = font_bmp->h / 16;
src.h = font_bmp->h / 16;
// print the characters in the string
for ( c = 0; c < numbytes; c++ )
{
src.x = (str[c] * src.w) % font_bmp->w;
src.y = (int)((str[c] * src.w) / font_bmp->w) * src.h;
if ( str[c] != 10 && str[c] != 13 ) // LF/CR
{
odest.x = dest.x;
odest.y = dest.y;
drawImage( font_bmp, &src, &dest );
dest.x = odest.x + src.w;
dest.y = odest.y;
}
else if ( str[c] == 10 )
{
dest.x = x;
dest.y += src.h;
}
}
}
/*-------------------------------------------------------------------------------
printTextFormatted
Prints formatted text to the screen using a font bitmap
-------------------------------------------------------------------------------*/
void printTextFormatted( SDL_Surface* font_bmp, int x, int y, char const * const fmt, ... )
{
int c;
int numbytes;
char str[1024] = { 0 };
va_list argptr;
SDL_Rect src, dest, odest;
// format the string
va_start( argptr, fmt );
numbytes = vsnprintf( str, 1023, fmt, argptr );
va_end( argptr );
// define font dimensions
dest.x = x;
dest.y = y;
dest.w = font_bmp->w / 16;
src.w = font_bmp->w / 16;
dest.h = font_bmp->h / 16;
src.h = font_bmp->h / 16;
// print the characters in the string
for ( c = 0; c < numbytes; c++ )
{
src.x = (str[c] * src.w) % font_bmp->w;
src.y = (int)((str[c] * src.w) / font_bmp->w) * src.h;
if ( str[c] != 10 && str[c] != 13 ) // LF/CR
{
odest.x = dest.x;
odest.y = dest.y;
drawImage( font_bmp, &src, &dest );
dest.x = odest.x + src.w;
dest.y = odest.y;
}
else if ( str[c] == 10 )
{
dest.x = x;
dest.y += src.h;
}
}
}
/*-------------------------------------------------------------------------------
printTextFormattedAlpha
Prints formatted text to the screen using a font bitmap and taking an
alpha value.
-------------------------------------------------------------------------------*/
void printTextFormattedAlpha(SDL_Surface* font_bmp, int x, int y, Uint8 alpha, char const * const fmt, ...)
{
int c;
int numbytes;
char str[1024] = { 0 };
va_list argptr;
SDL_Rect src, dest, odest;
// format the string
va_start( argptr, fmt );
numbytes = vsnprintf( str, 1023, fmt, argptr );
va_end( argptr );
// define font dimensions
dest.x = x;
dest.y = y;
dest.w = font_bmp->w / 16;
src.w = font_bmp->w / 16;
dest.h = font_bmp->h / 16;
src.h = font_bmp->h / 16;
// print the characters in the string
for ( c = 0; c < numbytes; c++ )
{
src.x = (str[c] * src.w) % font_bmp->w;
src.y = (int)((str[c] * src.w) / font_bmp->w) * src.h;
if ( str[c] != 10 && str[c] != 13 ) // LF/CR
{
odest.x = dest.x;
odest.y = dest.y;
drawImageAlpha( font_bmp, &src, &dest, alpha );
dest.x = odest.x + src.w;
dest.y = odest.y;
}
else if ( str[c] == 10 )
{
dest.x = x;
dest.y += src.h;
}
}
}
/*-------------------------------------------------------------------------------
printTextFormattedColor
Prints formatted text to the screen using a font bitmap and taking a
32-bit color value
-------------------------------------------------------------------------------*/
void printTextFormattedColor(SDL_Surface* font_bmp, int x, int y, Uint32 color, char const * const fmt, ...)
{
int c;
int numbytes;
char str[1024] = { 0 };
va_list argptr;
SDL_Rect src, dest, odest;
// format the string
va_start( argptr, fmt );
numbytes = vsnprintf( str, 1023, fmt, argptr );
va_end( argptr );
// define font dimensions
dest.x = x;
dest.y = y;
dest.w = font_bmp->w / 16;
src.w = font_bmp->w / 16;
dest.h = font_bmp->h / 16;
src.h = font_bmp->h / 16;
// print the characters in the string
for ( c = 0; c < numbytes; c++ )
{
src.x = (str[c] * src.w) % font_bmp->w;
src.y = (int)((str[c] * src.w) / font_bmp->w) * src.h;
if ( str[c] != 10 && str[c] != 13 ) // LF/CR
{
odest.x = dest.x;
odest.y = dest.y;
drawImageColor( font_bmp, &src, &dest, color );
dest.x = odest.x + src.w;
dest.y = odest.y;
}
else if ( str[c] == 10 )
{
dest.x = x;
dest.y += src.h;
}
}
}
/*-------------------------------------------------------------------------------
printTextFormattedColor
Prints formatted text to the screen using a font bitmap, while coloring,
rotating, and scaling it
-------------------------------------------------------------------------------*/
void printTextFormattedFancy(SDL_Surface* font_bmp, int x, int y, Uint32 color, real_t angle, real_t scale, char* fmt, ...)
{
int c;
int numbytes;
char str[1024] = { 0 };
va_list argptr;
SDL_Rect src, dest;
// format the string
va_start( argptr, fmt );
numbytes = vsnprintf( str, 1023, fmt, argptr );
va_end( argptr );
// define font dimensions
real_t newX = x;
real_t newY = y;
dest.w = ((real_t)font_bmp->w / 16.f) * scale;
src.w = font_bmp->w / 16;
dest.h = ((real_t)font_bmp->h / 16.f) * scale;
src.h = font_bmp->h / 16;
// print the characters in the string
int line = 0;
for ( c = 0; c < numbytes; c++ )
{
src.x = (str[c] * src.w) % font_bmp->w;
src.y = (int)((str[c] * src.w) / font_bmp->w) * src.h;
if ( str[c] != 10 && str[c] != 13 ) // LF/CR
{
dest.x = newX;
dest.y = newY;
drawImageFancy( font_bmp, color, angle, &src, &dest );
newX += (real_t)dest.w * cos(angle);
newY += (real_t)dest.h * sin(angle);
}
else if ( str[c] == 10 )
{
line++;
dest.x = x + dest.h * cos(angle + PI / 2) * line;
dest.y = y + dest.h * sin(angle + PI / 2) * line;
}
}
}
/*-------------------------------------------------------------------------------
draws a tooltip
Draws a tooltip box
-------------------------------------------------------------------------------*/
void drawTooltip(SDL_Rect* src, Uint32 optionalColor)
{
Uint32 color = SDL_MapRGB(mainsurface->format, 0, 192, 255);
if ( optionalColor == 0 )
{
drawRect(src, 0, 250);
}
else
{
color = optionalColor;
}
drawLine(src->x, src->y, src->x + src->w, src->y, color, 255);
drawLine(src->x, src->y + src->h, src->x + src->w, src->y + src->h, color, 255);
drawLine(src->x, src->y, src->x, src->y + src->h, color, 255);
drawLine(src->x + src->w, src->y, src->x + src->w, src->y + src->h, color, 255);
}
| 27.370927 | 200 | 0.54473 | [
"vector",
"solid"
] |
edabd96eb80e6ee871d3f88d20a1635c42176739 | 819 | hh | C++ | NetworkRelay/INetworkRelay.hh | deb0ch/R-Type | 8bb37cd5ec318efb97119afb87d4996f6bb7644e | [
"WTFPL"
] | 5 | 2016-03-15T20:14:10.000Z | 2020-10-30T23:56:24.000Z | NetworkRelay/INetworkRelay.hh | deb0ch/R-Type | 8bb37cd5ec318efb97119afb87d4996f6bb7644e | [
"WTFPL"
] | 3 | 2018-12-19T19:12:44.000Z | 2020-04-02T13:07:00.000Z | NetworkRelay/INetworkRelay.hh | deb0ch/R-Type | 8bb37cd5ec318efb97119afb87d4996f6bb7644e | [
"WTFPL"
] | 2 | 2016-04-11T19:29:28.000Z | 2021-11-26T20:53:22.000Z | #ifndef INETWORKRELAY_H_
# define INETWORKRELAY_H_
# include <vector>
# include "IBuffer.hh"
# include "Any.hpp"
class Remote;
class Room;
class INetworkRelay
{
public:
enum TCPType
{
CHANGE_ROOM_QUERY,
CHANGE_ROOM_QUERY_YES,
CHANGE_ROOM_QUERY_NON
};
public:
virtual ~INetworkRelay()
{}
virtual bool start() = 0;
virtual void start(Any) = 0;
virtual Room *getRoom(const std::string &room_name) = 0;
virtual IBuffer *getTCPBuffer() = 0;
virtual IBuffer *getUDPBuffer() = 0;
virtual Remote *getRemote(unsigned int) const = 0;
virtual Remote *getRemote(const std::string &ip, const int port) const = 0;
virtual void disposeUDPBuffer(IBuffer *) = 0;
virtual void disposeTCPBuffer(IBuffer *) = 0;
protected:
};
#endif /* !INETWORKRELAY_H_ */
| 21.552632 | 79 | 0.676435 | [
"vector"
] |
edac5ac71014740e793a188bd68137e27276b602 | 12,545 | cpp | C++ | DerivedSources/WebCore/JSAudioListener.cpp | VincentWei/mdolphin-core | 48ffdcf587a48a7bb4345ae469a45c5b64ffad0e | [
"Apache-2.0"
] | 6 | 2017-05-31T01:46:45.000Z | 2018-06-12T10:53:30.000Z | DerivedSources/WebCore/JSAudioListener.cpp | FMSoftCN/mdolphin-core | 48ffdcf587a48a7bb4345ae469a45c5b64ffad0e | [
"Apache-2.0"
] | null | null | null | DerivedSources/WebCore/JSAudioListener.cpp | FMSoftCN/mdolphin-core | 48ffdcf587a48a7bb4345ae469a45c5b64ffad0e | [
"Apache-2.0"
] | 2 | 2017-07-17T06:02:42.000Z | 2018-09-19T10:08:38.000Z | /*
This file is part of the WebKit open source project.
This file has been generated by generate-bindings.pl. DO NOT MODIFY!
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "config.h"
#if ENABLE(WEB_AUDIO)
#include "JSAudioListener.h"
#include "AudioListener.h"
#include "ExceptionCode.h"
#include "JSDOMBinding.h"
#include <runtime/Error.h>
#include <runtime/JSNumberCell.h>
#include <wtf/GetPtr.h>
using namespace JSC;
namespace WebCore {
ASSERT_CLASS_FITS_IN_CELL(JSAudioListener);
/* Hash table */
#if ENABLE(JIT)
#define THUNK_GENERATOR(generator) , generator
#else
#define THUNK_GENERATOR(generator)
#endif
static const HashTableValue JSAudioListenerTableValues[4] =
{
{ "dopplerFactor", DontDelete, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsAudioListenerDopplerFactor), (intptr_t)setJSAudioListenerDopplerFactor THUNK_GENERATOR(0) },
{ "speedOfSound", DontDelete, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsAudioListenerSpeedOfSound), (intptr_t)setJSAudioListenerSpeedOfSound THUNK_GENERATOR(0) },
{ "constructor", DontEnum | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsAudioListenerConstructor), (intptr_t)0 THUNK_GENERATOR(0) },
{ 0, 0, 0, 0 THUNK_GENERATOR(0) }
};
#undef THUNK_GENERATOR
static JSC_CONST_HASHTABLE HashTable JSAudioListenerTable = { 8, 7, JSAudioListenerTableValues, 0 };
/* Hash table for constructor */
#if ENABLE(JIT)
#define THUNK_GENERATOR(generator) , generator
#else
#define THUNK_GENERATOR(generator)
#endif
static const HashTableValue JSAudioListenerConstructorTableValues[1] =
{
{ 0, 0, 0, 0 THUNK_GENERATOR(0) }
};
#undef THUNK_GENERATOR
static JSC_CONST_HASHTABLE HashTable JSAudioListenerConstructorTable = { 1, 0, JSAudioListenerConstructorTableValues, 0 };
class JSAudioListenerConstructor : public DOMConstructorObject {
public:
JSAudioListenerConstructor(JSC::ExecState*, JSDOMGlobalObject*);
virtual bool getOwnPropertySlot(JSC::ExecState*, const JSC::Identifier&, JSC::PropertySlot&);
virtual bool getOwnPropertyDescriptor(JSC::ExecState*, const JSC::Identifier&, JSC::PropertyDescriptor&);
static const JSC::ClassInfo s_info;
static PassRefPtr<JSC::Structure> createStructure(JSC::JSGlobalData& globalData, JSC::JSValue prototype)
{
return JSC::Structure::create(globalData, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), AnonymousSlotCount, &s_info);
}
protected:
static const unsigned StructureFlags = JSC::OverridesGetOwnPropertySlot | JSC::ImplementsHasInstance | DOMConstructorObject::StructureFlags;
};
const ClassInfo JSAudioListenerConstructor::s_info = { "AudioListenerConstructor", &DOMConstructorObject::s_info, &JSAudioListenerConstructorTable, 0 };
JSAudioListenerConstructor::JSAudioListenerConstructor(ExecState* exec, JSDOMGlobalObject* globalObject)
: DOMConstructorObject(JSAudioListenerConstructor::createStructure(globalObject->globalData(), globalObject->objectPrototype()), globalObject)
{
ASSERT(inherits(&s_info));
putDirect(exec->globalData(), exec->propertyNames().prototype, JSAudioListenerPrototype::self(exec, globalObject), DontDelete | ReadOnly);
}
bool JSAudioListenerConstructor::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
return getStaticValueSlot<JSAudioListenerConstructor, DOMObject>(exec, &JSAudioListenerConstructorTable, this, propertyName, slot);
}
bool JSAudioListenerConstructor::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)
{
return getStaticValueDescriptor<JSAudioListenerConstructor, DOMObject>(exec, &JSAudioListenerConstructorTable, this, propertyName, descriptor);
}
/* Hash table for prototype */
#if ENABLE(JIT)
#define THUNK_GENERATOR(generator) , generator
#else
#define THUNK_GENERATOR(generator)
#endif
static const HashTableValue JSAudioListenerPrototypeTableValues[4] =
{
{ "setPosition", DontDelete | Function, (intptr_t)static_cast<NativeFunction>(jsAudioListenerPrototypeFunctionSetPosition), (intptr_t)3 THUNK_GENERATOR(0) },
{ "setOrientation", DontDelete | Function, (intptr_t)static_cast<NativeFunction>(jsAudioListenerPrototypeFunctionSetOrientation), (intptr_t)6 THUNK_GENERATOR(0) },
{ "setVelocity", DontDelete | Function, (intptr_t)static_cast<NativeFunction>(jsAudioListenerPrototypeFunctionSetVelocity), (intptr_t)3 THUNK_GENERATOR(0) },
{ 0, 0, 0, 0 THUNK_GENERATOR(0) }
};
#undef THUNK_GENERATOR
static JSC_CONST_HASHTABLE HashTable JSAudioListenerPrototypeTable = { 8, 7, JSAudioListenerPrototypeTableValues, 0 };
const ClassInfo JSAudioListenerPrototype::s_info = { "AudioListenerPrototype", &JSC::JSObjectWithGlobalObject::s_info, &JSAudioListenerPrototypeTable, 0 };
JSObject* JSAudioListenerPrototype::self(ExecState* exec, JSGlobalObject* globalObject)
{
return getDOMPrototype<JSAudioListener>(exec, globalObject);
}
bool JSAudioListenerPrototype::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
return getStaticFunctionSlot<JSObject>(exec, &JSAudioListenerPrototypeTable, this, propertyName, slot);
}
bool JSAudioListenerPrototype::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)
{
return getStaticFunctionDescriptor<JSObject>(exec, &JSAudioListenerPrototypeTable, this, propertyName, descriptor);
}
const ClassInfo JSAudioListener::s_info = { "AudioListener", &DOMObjectWithGlobalPointer::s_info, &JSAudioListenerTable, 0 };
JSAudioListener::JSAudioListener(NonNullPassRefPtr<Structure> structure, JSDOMGlobalObject* globalObject, PassRefPtr<AudioListener> impl)
: DOMObjectWithGlobalPointer(structure, globalObject)
, m_impl(impl)
{
ASSERT(inherits(&s_info));
}
JSObject* JSAudioListener::createPrototype(ExecState* exec, JSGlobalObject* globalObject)
{
return new (exec) JSAudioListenerPrototype(globalObject, JSAudioListenerPrototype::createStructure(globalObject->globalData(), globalObject->objectPrototype()));
}
bool JSAudioListener::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
return getStaticValueSlot<JSAudioListener, Base>(exec, &JSAudioListenerTable, this, propertyName, slot);
}
bool JSAudioListener::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)
{
return getStaticValueDescriptor<JSAudioListener, Base>(exec, &JSAudioListenerTable, this, propertyName, descriptor);
}
JSValue jsAudioListenerDopplerFactor(ExecState* exec, JSValue slotBase, const Identifier&)
{
JSAudioListener* castedThis = static_cast<JSAudioListener*>(asObject(slotBase));
UNUSED_PARAM(exec);
AudioListener* imp = static_cast<AudioListener*>(castedThis->impl());
JSValue result = jsNumber(imp->dopplerFactor());
return result;
}
JSValue jsAudioListenerSpeedOfSound(ExecState* exec, JSValue slotBase, const Identifier&)
{
JSAudioListener* castedThis = static_cast<JSAudioListener*>(asObject(slotBase));
UNUSED_PARAM(exec);
AudioListener* imp = static_cast<AudioListener*>(castedThis->impl());
JSValue result = jsNumber(imp->speedOfSound());
return result;
}
JSValue jsAudioListenerConstructor(ExecState* exec, JSValue slotBase, const Identifier&)
{
JSAudioListener* domObject = static_cast<JSAudioListener*>(asObject(slotBase));
return JSAudioListener::getConstructor(exec, domObject->globalObject());
}
void JSAudioListener::put(ExecState* exec, const Identifier& propertyName, JSValue value, PutPropertySlot& slot)
{
lookupPut<JSAudioListener, Base>(exec, propertyName, value, &JSAudioListenerTable, this, slot);
}
void setJSAudioListenerDopplerFactor(ExecState* exec, JSObject* thisObject, JSValue value)
{
JSAudioListener* castedThis = static_cast<JSAudioListener*>(thisObject);
AudioListener* imp = static_cast<AudioListener*>(castedThis->impl());
imp->setDopplerFactor(value.toFloat(exec));
}
void setJSAudioListenerSpeedOfSound(ExecState* exec, JSObject* thisObject, JSValue value)
{
JSAudioListener* castedThis = static_cast<JSAudioListener*>(thisObject);
AudioListener* imp = static_cast<AudioListener*>(castedThis->impl());
imp->setSpeedOfSound(value.toFloat(exec));
}
JSValue JSAudioListener::getConstructor(ExecState* exec, JSGlobalObject* globalObject)
{
return getDOMConstructor<JSAudioListenerConstructor>(exec, static_cast<JSDOMGlobalObject*>(globalObject));
}
EncodedJSValue JSC_HOST_CALL jsAudioListenerPrototypeFunctionSetPosition(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSAudioListener::s_info))
return throwVMTypeError(exec);
JSAudioListener* castedThis = static_cast<JSAudioListener*>(asObject(thisValue));
AudioListener* imp = static_cast<AudioListener*>(castedThis->impl());
float x(exec->argument(0).toFloat(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
float y(exec->argument(1).toFloat(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
float z(exec->argument(2).toFloat(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
imp->setPosition(x, y, z);
return JSValue::encode(jsUndefined());
}
EncodedJSValue JSC_HOST_CALL jsAudioListenerPrototypeFunctionSetOrientation(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSAudioListener::s_info))
return throwVMTypeError(exec);
JSAudioListener* castedThis = static_cast<JSAudioListener*>(asObject(thisValue));
AudioListener* imp = static_cast<AudioListener*>(castedThis->impl());
float x(exec->argument(0).toFloat(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
float y(exec->argument(1).toFloat(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
float z(exec->argument(2).toFloat(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
float xUp(exec->argument(3).toFloat(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
float yUp(exec->argument(4).toFloat(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
float zUp(exec->argument(5).toFloat(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
imp->setOrientation(x, y, z, xUp, yUp, zUp);
return JSValue::encode(jsUndefined());
}
EncodedJSValue JSC_HOST_CALL jsAudioListenerPrototypeFunctionSetVelocity(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSAudioListener::s_info))
return throwVMTypeError(exec);
JSAudioListener* castedThis = static_cast<JSAudioListener*>(asObject(thisValue));
AudioListener* imp = static_cast<AudioListener*>(castedThis->impl());
float x(exec->argument(0).toFloat(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
float y(exec->argument(1).toFloat(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
float z(exec->argument(2).toFloat(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
imp->setVelocity(x, y, z);
return JSValue::encode(jsUndefined());
}
JSC::JSValue toJS(JSC::ExecState* exec, JSDOMGlobalObject* globalObject, AudioListener* object)
{
return getDOMObjectWrapper<JSAudioListener>(exec, globalObject, object);
}
AudioListener* toAudioListener(JSC::JSValue value)
{
return value.inherits(&JSAudioListener::s_info) ? static_cast<JSAudioListener*>(asObject(value))->impl() : 0;
}
}
#endif // ENABLE(WEB_AUDIO)
| 42.525424 | 179 | 0.765803 | [
"object"
] |
edad70f6a0e187cafe4c3a26d173ddf70b56c104 | 777 | hpp | C++ | Modules/Core/Public/Dusk/SceneImporter.hpp | WhoBrokeTheBuild/dusk | c7248c88eaa282b09084a67038772e58f79102fc | [
"MIT"
] | 1 | 2017-05-30T19:10:25.000Z | 2017-05-30T19:10:25.000Z | Modules/Core/Public/Dusk/SceneImporter.hpp | WhoBrokeTheBuild/dusk | c7248c88eaa282b09084a67038772e58f79102fc | [
"MIT"
] | null | null | null | Modules/Core/Public/Dusk/SceneImporter.hpp | WhoBrokeTheBuild/dusk | c7248c88eaa282b09084a67038772e58f79102fc | [
"MIT"
] | 2 | 2017-08-23T18:47:54.000Z | 2020-07-08T01:51:31.000Z | #ifndef DUSK_SCENE_IMPORTER_HPP
#define DUSK_SCENE_IMPORTER_HPP
#include <Dusk/Config.hpp>
#include <Dusk/Object.hpp>
#include <Dusk/Entity.hpp>
#include <Dusk/String.hpp>
#include <Dusk/Path.hpp>
namespace Dusk {
class DUSK_CORE_API SceneImporter : public Object
{
public:
DISALLOW_COPY_AND_ASSIGN(SceneImporter)
SceneImporter() = default;
virtual ~SceneImporter() = default;
virtual bool LoadFromFile(Entity * root, const Path& path) = 0;
}; // class SceneImporter
DUSK_CORE_API
void AddSceneImporter(const string& id, std::unique_ptr<SceneImporter> importer);
DUSK_CORE_API
void RemoveSceneImporter(const string& id);
DUSK_CORE_API
const std::vector<SceneImporter *>& GetAllSceneImporters();
} // namespace Dusk
#endif // DUSK_SCENE_IMPORTER_HPP | 21 | 81 | 0.76834 | [
"object",
"vector"
] |
edad799513cf4241a4101c2c06f934fd3996706d | 2,032 | cpp | C++ | mr.Sadman/Classes/GameAct/Objects/Tech/Block.cpp | 1pkg/dump | 0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b | [
"MIT"
] | null | null | null | mr.Sadman/Classes/GameAct/Objects/Tech/Block.cpp | 1pkg/dump | 0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b | [
"MIT"
] | 3 | 2020-12-11T10:01:27.000Z | 2022-02-13T22:12:05.000Z | mr.Sadman/Classes/GameAct/Objects/Tech/Block.cpp | 1pkg/dump | 0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b | [
"MIT"
] | null | null | null | #include "Block.hpp"
#include "Game/Objects/DecorateObject.hpp"
#include "Game.hpp"
#include "Game/Cache/GameCache.hpp"
#include "Game/Objects/Factories/ObjectsFactory.hpp"
#include "Ball.hpp"
namespace Objects
{
namespace Tech
{
void
Block::interact( Ball * ball )
{
hide();
ball->hide();
}
Block::Block( const std::string & decorator )
: _decorator( createDecorator( decorator ) )
{
}
void
Block::initialize()
{
_sprite = Game::getInstance()->getGameCache()->getObjectSprite( getName() );
cocos2d::PhysicsBody * body = cocos2d::PhysicsBody::createBox( _sprite->getContentSize() );
_sprite->setPhysicsBody( body );
body->setDynamic( false );
body->setCategoryBitmask( 0x1 << 3 ); // who ?
body->setCollisionBitmask( 0x1 << 2 ); // with who ?
body->setContactTestBitmask( 0x1 << 2 );
}
std::string
Block::getName() const
{
return "Block";
}
void
Block::setPosition( cocos2d::Vec2 position )
{
if( _decorator )
_decorator->setPosition( position );
StaticObject::setPosition( position );
}
void
Block::setSize( cocos2d::Size size )
{
if( _decorator )
{
cocos2d::Size decSize = size;
decSize.width /= 2.0;
decSize.height /= 2.0;
_decorator->setSize( decSize );
}
StaticObject::setSize( size );
}
void
Block::hide()
{
if( _decorator )
_decorator->hide();
StaticObject::hide();
}
void
Block::show()
{
if( _decorator )
_decorator->show();
StaticObject::show();
}
void
Block::attachToChunk( Levels::Chunk & chunk, int zIndex )
{
if( _decorator )
_decorator->attachToChunk( chunk, zIndex + 3 );
StaticObject::attachToChunk( chunk, zIndex );
}
void
Block::runInteraction( Object * object )
{
object->interact( this );
}
DecorateObject *
Block::createDecorator( const std::string & decorator )
{
Object * obj = Game::getInstance()->getObjectsFactory()->create( decorator );
DecorateObject * decObj = dynamic_cast< DecorateObject * >( obj );
return decObj;
}
}
} | 17.982301 | 94 | 0.649606 | [
"object"
] |
edaf7b6ac133fede4eee9cf6d39e8dd17f9fe9c9 | 27,265 | cc | C++ | 3rdParty/V8/v5.7.492.77/test/cctest/compiler/test-branch-combine.cc | sita1999/arangodb | 6a4f462fa209010cd064f99e63d85ce1d432c500 | [
"Apache-2.0"
] | 1,244 | 2015-01-02T21:08:56.000Z | 2022-03-22T21:34:16.000Z | 3rdParty/V8/v5.7.492.77/test/cctest/compiler/test-branch-combine.cc | lipper/arangodb | 66ea1fd4946668192e3f0d1060f0844f324ad7b8 | [
"Apache-2.0"
] | 125 | 2015-01-22T01:08:00.000Z | 2020-05-25T08:28:17.000Z | 3rdParty/V8/v5.7.492.77/test/cctest/compiler/test-branch-combine.cc | lipper/arangodb | 66ea1fd4946668192e3f0d1060f0844f324ad7b8 | [
"Apache-2.0"
] | 124 | 2015-01-12T15:06:17.000Z | 2022-03-26T07:48:53.000Z | // Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "test/cctest/cctest.h"
#include "test/cctest/compiler/codegen-tester.h"
#include "test/cctest/compiler/value-helper.h"
namespace v8 {
namespace internal {
namespace compiler {
static IrOpcode::Value int32cmp_opcodes[] = {
IrOpcode::kWord32Equal, IrOpcode::kInt32LessThan,
IrOpcode::kInt32LessThanOrEqual, IrOpcode::kUint32LessThan,
IrOpcode::kUint32LessThanOrEqual};
TEST(BranchCombineWord32EqualZero_1) {
// Test combining a branch with x == 0
RawMachineAssemblerTester<int32_t> m(MachineType::Int32());
int32_t eq_constant = -1033;
int32_t ne_constant = 825118;
Node* p0 = m.Parameter(0);
RawMachineLabel blocka, blockb;
m.Branch(m.Word32Equal(p0, m.Int32Constant(0)), &blocka, &blockb);
m.Bind(&blocka);
m.Return(m.Int32Constant(eq_constant));
m.Bind(&blockb);
m.Return(m.Int32Constant(ne_constant));
FOR_INT32_INPUTS(i) {
int32_t a = *i;
int32_t expect = a == 0 ? eq_constant : ne_constant;
CHECK_EQ(expect, m.Call(a));
}
}
TEST(BranchCombineWord32EqualZero_chain) {
// Test combining a branch with a chain of x == 0 == 0 == 0 ...
int32_t eq_constant = -1133;
int32_t ne_constant = 815118;
for (int k = 0; k < 6; k++) {
RawMachineAssemblerTester<int32_t> m(MachineType::Int32());
Node* p0 = m.Parameter(0);
RawMachineLabel blocka, blockb;
Node* cond = p0;
for (int j = 0; j < k; j++) {
cond = m.Word32Equal(cond, m.Int32Constant(0));
}
m.Branch(cond, &blocka, &blockb);
m.Bind(&blocka);
m.Return(m.Int32Constant(eq_constant));
m.Bind(&blockb);
m.Return(m.Int32Constant(ne_constant));
FOR_INT32_INPUTS(i) {
int32_t a = *i;
int32_t expect = (k & 1) == 1 ? (a == 0 ? eq_constant : ne_constant)
: (a == 0 ? ne_constant : eq_constant);
CHECK_EQ(expect, m.Call(a));
}
}
}
TEST(BranchCombineInt32LessThanZero_1) {
// Test combining a branch with x < 0
RawMachineAssemblerTester<int32_t> m(MachineType::Int32());
int32_t eq_constant = -1433;
int32_t ne_constant = 845118;
Node* p0 = m.Parameter(0);
RawMachineLabel blocka, blockb;
m.Branch(m.Int32LessThan(p0, m.Int32Constant(0)), &blocka, &blockb);
m.Bind(&blocka);
m.Return(m.Int32Constant(eq_constant));
m.Bind(&blockb);
m.Return(m.Int32Constant(ne_constant));
FOR_INT32_INPUTS(i) {
int32_t a = *i;
int32_t expect = a < 0 ? eq_constant : ne_constant;
CHECK_EQ(expect, m.Call(a));
}
}
TEST(BranchCombineUint32LessThan100_1) {
// Test combining a branch with x < 100
RawMachineAssemblerTester<int32_t> m(MachineType::Uint32());
int32_t eq_constant = 1471;
int32_t ne_constant = 88845718;
Node* p0 = m.Parameter(0);
RawMachineLabel blocka, blockb;
m.Branch(m.Uint32LessThan(p0, m.Int32Constant(100)), &blocka, &blockb);
m.Bind(&blocka);
m.Return(m.Int32Constant(eq_constant));
m.Bind(&blockb);
m.Return(m.Int32Constant(ne_constant));
FOR_UINT32_INPUTS(i) {
uint32_t a = *i;
int32_t expect = a < 100 ? eq_constant : ne_constant;
CHECK_EQ(expect, m.Call(a));
}
}
TEST(BranchCombineUint32LessThanOrEqual100_1) {
// Test combining a branch with x <= 100
RawMachineAssemblerTester<int32_t> m(MachineType::Uint32());
int32_t eq_constant = 1479;
int32_t ne_constant = 77845719;
Node* p0 = m.Parameter(0);
RawMachineLabel blocka, blockb;
m.Branch(m.Uint32LessThanOrEqual(p0, m.Int32Constant(100)), &blocka, &blockb);
m.Bind(&blocka);
m.Return(m.Int32Constant(eq_constant));
m.Bind(&blockb);
m.Return(m.Int32Constant(ne_constant));
FOR_UINT32_INPUTS(i) {
uint32_t a = *i;
int32_t expect = a <= 100 ? eq_constant : ne_constant;
CHECK_EQ(expect, m.Call(a));
}
}
TEST(BranchCombineZeroLessThanInt32_1) {
// Test combining a branch with 0 < x
RawMachineAssemblerTester<int32_t> m(MachineType::Int32());
int32_t eq_constant = -2033;
int32_t ne_constant = 225118;
Node* p0 = m.Parameter(0);
RawMachineLabel blocka, blockb;
m.Branch(m.Int32LessThan(m.Int32Constant(0), p0), &blocka, &blockb);
m.Bind(&blocka);
m.Return(m.Int32Constant(eq_constant));
m.Bind(&blockb);
m.Return(m.Int32Constant(ne_constant));
FOR_INT32_INPUTS(i) {
int32_t a = *i;
int32_t expect = 0 < a ? eq_constant : ne_constant;
CHECK_EQ(expect, m.Call(a));
}
}
TEST(BranchCombineInt32GreaterThanZero_1) {
// Test combining a branch with x > 0
RawMachineAssemblerTester<int32_t> m(MachineType::Int32());
int32_t eq_constant = -1073;
int32_t ne_constant = 825178;
Node* p0 = m.Parameter(0);
RawMachineLabel blocka, blockb;
m.Branch(m.Int32GreaterThan(p0, m.Int32Constant(0)), &blocka, &blockb);
m.Bind(&blocka);
m.Return(m.Int32Constant(eq_constant));
m.Bind(&blockb);
m.Return(m.Int32Constant(ne_constant));
FOR_INT32_INPUTS(i) {
int32_t a = *i;
int32_t expect = a > 0 ? eq_constant : ne_constant;
CHECK_EQ(expect, m.Call(a));
}
}
TEST(BranchCombineWord32EqualP) {
// Test combining a branch with an Word32Equal.
RawMachineAssemblerTester<int32_t> m(MachineType::Int32(),
MachineType::Int32());
int32_t eq_constant = -1035;
int32_t ne_constant = 825018;
Node* p0 = m.Parameter(0);
Node* p1 = m.Parameter(1);
RawMachineLabel blocka, blockb;
m.Branch(m.Word32Equal(p0, p1), &blocka, &blockb);
m.Bind(&blocka);
m.Return(m.Int32Constant(eq_constant));
m.Bind(&blockb);
m.Return(m.Int32Constant(ne_constant));
FOR_INT32_INPUTS(i) {
FOR_INT32_INPUTS(j) {
int32_t a = *i;
int32_t b = *j;
int32_t expect = a == b ? eq_constant : ne_constant;
CHECK_EQ(expect, m.Call(a, b));
}
}
}
TEST(BranchCombineWord32EqualI) {
int32_t eq_constant = -1135;
int32_t ne_constant = 925718;
for (int left = 0; left < 2; left++) {
FOR_INT32_INPUTS(i) {
RawMachineAssemblerTester<int32_t> m(MachineType::Int32());
int32_t a = *i;
Node* p0 = m.Int32Constant(a);
Node* p1 = m.Parameter(0);
RawMachineLabel blocka, blockb;
if (left == 1) m.Branch(m.Word32Equal(p0, p1), &blocka, &blockb);
if (left == 0) m.Branch(m.Word32Equal(p1, p0), &blocka, &blockb);
m.Bind(&blocka);
m.Return(m.Int32Constant(eq_constant));
m.Bind(&blockb);
m.Return(m.Int32Constant(ne_constant));
FOR_INT32_INPUTS(j) {
int32_t b = *j;
int32_t expect = a == b ? eq_constant : ne_constant;
CHECK_EQ(expect, m.Call(b));
}
}
}
}
TEST(BranchCombineInt32CmpP) {
int32_t eq_constant = -1235;
int32_t ne_constant = 725018;
for (int op = 0; op < 2; op++) {
RawMachineAssemblerTester<int32_t> m(MachineType::Int32(),
MachineType::Int32());
Node* p0 = m.Parameter(0);
Node* p1 = m.Parameter(1);
RawMachineLabel blocka, blockb;
if (op == 0) m.Branch(m.Int32LessThan(p0, p1), &blocka, &blockb);
if (op == 1) m.Branch(m.Int32LessThanOrEqual(p0, p1), &blocka, &blockb);
m.Bind(&blocka);
m.Return(m.Int32Constant(eq_constant));
m.Bind(&blockb);
m.Return(m.Int32Constant(ne_constant));
FOR_INT32_INPUTS(i) {
FOR_INT32_INPUTS(j) {
int32_t a = *i;
int32_t b = *j;
int32_t expect = 0;
if (op == 0) expect = a < b ? eq_constant : ne_constant;
if (op == 1) expect = a <= b ? eq_constant : ne_constant;
CHECK_EQ(expect, m.Call(a, b));
}
}
}
}
TEST(BranchCombineInt32CmpI) {
int32_t eq_constant = -1175;
int32_t ne_constant = 927711;
for (int op = 0; op < 2; op++) {
FOR_INT32_INPUTS(i) {
RawMachineAssemblerTester<int32_t> m(MachineType::Int32());
int32_t a = *i;
Node* p0 = m.Int32Constant(a);
Node* p1 = m.Parameter(0);
RawMachineLabel blocka, blockb;
if (op == 0) m.Branch(m.Int32LessThan(p0, p1), &blocka, &blockb);
if (op == 1) m.Branch(m.Int32LessThanOrEqual(p0, p1), &blocka, &blockb);
m.Bind(&blocka);
m.Return(m.Int32Constant(eq_constant));
m.Bind(&blockb);
m.Return(m.Int32Constant(ne_constant));
FOR_INT32_INPUTS(j) {
int32_t b = *j;
int32_t expect = 0;
if (op == 0) expect = a < b ? eq_constant : ne_constant;
if (op == 1) expect = a <= b ? eq_constant : ne_constant;
CHECK_EQ(expect, m.Call(b));
}
}
}
}
// Now come the sophisticated tests for many input shape combinations.
// Materializes a boolean (1 or 0) from a comparison.
class CmpMaterializeBoolGen : public BinopGen<int32_t> {
public:
CompareWrapper w;
bool invert;
CmpMaterializeBoolGen(IrOpcode::Value opcode, bool i)
: w(opcode), invert(i) {}
virtual void gen(RawMachineAssemblerTester<int32_t>* m, Node* a, Node* b) {
Node* cond = w.MakeNode(m, a, b);
if (invert) cond = m->Word32Equal(cond, m->Int32Constant(0));
m->Return(cond);
}
virtual int32_t expected(int32_t a, int32_t b) {
if (invert) return !w.Int32Compare(a, b) ? 1 : 0;
return w.Int32Compare(a, b) ? 1 : 0;
}
};
// Generates a branch and return one of two values from a comparison.
class CmpBranchGen : public BinopGen<int32_t> {
public:
CompareWrapper w;
bool invert;
bool true_first;
int32_t eq_constant;
int32_t ne_constant;
CmpBranchGen(IrOpcode::Value opcode, bool i, bool t, int32_t eq, int32_t ne)
: w(opcode), invert(i), true_first(t), eq_constant(eq), ne_constant(ne) {}
virtual void gen(RawMachineAssemblerTester<int32_t>* m, Node* a, Node* b) {
RawMachineLabel blocka, blockb;
Node* cond = w.MakeNode(m, a, b);
if (invert) cond = m->Word32Equal(cond, m->Int32Constant(0));
m->Branch(cond, &blocka, &blockb);
if (true_first) {
m->Bind(&blocka);
m->Return(m->Int32Constant(eq_constant));
m->Bind(&blockb);
m->Return(m->Int32Constant(ne_constant));
} else {
m->Bind(&blockb);
m->Return(m->Int32Constant(ne_constant));
m->Bind(&blocka);
m->Return(m->Int32Constant(eq_constant));
}
}
virtual int32_t expected(int32_t a, int32_t b) {
if (invert) return !w.Int32Compare(a, b) ? eq_constant : ne_constant;
return w.Int32Compare(a, b) ? eq_constant : ne_constant;
}
};
TEST(BranchCombineInt32CmpAllInputShapes_materialized) {
for (size_t i = 0; i < arraysize(int32cmp_opcodes); i++) {
CmpMaterializeBoolGen gen(int32cmp_opcodes[i], false);
Int32BinopInputShapeTester tester(&gen);
tester.TestAllInputShapes();
}
}
TEST(BranchCombineInt32CmpAllInputShapes_inverted_materialized) {
for (size_t i = 0; i < arraysize(int32cmp_opcodes); i++) {
CmpMaterializeBoolGen gen(int32cmp_opcodes[i], true);
Int32BinopInputShapeTester tester(&gen);
tester.TestAllInputShapes();
}
}
TEST(BranchCombineInt32CmpAllInputShapes_branch_true) {
for (int i = 0; i < static_cast<int>(arraysize(int32cmp_opcodes)); i++) {
CmpBranchGen gen(int32cmp_opcodes[i], false, false, 995 + i, -1011 - i);
Int32BinopInputShapeTester tester(&gen);
tester.TestAllInputShapes();
}
}
TEST(BranchCombineInt32CmpAllInputShapes_branch_false) {
for (int i = 0; i < static_cast<int>(arraysize(int32cmp_opcodes)); i++) {
CmpBranchGen gen(int32cmp_opcodes[i], false, true, 795 + i, -2011 - i);
Int32BinopInputShapeTester tester(&gen);
tester.TestAllInputShapes();
}
}
TEST(BranchCombineInt32CmpAllInputShapes_inverse_branch_true) {
for (int i = 0; i < static_cast<int>(arraysize(int32cmp_opcodes)); i++) {
CmpBranchGen gen(int32cmp_opcodes[i], true, false, 695 + i, -3011 - i);
Int32BinopInputShapeTester tester(&gen);
tester.TestAllInputShapes();
}
}
TEST(BranchCombineInt32CmpAllInputShapes_inverse_branch_false) {
for (int i = 0; i < static_cast<int>(arraysize(int32cmp_opcodes)); i++) {
CmpBranchGen gen(int32cmp_opcodes[i], true, true, 595 + i, -4011 - i);
Int32BinopInputShapeTester tester(&gen);
tester.TestAllInputShapes();
}
}
TEST(BranchCombineFloat64Compares) {
double inf = V8_INFINITY;
double nan = std::numeric_limits<double>::quiet_NaN();
double inputs[] = {0.0, 1.0, -1.0, -inf, inf, nan};
int32_t eq_constant = -1733;
int32_t ne_constant = 915118;
double input_a = 0.0;
double input_b = 0.0;
CompareWrapper cmps[] = {CompareWrapper(IrOpcode::kFloat64Equal),
CompareWrapper(IrOpcode::kFloat64LessThan),
CompareWrapper(IrOpcode::kFloat64LessThanOrEqual)};
for (size_t c = 0; c < arraysize(cmps); c++) {
CompareWrapper cmp = cmps[c];
for (int invert = 0; invert < 2; invert++) {
RawMachineAssemblerTester<int32_t> m;
Node* a = m.LoadFromPointer(&input_a, MachineType::Float64());
Node* b = m.LoadFromPointer(&input_b, MachineType::Float64());
RawMachineLabel blocka, blockb;
Node* cond = cmp.MakeNode(&m, a, b);
if (invert) cond = m.Word32Equal(cond, m.Int32Constant(0));
m.Branch(cond, &blocka, &blockb);
m.Bind(&blocka);
m.Return(m.Int32Constant(eq_constant));
m.Bind(&blockb);
m.Return(m.Int32Constant(ne_constant));
for (size_t i = 0; i < arraysize(inputs); ++i) {
for (size_t j = 0; j < arraysize(inputs); ++j) {
input_a = inputs[i];
input_b = inputs[j];
int32_t expected =
invert ? (cmp.Float64Compare(input_a, input_b) ? ne_constant
: eq_constant)
: (cmp.Float64Compare(input_a, input_b) ? eq_constant
: ne_constant);
CHECK_EQ(expected, m.Call());
}
}
}
}
}
TEST(BranchCombineEffectLevel) {
// Test that the load doesn't get folded into the branch, as there's a store
// between them. See http://crbug.com/611976.
int32_t input = 0;
RawMachineAssemblerTester<int32_t> m;
Node* a = m.LoadFromPointer(&input, MachineType::Int32());
Node* compare = m.Word32And(a, m.Int32Constant(1));
Node* equal = m.Word32Equal(compare, m.Int32Constant(0));
m.StoreToPointer(&input, MachineRepresentation::kWord32, m.Int32Constant(1));
RawMachineLabel blocka, blockb;
m.Branch(equal, &blocka, &blockb);
m.Bind(&blocka);
m.Return(m.Int32Constant(42));
m.Bind(&blockb);
m.Return(m.Int32Constant(0));
CHECK_EQ(42, m.Call());
}
TEST(BranchCombineInt32AddLessThanZero) {
int32_t t_constant = -1033;
int32_t f_constant = 825118;
RawMachineAssemblerTester<int32_t> m(MachineType::Int32(),
MachineType::Int32());
Node* a = m.Parameter(0);
Node* b = m.Parameter(1);
Node* add = m.Int32Add(a, b);
Node* compare = m.Int32LessThan(add, m.Int32Constant(0));
RawMachineLabel blocka, blockb;
m.Branch(compare, &blocka, &blockb);
m.Bind(&blocka);
m.Return(m.Int32Constant(t_constant));
m.Bind(&blockb);
m.Return(m.Int32Constant(f_constant));
FOR_INT32_INPUTS(i) {
FOR_INT32_INPUTS(j) {
int32_t a = *i;
int32_t b = *j;
int32_t expect = (a + b < 0) ? t_constant : f_constant;
CHECK_EQ(expect, m.Call(a, b));
}
}
}
TEST(BranchCombineInt32AddGreaterThanOrEqualZero) {
int32_t t_constant = -1033;
int32_t f_constant = 825118;
RawMachineAssemblerTester<int32_t> m(MachineType::Int32(),
MachineType::Int32());
Node* a = m.Parameter(0);
Node* b = m.Parameter(1);
Node* add = m.Int32Add(a, b);
Node* compare = m.Int32GreaterThanOrEqual(add, m.Int32Constant(0));
RawMachineLabel blocka, blockb;
m.Branch(compare, &blocka, &blockb);
m.Bind(&blocka);
m.Return(m.Int32Constant(t_constant));
m.Bind(&blockb);
m.Return(m.Int32Constant(f_constant));
FOR_INT32_INPUTS(i) {
FOR_INT32_INPUTS(j) {
int32_t a = *i;
int32_t b = *j;
int32_t expect = (a + b >= 0) ? t_constant : f_constant;
CHECK_EQ(expect, m.Call(a, b));
}
}
}
TEST(BranchCombineInt32ZeroGreaterThanAdd) {
int32_t t_constant = -1033;
int32_t f_constant = 825118;
RawMachineAssemblerTester<int32_t> m(MachineType::Int32(),
MachineType::Int32());
Node* a = m.Parameter(0);
Node* b = m.Parameter(1);
Node* add = m.Int32Add(a, b);
Node* compare = m.Int32GreaterThan(m.Int32Constant(0), add);
RawMachineLabel blocka, blockb;
m.Branch(compare, &blocka, &blockb);
m.Bind(&blocka);
m.Return(m.Int32Constant(t_constant));
m.Bind(&blockb);
m.Return(m.Int32Constant(f_constant));
FOR_INT32_INPUTS(i) {
FOR_INT32_INPUTS(j) {
int32_t a = *i;
int32_t b = *j;
int32_t expect = (0 > a + b) ? t_constant : f_constant;
CHECK_EQ(expect, m.Call(a, b));
}
}
}
TEST(BranchCombineInt32ZeroLessThanOrEqualAdd) {
int32_t t_constant = -1033;
int32_t f_constant = 825118;
RawMachineAssemblerTester<int32_t> m(MachineType::Int32(),
MachineType::Int32());
Node* a = m.Parameter(0);
Node* b = m.Parameter(1);
Node* add = m.Int32Add(a, b);
Node* compare = m.Int32LessThanOrEqual(m.Int32Constant(0), add);
RawMachineLabel blocka, blockb;
m.Branch(compare, &blocka, &blockb);
m.Bind(&blocka);
m.Return(m.Int32Constant(t_constant));
m.Bind(&blockb);
m.Return(m.Int32Constant(f_constant));
FOR_INT32_INPUTS(i) {
FOR_INT32_INPUTS(j) {
int32_t a = *i;
int32_t b = *j;
int32_t expect = (0 <= a + b) ? t_constant : f_constant;
CHECK_EQ(expect, m.Call(a, b));
}
}
}
TEST(BranchCombineUint32AddLessThanOrEqualZero) {
int32_t t_constant = -1033;
int32_t f_constant = 825118;
RawMachineAssemblerTester<int32_t> m(MachineType::Uint32(),
MachineType::Uint32());
Node* a = m.Parameter(0);
Node* b = m.Parameter(1);
Node* add = m.Int32Add(a, b);
Node* compare = m.Uint32LessThanOrEqual(add, m.Int32Constant(0));
RawMachineLabel blocka, blockb;
m.Branch(compare, &blocka, &blockb);
m.Bind(&blocka);
m.Return(m.Int32Constant(t_constant));
m.Bind(&blockb);
m.Return(m.Int32Constant(f_constant));
FOR_INT32_INPUTS(i) {
FOR_INT32_INPUTS(j) {
uint32_t a = *i;
uint32_t b = *j;
int32_t expect = (a + b <= 0) ? t_constant : f_constant;
CHECK_EQ(expect, m.Call(a, b));
}
}
}
TEST(BranchCombineUint32AddGreaterThanZero) {
int32_t t_constant = -1033;
int32_t f_constant = 825118;
RawMachineAssemblerTester<int32_t> m(MachineType::Uint32(),
MachineType::Uint32());
Node* a = m.Parameter(0);
Node* b = m.Parameter(1);
Node* add = m.Int32Add(a, b);
Node* compare = m.Uint32GreaterThan(add, m.Int32Constant(0));
RawMachineLabel blocka, blockb;
m.Branch(compare, &blocka, &blockb);
m.Bind(&blocka);
m.Return(m.Int32Constant(t_constant));
m.Bind(&blockb);
m.Return(m.Int32Constant(f_constant));
FOR_INT32_INPUTS(i) {
FOR_INT32_INPUTS(j) {
uint32_t a = *i;
uint32_t b = *j;
int32_t expect = (a + b > 0) ? t_constant : f_constant;
CHECK_EQ(expect, m.Call(a, b));
}
}
}
TEST(BranchCombineUint32ZeroGreaterThanOrEqualAdd) {
int32_t t_constant = -1033;
int32_t f_constant = 825118;
RawMachineAssemblerTester<int32_t> m(MachineType::Uint32(),
MachineType::Uint32());
Node* a = m.Parameter(0);
Node* b = m.Parameter(1);
Node* add = m.Int32Add(a, b);
Node* compare = m.Uint32GreaterThanOrEqual(m.Int32Constant(0), add);
RawMachineLabel blocka, blockb;
m.Branch(compare, &blocka, &blockb);
m.Bind(&blocka);
m.Return(m.Int32Constant(t_constant));
m.Bind(&blockb);
m.Return(m.Int32Constant(f_constant));
FOR_INT32_INPUTS(i) {
FOR_INT32_INPUTS(j) {
uint32_t a = *i;
uint32_t b = *j;
int32_t expect = (0 >= a + b) ? t_constant : f_constant;
CHECK_EQ(expect, m.Call(a, b));
}
}
}
TEST(BranchCombineUint32ZeroLessThanAdd) {
int32_t t_constant = -1033;
int32_t f_constant = 825118;
RawMachineAssemblerTester<int32_t> m(MachineType::Uint32(),
MachineType::Uint32());
Node* a = m.Parameter(0);
Node* b = m.Parameter(1);
Node* add = m.Int32Add(a, b);
Node* compare = m.Uint32LessThan(m.Int32Constant(0), add);
RawMachineLabel blocka, blockb;
m.Branch(compare, &blocka, &blockb);
m.Bind(&blocka);
m.Return(m.Int32Constant(t_constant));
m.Bind(&blockb);
m.Return(m.Int32Constant(f_constant));
FOR_INT32_INPUTS(i) {
FOR_INT32_INPUTS(j) {
uint32_t a = *i;
uint32_t b = *j;
int32_t expect = (0 < a + b) ? t_constant : f_constant;
CHECK_EQ(expect, m.Call(a, b));
}
}
}
TEST(BranchCombineWord32AndLessThanZero) {
int32_t t_constant = -1033;
int32_t f_constant = 825118;
RawMachineAssemblerTester<int32_t> m(MachineType::Int32(),
MachineType::Int32());
Node* a = m.Parameter(0);
Node* b = m.Parameter(1);
Node* add = m.Word32And(a, b);
Node* compare = m.Int32LessThan(add, m.Int32Constant(0));
RawMachineLabel blocka, blockb;
m.Branch(compare, &blocka, &blockb);
m.Bind(&blocka);
m.Return(m.Int32Constant(t_constant));
m.Bind(&blockb);
m.Return(m.Int32Constant(f_constant));
FOR_INT32_INPUTS(i) {
FOR_INT32_INPUTS(j) {
int32_t a = *i;
int32_t b = *j;
int32_t expect = ((a & b) < 0) ? t_constant : f_constant;
CHECK_EQ(expect, m.Call(a, b));
}
}
}
TEST(BranchCombineWord32AndGreaterThanOrEqualZero) {
int32_t t_constant = -1033;
int32_t f_constant = 825118;
RawMachineAssemblerTester<int32_t> m(MachineType::Int32(),
MachineType::Int32());
Node* a = m.Parameter(0);
Node* b = m.Parameter(1);
Node* add = m.Word32And(a, b);
Node* compare = m.Int32GreaterThanOrEqual(add, m.Int32Constant(0));
RawMachineLabel blocka, blockb;
m.Branch(compare, &blocka, &blockb);
m.Bind(&blocka);
m.Return(m.Int32Constant(t_constant));
m.Bind(&blockb);
m.Return(m.Int32Constant(f_constant));
FOR_INT32_INPUTS(i) {
FOR_INT32_INPUTS(j) {
int32_t a = *i;
int32_t b = *j;
int32_t expect = ((a & b) >= 0) ? t_constant : f_constant;
CHECK_EQ(expect, m.Call(a, b));
}
}
}
TEST(BranchCombineInt32ZeroGreaterThanAnd) {
int32_t t_constant = -1033;
int32_t f_constant = 825118;
RawMachineAssemblerTester<int32_t> m(MachineType::Int32(),
MachineType::Int32());
Node* a = m.Parameter(0);
Node* b = m.Parameter(1);
Node* add = m.Word32And(a, b);
Node* compare = m.Int32GreaterThan(m.Int32Constant(0), add);
RawMachineLabel blocka, blockb;
m.Branch(compare, &blocka, &blockb);
m.Bind(&blocka);
m.Return(m.Int32Constant(t_constant));
m.Bind(&blockb);
m.Return(m.Int32Constant(f_constant));
FOR_INT32_INPUTS(i) {
FOR_INT32_INPUTS(j) {
int32_t a = *i;
int32_t b = *j;
int32_t expect = (0 > (a & b)) ? t_constant : f_constant;
CHECK_EQ(expect, m.Call(a, b));
}
}
}
TEST(BranchCombineInt32ZeroLessThanOrEqualAnd) {
int32_t t_constant = -1033;
int32_t f_constant = 825118;
RawMachineAssemblerTester<int32_t> m(MachineType::Int32(),
MachineType::Int32());
Node* a = m.Parameter(0);
Node* b = m.Parameter(1);
Node* add = m.Word32And(a, b);
Node* compare = m.Int32LessThanOrEqual(m.Int32Constant(0), add);
RawMachineLabel blocka, blockb;
m.Branch(compare, &blocka, &blockb);
m.Bind(&blocka);
m.Return(m.Int32Constant(t_constant));
m.Bind(&blockb);
m.Return(m.Int32Constant(f_constant));
FOR_INT32_INPUTS(i) {
FOR_INT32_INPUTS(j) {
int32_t a = *i;
int32_t b = *j;
int32_t expect = (0 <= (a & b)) ? t_constant : f_constant;
CHECK_EQ(expect, m.Call(a, b));
}
}
}
TEST(BranchCombineUint32AndLessThanOrEqualZero) {
int32_t t_constant = -1033;
int32_t f_constant = 825118;
RawMachineAssemblerTester<int32_t> m(MachineType::Uint32(),
MachineType::Uint32());
Node* a = m.Parameter(0);
Node* b = m.Parameter(1);
Node* add = m.Word32And(a, b);
Node* compare = m.Uint32LessThanOrEqual(add, m.Int32Constant(0));
RawMachineLabel blocka, blockb;
m.Branch(compare, &blocka, &blockb);
m.Bind(&blocka);
m.Return(m.Int32Constant(t_constant));
m.Bind(&blockb);
m.Return(m.Int32Constant(f_constant));
FOR_INT32_INPUTS(i) {
FOR_INT32_INPUTS(j) {
uint32_t a = *i;
uint32_t b = *j;
int32_t expect = ((a & b) <= 0) ? t_constant : f_constant;
CHECK_EQ(expect, m.Call(a, b));
}
}
}
TEST(BranchCombineUint32AndGreaterThanZero) {
int32_t t_constant = -1033;
int32_t f_constant = 825118;
RawMachineAssemblerTester<int32_t> m(MachineType::Uint32(),
MachineType::Uint32());
Node* a = m.Parameter(0);
Node* b = m.Parameter(1);
Node* add = m.Word32And(a, b);
Node* compare = m.Uint32GreaterThan(add, m.Int32Constant(0));
RawMachineLabel blocka, blockb;
m.Branch(compare, &blocka, &blockb);
m.Bind(&blocka);
m.Return(m.Int32Constant(t_constant));
m.Bind(&blockb);
m.Return(m.Int32Constant(f_constant));
FOR_INT32_INPUTS(i) {
FOR_INT32_INPUTS(j) {
uint32_t a = *i;
uint32_t b = *j;
int32_t expect = ((a & b) > 0) ? t_constant : f_constant;
CHECK_EQ(expect, m.Call(a, b));
}
}
}
TEST(BranchCombineUint32ZeroGreaterThanOrEqualAnd) {
int32_t t_constant = -1033;
int32_t f_constant = 825118;
RawMachineAssemblerTester<int32_t> m(MachineType::Uint32(),
MachineType::Uint32());
Node* a = m.Parameter(0);
Node* b = m.Parameter(1);
Node* add = m.Word32And(a, b);
Node* compare = m.Uint32GreaterThanOrEqual(m.Int32Constant(0), add);
RawMachineLabel blocka, blockb;
m.Branch(compare, &blocka, &blockb);
m.Bind(&blocka);
m.Return(m.Int32Constant(t_constant));
m.Bind(&blockb);
m.Return(m.Int32Constant(f_constant));
FOR_INT32_INPUTS(i) {
FOR_INT32_INPUTS(j) {
uint32_t a = *i;
uint32_t b = *j;
int32_t expect = (0 >= (a & b)) ? t_constant : f_constant;
CHECK_EQ(expect, m.Call(a, b));
}
}
}
TEST(BranchCombineUint32ZeroLessThanAnd) {
int32_t t_constant = -1033;
int32_t f_constant = 825118;
RawMachineAssemblerTester<int32_t> m(MachineType::Uint32(),
MachineType::Uint32());
Node* a = m.Parameter(0);
Node* b = m.Parameter(1);
Node* add = m.Word32And(a, b);
Node* compare = m.Uint32LessThan(m.Int32Constant(0), add);
RawMachineLabel blocka, blockb;
m.Branch(compare, &blocka, &blockb);
m.Bind(&blocka);
m.Return(m.Int32Constant(t_constant));
m.Bind(&blockb);
m.Return(m.Int32Constant(f_constant));
FOR_INT32_INPUTS(i) {
FOR_INT32_INPUTS(j) {
uint32_t a = *i;
uint32_t b = *j;
int32_t expect = (0 < (a & b)) ? t_constant : f_constant;
CHECK_EQ(expect, m.Call(a, b));
}
}
}
} // namespace compiler
} // namespace internal
} // namespace v8
| 29.254292 | 80 | 0.640895 | [
"shape"
] |
edb0762d097deee646f018ee90a3bc3094340f43 | 1,575 | cpp | C++ | 4/1/nuggets.cpp | ilimugur/usaco | ec5edba0d3c2f1c1f5dd1905929f96b6629ffa0d | [
"MIT"
] | null | null | null | 4/1/nuggets.cpp | ilimugur/usaco | ec5edba0d3c2f1c1f5dd1905929f96b6629ffa0d | [
"MIT"
] | null | null | null | 4/1/nuggets.cpp | ilimugur/usaco | ec5edba0d3c2f1c1f5dd1905929f96b6629ffa0d | [
"MIT"
] | null | null | null | /*
ID:ilimugu1
LANG:C++
PROB:nuggets
*/
#include <iostream>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#define SIEVELENGTH 65537
using namespace std;
int gcd(int a, int b)
{
return (b > 0 ? gcd(b, a%b) : a);
}
int solve(const vector<int>& nums)
{
int n = nums.size();
bool found = false;
for(int i=0; i < n; ++i)
{
if(nums[i] == 1)
return 0;
for(int j=0; j < n; ++j)
{
if(i != j)
{
if(gcd(nums[i], nums[j]) == 1)
{
found = true;
break;
}
}
}
if(found)
break;
}
int result;
if(found)
{
bool sieve[SIEVELENGTH];
memset(sieve, false, SIEVELENGTH * sizeof(bool));
sieve[0] = true;
for(int i=0; i < SIEVELENGTH; ++i)
{
if(sieve[i])
{
for(int j=0; j < n; ++j)
{
if(i + nums[j] < SIEVELENGTH)
sieve[i + nums[j]] = true;
}
}
}
for(int i= SIEVELENGTH - 1; i >= 0; --i)
{
if(!sieve[i])
{
return i;
}
}
}
return 0;
}
int main()
{
freopen("nuggets.in", "r", stdin);
freopen("nuggets.out", "w", stdout);
int n;
cin >> n;
vector<int> nums(n);
for(int i=0; i < n; ++i)
cin >> nums[i];
cout << solve(nums) << endl;
return 0;
}
| 18.103448 | 57 | 0.391746 | [
"vector"
] |
edb12859d83e213eccdbd32f6522ab3d31ae82e7 | 92,475 | cpp | C++ | Flatten/GA/e3ga.cpp | mauriciocele/arap-svd | bbefe4b0f18d7cd5e834b4c54e518f0d70f49565 | [
"MIT"
] | 4 | 2020-01-10T17:26:34.000Z | 2022-03-25T10:40:58.000Z | Flatten/GA/e3ga.cpp | mauriciocele/arap-svd | bbefe4b0f18d7cd5e834b4c54e518f0d70f49565 | [
"MIT"
] | null | null | null | Flatten/GA/e3ga.cpp | mauriciocele/arap-svd | bbefe4b0f18d7cd5e834b4c54e518f0d70f49565 | [
"MIT"
] | null | null | null |
// Generated on 2007-08-08 10:15:15 by G2 0.1 from 'E:\gasandbox\ga_sandbox\libgasandbox\e3ga.gs2'
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#include <string.h>
#include "e3ga.h"
// pre_cpp_include
namespace e3ga {
// The dimension of the space:
const int mv_spaceDim = 3;
// Is the metric of the space Euclidean?
const bool mv_metricEuclidean = true;
// This array can be used to lookup the number of coordinates for a grade part of a general multivector
const int mv_gradeSize[4] = {
1, 3, 3, 1
};
// This array can be used to lookup the number of coordinates based on a grade usage bitmap
const int mv_size[16] = {
0, 1, 3, 4, 3, 4, 6, 7, 1, 2, 4, 5, 4, 5, 7, 8
};
// This array of ASCIIZ strings contains the names of the basis vectors
const char *mv_basisVectorNames[3] = {
"e1", "e2", "e3"
};
// This array of integers contains the order of basis elements in the general multivector
const int mv_basisElements[8][4] = {
{-1}
, {0, -1}
, {1, -1}
, {2, -1}
, {0, 1, -1}
, {1, 2, -1}
, {0, 2, -1}
, {0, 1, 2, -1}
};
// This array of integers contains the 'sign' (even/odd permutation of the canonical order) of basis elements in the general multivector
// Use it to answer 'what is the permutation of the coordinate at index [x]'?
const double mv_basisElementSignByIndex[8] = {
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0
};
// This array of integers contains the 'sign' (even/odd permutation of canonical order) of basis elements in the general multivector
// Use it to answer 'what is the permutation of the coordinate of bitmap [x]'?
const double mv_basisElementSignByBitmap[8] = {
1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0
};
// This array of integers contains the order of basis elements in the general multivector
// Use it to answer: 'at what index do I find basis element [x] (x = basis vector bitmap)?
const int mv_basisElementIndexByBitmap[8] = {
0, 1, 2, 4, 3, 6, 5, 7
};
// This array of integers contains the indices of basis elements in the general multivector
// Use it to answer: 'what basis element do I find at index [x]'?
const int mv_basisElementBitmapByIndex[8] = {
0, 1, 2, 4, 3, 6, 5, 7
};
// This array of grade of each basis elements in the general multivector
// Use it to answer: 'what is the grade of basis element bitmap [x]'?
extern const int mv_basisElementGradeByBitmap[8] = {
0, 1, 1, 2, 1, 2, 2, 3
};
// These strings determine how the output of string() is formatted.
// You can alter them at runtime using mv_setStringFormat().
const char *mv_string_fp = "%2.2f";
const char *mv_string_start = "";
const char *mv_string_end = "";
const char *mv_string_mul = "*";
const char *mv_string_wedge = "^";
const char *mv_string_plus = " + ";
const char *mv_string_minus = " - ";
void mv_setStringFormat(const char *what, const char *format) {
if (!strcmp(what, "fp"))
mv_string_fp = (format) ? format : "%2.2f";
else if (!strcmp(what, "start"))
mv_string_start = (format) ? format : "";
else if (!strcmp(what, "end"))
mv_string_end = (format) ? format : "";
else if (!strcmp(what, "mul"))
mv_string_mul = (format) ? format : "*";
else if (!strcmp(what, "wedge"))
mv_string_wedge = (format) ? format : "^";
else if (!strcmp(what, "plus"))
mv_string_plus = (format) ? format : " + ";
else if (!strcmp(what, "minus"))
mv_string_minus = (format) ? format : " - "; else {
char msg[1024];
sprintf(msg, "invalid argument to mv_setStringFormat(): %s", what);
mv_throw_exception(msg, MV_EXCEPTION_WARNING);
}
}
namespace g2Profiling {
// Just a bunch of dummy functions:
// Profiling is disabled, but having these functions around
// simplifies a lot.
void profile(unsigned int funcIdx, unsigned short storageTypeIdx, unsigned short nbArg, unsigned short argType[]) {
}
void reset() {
}
void save(const char *filename /*= "E:\\gasandbox\\ga_sandbox\\libgasandbox\\e3ga.gp2"*/, bool append /*= false*/) {
}
void init(const char *filename /*= "E:\\gasandbox\\ga_sandbox\\libgasandbox\\e3ga.gp2"*/,
const char *hostName /*= "localhost"*/, int port /*= 7693*/) {
}
} // end of namespace g2Profiling
// todo: for all storage formats, generate constants
// set to 0
void mv::set() {
// set grade usage
gu(0);
}
// set to copy
void mv::set(const mv &arg1) {
// copy grade usage
gu(arg1.gu());
// copy coordinates
mv_memcpy(m_c, arg1.m_c, mv_size[gu()]);
}
// set to scalar
void mv::set(Float scalarVal) {
// set grade usage
gu(1);
// set type (if profile)
// set coordinate
m_c[0] = scalarVal;
}
// set to coordinates
void mv::set(unsigned int gradeUsage, const Float *coordinates) {
// set grade usage
gu(gradeUsage);
// set coordinates
mv_memcpy(m_c, coordinates, mv_size[gu()]);
}
// set to 1 coordinates
void mv::set(unsigned int gradeUsage, Float c0 ) {
// set grade usage
gu(gradeUsage);
// check the number of coordinates
if (mv_size[gu()] != 1)
throw (-1); // todo: more sensible exception
// set coordinates
m_c[0] = c0;
}
// set to 2 coordinates
void mv::set(unsigned int gradeUsage, Float c0, Float c1 ) {
// set grade usage
gu(gradeUsage);
// check the number of coordinates
if (mv_size[gu()] != 2)
throw (-1); // todo: more sensible exception
// set coordinates
m_c[0] = c0;
m_c[1] = c1;
}
// set to 3 coordinates
void mv::set(unsigned int gradeUsage, Float c0, Float c1, Float c2 ) {
// set grade usage
gu(gradeUsage);
// check the number of coordinates
if (mv_size[gu()] != 3)
throw (-1); // todo: more sensible exception
// set coordinates
m_c[0] = c0;
m_c[1] = c1;
m_c[2] = c2;
}
// set to 4 coordinates
void mv::set(unsigned int gradeUsage, Float c0, Float c1, Float c2, Float c3 ) {
// set grade usage
gu(gradeUsage);
// check the number of coordinates
if (mv_size[gu()] != 4)
throw (-1); // todo: more sensible exception
// set coordinates
m_c[0] = c0;
m_c[1] = c1;
m_c[2] = c2;
m_c[3] = c3;
}
// set to 5 coordinates
void mv::set(unsigned int gradeUsage, Float c0, Float c1, Float c2, Float c3, Float c4 ) {
// set grade usage
gu(gradeUsage);
// check the number of coordinates
if (mv_size[gu()] != 5)
throw (-1); // todo: more sensible exception
// set coordinates
m_c[0] = c0;
m_c[1] = c1;
m_c[2] = c2;
m_c[3] = c3;
m_c[4] = c4;
}
// set to 6 coordinates
void mv::set(unsigned int gradeUsage, Float c0, Float c1, Float c2, Float c3, Float c4, Float c5 ) {
// set grade usage
gu(gradeUsage);
// check the number of coordinates
if (mv_size[gu()] != 6)
throw (-1); // todo: more sensible exception
// set coordinates
m_c[0] = c0;
m_c[1] = c1;
m_c[2] = c2;
m_c[3] = c3;
m_c[4] = c4;
m_c[5] = c5;
}
// set to 7 coordinates
void mv::set(unsigned int gradeUsage, Float c0, Float c1, Float c2, Float c3, Float c4, Float c5, Float c6 ) {
// set grade usage
gu(gradeUsage);
// check the number of coordinates
if (mv_size[gu()] != 7)
throw (-1); // todo: more sensible exception
// set coordinates
m_c[0] = c0;
m_c[1] = c1;
m_c[2] = c2;
m_c[3] = c3;
m_c[4] = c4;
m_c[5] = c5;
m_c[6] = c6;
}
// set to 8 coordinates
void mv::set(unsigned int gradeUsage, Float c0, Float c1, Float c2, Float c3, Float c4, Float c5, Float c6, Float c7 ) {
// set grade usage
gu(gradeUsage);
// check the number of coordinates
if (mv_size[gu()] != 8)
throw (-1); // todo: more sensible exception
// set coordinates
m_c[0] = c0;
m_c[1] = c1;
m_c[2] = c2;
m_c[3] = c3;
m_c[4] = c4;
m_c[5] = c5;
m_c[6] = c6;
m_c[7] = c7;
}
// set to e1_t
void mv::set(const e1_t & arg1) {
// set grade usage
gu(2);
m_c[0] = arg1.m_c[0] ;
m_c[1] = (Float)0;
m_c[2] = (Float)0;
}
// set to e2_t
void mv::set(const e2_t & arg1) {
// set grade usage
gu(2);
m_c[0] = (Float)0;
m_c[1] = arg1.m_c[0] ;
m_c[2] = (Float)0;
}
// set to e3_t
void mv::set(const e3_t & arg1) {
// set grade usage
gu(2);
m_c[0] = (Float)0;
m_c[1] = (Float)0;
m_c[2] = arg1.m_c[0] ;
}
// set to scalar
void mv::set(const scalar & arg1) {
// set grade usage
gu(1);
m_c[0] = arg1.m_c[0] ;
}
// set to vector2D
void mv::set(const vector2D & arg1) {
// set grade usage
gu(2);
m_c[0] = arg1.m_c[0] ;
m_c[1] = arg1.m_c[1] ;
m_c[2] = (Float)0;
}
// set to vector
void mv::set(const vector & arg1) {
// set grade usage
gu(2);
m_c[0] = arg1.m_c[0] ;
m_c[1] = arg1.m_c[1] ;
m_c[2] = arg1.m_c[2] ;
}
// set to bivector
void mv::set(const bivector & arg1) {
// set grade usage
gu(4);
m_c[0] = arg1.m_c[0] ;
m_c[1] = arg1.m_c[1] ;
m_c[2] = arg1.m_c[2] ;
}
// set to trivector
void mv::set(const trivector & arg1) {
// set grade usage
gu(8);
m_c[0] = arg1.m_c[0] ;
}
// set to rotor
void mv::set(const rotor & arg1) {
// set grade usage
gu(5);
m_c[0] = arg1.m_c[0] ;
m_c[1] = arg1.m_c[1] ;
m_c[2] = arg1.m_c[2] ;
m_c[3] = arg1.m_c[3] ;
}
// set to __e1_ct__
void mv::set(const __e1_ct__ & arg1) {
// set grade usage
gu(2);
m_c[0] = (Float)1.0f;
m_c[1] = (Float)0;
m_c[2] = (Float)0;
}
// set to __e2_ct__
void mv::set(const __e2_ct__ & arg1) {
// set grade usage
gu(2);
m_c[0] = (Float)0;
m_c[1] = (Float)1.0f;
m_c[2] = (Float)0;
}
// set to __e3_ct__
void mv::set(const __e3_ct__ & arg1) {
// set grade usage
gu(2);
m_c[0] = (Float)0;
m_c[1] = (Float)0;
m_c[2] = (Float)1.0f;
}
// set to __I3_ct__
void mv::set(const __I3_ct__ & arg1) {
// set grade usage
gu(8);
m_c[0] = (Float)1.0f;
}
// set to __I3i_ct__
void mv::set(const __I3i_ct__ & arg1) {
// set grade usage
gu(8);
m_c[0] = (Float)-1.0f;
}
// set to __syn_smv___e1_e2_e3_e1e2e3
void mv::set(const __syn_smv___e1_e2_e3_e1e2e3 & arg1) {
// set grade usage
gu(10);
m_c[0] = arg1.m_c[0] ;
m_c[1] = arg1.m_c[1] ;
m_c[2] = arg1.m_c[2] ;
m_c[3] = arg1.m_c[3] ;
}
// set to __syn_smv___e1e2f1_0
void mv::set(const __syn_smv___e1e2f1_0 & arg1) {
// set grade usage
gu(4);
m_c[0] = (Float)1.0f;
m_c[1] = (Float)0;
m_c[2] = (Float)0;
}
// set to __syn_smv___e1e2
void mv::set(const __syn_smv___e1e2 & arg1) {
// set grade usage
gu(4);
m_c[0] = arg1.m_c[0] ;
m_c[1] = (Float)0;
m_c[2] = (Float)0;
}
// set to __syn_smv___scalar_e1e2
void mv::set(const __syn_smv___scalar_e1e2 & arg1) {
// set grade usage
gu(5);
m_c[0] = arg1.m_c[0] ;
m_c[1] = arg1.m_c[1] ;
m_c[2] = (Float)0;
m_c[3] = (Float)0;
}
// set to __syn_smv___e3f_1_0
void mv::set(const __syn_smv___e3f_1_0 & arg1) {
// set grade usage
gu(2);
m_c[0] = (Float)0;
m_c[1] = (Float)0;
m_c[2] = (Float)-1.0f;
}
// set to __syn_smv___e1e3_e2e3
void mv::set(const __syn_smv___e1e3_e2e3 & arg1) {
// set grade usage
gu(4);
m_c[0] = (Float)0;
m_c[1] = arg1.m_c[1] ;
m_c[2] = arg1.m_c[0] * (Float)-1.0;
}
// set to __syn_smv___scalar_e1e3_e2e3
void mv::set(const __syn_smv___scalar_e1e3_e2e3 & arg1) {
// set grade usage
gu(5);
m_c[0] = arg1.m_c[0] ;
m_c[1] = (Float)0;
m_c[2] = arg1.m_c[2] ;
m_c[3] = arg1.m_c[1] * (Float)-1.0;
}
// set to __syn_smv___e1e2_e1e3_e2e3_e1e2e3
void mv::set(const __syn_smv___e1e2_e1e3_e2e3_e1e2e3 & arg1) {
// set grade usage
gu(12);
m_c[0] = arg1.m_c[0] ;
m_c[1] = arg1.m_c[2] ;
m_c[2] = arg1.m_c[1] * (Float)-1.0;
m_c[3] = arg1.m_c[3] ;
}
// set to __syn_smv___e1e3f_1_0
void mv::set(const __syn_smv___e1e3f_1_0 & arg1) {
// set grade usage
gu(4);
m_c[0] = (Float)0;
m_c[1] = (Float)0;
m_c[2] = (Float)1.0f;
}
// set to __syn_smv___e1e3
void mv::set(const __syn_smv___e1e3 & arg1) {
// set grade usage
gu(4);
m_c[0] = (Float)0;
m_c[1] = (Float)0;
m_c[2] = arg1.m_c[0] * (Float)-1.0;
}
// set to __syn_smv___scalar_e1e3
void mv::set(const __syn_smv___scalar_e1e3 & arg1) {
// set grade usage
gu(5);
m_c[0] = arg1.m_c[0] ;
m_c[1] = (Float)0;
m_c[2] = (Float)0;
m_c[3] = arg1.m_c[1] * (Float)-1.0;
}
// set to __syn_smv___e2e3f1_0
void mv::set(const __syn_smv___e2e3f1_0 & arg1) {
// set grade usage
gu(4);
m_c[0] = (Float)0;
m_c[1] = (Float)1.0f;
m_c[2] = (Float)0;
}
// set to __syn_smv___e2e3
void mv::set(const __syn_smv___e2e3 & arg1) {
// set grade usage
gu(4);
m_c[0] = (Float)0;
m_c[1] = arg1.m_c[0] ;
m_c[2] = (Float)0;
}
// set to __syn_smv___scalar_e2e3
void mv::set(const __syn_smv___scalar_e2e3 & arg1) {
// set grade usage
gu(5);
m_c[0] = arg1.m_c[0] ;
m_c[1] = (Float)0;
m_c[2] = arg1.m_c[1] ;
m_c[3] = (Float)0;
}
// set to __syn_smv___e2_e3
void mv::set(const __syn_smv___e2_e3 & arg1) {
// set grade usage
gu(2);
m_c[0] = (Float)0;
m_c[1] = arg1.m_c[0] ;
m_c[2] = arg1.m_c[1] ;
}
// set to __syn_smv___e1_e3
void mv::set(const __syn_smv___e1_e3 & arg1) {
// set grade usage
gu(2);
m_c[0] = arg1.m_c[0] ;
m_c[1] = (Float)0;
m_c[2] = arg1.m_c[1] ;
}
// set to __syn_smv___e2_e3_e1e2e3
void mv::set(const __syn_smv___e2_e3_e1e2e3 & arg1) {
// set grade usage
gu(10);
m_c[0] = (Float)0;
m_c[1] = arg1.m_c[0] ;
m_c[2] = arg1.m_c[1] ;
m_c[3] = arg1.m_c[2] ;
}
// set to __syn_smv___e1_e3_e1e2e3
void mv::set(const __syn_smv___e1_e3_e1e2e3 & arg1) {
// set grade usage
gu(10);
m_c[0] = arg1.m_c[0] ;
m_c[1] = (Float)0;
m_c[2] = arg1.m_c[1] ;
m_c[3] = arg1.m_c[2] ;
}
// set to __syn_smv___e1_e2_e1e2e3
void mv::set(const __syn_smv___e1_e2_e1e2e3 & arg1) {
// set grade usage
gu(10);
m_c[0] = arg1.m_c[0] ;
m_c[1] = arg1.m_c[1] ;
m_c[2] = (Float)0;
m_c[3] = arg1.m_c[2] ;
}
// set to __syn_smv___scalar_e1e2_e1e3
void mv::set(const __syn_smv___scalar_e1e2_e1e3 & arg1) {
// set grade usage
gu(5);
m_c[0] = arg1.m_c[0] ;
m_c[1] = arg1.m_c[1] ;
m_c[2] = (Float)0;
m_c[3] = arg1.m_c[2] * (Float)-1.0;
}
// set to __syn_smv___scalar_e1e2_e2e3
void mv::set(const __syn_smv___scalar_e1e2_e2e3 & arg1) {
// set grade usage
gu(5);
m_c[0] = arg1.m_c[0] ;
m_c[1] = arg1.m_c[1] ;
m_c[2] = arg1.m_c[2] ;
m_c[3] = (Float)0;
}
// set to __syn_smv___e2f_1_0
void mv::set(const __syn_smv___e2f_1_0 & arg1) {
// set grade usage
gu(2);
m_c[0] = (Float)0;
m_c[1] = (Float)-1.0f;
m_c[2] = (Float)0;
}
// set to __syn_smv___e1e2_e1e3
void mv::set(const __syn_smv___e1e2_e1e3 & arg1) {
// set grade usage
gu(4);
m_c[0] = arg1.m_c[0] ;
m_c[1] = (Float)0;
m_c[2] = arg1.m_c[1] * (Float)-1.0;
}
// set to __syn_smv___e1e2_e2e3
void mv::set(const __syn_smv___e1e2_e2e3 & arg1) {
// set grade usage
gu(4);
m_c[0] = arg1.m_c[0] ;
m_c[1] = arg1.m_c[1] ;
m_c[2] = (Float)0;
}
// set to __syn_smv___e1f1_0_e2f1_0
void mv::set(const __syn_smv___e1f1_0_e2f1_0 & arg1) {
// set grade usage
gu(2);
m_c[0] = (Float)1.0f;
m_c[1] = (Float)1.0f;
m_c[2] = (Float)0;
}
// set to __syn_smv___e1f1_0_e2f1_0_e3f1_0
void mv::set(const __syn_smv___e1f1_0_e2f1_0_e3f1_0 & arg1) {
// set grade usage
gu(2);
m_c[0] = (Float)1.0f;
m_c[1] = (Float)1.0f;
m_c[2] = (Float)1.0f;
}
// set to __syn_smv___e2_e1f1_0
void mv::set(const __syn_smv___e2_e1f1_0 & arg1) {
// set grade usage
gu(2);
m_c[0] = (Float)1.0f;
m_c[1] = arg1.m_c[0] ;
m_c[2] = (Float)0;
}
// set to __syn_smv___scalar_e1_e2_e3_e1e2e3
void mv::set(const __syn_smv___scalar_e1_e2_e3_e1e2e3 & arg1) {
// set grade usage
gu(11);
m_c[0] = arg1.m_c[0] ;
m_c[1] = arg1.m_c[1] ;
m_c[2] = arg1.m_c[2] ;
m_c[3] = arg1.m_c[3] ;
m_c[4] = arg1.m_c[4] ;
}
// set to __syn_smv___e1_e3f1_0
void mv::set(const __syn_smv___e1_e3f1_0 & arg1) {
// set grade usage
gu(2);
m_c[0] = arg1.m_c[0] ;
m_c[1] = (Float)0;
m_c[2] = (Float)1.0f;
}
// assign copy
mv& mv::operator=(const mv &arg1) {
set(arg1);
return *this;
}
// assign scalar
mv& mv::operator=(Float s) {
set(s);
return *this;
}
// assign e1_t
mv& mv::operator=(const e1_t& arg1) {
set(arg1);
return *this;
}
// assign e2_t
mv& mv::operator=(const e2_t& arg1) {
set(arg1);
return *this;
}
// assign e3_t
mv& mv::operator=(const e3_t& arg1) {
set(arg1);
return *this;
}
// assign scalar
mv& mv::operator=(const scalar& arg1) {
set(arg1);
return *this;
}
// assign vector2D
mv& mv::operator=(const vector2D& arg1) {
set(arg1);
return *this;
}
// assign vector
mv& mv::operator=(const vector& arg1) {
set(arg1);
return *this;
}
// assign bivector
mv& mv::operator=(const bivector& arg1) {
set(arg1);
return *this;
}
// assign trivector
mv& mv::operator=(const trivector& arg1) {
set(arg1);
return *this;
}
// assign rotor
mv& mv::operator=(const rotor& arg1) {
set(arg1);
return *this;
}
// assign __e1_ct__
mv& mv::operator=(const __e1_ct__& arg1) {
set(arg1);
return *this;
}
// assign __e2_ct__
mv& mv::operator=(const __e2_ct__& arg1) {
set(arg1);
return *this;
}
// assign __e3_ct__
mv& mv::operator=(const __e3_ct__& arg1) {
set(arg1);
return *this;
}
// assign __I3_ct__
mv& mv::operator=(const __I3_ct__& arg1) {
set(arg1);
return *this;
}
// assign __I3i_ct__
mv& mv::operator=(const __I3i_ct__& arg1) {
set(arg1);
return *this;
}
// assign __syn_smv___e1_e2_e3_e1e2e3
mv& mv::operator=(const __syn_smv___e1_e2_e3_e1e2e3& arg1) {
set(arg1);
return *this;
}
// assign __syn_smv___e1e2f1_0
mv& mv::operator=(const __syn_smv___e1e2f1_0& arg1) {
set(arg1);
return *this;
}
// assign __syn_smv___e1e2
mv& mv::operator=(const __syn_smv___e1e2& arg1) {
set(arg1);
return *this;
}
// assign __syn_smv___scalar_e1e2
mv& mv::operator=(const __syn_smv___scalar_e1e2& arg1) {
set(arg1);
return *this;
}
// assign __syn_smv___e3f_1_0
mv& mv::operator=(const __syn_smv___e3f_1_0& arg1) {
set(arg1);
return *this;
}
// assign __syn_smv___e1e3_e2e3
mv& mv::operator=(const __syn_smv___e1e3_e2e3& arg1) {
set(arg1);
return *this;
}
// assign __syn_smv___scalar_e1e3_e2e3
mv& mv::operator=(const __syn_smv___scalar_e1e3_e2e3& arg1) {
set(arg1);
return *this;
}
// assign __syn_smv___e1e2_e1e3_e2e3_e1e2e3
mv& mv::operator=(const __syn_smv___e1e2_e1e3_e2e3_e1e2e3& arg1) {
set(arg1);
return *this;
}
// assign __syn_smv___e1e3f_1_0
mv& mv::operator=(const __syn_smv___e1e3f_1_0& arg1) {
set(arg1);
return *this;
}
// assign __syn_smv___e1e3
mv& mv::operator=(const __syn_smv___e1e3& arg1) {
set(arg1);
return *this;
}
// assign __syn_smv___scalar_e1e3
mv& mv::operator=(const __syn_smv___scalar_e1e3& arg1) {
set(arg1);
return *this;
}
// assign __syn_smv___e2e3f1_0
mv& mv::operator=(const __syn_smv___e2e3f1_0& arg1) {
set(arg1);
return *this;
}
// assign __syn_smv___e2e3
mv& mv::operator=(const __syn_smv___e2e3& arg1) {
set(arg1);
return *this;
}
// assign __syn_smv___scalar_e2e3
mv& mv::operator=(const __syn_smv___scalar_e2e3& arg1) {
set(arg1);
return *this;
}
// assign __syn_smv___e2_e3
mv& mv::operator=(const __syn_smv___e2_e3& arg1) {
set(arg1);
return *this;
}
// assign __syn_smv___e1_e3
mv& mv::operator=(const __syn_smv___e1_e3& arg1) {
set(arg1);
return *this;
}
// assign __syn_smv___e2_e3_e1e2e3
mv& mv::operator=(const __syn_smv___e2_e3_e1e2e3& arg1) {
set(arg1);
return *this;
}
// assign __syn_smv___e1_e3_e1e2e3
mv& mv::operator=(const __syn_smv___e1_e3_e1e2e3& arg1) {
set(arg1);
return *this;
}
// assign __syn_smv___e1_e2_e1e2e3
mv& mv::operator=(const __syn_smv___e1_e2_e1e2e3& arg1) {
set(arg1);
return *this;
}
// assign __syn_smv___scalar_e1e2_e1e3
mv& mv::operator=(const __syn_smv___scalar_e1e2_e1e3& arg1) {
set(arg1);
return *this;
}
// assign __syn_smv___scalar_e1e2_e2e3
mv& mv::operator=(const __syn_smv___scalar_e1e2_e2e3& arg1) {
set(arg1);
return *this;
}
// assign __syn_smv___e2f_1_0
mv& mv::operator=(const __syn_smv___e2f_1_0& arg1) {
set(arg1);
return *this;
}
// assign __syn_smv___e1e2_e1e3
mv& mv::operator=(const __syn_smv___e1e2_e1e3& arg1) {
set(arg1);
return *this;
}
// assign __syn_smv___e1e2_e2e3
mv& mv::operator=(const __syn_smv___e1e2_e2e3& arg1) {
set(arg1);
return *this;
}
// assign __syn_smv___e1f1_0_e2f1_0
mv& mv::operator=(const __syn_smv___e1f1_0_e2f1_0& arg1) {
set(arg1);
return *this;
}
// assign __syn_smv___e1f1_0_e2f1_0_e3f1_0
mv& mv::operator=(const __syn_smv___e1f1_0_e2f1_0_e3f1_0& arg1) {
set(arg1);
return *this;
}
// assign __syn_smv___e2_e1f1_0
mv& mv::operator=(const __syn_smv___e2_e1f1_0& arg1) {
set(arg1);
return *this;
}
// assign __syn_smv___scalar_e1_e2_e3_e1e2e3
mv& mv::operator=(const __syn_smv___scalar_e1_e2_e3_e1e2e3& arg1) {
set(arg1);
return *this;
}
// assign __syn_smv___e1_e3f1_0
mv& mv::operator=(const __syn_smv___e1_e3f1_0& arg1) {
set(arg1);
return *this;
}
float mv::largestCoordinate() const {
int nc = mv_size[gu()], i;
Float maxC = -1.0, C;
for (i = 0; i < nc; i++) {
C = (m_c[i] < (Float)0.0) ? -m_c[i] : m_c[i];
if (C > maxC) maxC = C;
}
return maxC;
}
float mv::largestBasisBlade(unsigned int &bm) const {
int nc = mv_size[gu()];
Float maxC = -1.0, C;
int idx = 0;
int grade = 0;
int i = 0;
while (i < nc) {
if (gu() & (1 << grade)) {
for (int j = 0; j < mv_gradeSize[grade]; j++) {
C = (m_c[i] < (Float)0.0) ? -m_c[i] : m_c[i];
if (C > maxC) {
maxC = C;
bm = mv_basisElementBitmapByIndex[idx];
}
idx++;
i++;
}
}
else idx += mv_gradeSize[grade];
grade++;
}
return maxC;
}
// set to mv
void e1_t::set(const mv & arg1) {
int gidx = 0;
if (arg1.gu() & 1) {
gidx += 1; }
else {
}
if (arg1.gu() & 2) {
m_c[0] = arg1.m_c[gidx + 0];
}
else {
m_c[0] = (Float)0.0;
}
}
float e1_t::largestCoordinate() const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0];
return maxC;
}
float e1_t::largestBasisBlade(unsigned int &bm) const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0];
bm = 1;
return maxC;
}
// set to mv
void e2_t::set(const mv & arg1) {
int gidx = 0;
if (arg1.gu() & 1) {
gidx += 1; }
else {
}
if (arg1.gu() & 2) {
m_c[0] = arg1.m_c[gidx + 1];
}
else {
m_c[0] = (Float)0.0;
}
}
float e2_t::largestCoordinate() const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0];
return maxC;
}
float e2_t::largestBasisBlade(unsigned int &bm) const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0];
bm = 2;
return maxC;
}
// set to mv
void e3_t::set(const mv & arg1) {
int gidx = 0;
if (arg1.gu() & 1) {
gidx += 1; }
else {
}
if (arg1.gu() & 2) {
m_c[0] = arg1.m_c[gidx + 2];
}
else {
m_c[0] = (Float)0.0;
}
}
float e3_t::largestCoordinate() const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0];
return maxC;
}
float e3_t::largestBasisBlade(unsigned int &bm) const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0];
bm = 4;
return maxC;
}
// set to mv
void scalar::set(const mv & arg1) {
if (arg1.gu() & 1) {
m_c[0] = arg1.m_c[0];
}
else {
m_c[0] = (Float)0.0;
}
}
float scalar::largestCoordinate() const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0];
return maxC;
}
float scalar::largestBasisBlade(unsigned int &bm) const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0];
bm = 0;
return maxC;
}
// set to mv
void vector2D::set(const mv & arg1) {
int gidx = 0;
if (arg1.gu() & 1) {
gidx += 1; }
else {
}
if (arg1.gu() & 2) {
m_c[0] = arg1.m_c[gidx + 0];
m_c[1] = arg1.m_c[gidx + 1];
}
else {
m_c[0] = (Float)0.0;
m_c[1] = (Float)0.0;
}
}
float vector2D::largestCoordinate() const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) maxC = C;
return maxC;
}
float vector2D::largestBasisBlade(unsigned int &bm) const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
bm = 1;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) {
maxC = C;
bm = 2;
}
return maxC;
}
// set to mv
void vector::set(const mv & arg1) {
int gidx = 0;
if (arg1.gu() & 1) {
gidx += 1; }
else {
}
if (arg1.gu() & 2) {
m_c[0] = arg1.m_c[gidx + 0];
m_c[1] = arg1.m_c[gidx + 1];
m_c[2] = arg1.m_c[gidx + 2];
}
else {
m_c[0] = (Float)0.0;
m_c[1] = (Float)0.0;
m_c[2] = (Float)0.0;
}
}
float vector::largestCoordinate() const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) maxC = C;
C = (m_c[2] < (Float)0.0) ? -m_c[2] : m_c[2];
if (C > maxC) maxC = C;
return maxC;
}
float vector::largestBasisBlade(unsigned int &bm) const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
bm = 1;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) {
maxC = C;
bm = 2;
}
C = (m_c[2] < (Float)0.0) ? -m_c[2] : m_c[2];
if (C > maxC) {
maxC = C;
bm = 4;
}
return maxC;
}
// set to mv
void bivector::set(const mv & arg1) {
int gidx = 0;
if (arg1.gu() & 1) {
gidx += 1; }
else {
}
if (arg1.gu() & 2) {
gidx += 3; }
else {
}
if (arg1.gu() & 4) {
m_c[0] = arg1.m_c[gidx + 0];
m_c[1] = arg1.m_c[gidx + 1];
m_c[2] = arg1.m_c[gidx + 2];
}
else {
m_c[0] = (Float)0.0;
m_c[1] = (Float)0.0;
m_c[2] = (Float)0.0;
}
}
float bivector::largestCoordinate() const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) maxC = C;
C = (m_c[2] < (Float)0.0) ? -m_c[2] : m_c[2];
if (C > maxC) maxC = C;
return maxC;
}
float bivector::largestBasisBlade(unsigned int &bm) const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
bm = 3;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) {
maxC = C;
bm = 6;
}
C = (m_c[2] < (Float)0.0) ? -m_c[2] : m_c[2];
if (C > maxC) {
maxC = C;
bm = 5;
}
return maxC;
}
// set to mv
void trivector::set(const mv & arg1) {
int gidx = 0;
if (arg1.gu() & 1) {
gidx += 1; }
else {
}
if (arg1.gu() & 2) {
gidx += 3; }
else {
}
if (arg1.gu() & 4) {
gidx += 3; }
else {
}
if (arg1.gu() & 8) {
m_c[0] = arg1.m_c[gidx + 0];
}
else {
m_c[0] = (Float)0.0;
}
}
float trivector::largestCoordinate() const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0];
return maxC;
}
float trivector::largestBasisBlade(unsigned int &bm) const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0];
bm = 7;
return maxC;
}
// set to mv
void rotor::set(const mv & arg1) {
int gidx = 0;
if (arg1.gu() & 1) {
m_c[0] = arg1.m_c[gidx + 0];
gidx += 1; }
else {
m_c[0] = (Float)0.0;
}
if (arg1.gu() & 2) {
gidx += 3; }
else {
}
if (arg1.gu() & 4) {
m_c[1] = arg1.m_c[gidx + 0];
m_c[2] = arg1.m_c[gidx + 1];
m_c[3] = arg1.m_c[gidx + 2];
}
else {
m_c[1] = (Float)0.0;
m_c[2] = (Float)0.0;
m_c[3] = (Float)0.0;
}
}
float rotor::largestCoordinate() const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) maxC = C;
C = (m_c[2] < (Float)0.0) ? -m_c[2] : m_c[2];
if (C > maxC) maxC = C;
C = (m_c[3] < (Float)0.0) ? -m_c[3] : m_c[3];
if (C > maxC) maxC = C;
return maxC;
}
float rotor::largestBasisBlade(unsigned int &bm) const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
bm = 0;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) {
maxC = C;
bm = 3;
}
C = (m_c[2] < (Float)0.0) ? -m_c[2] : m_c[2];
if (C > maxC) {
maxC = C;
bm = 6;
}
C = (m_c[3] < (Float)0.0) ? -m_c[3] : m_c[3];
if (C > maxC) {
maxC = C;
bm = 5;
}
return maxC;
}
// set to mv
void __e1_ct__::set(const mv & arg1) {
}
float __e1_ct__::largestCoordinate() const {
Float maxC = (Float)1.0f;
return maxC;
}
float __e1_ct__::largestBasisBlade(unsigned int &bm) const {
Float maxC = (Float)1.0f;
bm = 1;
return maxC;
}
// set to mv
void __e2_ct__::set(const mv & arg1) {
}
float __e2_ct__::largestCoordinate() const {
Float maxC = (Float)1.0f;
return maxC;
}
float __e2_ct__::largestBasisBlade(unsigned int &bm) const {
Float maxC = (Float)1.0f;
bm = 2;
return maxC;
}
// set to mv
void __e3_ct__::set(const mv & arg1) {
}
float __e3_ct__::largestCoordinate() const {
Float maxC = (Float)1.0f;
return maxC;
}
float __e3_ct__::largestBasisBlade(unsigned int &bm) const {
Float maxC = (Float)1.0f;
bm = 4;
return maxC;
}
// set to mv
void __I3_ct__::set(const mv & arg1) {
}
float __I3_ct__::largestCoordinate() const {
Float maxC = (Float)1.0f;
return maxC;
}
float __I3_ct__::largestBasisBlade(unsigned int &bm) const {
Float maxC = (Float)1.0f;
bm = 7;
return maxC;
}
// set to mv
void __I3i_ct__::set(const mv & arg1) {
}
float __I3i_ct__::largestCoordinate() const {
Float maxC = (Float)1.0f;
return maxC;
}
float __I3i_ct__::largestBasisBlade(unsigned int &bm) const {
Float maxC = (Float)1.0f;
bm = 7;
return maxC;
}
// set to mv
void __syn_smv___e1_e2_e3_e1e2e3::set(const mv & arg1) {
int gidx = 0;
if (arg1.gu() & 1) {
gidx += 1; }
else {
}
if (arg1.gu() & 2) {
m_c[0] = arg1.m_c[gidx + 0];
m_c[1] = arg1.m_c[gidx + 1];
m_c[2] = arg1.m_c[gidx + 2];
gidx += 3; }
else {
m_c[0] = (Float)0.0;
m_c[1] = (Float)0.0;
m_c[2] = (Float)0.0;
}
if (arg1.gu() & 4) {
gidx += 3; }
else {
}
if (arg1.gu() & 8) {
m_c[3] = arg1.m_c[gidx + 0];
}
else {
m_c[3] = (Float)0.0;
}
}
float __syn_smv___e1_e2_e3_e1e2e3::largestCoordinate() const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) maxC = C;
C = (m_c[2] < (Float)0.0) ? -m_c[2] : m_c[2];
if (C > maxC) maxC = C;
C = (m_c[3] < (Float)0.0) ? -m_c[3] : m_c[3];
if (C > maxC) maxC = C;
return maxC;
}
float __syn_smv___e1_e2_e3_e1e2e3::largestBasisBlade(unsigned int &bm) const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
bm = 1;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) {
maxC = C;
bm = 2;
}
C = (m_c[2] < (Float)0.0) ? -m_c[2] : m_c[2];
if (C > maxC) {
maxC = C;
bm = 4;
}
C = (m_c[3] < (Float)0.0) ? -m_c[3] : m_c[3];
if (C > maxC) {
maxC = C;
bm = 7;
}
return maxC;
}
// set to mv
void __syn_smv___e1e2f1_0::set(const mv & arg1) {
}
float __syn_smv___e1e2f1_0::largestCoordinate() const {
Float maxC = (Float)1.0f;
return maxC;
}
float __syn_smv___e1e2f1_0::largestBasisBlade(unsigned int &bm) const {
Float maxC = (Float)1.0f;
bm = 3;
return maxC;
}
// set to mv
void __syn_smv___e1e2::set(const mv & arg1) {
int gidx = 0;
if (arg1.gu() & 1) {
gidx += 1; }
else {
}
if (arg1.gu() & 2) {
gidx += 3; }
else {
}
if (arg1.gu() & 4) {
m_c[0] = arg1.m_c[gidx + 0];
}
else {
m_c[0] = (Float)0.0;
}
}
float __syn_smv___e1e2::largestCoordinate() const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0];
return maxC;
}
float __syn_smv___e1e2::largestBasisBlade(unsigned int &bm) const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0];
bm = 3;
return maxC;
}
// set to mv
void __syn_smv___scalar_e1e2::set(const mv & arg1) {
int gidx = 0;
if (arg1.gu() & 1) {
m_c[0] = arg1.m_c[gidx + 0];
gidx += 1; }
else {
m_c[0] = (Float)0.0;
}
if (arg1.gu() & 2) {
gidx += 3; }
else {
}
if (arg1.gu() & 4) {
m_c[1] = arg1.m_c[gidx + 0];
}
else {
m_c[1] = (Float)0.0;
}
}
float __syn_smv___scalar_e1e2::largestCoordinate() const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) maxC = C;
return maxC;
}
float __syn_smv___scalar_e1e2::largestBasisBlade(unsigned int &bm) const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
bm = 0;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) {
maxC = C;
bm = 3;
}
return maxC;
}
// set to mv
void __syn_smv___e3f_1_0::set(const mv & arg1) {
}
float __syn_smv___e3f_1_0::largestCoordinate() const {
Float maxC = (Float)1.0f;
return maxC;
}
float __syn_smv___e3f_1_0::largestBasisBlade(unsigned int &bm) const {
Float maxC = (Float)1.0f;
bm = 4;
return maxC;
}
// set to mv
void __syn_smv___e1e3_e2e3::set(const mv & arg1) {
int gidx = 0;
if (arg1.gu() & 1) {
gidx += 1; }
else {
}
if (arg1.gu() & 2) {
gidx += 3; }
else {
}
if (arg1.gu() & 4) {
m_c[0] = arg1.m_c[gidx + 2]* (Float)-1.0;
m_c[1] = arg1.m_c[gidx + 1];
}
else {
m_c[0] = (Float)0.0;
m_c[1] = (Float)0.0;
}
}
float __syn_smv___e1e3_e2e3::largestCoordinate() const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) maxC = C;
return maxC;
}
float __syn_smv___e1e3_e2e3::largestBasisBlade(unsigned int &bm) const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
bm = 5;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) {
maxC = C;
bm = 6;
}
return maxC;
}
// set to mv
void __syn_smv___scalar_e1e3_e2e3::set(const mv & arg1) {
int gidx = 0;
if (arg1.gu() & 1) {
m_c[0] = arg1.m_c[gidx + 0];
gidx += 1; }
else {
m_c[0] = (Float)0.0;
}
if (arg1.gu() & 2) {
gidx += 3; }
else {
}
if (arg1.gu() & 4) {
m_c[1] = arg1.m_c[gidx + 2]* (Float)-1.0;
m_c[2] = arg1.m_c[gidx + 1];
}
else {
m_c[1] = (Float)0.0;
m_c[2] = (Float)0.0;
}
}
float __syn_smv___scalar_e1e3_e2e3::largestCoordinate() const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) maxC = C;
C = (m_c[2] < (Float)0.0) ? -m_c[2] : m_c[2];
if (C > maxC) maxC = C;
return maxC;
}
float __syn_smv___scalar_e1e3_e2e3::largestBasisBlade(unsigned int &bm) const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
bm = 0;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) {
maxC = C;
bm = 5;
}
C = (m_c[2] < (Float)0.0) ? -m_c[2] : m_c[2];
if (C > maxC) {
maxC = C;
bm = 6;
}
return maxC;
}
// set to mv
void __syn_smv___e1e2_e1e3_e2e3_e1e2e3::set(const mv & arg1) {
int gidx = 0;
if (arg1.gu() & 1) {
gidx += 1; }
else {
}
if (arg1.gu() & 2) {
gidx += 3; }
else {
}
if (arg1.gu() & 4) {
m_c[0] = arg1.m_c[gidx + 0];
m_c[1] = arg1.m_c[gidx + 2]* (Float)-1.0;
m_c[2] = arg1.m_c[gidx + 1];
gidx += 3; }
else {
m_c[0] = (Float)0.0;
m_c[1] = (Float)0.0;
m_c[2] = (Float)0.0;
}
if (arg1.gu() & 8) {
m_c[3] = arg1.m_c[gidx + 0];
}
else {
m_c[3] = (Float)0.0;
}
}
float __syn_smv___e1e2_e1e3_e2e3_e1e2e3::largestCoordinate() const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) maxC = C;
C = (m_c[2] < (Float)0.0) ? -m_c[2] : m_c[2];
if (C > maxC) maxC = C;
C = (m_c[3] < (Float)0.0) ? -m_c[3] : m_c[3];
if (C > maxC) maxC = C;
return maxC;
}
float __syn_smv___e1e2_e1e3_e2e3_e1e2e3::largestBasisBlade(unsigned int &bm) const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
bm = 3;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) {
maxC = C;
bm = 5;
}
C = (m_c[2] < (Float)0.0) ? -m_c[2] : m_c[2];
if (C > maxC) {
maxC = C;
bm = 6;
}
C = (m_c[3] < (Float)0.0) ? -m_c[3] : m_c[3];
if (C > maxC) {
maxC = C;
bm = 7;
}
return maxC;
}
// set to mv
void __syn_smv___e1e3f_1_0::set(const mv & arg1) {
}
float __syn_smv___e1e3f_1_0::largestCoordinate() const {
Float maxC = (Float)1.0f;
return maxC;
}
float __syn_smv___e1e3f_1_0::largestBasisBlade(unsigned int &bm) const {
Float maxC = (Float)1.0f;
bm = 5;
return maxC;
}
// set to mv
void __syn_smv___e1e3::set(const mv & arg1) {
int gidx = 0;
if (arg1.gu() & 1) {
gidx += 1; }
else {
}
if (arg1.gu() & 2) {
gidx += 3; }
else {
}
if (arg1.gu() & 4) {
m_c[0] = arg1.m_c[gidx + 2]* (Float)-1.0;
}
else {
m_c[0] = (Float)0.0;
}
}
float __syn_smv___e1e3::largestCoordinate() const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0];
return maxC;
}
float __syn_smv___e1e3::largestBasisBlade(unsigned int &bm) const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0];
bm = 5;
return maxC;
}
// set to mv
void __syn_smv___scalar_e1e3::set(const mv & arg1) {
int gidx = 0;
if (arg1.gu() & 1) {
m_c[0] = arg1.m_c[gidx + 0];
gidx += 1; }
else {
m_c[0] = (Float)0.0;
}
if (arg1.gu() & 2) {
gidx += 3; }
else {
}
if (arg1.gu() & 4) {
m_c[1] = arg1.m_c[gidx + 2]* (Float)-1.0;
}
else {
m_c[1] = (Float)0.0;
}
}
float __syn_smv___scalar_e1e3::largestCoordinate() const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) maxC = C;
return maxC;
}
float __syn_smv___scalar_e1e3::largestBasisBlade(unsigned int &bm) const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
bm = 0;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) {
maxC = C;
bm = 5;
}
return maxC;
}
// set to mv
void __syn_smv___e2e3f1_0::set(const mv & arg1) {
}
float __syn_smv___e2e3f1_0::largestCoordinate() const {
Float maxC = (Float)1.0f;
return maxC;
}
float __syn_smv___e2e3f1_0::largestBasisBlade(unsigned int &bm) const {
Float maxC = (Float)1.0f;
bm = 6;
return maxC;
}
// set to mv
void __syn_smv___e2e3::set(const mv & arg1) {
int gidx = 0;
if (arg1.gu() & 1) {
gidx += 1; }
else {
}
if (arg1.gu() & 2) {
gidx += 3; }
else {
}
if (arg1.gu() & 4) {
m_c[0] = arg1.m_c[gidx + 1];
}
else {
m_c[0] = (Float)0.0;
}
}
float __syn_smv___e2e3::largestCoordinate() const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0];
return maxC;
}
float __syn_smv___e2e3::largestBasisBlade(unsigned int &bm) const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0];
bm = 6;
return maxC;
}
// set to mv
void __syn_smv___scalar_e2e3::set(const mv & arg1) {
int gidx = 0;
if (arg1.gu() & 1) {
m_c[0] = arg1.m_c[gidx + 0];
gidx += 1; }
else {
m_c[0] = (Float)0.0;
}
if (arg1.gu() & 2) {
gidx += 3; }
else {
}
if (arg1.gu() & 4) {
m_c[1] = arg1.m_c[gidx + 1];
}
else {
m_c[1] = (Float)0.0;
}
}
float __syn_smv___scalar_e2e3::largestCoordinate() const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) maxC = C;
return maxC;
}
float __syn_smv___scalar_e2e3::largestBasisBlade(unsigned int &bm) const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
bm = 0;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) {
maxC = C;
bm = 6;
}
return maxC;
}
// set to mv
void __syn_smv___e2_e3::set(const mv & arg1) {
int gidx = 0;
if (arg1.gu() & 1) {
gidx += 1; }
else {
}
if (arg1.gu() & 2) {
m_c[0] = arg1.m_c[gidx + 1];
m_c[1] = arg1.m_c[gidx + 2];
}
else {
m_c[0] = (Float)0.0;
m_c[1] = (Float)0.0;
}
}
float __syn_smv___e2_e3::largestCoordinate() const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) maxC = C;
return maxC;
}
float __syn_smv___e2_e3::largestBasisBlade(unsigned int &bm) const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
bm = 2;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) {
maxC = C;
bm = 4;
}
return maxC;
}
// set to mv
void __syn_smv___e1_e3::set(const mv & arg1) {
int gidx = 0;
if (arg1.gu() & 1) {
gidx += 1; }
else {
}
if (arg1.gu() & 2) {
m_c[0] = arg1.m_c[gidx + 0];
m_c[1] = arg1.m_c[gidx + 2];
}
else {
m_c[0] = (Float)0.0;
m_c[1] = (Float)0.0;
}
}
float __syn_smv___e1_e3::largestCoordinate() const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) maxC = C;
return maxC;
}
float __syn_smv___e1_e3::largestBasisBlade(unsigned int &bm) const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
bm = 1;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) {
maxC = C;
bm = 4;
}
return maxC;
}
// set to mv
void __syn_smv___e2_e3_e1e2e3::set(const mv & arg1) {
int gidx = 0;
if (arg1.gu() & 1) {
gidx += 1; }
else {
}
if (arg1.gu() & 2) {
m_c[0] = arg1.m_c[gidx + 1];
m_c[1] = arg1.m_c[gidx + 2];
gidx += 3; }
else {
m_c[0] = (Float)0.0;
m_c[1] = (Float)0.0;
}
if (arg1.gu() & 4) {
gidx += 3; }
else {
}
if (arg1.gu() & 8) {
m_c[2] = arg1.m_c[gidx + 0];
}
else {
m_c[2] = (Float)0.0;
}
}
float __syn_smv___e2_e3_e1e2e3::largestCoordinate() const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) maxC = C;
C = (m_c[2] < (Float)0.0) ? -m_c[2] : m_c[2];
if (C > maxC) maxC = C;
return maxC;
}
float __syn_smv___e2_e3_e1e2e3::largestBasisBlade(unsigned int &bm) const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
bm = 2;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) {
maxC = C;
bm = 4;
}
C = (m_c[2] < (Float)0.0) ? -m_c[2] : m_c[2];
if (C > maxC) {
maxC = C;
bm = 7;
}
return maxC;
}
// set to mv
void __syn_smv___e1_e3_e1e2e3::set(const mv & arg1) {
int gidx = 0;
if (arg1.gu() & 1) {
gidx += 1; }
else {
}
if (arg1.gu() & 2) {
m_c[0] = arg1.m_c[gidx + 0];
m_c[1] = arg1.m_c[gidx + 2];
gidx += 3; }
else {
m_c[0] = (Float)0.0;
m_c[1] = (Float)0.0;
}
if (arg1.gu() & 4) {
gidx += 3; }
else {
}
if (arg1.gu() & 8) {
m_c[2] = arg1.m_c[gidx + 0];
}
else {
m_c[2] = (Float)0.0;
}
}
float __syn_smv___e1_e3_e1e2e3::largestCoordinate() const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) maxC = C;
C = (m_c[2] < (Float)0.0) ? -m_c[2] : m_c[2];
if (C > maxC) maxC = C;
return maxC;
}
float __syn_smv___e1_e3_e1e2e3::largestBasisBlade(unsigned int &bm) const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
bm = 1;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) {
maxC = C;
bm = 4;
}
C = (m_c[2] < (Float)0.0) ? -m_c[2] : m_c[2];
if (C > maxC) {
maxC = C;
bm = 7;
}
return maxC;
}
// set to mv
void __syn_smv___e1_e2_e1e2e3::set(const mv & arg1) {
int gidx = 0;
if (arg1.gu() & 1) {
gidx += 1; }
else {
}
if (arg1.gu() & 2) {
m_c[0] = arg1.m_c[gidx + 0];
m_c[1] = arg1.m_c[gidx + 1];
gidx += 3; }
else {
m_c[0] = (Float)0.0;
m_c[1] = (Float)0.0;
}
if (arg1.gu() & 4) {
gidx += 3; }
else {
}
if (arg1.gu() & 8) {
m_c[2] = arg1.m_c[gidx + 0];
}
else {
m_c[2] = (Float)0.0;
}
}
float __syn_smv___e1_e2_e1e2e3::largestCoordinate() const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) maxC = C;
C = (m_c[2] < (Float)0.0) ? -m_c[2] : m_c[2];
if (C > maxC) maxC = C;
return maxC;
}
float __syn_smv___e1_e2_e1e2e3::largestBasisBlade(unsigned int &bm) const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
bm = 1;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) {
maxC = C;
bm = 2;
}
C = (m_c[2] < (Float)0.0) ? -m_c[2] : m_c[2];
if (C > maxC) {
maxC = C;
bm = 7;
}
return maxC;
}
// set to mv
void __syn_smv___scalar_e1e2_e1e3::set(const mv & arg1) {
int gidx = 0;
if (arg1.gu() & 1) {
m_c[0] = arg1.m_c[gidx + 0];
gidx += 1; }
else {
m_c[0] = (Float)0.0;
}
if (arg1.gu() & 2) {
gidx += 3; }
else {
}
if (arg1.gu() & 4) {
m_c[1] = arg1.m_c[gidx + 0];
m_c[2] = arg1.m_c[gidx + 2]* (Float)-1.0;
}
else {
m_c[1] = (Float)0.0;
m_c[2] = (Float)0.0;
}
}
float __syn_smv___scalar_e1e2_e1e3::largestCoordinate() const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) maxC = C;
C = (m_c[2] < (Float)0.0) ? -m_c[2] : m_c[2];
if (C > maxC) maxC = C;
return maxC;
}
float __syn_smv___scalar_e1e2_e1e3::largestBasisBlade(unsigned int &bm) const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
bm = 0;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) {
maxC = C;
bm = 3;
}
C = (m_c[2] < (Float)0.0) ? -m_c[2] : m_c[2];
if (C > maxC) {
maxC = C;
bm = 5;
}
return maxC;
}
// set to mv
void __syn_smv___scalar_e1e2_e2e3::set(const mv & arg1) {
int gidx = 0;
if (arg1.gu() & 1) {
m_c[0] = arg1.m_c[gidx + 0];
gidx += 1; }
else {
m_c[0] = (Float)0.0;
}
if (arg1.gu() & 2) {
gidx += 3; }
else {
}
if (arg1.gu() & 4) {
m_c[1] = arg1.m_c[gidx + 0];
m_c[2] = arg1.m_c[gidx + 1];
}
else {
m_c[1] = (Float)0.0;
m_c[2] = (Float)0.0;
}
}
float __syn_smv___scalar_e1e2_e2e3::largestCoordinate() const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) maxC = C;
C = (m_c[2] < (Float)0.0) ? -m_c[2] : m_c[2];
if (C > maxC) maxC = C;
return maxC;
}
float __syn_smv___scalar_e1e2_e2e3::largestBasisBlade(unsigned int &bm) const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
bm = 0;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) {
maxC = C;
bm = 3;
}
C = (m_c[2] < (Float)0.0) ? -m_c[2] : m_c[2];
if (C > maxC) {
maxC = C;
bm = 6;
}
return maxC;
}
// set to mv
void __syn_smv___e2f_1_0::set(const mv & arg1) {
}
float __syn_smv___e2f_1_0::largestCoordinate() const {
Float maxC = (Float)1.0f;
return maxC;
}
float __syn_smv___e2f_1_0::largestBasisBlade(unsigned int &bm) const {
Float maxC = (Float)1.0f;
bm = 2;
return maxC;
}
// set to mv
void __syn_smv___e1e2_e1e3::set(const mv & arg1) {
int gidx = 0;
if (arg1.gu() & 1) {
gidx += 1; }
else {
}
if (arg1.gu() & 2) {
gidx += 3; }
else {
}
if (arg1.gu() & 4) {
m_c[0] = arg1.m_c[gidx + 0];
m_c[1] = arg1.m_c[gidx + 2]* (Float)-1.0;
}
else {
m_c[0] = (Float)0.0;
m_c[1] = (Float)0.0;
}
}
float __syn_smv___e1e2_e1e3::largestCoordinate() const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) maxC = C;
return maxC;
}
float __syn_smv___e1e2_e1e3::largestBasisBlade(unsigned int &bm) const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
bm = 3;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) {
maxC = C;
bm = 5;
}
return maxC;
}
// set to mv
void __syn_smv___e1e2_e2e3::set(const mv & arg1) {
int gidx = 0;
if (arg1.gu() & 1) {
gidx += 1; }
else {
}
if (arg1.gu() & 2) {
gidx += 3; }
else {
}
if (arg1.gu() & 4) {
m_c[0] = arg1.m_c[gidx + 0];
m_c[1] = arg1.m_c[gidx + 1];
}
else {
m_c[0] = (Float)0.0;
m_c[1] = (Float)0.0;
}
}
float __syn_smv___e1e2_e2e3::largestCoordinate() const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) maxC = C;
return maxC;
}
float __syn_smv___e1e2_e2e3::largestBasisBlade(unsigned int &bm) const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
bm = 3;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) {
maxC = C;
bm = 6;
}
return maxC;
}
// set to mv
void __syn_smv___e1f1_0_e2f1_0::set(const mv & arg1) {
}
float __syn_smv___e1f1_0_e2f1_0::largestCoordinate() const {
Float maxC = (Float)1.0f;
return maxC;
}
float __syn_smv___e1f1_0_e2f1_0::largestBasisBlade(unsigned int &bm) const {
Float maxC = (Float)1.0f;
bm = 2;
return maxC;
}
// set to mv
void __syn_smv___e1f1_0_e2f1_0_e3f1_0::set(const mv & arg1) {
}
float __syn_smv___e1f1_0_e2f1_0_e3f1_0::largestCoordinate() const {
Float maxC = (Float)1.0f;
return maxC;
}
float __syn_smv___e1f1_0_e2f1_0_e3f1_0::largestBasisBlade(unsigned int &bm) const {
Float maxC = (Float)1.0f;
bm = 4;
return maxC;
}
// set to mv
void __syn_smv___e2_e1f1_0::set(const mv & arg1) {
int gidx = 0;
if (arg1.gu() & 1) {
gidx += 1; }
else {
}
if (arg1.gu() & 2) {
m_c[0] = arg1.m_c[gidx + 1];
}
else {
m_c[0] = (Float)0.0;
}
}
float __syn_smv___e2_e1f1_0::largestCoordinate() const {
Float maxC = (Float)1.0f, C;
C = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0];
if (C > maxC) maxC = C;
return maxC;
}
float __syn_smv___e2_e1f1_0::largestBasisBlade(unsigned int &bm) const {
Float maxC = (Float)1.0f, C;
bm = 1;
C = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0];
if (C > maxC) {
maxC = C;
bm = 2;
}
return maxC;
}
// set to mv
void __syn_smv___scalar_e1_e2_e3_e1e2e3::set(const mv & arg1) {
int gidx = 0;
if (arg1.gu() & 1) {
m_c[0] = arg1.m_c[gidx + 0];
gidx += 1; }
else {
m_c[0] = (Float)0.0;
}
if (arg1.gu() & 2) {
m_c[1] = arg1.m_c[gidx + 0];
m_c[2] = arg1.m_c[gidx + 1];
m_c[3] = arg1.m_c[gidx + 2];
gidx += 3; }
else {
m_c[1] = (Float)0.0;
m_c[2] = (Float)0.0;
m_c[3] = (Float)0.0;
}
if (arg1.gu() & 4) {
gidx += 3; }
else {
}
if (arg1.gu() & 8) {
m_c[4] = arg1.m_c[gidx + 0];
}
else {
m_c[4] = (Float)0.0;
}
}
float __syn_smv___scalar_e1_e2_e3_e1e2e3::largestCoordinate() const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) maxC = C;
C = (m_c[2] < (Float)0.0) ? -m_c[2] : m_c[2];
if (C > maxC) maxC = C;
C = (m_c[3] < (Float)0.0) ? -m_c[3] : m_c[3];
if (C > maxC) maxC = C;
C = (m_c[4] < (Float)0.0) ? -m_c[4] : m_c[4];
if (C > maxC) maxC = C;
return maxC;
}
float __syn_smv___scalar_e1_e2_e3_e1e2e3::largestBasisBlade(unsigned int &bm) const {
Float maxC = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0], C;
bm = 0;
C = (m_c[1] < (Float)0.0) ? -m_c[1] : m_c[1];
if (C > maxC) {
maxC = C;
bm = 1;
}
C = (m_c[2] < (Float)0.0) ? -m_c[2] : m_c[2];
if (C > maxC) {
maxC = C;
bm = 2;
}
C = (m_c[3] < (Float)0.0) ? -m_c[3] : m_c[3];
if (C > maxC) {
maxC = C;
bm = 4;
}
C = (m_c[4] < (Float)0.0) ? -m_c[4] : m_c[4];
if (C > maxC) {
maxC = C;
bm = 7;
}
return maxC;
}
// set to mv
void __syn_smv___e1_e3f1_0::set(const mv & arg1) {
int gidx = 0;
if (arg1.gu() & 1) {
gidx += 1; }
else {
}
if (arg1.gu() & 2) {
m_c[0] = arg1.m_c[gidx + 0];
}
else {
m_c[0] = (Float)0.0;
}
}
float __syn_smv___e1_e3f1_0::largestCoordinate() const {
Float maxC = (Float)1.0f, C;
C = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0];
if (C > maxC) maxC = C;
return maxC;
}
float __syn_smv___e1_e3f1_0::largestBasisBlade(unsigned int &bm) const {
Float maxC = (Float)1.0f, C;
bm = 4;
C = (m_c[0] < (Float)0.0) ? -m_c[0] : m_c[0];
if (C > maxC) {
maxC = C;
bm = 1;
}
return maxC;
}
// set to identity 'I'
void om::set() {
// simplify forward call to set(scalar)
set(1.0);
}
// set to copy
void om::set(const om &arg1) {
mv_memcpy(m_c, arg1.m_c, 19);
}
// set to scalar
void om::set(Float scalarVal) {
e3ga::__G2_GENERATED__::set(*this, vector(vector_e1_e2_e3, scalarVal, (Float)0, (Float)0), vector(vector_e1_e2_e3, (Float)0, scalarVal, (Float)0), vector(vector_e1_e2_e3, (Float)0, (Float)0, scalarVal));
}
// set to coordinates
void om::set(const Float *coordinates) {
mv_memcpy(m_c, coordinates, 19);
}
// set from basis vectors array
void om::set(const vector *vectors) {
e3ga::__G2_GENERATED__::set(*this, vectors[0], vectors[1], vectors[2]);
}
// set from basis vectors
void om::set(const vector & image_of_e1, const vector & image_of_e2, const vector & image_of_e3) {
e3ga::__G2_GENERATED__::set(*this, image_of_e1, image_of_e2, image_of_e3);
}
// set by coordinates, transpose
void om::set(const Float *coordinates, bool transpose) {
if (transpose) {
m_c[0] = coordinates[0];
m_c[3] = coordinates[1];
m_c[6] = coordinates[2];
m_c[1] = coordinates[3];
m_c[4] = coordinates[4];
m_c[7] = coordinates[5];
m_c[2] = coordinates[6];
m_c[5] = coordinates[7];
m_c[8] = coordinates[8];
m_c[9] = coordinates[9];
m_c[12] = coordinates[10];
m_c[15] = coordinates[11];
m_c[10] = coordinates[12];
m_c[13] = coordinates[13];
m_c[16] = coordinates[14];
m_c[11] = coordinates[15];
m_c[14] = coordinates[16];
m_c[17] = coordinates[17];
m_c[18] = coordinates[18];
}
else set(coordinates);
}
// assign copy
om &om::operator=(const om &arg1) {
set(arg1);
return *this;
}
// assign scalar (creates scalar * 'I' outermorphism)
om &om::operator=(Float scalarVal) {
set(scalarVal);
return *this;
}
/// assign specialization:
// G2 functions:
mv lcont(const mv& x, const mv& y) {
mv __temp_var_1__;
float __tmp_coord_array_1__[8] ;
mv_zero(__tmp_coord_array_1__, 8);
const float* __y_xpd__[4] ;
y.expand(__y_xpd__, true);
const float* __x_xpd__[4] ;
x.expand(__x_xpd__, true);
if (((y.m_gu & 1) != 0)) {
if (((x.m_gu & 1) != 0)) {
__tmp_coord_array_1__[0] += (__x_xpd__[0][0] * __y_xpd__[0][0]);
}
}
if (((y.m_gu & 2) != 0)) {
if (((x.m_gu & 1) != 0)) {
__tmp_coord_array_1__[1] += (__y_xpd__[1][0] * __x_xpd__[0][0]);
__tmp_coord_array_1__[2] += (__y_xpd__[1][1] * __x_xpd__[0][0]);
__tmp_coord_array_1__[3] += (__y_xpd__[1][2] * __x_xpd__[0][0]);
}
if (((x.m_gu & 2) != 0)) {
__tmp_coord_array_1__[0] += ((__x_xpd__[1][1] * __y_xpd__[1][1]) + (__x_xpd__[1][0] * __y_xpd__[1][0]) + (__x_xpd__[1][2] * __y_xpd__[1][2]));
}
}
if (((y.m_gu & 4) != 0)) {
if (((x.m_gu & 1) != 0)) {
__tmp_coord_array_1__[4] += (__y_xpd__[2][0] * __x_xpd__[0][0]);
__tmp_coord_array_1__[5] += (__y_xpd__[2][1] * __x_xpd__[0][0]);
__tmp_coord_array_1__[6] += (__y_xpd__[2][2] * __x_xpd__[0][0]);
}
if (((x.m_gu & 2) != 0)) {
__tmp_coord_array_1__[1] += ((-1.0f * __x_xpd__[1][1] * __y_xpd__[2][0]) + (__x_xpd__[1][2] * __y_xpd__[2][2]));
__tmp_coord_array_1__[2] += ((-1.0f * __x_xpd__[1][2] * __y_xpd__[2][1]) + (__x_xpd__[1][0] * __y_xpd__[2][0]));
__tmp_coord_array_1__[3] += ((__x_xpd__[1][1] * __y_xpd__[2][1]) + (-1.0f * __x_xpd__[1][0] * __y_xpd__[2][2]));
}
if (((x.m_gu & 4) != 0)) {
__tmp_coord_array_1__[0] += ((-1.0f * __x_xpd__[2][2] * __y_xpd__[2][2]) + (-1.0f * __x_xpd__[2][1] * __y_xpd__[2][1]) + (-1.0f * __x_xpd__[2][0] * __y_xpd__[2][0]));
}
}
if (((y.m_gu & 8) != 0)) {
if (((x.m_gu & 1) != 0)) {
__tmp_coord_array_1__[7] += (__y_xpd__[3][0] * __x_xpd__[0][0]);
}
if (((x.m_gu & 2) != 0)) {
__tmp_coord_array_1__[4] += (__x_xpd__[1][2] * __y_xpd__[3][0]);
__tmp_coord_array_1__[5] += (__x_xpd__[1][0] * __y_xpd__[3][0]);
__tmp_coord_array_1__[6] += (__x_xpd__[1][1] * __y_xpd__[3][0]);
}
if (((x.m_gu & 4) != 0)) {
__tmp_coord_array_1__[1] += (-1.0f * __x_xpd__[2][1] * __y_xpd__[3][0]);
__tmp_coord_array_1__[2] += (-1.0f * __x_xpd__[2][2] * __y_xpd__[3][0]);
__tmp_coord_array_1__[3] += (-1.0f * __x_xpd__[2][0] * __y_xpd__[3][0]);
}
if (((x.m_gu & 8) != 0)) {
__tmp_coord_array_1__[0] += (-1.0f * __x_xpd__[3][0] * __y_xpd__[3][0]);
}
}
__temp_var_1__ = mv_compress(__tmp_coord_array_1__);
return __temp_var_1__;
}
scalar scp(const mv& x, const mv& y) {
scalar __temp_var_1__;
const float* __x_xpd__[4] ;
x.expand(__x_xpd__, true);
const float* __y_xpd__[4] ;
y.expand(__y_xpd__, true);
if (((x.m_gu & 1) != 0)) {
if (((y.m_gu & 1) != 0)) {
__temp_var_1__.m_c[0] += (__x_xpd__[0][0] * __y_xpd__[0][0]);
}
}
if (((x.m_gu & 2) != 0)) {
if (((y.m_gu & 2) != 0)) {
__temp_var_1__.m_c[0] += ((__x_xpd__[1][1] * __y_xpd__[1][1]) + (__x_xpd__[1][2] * __y_xpd__[1][2]) + (__x_xpd__[1][0] * __y_xpd__[1][0]));
}
}
if (((x.m_gu & 4) != 0)) {
if (((y.m_gu & 4) != 0)) {
__temp_var_1__.m_c[0] += ((-1.0f * __x_xpd__[2][2] * __y_xpd__[2][2]) + (-1.0f * __x_xpd__[2][1] * __y_xpd__[2][1]) + (-1.0f * __x_xpd__[2][0] * __y_xpd__[2][0]));
}
}
if (((x.m_gu & 8) != 0)) {
if (((y.m_gu & 8) != 0)) {
__temp_var_1__.m_c[0] += (-1.0f * __x_xpd__[3][0] * __y_xpd__[3][0]);
}
}
return __temp_var_1__;
}
mv gp(const mv& x, const mv& y) {
mv __temp_var_1__;
float __tmp_coord_array_2__[8] ;
mv_zero(__tmp_coord_array_2__, 8);
const float* __x_xpd__[4] ;
x.expand(__x_xpd__, true);
const float* __y_xpd__[4] ;
y.expand(__y_xpd__, true);
if (((x.m_gu & 1) != 0)) {
if (((y.m_gu & 1) != 0)) {
__tmp_coord_array_2__[0] += (__x_xpd__[0][0] * __y_xpd__[0][0]);
}
if (((y.m_gu & 2) != 0)) {
__tmp_coord_array_2__[1] += (__x_xpd__[0][0] * __y_xpd__[1][0]);
__tmp_coord_array_2__[2] += (__x_xpd__[0][0] * __y_xpd__[1][1]);
__tmp_coord_array_2__[3] += (__x_xpd__[0][0] * __y_xpd__[1][2]);
}
if (((y.m_gu & 4) != 0)) {
__tmp_coord_array_2__[4] += (__x_xpd__[0][0] * __y_xpd__[2][0]);
__tmp_coord_array_2__[5] += (__x_xpd__[0][0] * __y_xpd__[2][1]);
__tmp_coord_array_2__[6] += (__x_xpd__[0][0] * __y_xpd__[2][2]);
}
if (((y.m_gu & 8) != 0)) {
__tmp_coord_array_2__[7] += (__x_xpd__[0][0] * __y_xpd__[3][0]);
}
}
if (((x.m_gu & 2) != 0)) {
if (((y.m_gu & 1) != 0)) {
__tmp_coord_array_2__[1] += (__x_xpd__[1][0] * __y_xpd__[0][0]);
__tmp_coord_array_2__[2] += (__x_xpd__[1][1] * __y_xpd__[0][0]);
__tmp_coord_array_2__[3] += (__x_xpd__[1][2] * __y_xpd__[0][0]);
}
if (((y.m_gu & 2) != 0)) {
__tmp_coord_array_2__[0] += ((__x_xpd__[1][2] * __y_xpd__[1][2]) + (__x_xpd__[1][1] * __y_xpd__[1][1]) + (__x_xpd__[1][0] * __y_xpd__[1][0]));
__tmp_coord_array_2__[4] += ((__x_xpd__[1][0] * __y_xpd__[1][1]) + (-1.0f * __x_xpd__[1][1] * __y_xpd__[1][0]));
__tmp_coord_array_2__[5] += ((__x_xpd__[1][1] * __y_xpd__[1][2]) + (-1.0f * __x_xpd__[1][2] * __y_xpd__[1][1]));
__tmp_coord_array_2__[6] += ((__x_xpd__[1][2] * __y_xpd__[1][0]) + (-1.0f * __x_xpd__[1][0] * __y_xpd__[1][2]));
}
if (((y.m_gu & 4) != 0)) {
__tmp_coord_array_2__[1] += ((-1.0f * __x_xpd__[1][1] * __y_xpd__[2][0]) + (__x_xpd__[1][2] * __y_xpd__[2][2]));
__tmp_coord_array_2__[2] += ((-1.0f * __x_xpd__[1][2] * __y_xpd__[2][1]) + (__x_xpd__[1][0] * __y_xpd__[2][0]));
__tmp_coord_array_2__[3] += ((-1.0f * __x_xpd__[1][0] * __y_xpd__[2][2]) + (__x_xpd__[1][1] * __y_xpd__[2][1]));
__tmp_coord_array_2__[7] += ((__x_xpd__[1][1] * __y_xpd__[2][2]) + (__x_xpd__[1][0] * __y_xpd__[2][1]) + (__x_xpd__[1][2] * __y_xpd__[2][0]));
}
if (((y.m_gu & 8) != 0)) {
__tmp_coord_array_2__[4] += (__x_xpd__[1][2] * __y_xpd__[3][0]);
__tmp_coord_array_2__[5] += (__x_xpd__[1][0] * __y_xpd__[3][0]);
__tmp_coord_array_2__[6] += (__x_xpd__[1][1] * __y_xpd__[3][0]);
}
}
if (((x.m_gu & 4) != 0)) {
if (((y.m_gu & 1) != 0)) {
__tmp_coord_array_2__[4] += (__x_xpd__[2][0] * __y_xpd__[0][0]);
__tmp_coord_array_2__[5] += (__x_xpd__[2][1] * __y_xpd__[0][0]);
__tmp_coord_array_2__[6] += (__x_xpd__[2][2] * __y_xpd__[0][0]);
}
if (((y.m_gu & 2) != 0)) {
__tmp_coord_array_2__[1] += ((__x_xpd__[2][0] * __y_xpd__[1][1]) + (-1.0f * __x_xpd__[2][2] * __y_xpd__[1][2]));
__tmp_coord_array_2__[2] += ((__x_xpd__[2][1] * __y_xpd__[1][2]) + (-1.0f * __x_xpd__[2][0] * __y_xpd__[1][0]));
__tmp_coord_array_2__[3] += ((-1.0f * __x_xpd__[2][1] * __y_xpd__[1][1]) + (__x_xpd__[2][2] * __y_xpd__[1][0]));
__tmp_coord_array_2__[7] += ((__x_xpd__[2][0] * __y_xpd__[1][2]) + (__x_xpd__[2][1] * __y_xpd__[1][0]) + (__x_xpd__[2][2] * __y_xpd__[1][1]));
}
if (((y.m_gu & 4) != 0)) {
__tmp_coord_array_2__[0] += ((-1.0f * __x_xpd__[2][1] * __y_xpd__[2][1]) + (-1.0f * __x_xpd__[2][2] * __y_xpd__[2][2]) + (-1.0f * __x_xpd__[2][0] * __y_xpd__[2][0]));
__tmp_coord_array_2__[4] += ((-1.0f * __x_xpd__[2][1] * __y_xpd__[2][2]) + (__x_xpd__[2][2] * __y_xpd__[2][1]));
__tmp_coord_array_2__[5] += ((__x_xpd__[2][0] * __y_xpd__[2][2]) + (-1.0f * __x_xpd__[2][2] * __y_xpd__[2][0]));
__tmp_coord_array_2__[6] += ((__x_xpd__[2][1] * __y_xpd__[2][0]) + (-1.0f * __x_xpd__[2][0] * __y_xpd__[2][1]));
}
if (((y.m_gu & 8) != 0)) {
__tmp_coord_array_2__[1] += (-1.0f * __x_xpd__[2][1] * __y_xpd__[3][0]);
__tmp_coord_array_2__[2] += (-1.0f * __x_xpd__[2][2] * __y_xpd__[3][0]);
__tmp_coord_array_2__[3] += (-1.0f * __x_xpd__[2][0] * __y_xpd__[3][0]);
}
}
if (((x.m_gu & 8) != 0)) {
if (((y.m_gu & 1) != 0)) {
__tmp_coord_array_2__[7] += (__x_xpd__[3][0] * __y_xpd__[0][0]);
}
if (((y.m_gu & 2) != 0)) {
__tmp_coord_array_2__[4] += (__x_xpd__[3][0] * __y_xpd__[1][2]);
__tmp_coord_array_2__[5] += (__x_xpd__[3][0] * __y_xpd__[1][0]);
__tmp_coord_array_2__[6] += (__x_xpd__[3][0] * __y_xpd__[1][1]);
}
if (((y.m_gu & 4) != 0)) {
__tmp_coord_array_2__[1] += (-1.0f * __x_xpd__[3][0] * __y_xpd__[2][1]);
__tmp_coord_array_2__[2] += (-1.0f * __x_xpd__[3][0] * __y_xpd__[2][2]);
__tmp_coord_array_2__[3] += (-1.0f * __x_xpd__[3][0] * __y_xpd__[2][0]);
}
if (((y.m_gu & 8) != 0)) {
__tmp_coord_array_2__[0] += (-1.0f * __x_xpd__[3][0] * __y_xpd__[3][0]);
}
}
__temp_var_1__ = mv_compress(__tmp_coord_array_2__);
return __temp_var_1__;
}
mv op(const mv& x, const mv& y) {
mv __temp_var_1__;
float __tmp_coord_array_3__[8] ;
mv_zero(__tmp_coord_array_3__, 8);
const float* __x_xpd__[4] ;
x.expand(__x_xpd__, true);
const float* __y_xpd__[4] ;
y.expand(__y_xpd__, true);
if (((x.m_gu & 1) != 0)) {
if (((y.m_gu & 1) != 0)) {
__tmp_coord_array_3__[0] += (__x_xpd__[0][0] * __y_xpd__[0][0]);
}
if (((y.m_gu & 2) != 0)) {
__tmp_coord_array_3__[1] += (__x_xpd__[0][0] * __y_xpd__[1][0]);
__tmp_coord_array_3__[2] += (__x_xpd__[0][0] * __y_xpd__[1][1]);
__tmp_coord_array_3__[3] += (__x_xpd__[0][0] * __y_xpd__[1][2]);
}
if (((y.m_gu & 4) != 0)) {
__tmp_coord_array_3__[4] += (__x_xpd__[0][0] * __y_xpd__[2][0]);
__tmp_coord_array_3__[5] += (__x_xpd__[0][0] * __y_xpd__[2][1]);
__tmp_coord_array_3__[6] += (__x_xpd__[0][0] * __y_xpd__[2][2]);
}
if (((y.m_gu & 8) != 0)) {
__tmp_coord_array_3__[7] += (__x_xpd__[0][0] * __y_xpd__[3][0]);
}
}
if (((x.m_gu & 2) != 0)) {
if (((y.m_gu & 1) != 0)) {
__tmp_coord_array_3__[1] += (__x_xpd__[1][0] * __y_xpd__[0][0]);
__tmp_coord_array_3__[2] += (__x_xpd__[1][1] * __y_xpd__[0][0]);
__tmp_coord_array_3__[3] += (__x_xpd__[1][2] * __y_xpd__[0][0]);
}
if (((y.m_gu & 2) != 0)) {
__tmp_coord_array_3__[4] += ((-1.0f * __x_xpd__[1][1] * __y_xpd__[1][0]) + (__x_xpd__[1][0] * __y_xpd__[1][1]));
__tmp_coord_array_3__[5] += ((__x_xpd__[1][1] * __y_xpd__[1][2]) + (-1.0f * __x_xpd__[1][2] * __y_xpd__[1][1]));
__tmp_coord_array_3__[6] += ((-1.0f * __x_xpd__[1][0] * __y_xpd__[1][2]) + (__x_xpd__[1][2] * __y_xpd__[1][0]));
}
if (((y.m_gu & 4) != 0)) {
__tmp_coord_array_3__[7] += ((__x_xpd__[1][0] * __y_xpd__[2][1]) + (__x_xpd__[1][2] * __y_xpd__[2][0]) + (__x_xpd__[1][1] * __y_xpd__[2][2]));
}
}
if (((x.m_gu & 4) != 0)) {
if (((y.m_gu & 1) != 0)) {
__tmp_coord_array_3__[4] += (__x_xpd__[2][0] * __y_xpd__[0][0]);
__tmp_coord_array_3__[5] += (__x_xpd__[2][1] * __y_xpd__[0][0]);
__tmp_coord_array_3__[6] += (__x_xpd__[2][2] * __y_xpd__[0][0]);
}
if (((y.m_gu & 2) != 0)) {
__tmp_coord_array_3__[7] += ((__x_xpd__[2][2] * __y_xpd__[1][1]) + (__x_xpd__[2][0] * __y_xpd__[1][2]) + (__x_xpd__[2][1] * __y_xpd__[1][0]));
}
}
if (((x.m_gu & 8) != 0)) {
if (((y.m_gu & 1) != 0)) {
__tmp_coord_array_3__[7] += (__x_xpd__[3][0] * __y_xpd__[0][0]);
}
}
__temp_var_1__ = mv_compress(__tmp_coord_array_3__);
return __temp_var_1__;
}
mv add(const mv& x, const mv& y) {
mv __temp_var_1__;
float __tmp_coord_array_4__[8] ;
mv_zero(__tmp_coord_array_4__, 8);
const float* __x_xpd__[4] ;
x.expand(__x_xpd__, true);
const float* __y_xpd__[4] ;
y.expand(__y_xpd__, true);
if (((y.m_gu & 1) != 0)) {
__tmp_coord_array_4__[0] += __y_xpd__[0][0];
}
if (((y.m_gu & 2) != 0)) {
__tmp_coord_array_4__[1] += __y_xpd__[1][0];
__tmp_coord_array_4__[2] += __y_xpd__[1][1];
__tmp_coord_array_4__[3] += __y_xpd__[1][2];
}
if (((y.m_gu & 4) != 0)) {
__tmp_coord_array_4__[4] += __y_xpd__[2][0];
__tmp_coord_array_4__[5] += __y_xpd__[2][1];
__tmp_coord_array_4__[6] += __y_xpd__[2][2];
}
if (((y.m_gu & 8) != 0)) {
__tmp_coord_array_4__[7] += __y_xpd__[3][0];
}
if (((x.m_gu & 1) != 0)) {
__tmp_coord_array_4__[0] += __x_xpd__[0][0];
}
if (((x.m_gu & 2) != 0)) {
__tmp_coord_array_4__[1] += __x_xpd__[1][0];
__tmp_coord_array_4__[2] += __x_xpd__[1][1];
__tmp_coord_array_4__[3] += __x_xpd__[1][2];
}
if (((x.m_gu & 4) != 0)) {
__tmp_coord_array_4__[4] += __x_xpd__[2][0];
__tmp_coord_array_4__[5] += __x_xpd__[2][1];
__tmp_coord_array_4__[6] += __x_xpd__[2][2];
}
if (((x.m_gu & 8) != 0)) {
__tmp_coord_array_4__[7] += __x_xpd__[3][0];
}
__temp_var_1__ = mv_compress(__tmp_coord_array_4__);
return __temp_var_1__;
}
mv subtract(const mv& x, const mv& y) {
mv __temp_var_1__;
float __tmp_coord_array_5__[8] ;
mv_zero(__tmp_coord_array_5__, 8);
const float* __x_xpd__[4] ;
x.expand(__x_xpd__, true);
const float* __y_xpd__[4] ;
y.expand(__y_xpd__, true);
if (((y.m_gu & 1) != 0)) {
__tmp_coord_array_5__[0] += (-1.0f * __y_xpd__[0][0]);
}
if (((y.m_gu & 2) != 0)) {
__tmp_coord_array_5__[1] += (-1.0f * __y_xpd__[1][0]);
__tmp_coord_array_5__[2] += (-1.0f * __y_xpd__[1][1]);
__tmp_coord_array_5__[3] += (-1.0f * __y_xpd__[1][2]);
}
if (((y.m_gu & 4) != 0)) {
__tmp_coord_array_5__[4] += (-1.0f * __y_xpd__[2][0]);
__tmp_coord_array_5__[5] += (-1.0f * __y_xpd__[2][1]);
__tmp_coord_array_5__[6] += (-1.0f * __y_xpd__[2][2]);
}
if (((y.m_gu & 8) != 0)) {
__tmp_coord_array_5__[7] += (-1.0f * __y_xpd__[3][0]);
}
if (((x.m_gu & 1) != 0)) {
__tmp_coord_array_5__[0] += __x_xpd__[0][0];
}
if (((x.m_gu & 2) != 0)) {
__tmp_coord_array_5__[1] += __x_xpd__[1][0];
__tmp_coord_array_5__[2] += __x_xpd__[1][1];
__tmp_coord_array_5__[3] += __x_xpd__[1][2];
}
if (((x.m_gu & 4) != 0)) {
__tmp_coord_array_5__[4] += __x_xpd__[2][0];
__tmp_coord_array_5__[5] += __x_xpd__[2][1];
__tmp_coord_array_5__[6] += __x_xpd__[2][2];
}
if (((x.m_gu & 8) != 0)) {
__tmp_coord_array_5__[7] += __x_xpd__[3][0];
}
__temp_var_1__ = mv_compress(__tmp_coord_array_5__);
return __temp_var_1__;
}
scalar norm_e2(const mv& x) {
scalar __temp_var_1__;
const float* __x_xpd__[4] ;
x.expand(__x_xpd__, true);
if (((x.m_gu & 1) != 0)) {
__temp_var_1__.m_c[0] += (__x_xpd__[0][0] * __x_xpd__[0][0]);
}
if (((x.m_gu & 2) != 0)) {
__temp_var_1__.m_c[0] += ((__x_xpd__[1][1] * __x_xpd__[1][1]) + (__x_xpd__[1][0] * __x_xpd__[1][0]) + (__x_xpd__[1][2] * __x_xpd__[1][2]));
}
if (((x.m_gu & 4) != 0)) {
__temp_var_1__.m_c[0] += ((__x_xpd__[2][2] * __x_xpd__[2][2]) + (__x_xpd__[2][1] * __x_xpd__[2][1]) + (__x_xpd__[2][0] * __x_xpd__[2][0]));
}
if (((x.m_gu & 8) != 0)) {
__temp_var_1__.m_c[0] += (__x_xpd__[3][0] * __x_xpd__[3][0]);
}
return __temp_var_1__;
}
scalar norm_e(const mv& x) {
scalar e2;
const float* __x_xpd__[4] ;
x.expand(__x_xpd__, true);
if (((x.m_gu & 1) != 0)) {
e2.m_c[0] += (__x_xpd__[0][0] * __x_xpd__[0][0]);
}
if (((x.m_gu & 2) != 0)) {
e2.m_c[0] += ((__x_xpd__[1][0] * __x_xpd__[1][0]) + (__x_xpd__[1][2] * __x_xpd__[1][2]) + (__x_xpd__[1][1] * __x_xpd__[1][1]));
}
if (((x.m_gu & 4) != 0)) {
e2.m_c[0] += ((__x_xpd__[2][0] * __x_xpd__[2][0]) + (__x_xpd__[2][1] * __x_xpd__[2][1]) + (__x_xpd__[2][2] * __x_xpd__[2][2]));
}
if (((x.m_gu & 8) != 0)) {
e2.m_c[0] += (__x_xpd__[3][0] * __x_xpd__[3][0]);
}
return scalar(scalar_scalar, sqrt(e2.m_c[0]));
}
mv unit_e(const mv& x) {
scalar e2;
const float* __x_xpd__[4] ;
x.expand(__x_xpd__, true);
if (((x.m_gu & 1) != 0)) {
e2.m_c[0] += (__x_xpd__[0][0] * __x_xpd__[0][0]);
}
if (((x.m_gu & 2) != 0)) {
e2.m_c[0] += ((__x_xpd__[1][2] * __x_xpd__[1][2]) + (__x_xpd__[1][1] * __x_xpd__[1][1]) + (__x_xpd__[1][0] * __x_xpd__[1][0]));
}
if (((x.m_gu & 4) != 0)) {
e2.m_c[0] += ((__x_xpd__[2][1] * __x_xpd__[2][1]) + (__x_xpd__[2][0] * __x_xpd__[2][0]) + (__x_xpd__[2][2] * __x_xpd__[2][2]));
}
if (((x.m_gu & 8) != 0)) {
e2.m_c[0] += (__x_xpd__[3][0] * __x_xpd__[3][0]);
}
scalar ie;
ie.m_c[0] = ((char)1 / sqrt(e2.m_c[0]));
mv __temp_var_1__;
float __tmp_coord_array_6__[8] ;
mv_zero(__tmp_coord_array_6__, 8);
if (((x.m_gu & 1) != 0)) {
__tmp_coord_array_6__[0] += (__x_xpd__[0][0] * ie.m_c[0]);
}
if (((x.m_gu & 2) != 0)) {
__tmp_coord_array_6__[1] += (__x_xpd__[1][0] * ie.m_c[0]);
__tmp_coord_array_6__[2] += (__x_xpd__[1][1] * ie.m_c[0]);
__tmp_coord_array_6__[3] += (__x_xpd__[1][2] * ie.m_c[0]);
}
if (((x.m_gu & 4) != 0)) {
__tmp_coord_array_6__[4] += (__x_xpd__[2][0] * ie.m_c[0]);
__tmp_coord_array_6__[5] += (__x_xpd__[2][1] * ie.m_c[0]);
__tmp_coord_array_6__[6] += (__x_xpd__[2][2] * ie.m_c[0]);
}
if (((x.m_gu & 8) != 0)) {
__tmp_coord_array_6__[7] += (__x_xpd__[3][0] * ie.m_c[0]);
}
__temp_var_1__ = mv_compress(__tmp_coord_array_6__);
return __temp_var_1__;
}
scalar norm_r2(const mv& x) {
scalar __temp_var_1__;
const float* __x_xpd__[4] ;
x.expand(__x_xpd__, true);
if (((x.m_gu & 1) != 0)) {
__temp_var_1__.m_c[0] += (__x_xpd__[0][0] * __x_xpd__[0][0]);
}
if (((x.m_gu & 2) != 0)) {
__temp_var_1__.m_c[0] += ((__x_xpd__[1][1] * __x_xpd__[1][1]) + (__x_xpd__[1][2] * __x_xpd__[1][2]) + (__x_xpd__[1][0] * __x_xpd__[1][0]));
}
if (((x.m_gu & 4) != 0)) {
__temp_var_1__.m_c[0] += ((__x_xpd__[2][0] * __x_xpd__[2][0]) + (__x_xpd__[2][1] * __x_xpd__[2][1]) + (__x_xpd__[2][2] * __x_xpd__[2][2]));
}
if (((x.m_gu & 8) != 0)) {
__temp_var_1__.m_c[0] += (__x_xpd__[3][0] * __x_xpd__[3][0]);
}
return __temp_var_1__;
}
scalar norm_r(const mv& x) {
scalar r2;
const float* __x_xpd__[4] ;
x.expand(__x_xpd__, true);
if (((x.m_gu & 1) != 0)) {
r2.m_c[0] += (__x_xpd__[0][0] * __x_xpd__[0][0]);
}
if (((x.m_gu & 2) != 0)) {
r2.m_c[0] += ((__x_xpd__[1][1] * __x_xpd__[1][1]) + (__x_xpd__[1][0] * __x_xpd__[1][0]) + (__x_xpd__[1][2] * __x_xpd__[1][2]));
}
if (((x.m_gu & 4) != 0)) {
r2.m_c[0] += ((__x_xpd__[2][1] * __x_xpd__[2][1]) + (__x_xpd__[2][0] * __x_xpd__[2][0]) + (__x_xpd__[2][2] * __x_xpd__[2][2]));
}
if (((x.m_gu & 8) != 0)) {
r2.m_c[0] += (__x_xpd__[3][0] * __x_xpd__[3][0]);
}
return scalar(scalar_scalar, ((((r2.m_c[0] < (char)0)) ? (char)-1 : ((((r2.m_c[0] > (char)0)) ? (char)1 : (char)0))) * sqrt((((r2.m_c[0] < (char)0)) ? ((-r2.m_c[0])) : (r2.m_c[0])))));
}
mv unit_r(const mv& x) {
scalar r2;
const float* __x_xpd__[4] ;
x.expand(__x_xpd__, true);
if (((x.m_gu & 1) != 0)) {
r2.m_c[0] += (__x_xpd__[0][0] * __x_xpd__[0][0]);
}
if (((x.m_gu & 2) != 0)) {
r2.m_c[0] += ((__x_xpd__[1][2] * __x_xpd__[1][2]) + (__x_xpd__[1][1] * __x_xpd__[1][1]) + (__x_xpd__[1][0] * __x_xpd__[1][0]));
}
if (((x.m_gu & 4) != 0)) {
r2.m_c[0] += ((__x_xpd__[2][1] * __x_xpd__[2][1]) + (__x_xpd__[2][2] * __x_xpd__[2][2]) + (__x_xpd__[2][0] * __x_xpd__[2][0]));
}
if (((x.m_gu & 8) != 0)) {
r2.m_c[0] += (__x_xpd__[3][0] * __x_xpd__[3][0]);
}
scalar ir;
ir.m_c[0] = ((char)1 / sqrt((((r2.m_c[0] < (char)0)) ? ((-r2.m_c[0])) : (r2.m_c[0]))));
mv __temp_var_1__;
float __tmp_coord_array_7__[8] ;
mv_zero(__tmp_coord_array_7__, 8);
if (((x.m_gu & 1) != 0)) {
__tmp_coord_array_7__[0] += (__x_xpd__[0][0] * ir.m_c[0]);
}
if (((x.m_gu & 2) != 0)) {
__tmp_coord_array_7__[1] += (__x_xpd__[1][0] * ir.m_c[0]);
__tmp_coord_array_7__[2] += (__x_xpd__[1][1] * ir.m_c[0]);
__tmp_coord_array_7__[3] += (__x_xpd__[1][2] * ir.m_c[0]);
}
if (((x.m_gu & 4) != 0)) {
__tmp_coord_array_7__[4] += (__x_xpd__[2][0] * ir.m_c[0]);
__tmp_coord_array_7__[5] += (__x_xpd__[2][1] * ir.m_c[0]);
__tmp_coord_array_7__[6] += (__x_xpd__[2][2] * ir.m_c[0]);
}
if (((x.m_gu & 8) != 0)) {
__tmp_coord_array_7__[7] += (__x_xpd__[3][0] * ir.m_c[0]);
}
__temp_var_1__ = mv_compress(__tmp_coord_array_7__);
return __temp_var_1__;
}
mv reverse(const mv& x) {
mv __temp_var_1__;
float __tmp_coord_array_8__[8] ;
mv_zero(__tmp_coord_array_8__, 8);
const float* __x_xpd__[4] ;
x.expand(__x_xpd__, true);
if (((x.m_gu & 1) != 0)) {
__tmp_coord_array_8__[0] += __x_xpd__[0][0];
}
if (((x.m_gu & 2) != 0)) {
__tmp_coord_array_8__[1] += __x_xpd__[1][0];
__tmp_coord_array_8__[2] += __x_xpd__[1][1];
__tmp_coord_array_8__[3] += __x_xpd__[1][2];
}
if (((x.m_gu & 4) != 0)) {
__tmp_coord_array_8__[4] += (-1.0f * __x_xpd__[2][0]);
__tmp_coord_array_8__[5] += (-1.0f * __x_xpd__[2][1]);
__tmp_coord_array_8__[6] += (-1.0f * __x_xpd__[2][2]);
}
if (((x.m_gu & 8) != 0)) {
__tmp_coord_array_8__[7] += (-1.0f * __x_xpd__[3][0]);
}
__temp_var_1__ = mv_compress(__tmp_coord_array_8__);
return __temp_var_1__;
}
mv negate(const mv& x) {
mv __temp_var_1__;
float __tmp_coord_array_9__[8] ;
mv_zero(__tmp_coord_array_9__, 8);
const float* __x_xpd__[4] ;
x.expand(__x_xpd__, true);
if (((x.m_gu & 1) != 0)) {
__tmp_coord_array_9__[0] += (-1.0f * __x_xpd__[0][0]);
}
if (((x.m_gu & 2) != 0)) {
__tmp_coord_array_9__[1] += (-1.0f * __x_xpd__[1][0]);
__tmp_coord_array_9__[2] += (-1.0f * __x_xpd__[1][1]);
__tmp_coord_array_9__[3] += (-1.0f * __x_xpd__[1][2]);
}
if (((x.m_gu & 4) != 0)) {
__tmp_coord_array_9__[4] += (-1.0f * __x_xpd__[2][0]);
__tmp_coord_array_9__[5] += (-1.0f * __x_xpd__[2][1]);
__tmp_coord_array_9__[6] += (-1.0f * __x_xpd__[2][2]);
}
if (((x.m_gu & 8) != 0)) {
__tmp_coord_array_9__[7] += (-1.0f * __x_xpd__[3][0]);
}
__temp_var_1__ = mv_compress(__tmp_coord_array_9__);
return __temp_var_1__;
}
mv dual(const mv& x) {
mv __temp_var_1__;
float __tmp_coord_array_10__[8] ;
mv_zero(__tmp_coord_array_10__, 8);
const float* __x_xpd__[4] ;
x.expand(__x_xpd__, true);
if (((x.m_gu & 1) != 0)) {
__tmp_coord_array_10__[7] += (-1.0f * __x_xpd__[0][0]);
}
if (((x.m_gu & 2) != 0)) {
__tmp_coord_array_10__[4] += (-1.0f * __x_xpd__[1][2]);
__tmp_coord_array_10__[5] += (-1.0f * __x_xpd__[1][0]);
__tmp_coord_array_10__[6] += (-1.0f * __x_xpd__[1][1]);
}
if (((x.m_gu & 4) != 0)) {
__tmp_coord_array_10__[1] += __x_xpd__[2][1];
__tmp_coord_array_10__[2] += __x_xpd__[2][2];
__tmp_coord_array_10__[3] += __x_xpd__[2][0];
}
if (((x.m_gu & 8) != 0)) {
__tmp_coord_array_10__[0] += __x_xpd__[3][0];
}
__temp_var_1__ = mv_compress(__tmp_coord_array_10__);
return __temp_var_1__;
}
mv undual(const mv& x) {
mv __temp_var_1__;
float __tmp_coord_array_11__[8] ;
mv_zero(__tmp_coord_array_11__, 8);
const float* __x_xpd__[4] ;
x.expand(__x_xpd__, true);
if (((x.m_gu & 1) != 0)) {
__tmp_coord_array_11__[7] += __x_xpd__[0][0];
}
if (((x.m_gu & 2) != 0)) {
__tmp_coord_array_11__[4] += __x_xpd__[1][2];
__tmp_coord_array_11__[5] += __x_xpd__[1][0];
__tmp_coord_array_11__[6] += __x_xpd__[1][1];
}
if (((x.m_gu & 4) != 0)) {
__tmp_coord_array_11__[1] += (-1.0f * __x_xpd__[2][1]);
__tmp_coord_array_11__[2] += (-1.0f * __x_xpd__[2][2]);
__tmp_coord_array_11__[3] += (-1.0f * __x_xpd__[2][0]);
}
if (((x.m_gu & 8) != 0)) {
__tmp_coord_array_11__[0] += (-1.0f * __x_xpd__[3][0]);
}
__temp_var_1__ = mv_compress(__tmp_coord_array_11__);
return __temp_var_1__;
}
mv inverse(const mv& x) {
scalar n;
const float* __x_xpd__[4] ;
x.expand(__x_xpd__, true);
if (((x.m_gu & 1) != 0)) {
n.m_c[0] += (__x_xpd__[0][0] * __x_xpd__[0][0]);
}
if (((x.m_gu & 2) != 0)) {
n.m_c[0] += ((__x_xpd__[1][0] * __x_xpd__[1][0]) + (__x_xpd__[1][1] * __x_xpd__[1][1]) + (__x_xpd__[1][2] * __x_xpd__[1][2]));
}
if (((x.m_gu & 4) != 0)) {
n.m_c[0] += ((__x_xpd__[2][0] * __x_xpd__[2][0]) + (__x_xpd__[2][2] * __x_xpd__[2][2]) + (__x_xpd__[2][1] * __x_xpd__[2][1]));
}
if (((x.m_gu & 8) != 0)) {
n.m_c[0] += (__x_xpd__[3][0] * __x_xpd__[3][0]);
}
scalar in;
in.m_c[0] = ((char)1 / n.m_c[0]);
mv __temp_var_1__;
float __tmp_coord_array_12__[8] ;
mv_zero(__tmp_coord_array_12__, 8);
if (((x.m_gu & 1) != 0)) {
__tmp_coord_array_12__[0] += (__x_xpd__[0][0] * in.m_c[0]);
}
if (((x.m_gu & 2) != 0)) {
__tmp_coord_array_12__[1] += (__x_xpd__[1][0] * in.m_c[0]);
__tmp_coord_array_12__[2] += (__x_xpd__[1][1] * in.m_c[0]);
__tmp_coord_array_12__[3] += (__x_xpd__[1][2] * in.m_c[0]);
}
if (((x.m_gu & 4) != 0)) {
__tmp_coord_array_12__[4] += (-1.0f * __x_xpd__[2][0] * in.m_c[0]);
__tmp_coord_array_12__[5] += (-1.0f * __x_xpd__[2][1] * in.m_c[0]);
__tmp_coord_array_12__[6] += (-1.0f * __x_xpd__[2][2] * in.m_c[0]);
}
if (((x.m_gu & 8) != 0)) {
__tmp_coord_array_12__[7] += (-1.0f * __x_xpd__[3][0] * in.m_c[0]);
}
__temp_var_1__ = mv_compress(__tmp_coord_array_12__);
return __temp_var_1__;
}
mv gradeInvolution(const mv& x) {
mv __temp_var_1__;
float __tmp_coord_array_13__[8] ;
mv_zero(__tmp_coord_array_13__, 8);
const float* __x_xpd__[4] ;
x.expand(__x_xpd__, true);
if (((x.m_gu & 1) != 0)) {
__tmp_coord_array_13__[0] += __x_xpd__[0][0];
}
if (((x.m_gu & 2) != 0)) {
__tmp_coord_array_13__[1] += (-1.0f * __x_xpd__[1][0]);
__tmp_coord_array_13__[2] += (-1.0f * __x_xpd__[1][1]);
__tmp_coord_array_13__[3] += (-1.0f * __x_xpd__[1][2]);
}
if (((x.m_gu & 4) != 0)) {
__tmp_coord_array_13__[4] += __x_xpd__[2][0];
__tmp_coord_array_13__[5] += __x_xpd__[2][1];
__tmp_coord_array_13__[6] += __x_xpd__[2][2];
}
if (((x.m_gu & 8) != 0)) {
__tmp_coord_array_13__[7] += (-1.0f * __x_xpd__[3][0]);
}
__temp_var_1__ = mv_compress(__tmp_coord_array_13__);
return __temp_var_1__;
}
// G2 functions:
mv apply_om(const om& x, const mv& y) {
mv __temp_var_1__;
float __tmp_coord_array_14__[8] ;
mv_zero(__tmp_coord_array_14__, 8);
const float* __y_xpd__[4] ;
y.expand(__y_xpd__, true);
if (((y.m_gu & 2) != 0)) {
__tmp_coord_array_14__[1] += ((x.m_c[2] * __y_xpd__[1][2]) + (x.m_c[1] * __y_xpd__[1][1]) + (x.m_c[0] * __y_xpd__[1][0]));
__tmp_coord_array_14__[2] += ((x.m_c[3] * __y_xpd__[1][0]) + (x.m_c[4] * __y_xpd__[1][1]) + (x.m_c[5] * __y_xpd__[1][2]));
__tmp_coord_array_14__[3] += ((x.m_c[6] * __y_xpd__[1][0]) + (x.m_c[7] * __y_xpd__[1][1]) + (x.m_c[8] * __y_xpd__[1][2]));
}
if (((y.m_gu & 4) != 0)) {
__tmp_coord_array_14__[4] += ((x.m_c[9] * __y_xpd__[2][0]) + (x.m_c[11] * __y_xpd__[2][2]) + (x.m_c[10] * __y_xpd__[2][1]));
__tmp_coord_array_14__[5] += ((x.m_c[14] * __y_xpd__[2][2]) + (x.m_c[12] * __y_xpd__[2][0]) + (x.m_c[13] * __y_xpd__[2][1]));
__tmp_coord_array_14__[6] += ((x.m_c[15] * __y_xpd__[2][0]) + (x.m_c[17] * __y_xpd__[2][2]) + (x.m_c[16] * __y_xpd__[2][1]));
}
if (((y.m_gu & 8) != 0)) {
__tmp_coord_array_14__[7] += (x.m_c[18] * __y_xpd__[3][0]);
}
__temp_var_1__ = mv_compress(__tmp_coord_array_14__);
return __temp_var_1__;
}
namespace __G2_GENERATED__ {
void set(om& __x__, const vector& __image_of_e1__, const vector& __image_of_e2__, const vector& __image_of_e3__) {
__x__.m_c[0] = __image_of_e1__.m_c[0];
__x__.m_c[3] = __image_of_e1__.m_c[1];
__x__.m_c[6] = __image_of_e1__.m_c[2];
__x__.m_c[1] = __image_of_e2__.m_c[0];
__x__.m_c[4] = __image_of_e2__.m_c[1];
__x__.m_c[7] = __image_of_e2__.m_c[2];
__x__.m_c[2] = __image_of_e3__.m_c[0];
__x__.m_c[5] = __image_of_e3__.m_c[1];
__x__.m_c[8] = __image_of_e3__.m_c[2];
__x__.m_c[9] = ((-1.0f * __x__.m_c[1] * __x__.m_c[3]) + (__x__.m_c[4] * __x__.m_c[0]));
__x__.m_c[12] = ((-1.0f * __x__.m_c[4] * __x__.m_c[6]) + (__x__.m_c[7] * __x__.m_c[3]));
__x__.m_c[15] = ((__x__.m_c[1] * __x__.m_c[6]) + (-1.0f * __x__.m_c[7] * __x__.m_c[0]));
__x__.m_c[10] = ((__x__.m_c[5] * __x__.m_c[1]) + (-1.0f * __x__.m_c[2] * __x__.m_c[4]));
__x__.m_c[13] = ((-1.0f * __x__.m_c[5] * __x__.m_c[7]) + (__x__.m_c[8] * __x__.m_c[4]));
__x__.m_c[16] = ((-1.0f * __x__.m_c[8] * __x__.m_c[1]) + (__x__.m_c[2] * __x__.m_c[7]));
__x__.m_c[11] = ((__x__.m_c[2] * __x__.m_c[3]) + (-1.0f * __x__.m_c[5] * __x__.m_c[0]));
__x__.m_c[14] = ((-1.0f * __x__.m_c[8] * __x__.m_c[3]) + (__x__.m_c[5] * __x__.m_c[6]));
__x__.m_c[17] = ((-1.0f * __x__.m_c[2] * __x__.m_c[6]) + (__x__.m_c[8] * __x__.m_c[0]));
__x__.m_c[18] = ((__x__.m_c[17] * __x__.m_c[4]) + (__x__.m_c[11] * __x__.m_c[7]) + (__x__.m_c[14] * __x__.m_c[1]));
}
} /* end of namespace __G2_GENERATED__ */
vector apply_om(const om& x, const vector& y) {
return vector(vector_e1_e2_e3, ((x.m_c[2] * y.m_c[2]) + (x.m_c[1] * y.m_c[1]) + (x.m_c[0] * y.m_c[0])), ((x.m_c[4] * y.m_c[1]) + (x.m_c[3] * y.m_c[0]) + (x.m_c[5] * y.m_c[2])), ((x.m_c[7] * y.m_c[1]) + (x.m_c[6] * y.m_c[0]) + (x.m_c[8] * y.m_c[2])));
}
bivector apply_om(const om& x, const bivector& y) {
return bivector(bivector_e1e2_e2e3_e3e1, ((x.m_c[10] * y.m_c[1]) + (x.m_c[11] * y.m_c[2]) + (x.m_c[9] * y.m_c[0])), ((x.m_c[12] * y.m_c[0]) + (x.m_c[14] * y.m_c[2]) + (x.m_c[13] * y.m_c[1])), ((x.m_c[15] * y.m_c[0]) + (x.m_c[16] * y.m_c[1]) + (x.m_c[17] * y.m_c[2])));
}
// algebra / user constants:
__I3i_ct__ I3i;
__e3_ct__ e3;
__I3_ct__ I3;
__e1_ct__ e1;
__e2_ct__ e2;
char *string(const mv & obj, char *str, int maxLength, const char *fp /* = NULL */) {
int stdIdx = 0, l;
char tmpBuf[256], tmpFloatBuf[256];
int i, j, k = 0, bei, ia = 0, s = mv_size[obj.gu()], p = 0, cnt = 0;
// set up the floating point precision
if (fp == NULL) fp = mv_string_fp;
// start the string
l = sprintf(tmpBuf, "%s", mv_string_start);
if (stdIdx + l <= maxLength) {
strcpy(str + stdIdx, tmpBuf);
stdIdx += l;
}
else mv_throw_exception("Buffer supplied to string() is too small", MV_EXCEPTION_ERROR);
// print all coordinates
for (i = 0; i <= 3; i++) {
if (obj.gu() & (1 << i)) {
for (j = 0; j < mv_gradeSize[i]; j++) {
float coord = (float)mv_basisElementSignByIndex[ia] * obj.m_c[k];
/* goal: print [+|-]obj.m_c[k][* basisVector1 ^ ... ^ basisVectorN] */
sprintf(tmpFloatBuf, fp, fabs(coord));
if (atof(tmpFloatBuf) != 0.0) {
l = 0;
// print [+|-]
l += sprintf(tmpBuf + l, "%s", (coord >= 0.0)
? (cnt ? mv_string_plus : "")
: mv_string_minus);
// print obj.m_c[k]
l += sprintf(tmpBuf + l, tmpFloatBuf);
if (i) { // if not grade 0, print [* basisVector1 ^ ... ^ basisVectorN]
l += sprintf(tmpBuf + l, "%s", mv_string_mul);
// print all basis vectors
bei = 0;
while (mv_basisElements[ia][bei] >= 0) {
l += sprintf(tmpBuf + l, "%s%s", (bei) ? mv_string_wedge : "",
mv_basisVectorNames[mv_basisElements[ia][bei]]);
bei++;
}
}
//copy all to 'str'
if (stdIdx + l <= maxLength) {
strcpy(str + stdIdx, tmpBuf);
stdIdx += l;
}
else mv_throw_exception("Buffer supplied to string() is too small", MV_EXCEPTION_ERROR);
cnt++;
}
k++; ia++;
}
}
else ia += mv_gradeSize[i];
}
// if no coordinates printed: 0
l = 0;
if (cnt == 0) {
l += sprintf(tmpBuf + l, "0");
}
// end the string
l += sprintf(tmpBuf + l, "%s", mv_string_end);
if (stdIdx + l <= maxLength) {
strcpy(str + stdIdx, tmpBuf);
stdIdx += l;
}
else mv_throw_exception("Buffer supplied to string() is too small", MV_EXCEPTION_ERROR);
return str;
}
// this function should be deprecated (conflicts with C++ stdlib)
char *string(const mv & obj, const char *fp /* = NULL */) {
// not multithreading safe, but not fatal either.
static char str[2048];
return string(obj, str, 2047, fp);
}
char *c_str(const mv & obj, const char *fp /* = NULL */) {
return string(obj, fp);
}
std::string toString(const mv & obj, const char *fp /* = NULL */) {
std::string str;
const int SIZE = 2048;
str.resize(SIZE);
string(obj, &(str[0]), SIZE-1, fp);
str.resize(strlen(&(str[0])));
return str;
}
/** This function is not for external use. It compressed arrays of floats for storage in multivectors. */
void compress(const float *c, float *cc, int &cgu, float epsilon /*= 0.0*/, int gu /*= ...*/) {
int i, j, ia = 0, ib = 0, f, s;
cgu = 0;
// for all grade parts...
for (i = 0; i <= 3; i++) {
// check if grade part has memory use:
if (!(gu & (1 << i))) continue;
// check if abs coordinates of grade part are all < epsilon
s = mv_gradeSize[i];
j = ia + s;
f = 0;
for (; ia < j; ia++)
if (mv_absLessThan(c[ia], epsilon)) {f = 1; break;}
ia = j;
if (f) {
mv_memcpy(cc + ib, c + ia - s, s);
ib += s;
cgu |= (1 << i);
}
}
}
mv mv_compress(const float *c, float epsilon/*= 0.0*/, int gu /*= ...*/) {
float cc[8];
int cgu;
compress(c, cc, cgu, epsilon, gu);
return mv(cgu, cc);
}
mv compress(const mv & arg1, float epsilon /*= 0.0*/) {
return mv_compress(arg1.m_c, epsilon, arg1.m_gu);
}
void mv::compress(float epsilon /*= 0.0*/) {
float cc[8];
int cgu;
e3ga::compress(m_c, cc, cgu, epsilon, m_gu);
set(cgu, cc);
}
mv mv_compress(int nbBlades, const unsigned int *bitmaps, const mv::Float *coords) {
// convert basis blade compression to regular coordinate array:
mv::Float A[8];
mv_zero(A, 8);
// int gu = 0;
for (int i = 0; i < nbBlades; i++) {
A[mv_basisElementIndexByBitmap[bitmaps[i]]] = coords[i] * (mv::Float)mv_basisElementSignByBitmap[bitmaps[i]];
// gu |= (1 << mv_basisElementGradeByBitmap[bitmaps[i]]);
}
return mv_compress(A); //, (mv::Float)0.0, gu);
}
/** This function is not for external use. It decompresses the coordinates stored in this */
void mv::expand(const Float *ptrs[], bool nulls /* = true */) const {
const Float *c(m_c);
const Float *null = (nulls) ? NULL : nullFloats();
if (m_gu & 1) {
ptrs[0] = c;
c += 1;
}
else ptrs[0] = null;
if (m_gu & 2) {
ptrs[1] = c;
c += 3;
}
else ptrs[1] = null;
if (m_gu & 4) {
ptrs[2] = c;
c += 3;
}
else ptrs[2] = null;
if (m_gu & 8) {
ptrs[3] = c;
c += 1;
}
else ptrs[3] = null;
}
void mvType::init(const mv &X, mv::Float epsilon) {
m_type = MULTIVECTOR;
// first of all determine grade usage & parity
mv cX = X;
cX.compress(epsilon);
m_gradeUsage = (int)cX.gu();
int cnt[2] = {0,0}; // nb even, odd grade parts in use
{
// count grade part usage:
int cntIdx = 0;
int gu = m_gradeUsage;
while (gu != 0) {
if ((gu & 1) != 0)
cnt[cntIdx & 1]++;
gu >>= 1;
m_grade = cntIdx;
cntIdx++;
}
// if no grade part in use: zero blade
if ((cnt[0] == 0) && (cnt[1] == 0)) {
// multivector = zero blade, case closed
m_zero = true;
m_type = BLADE;
m_parity = 0;
m_grade = 0; // forced to grade 0, but actually, does not really have a grade
return;
}
else {
m_zero = false;
// if both even and odd grade parts in use: multivector
if ((cnt[0] != 0) && (cnt[1] != 0)) {
// X = multivector, case closed
m_parity = -1;
return;
}
else // more work to do, but parity is known:
// either a blade, or a versor, TBD below
m_parity = (cnt[1] != 0) ? 1 : 0;
}
}
// first test for versor:
bool useAlgebraMetric = true;
init(X, epsilon, useAlgebraMetric, cnt[0] + cnt[1]);
}
void mvType::init(const mv &X, mv::Float epsilon, bool useAlgebraMetric, int guCnt) {
mv rX = reverse(X);
// test if null:
mv Sq = (useAlgebraMetric) ? scp(X, rX) : scp(X, rX);
Sq.compress(epsilon);
if (_Float(Sq) == 0) {
// X = multivector, case closed
m_type = MULTIVECTOR;
return;
}
// versor inverse must be true inverse:
mv Xvi = (useAlgebraMetric) ? inverse(X) : inverse(X);
mv Xgi = gradeInvolution(X);
// check if (Xgi Xvi) is a scalar:
mv XgiXvi = (useAlgebraMetric) ? gp(Xgi, Xvi) : gp(Xgi, Xvi);
{
mv tmp = XgiXvi;
tmp.compress(epsilon);
if (tmp.gu() != GRADE_0) { // if not scalar:
// X = multivector, case closed
m_type = MULTIVECTOR;
return;
}
}
// check if Xgi Xvi == Xvi Xgi
mv XviXgi = (useAlgebraMetric) ? gp(Xvi, Xgi) : gp(Xvi, Xgi);
{
mv tmp = XviXgi - XgiXvi;
tmp.compress(epsilon); // this should result in 0
if (tmp.gu()) {
// if not:
// X = multivector, case closed
m_type = MULTIVECTOR;
return;
}
}
// check if grade preserving for all basis vectors:
{
{
// test e1
mv tmp = (useAlgebraMetric) ? gp(gp(Xvi, e1), Xgi) : gp(gp(Xvi, e1), Xgi);
tmp.compress(epsilon);
if (tmp.gu() != GRADE_1) { // X = multivector, case closed
m_type = MULTIVECTOR;
return;
}
}
{
// test e2
mv tmp = (useAlgebraMetric) ? gp(gp(Xvi, e2), Xgi) : gp(gp(Xvi, e2), Xgi);
tmp.compress(epsilon);
if (tmp.gu() != GRADE_1) { // X = multivector, case closed
m_type = MULTIVECTOR;
return;
}
}
{
// test e3
mv tmp = (useAlgebraMetric) ? gp(gp(Xvi, e3), Xgi) : gp(gp(Xvi, e3), Xgi);
tmp.compress(epsilon);
if (tmp.gu() != GRADE_1) { // X = multivector, case closed
m_type = MULTIVECTOR;
return;
}
}
}
// if homogeneous: blade
if (guCnt == 1) m_type = BLADE;
else m_type = VERSOR;
}
std::string mvType::toString() const {
char buf[1024];
sprintf(buf, "%s, grade: %d, gradeUsage: %X, parity: %s",
(m_type == MULTIVECTOR) ? "multivector" : ((m_type == BLADE) ? "blade" : "versor"),
m_grade, m_gradeUsage,
(m_parity < 0) ? "none" : ((m_parity == 0) ? "even" : "odd"));
return buf;
}
} // end of namespace e3ga
// post_cpp_include
| 20.395898 | 270 | 0.563179 | [
"vector"
] |
edb73477889d3a36094d13bc8fcb2544b2e63cb8 | 30,876 | cc | C++ | media/remoting/courier_renderer_unittest.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | media/remoting/courier_renderer_unittest.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | media/remoting/courier_renderer_unittest.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-03-07T14:20:02.000Z | 2021-03-07T14:20:02.000Z | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/remoting/courier_renderer.h"
#include <memory>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/check.h"
#include "base/run_loop.h"
#include "base/test/simple_test_tick_clock.h"
#include "base/test/task_environment.h"
#include "base/threading/thread_task_runner_handle.h"
#include "media/base/media_util.h"
#include "media/base/pipeline_status.h"
#include "media/base/renderer_client.h"
#include "media/base/test_helpers.h"
#include "media/remoting/fake_media_resource.h"
#include "media/remoting/fake_remoter.h"
#include "media/remoting/proto_enum_utils.h"
#include "media/remoting/proto_utils.h"
#include "media/remoting/renderer_controller.h"
#include "media/remoting/rpc_broker.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using testing::_;
using testing::Invoke;
using testing::Return;
namespace media {
namespace remoting {
namespace {
PipelineMetadata DefaultMetadata() {
PipelineMetadata data;
data.has_audio = true;
data.has_video = true;
data.video_decoder_config = TestVideoConfig::Normal();
return data;
}
PipelineStatistics DefaultStats() {
PipelineStatistics stats;
stats.audio_bytes_decoded = 1234U;
stats.video_bytes_decoded = 2345U;
stats.video_frames_decoded = 3000U;
stats.video_frames_dropped = 91U;
stats.audio_memory_usage = 5678;
stats.video_memory_usage = 6789;
stats.video_keyframe_distance_average = base::TimeDelta::Max();
stats.audio_decoder_info = {false, false, AudioDecoderType::kUnknown};
stats.video_decoder_info = {false, false, VideoDecoderType::kUnknown};
return stats;
}
class RendererClientImpl final : public RendererClient {
public:
RendererClientImpl() {
ON_CALL(*this, OnStatisticsUpdate(_))
.WillByDefault(
Invoke(this, &RendererClientImpl::DelegateOnStatisticsUpdate));
ON_CALL(*this, OnPipelineStatus(_))
.WillByDefault(
Invoke(this, &RendererClientImpl::DelegateOnPipelineStatus));
ON_CALL(*this, OnBufferingStateChange(_, _))
.WillByDefault(
Invoke(this, &RendererClientImpl::DelegateOnBufferingStateChange));
ON_CALL(*this, OnAudioConfigChange(_))
.WillByDefault(
Invoke(this, &RendererClientImpl::DelegateOnAudioConfigChange));
ON_CALL(*this, OnVideoConfigChange(_))
.WillByDefault(
Invoke(this, &RendererClientImpl::DelegateOnVideoConfigChange));
ON_CALL(*this, OnVideoNaturalSizeChange(_))
.WillByDefault(Invoke(
this, &RendererClientImpl::DelegateOnVideoNaturalSizeChange));
ON_CALL(*this, OnVideoOpacityChange(_))
.WillByDefault(
Invoke(this, &RendererClientImpl::DelegateOnVideoOpacityChange));
}
~RendererClientImpl() = default;
// RendererClient implementation.
void OnError(PipelineStatus status) override {}
void OnEnded() override {}
MOCK_METHOD1(OnStatisticsUpdate, void(const PipelineStatistics& stats));
MOCK_METHOD2(OnBufferingStateChange,
void(BufferingState state, BufferingStateChangeReason reason));
MOCK_METHOD1(OnAudioConfigChange, void(const AudioDecoderConfig& config));
MOCK_METHOD1(OnVideoConfigChange, void(const VideoDecoderConfig& config));
void OnWaiting(WaitingReason reason) override {}
MOCK_METHOD1(OnVideoNaturalSizeChange, void(const gfx::Size& size));
MOCK_METHOD1(OnVideoOpacityChange, void(bool opaque));
MOCK_METHOD1(OnVideoFrameRateChange, void(base::Optional<int>));
MOCK_METHOD1(OnRemotePlayStateChange, void(MediaStatus::State state));
void DelegateOnStatisticsUpdate(const PipelineStatistics& stats) {
stats_ = stats;
}
void DelegateOnBufferingStateChange(BufferingState state,
BufferingStateChangeReason reason) {
state_ = state;
}
void DelegateOnAudioConfigChange(const AudioDecoderConfig& config) {
audio_decoder_config_ = config;
}
void DelegateOnVideoConfigChange(const VideoDecoderConfig& config) {
video_decoder_config_ = config;
}
void DelegateOnVideoNaturalSizeChange(const gfx::Size& size) { size_ = size; }
void DelegateOnVideoOpacityChange(bool opaque) { opaque_ = opaque; }
MOCK_METHOD1(OnPipelineStatus, void(PipelineStatus status));
void DelegateOnPipelineStatus(PipelineStatus status) {
VLOG(2) << "OnPipelineStatus status:" << status;
status_ = status;
}
MOCK_METHOD0(OnFlushCallback, void());
PipelineStatus status() const { return status_; }
PipelineStatistics stats() const { return stats_; }
BufferingState state() const { return state_; }
gfx::Size size() const { return size_; }
bool opaque() const { return opaque_; }
VideoDecoderConfig video_decoder_config() const {
return video_decoder_config_;
}
AudioDecoderConfig audio_decoder_config() const {
return audio_decoder_config_;
}
private:
PipelineStatus status_ = PIPELINE_OK;
BufferingState state_ = BUFFERING_HAVE_NOTHING;
gfx::Size size_;
bool opaque_ = false;
PipelineStatistics stats_;
VideoDecoderConfig video_decoder_config_;
AudioDecoderConfig audio_decoder_config_;
DISALLOW_COPY_AND_ASSIGN(RendererClientImpl);
};
} // namespace
class CourierRendererTest : public testing::Test {
public:
CourierRendererTest() = default;
~CourierRendererTest() override = default;
// Use this function to mimic receiver to handle RPC message for renderer
// initialization,
void RpcMessageResponseBot(std::unique_ptr<std::vector<uint8_t>> message) {
std::unique_ptr<pb::RpcMessage> rpc(new pb::RpcMessage());
ASSERT_TRUE(rpc->ParseFromArray(message->data(), message->size()));
switch (rpc->proc()) {
case pb::RpcMessage::RPC_ACQUIRE_RENDERER: {
DCHECK(rpc->has_integer_value());
sender_renderer_handle_ = rpc->integer_value();
// Issues RPC_ACQUIRE_RENDERER_DONE RPC message.
auto acquire_done = std::make_unique<pb::RpcMessage>();
acquire_done->set_handle(sender_renderer_handle_);
acquire_done->set_proc(pb::RpcMessage::RPC_ACQUIRE_RENDERER_DONE);
acquire_done->set_integer_value(receiver_renderer_handle_);
controller_->GetRpcBroker()->ProcessMessageFromRemote(
std::move(acquire_done));
} break;
case pb::RpcMessage::RPC_ACQUIRE_DEMUXER: {
if (!is_backward_compatible_mode_) {
int acquire_demuxer_handle = RpcBroker::kAcquireDemuxerHandle;
EXPECT_EQ(rpc->handle(), acquire_demuxer_handle);
sender_audio_demuxer_handle_ =
rpc->acquire_demuxer_rpc().audio_demuxer_handle();
sender_video_demuxer_handle_ =
rpc->acquire_demuxer_rpc().video_demuxer_handle();
// Issues audio RPC_DS_INITIALIZE RPC message.
if (sender_audio_demuxer_handle_ != RpcBroker::kInvalidHandle) {
auto ds_init = std::make_unique<pb::RpcMessage>();
ds_init->set_handle(sender_audio_demuxer_handle_);
ds_init->set_proc(pb::RpcMessage::RPC_DS_INITIALIZE);
ds_init->set_integer_value(receiver_audio_demuxer_callback_handle_);
controller_->GetRpcBroker()->ProcessMessageFromRemote(
std::move(ds_init));
}
// Issues video RPC_DS_INITIALIZE RPC message.
if (sender_video_demuxer_handle_ != RpcBroker::kInvalidHandle) {
auto ds_init = std::make_unique<pb::RpcMessage>();
ds_init->set_handle(sender_video_demuxer_handle_);
ds_init->set_proc(pb::RpcMessage::RPC_DS_INITIALIZE);
ds_init->set_integer_value(receiver_video_demuxer_callback_handle_);
controller_->GetRpcBroker()->ProcessMessageFromRemote(
std::move(ds_init));
}
}
} break;
case pb::RpcMessage::RPC_R_INITIALIZE: {
sender_renderer_callback_handle_ =
rpc->renderer_initialize_rpc().callback_handle();
sender_client_handle_ = rpc->renderer_initialize_rpc().client_handle();
if (is_backward_compatible_mode_) {
EXPECT_EQ(rpc->handle(), receiver_renderer_handle_);
sender_audio_demuxer_handle_ =
rpc->renderer_initialize_rpc().audio_demuxer_handle();
sender_video_demuxer_handle_ =
rpc->renderer_initialize_rpc().video_demuxer_handle();
// Issues audio RPC_DS_INITIALIZE RPC message.
if (sender_audio_demuxer_handle_ != RpcBroker::kInvalidHandle) {
auto ds_init = std::make_unique<pb::RpcMessage>();
ds_init->set_handle(sender_audio_demuxer_handle_);
ds_init->set_proc(pb::RpcMessage::RPC_DS_INITIALIZE);
ds_init->set_integer_value(receiver_audio_demuxer_callback_handle_);
controller_->GetRpcBroker()->ProcessMessageFromRemote(
std::move(ds_init));
}
// Issues video RPC_DS_INITIALIZE RPC message.
if (sender_video_demuxer_handle_ != RpcBroker::kInvalidHandle) {
auto ds_init = std::make_unique<pb::RpcMessage>();
ds_init->set_handle(sender_video_demuxer_handle_);
ds_init->set_proc(pb::RpcMessage::RPC_DS_INITIALIZE);
ds_init->set_integer_value(receiver_video_demuxer_callback_handle_);
controller_->GetRpcBroker()->ProcessMessageFromRemote(
std::move(ds_init));
}
} else {
// Issues RPC_R_INITIALIZE_CALLBACK RPC message when receiving
// RPC_R_INITIALIZE.
auto init_cb = std::make_unique<pb::RpcMessage>();
init_cb->set_handle(sender_renderer_callback_handle_);
init_cb->set_proc(pb::RpcMessage::RPC_R_INITIALIZE_CALLBACK);
init_cb->set_boolean_value(is_successfully_initialized_);
controller_->GetRpcBroker()->ProcessMessageFromRemote(
std::move(init_cb));
}
} break;
case pb::RpcMessage::RPC_DS_INITIALIZE_CALLBACK: {
if (rpc->handle() == receiver_audio_demuxer_callback_handle_)
received_audio_ds_init_cb_ = true;
if (rpc->handle() == receiver_video_demuxer_callback_handle_)
received_video_ds_init_cb_ = true;
// Check whether the demuxer at the receiver end is initialized.
if (received_audio_ds_init_cb_ ==
(sender_audio_demuxer_handle_ != RpcBroker::kInvalidHandle) &&
received_video_ds_init_cb_ ==
(sender_video_demuxer_handle_ != RpcBroker::kInvalidHandle)) {
is_receiver_demuxer_initialized_ = true;
}
if (is_backward_compatible_mode_ && is_receiver_demuxer_initialized_) {
// Issues RPC_R_INITIALIZE_CALLBACK RPC message when receiving
// RPC_DS_INITIALIZE_CALLBACK on available streams.
auto init_cb = std::make_unique<pb::RpcMessage>();
init_cb->set_handle(sender_renderer_callback_handle_);
init_cb->set_proc(pb::RpcMessage::RPC_R_INITIALIZE_CALLBACK);
init_cb->set_boolean_value(is_successfully_initialized_);
controller_->GetRpcBroker()->ProcessMessageFromRemote(
std::move(init_cb));
}
} break;
case pb::RpcMessage::RPC_R_FLUSHUNTIL: {
// Issues RPC_R_FLUSHUNTIL_CALLBACK RPC message.
std::unique_ptr<pb::RpcMessage> flush_cb(new pb::RpcMessage());
flush_cb->set_handle(rpc->renderer_flushuntil_rpc().callback_handle());
flush_cb->set_proc(pb::RpcMessage::RPC_R_FLUSHUNTIL_CALLBACK);
controller_->GetRpcBroker()->ProcessMessageFromRemote(
std::move(flush_cb));
} break;
case pb::RpcMessage::RPC_R_SETVOLUME:
// No response needed.
break;
default:
NOTREACHED();
}
RunPendingTasks();
}
// Callback from RpcBroker when sending message to remote sink.
void OnSendMessageToSink(std::unique_ptr<std::vector<uint8_t>> message) {
std::unique_ptr<pb::RpcMessage> rpc(new pb::RpcMessage());
ASSERT_TRUE(rpc->ParseFromArray(message->data(), message->size()));
received_rpc_.push_back(std::move(rpc));
}
protected:
void InitializeRenderer() {
// Register media::RendererClient implementation.
render_client_.reset(new RendererClientImpl());
media_resource_.reset(new FakeMediaResource());
EXPECT_CALL(*render_client_, OnPipelineStatus(_)).Times(1);
DCHECK(renderer_);
// Redirect RPC message for simulate receiver scenario
controller_->GetRpcBroker()->SetMessageCallbackForTesting(
base::BindRepeating(&CourierRendererTest::RpcMessageResponseBot,
base::Unretained(this)));
RunPendingTasks();
renderer_->Initialize(
media_resource_.get(), render_client_.get(),
base::BindOnce(&RendererClientImpl::OnPipelineStatus,
base::Unretained(render_client_.get())));
RunPendingTasks();
// Redirect RPC message back to save for later check.
controller_->GetRpcBroker()->SetMessageCallbackForTesting(
base::BindRepeating(&CourierRendererTest::OnSendMessageToSink,
base::Unretained(this)));
RunPendingTasks();
}
void InitializeRendererBackwardsCompatible() {
is_backward_compatible_mode_ = true;
InitializeRenderer();
}
bool IsRendererInitialized() const {
EXPECT_TRUE(received_audio_ds_init_cb_);
EXPECT_TRUE(received_video_ds_init_cb_);
return renderer_->state_ == CourierRenderer::STATE_PLAYING &&
is_receiver_demuxer_initialized_;
}
bool DidEncounterFatalError() const {
return renderer_->state_ == CourierRenderer::STATE_ERROR;
}
void OnReceivedRpc(std::unique_ptr<pb::RpcMessage> message) {
renderer_->OnReceivedRpc(std::move(message));
}
void SetUp() override {
controller_ = FakeRemoterFactory::CreateController(false);
controller_->OnMetadataChanged(DefaultMetadata());
// Redirect RPC message to CourierRendererTest::OnSendMessageToSink().
controller_->GetRpcBroker()->SetMessageCallbackForTesting(
base::BindRepeating(&CourierRendererTest::OnSendMessageToSink,
base::Unretained(this)));
renderer_.reset(new CourierRenderer(base::ThreadTaskRunnerHandle::Get(),
controller_->GetWeakPtr(), nullptr));
renderer_->clock_ = &clock_;
clock_.Advance(base::TimeDelta::FromSeconds(1));
RunPendingTasks();
}
CourierRenderer::State state() const { return renderer_->state_; }
void RunPendingTasks() { base::RunLoop().RunUntilIdle(); }
// Gets first available RpcMessage with specific |proc|.
const pb::RpcMessage* PeekRpcMessage(int proc) const {
for (auto& s : received_rpc_) {
if (proc == s->proc())
return s.get();
}
return nullptr;
}
int ReceivedRpcMessageCount() const { return received_rpc_.size(); }
void ResetReceivedRpcMessage() { received_rpc_.clear(); }
void ValidateCurrentTime(base::TimeDelta current,
base::TimeDelta current_max) const {
ASSERT_EQ(renderer_->current_media_time_, current);
ASSERT_EQ(renderer_->current_max_time_, current_max);
}
// Issues RPC_RC_ONTIMEUPDATE RPC message.
void IssueTimeUpdateRpc(base::TimeDelta media_time,
base::TimeDelta max_media_time) {
std::unique_ptr<remoting::pb::RpcMessage> rpc(
new remoting::pb::RpcMessage());
rpc->set_handle(5);
rpc->set_proc(remoting::pb::RpcMessage::RPC_RC_ONTIMEUPDATE);
auto* time_message = rpc->mutable_rendererclient_ontimeupdate_rpc();
time_message->set_time_usec(media_time.InMicroseconds());
time_message->set_max_time_usec(max_media_time.InMicroseconds());
OnReceivedRpc(std::move(rpc));
RunPendingTasks();
}
// Verifies no error reported and issues a series of time updates RPC
// messages. No verification after the last message is issued.
void VerifyAndReportTimeUpdates(int start_serial_number,
int end_serial_number) {
for (int i = start_serial_number; i < end_serial_number; ++i) {
ASSERT_FALSE(DidEncounterFatalError());
IssueTimeUpdateRpc(base::TimeDelta::FromMilliseconds(100 + i * 800),
base::TimeDelta::FromSeconds(100));
clock_.Advance(base::TimeDelta::FromSeconds(1));
RunPendingTasks();
}
}
// Issues RPC_RC_ONSTATISTICSUPDATE RPC message with DefaultStats().
void IssueStatisticsUpdateRpc() {
EXPECT_CALL(*render_client_, OnStatisticsUpdate(_)).Times(1);
const PipelineStatistics stats = DefaultStats();
std::unique_ptr<remoting::pb::RpcMessage> rpc(
new remoting::pb::RpcMessage());
rpc->set_handle(5);
rpc->set_proc(remoting::pb::RpcMessage::RPC_RC_ONSTATISTICSUPDATE);
auto* message = rpc->mutable_rendererclient_onstatisticsupdate_rpc();
message->set_audio_bytes_decoded(stats.audio_bytes_decoded);
message->set_video_bytes_decoded(stats.video_bytes_decoded);
message->set_video_frames_decoded(stats.video_frames_decoded);
message->set_video_frames_dropped(stats.video_frames_dropped);
message->set_audio_memory_usage(stats.audio_memory_usage);
message->set_video_memory_usage(stats.video_memory_usage);
message->mutable_audio_decoder_info()->set_is_platform_decoder(
stats.audio_decoder_info.is_platform_decoder);
message->mutable_audio_decoder_info()->set_decoder_type(
static_cast<int64_t>(stats.audio_decoder_info.decoder_type));
message->mutable_video_decoder_info()->set_is_platform_decoder(
stats.video_decoder_info.is_platform_decoder);
message->mutable_video_decoder_info()->set_decoder_type(
static_cast<int64_t>(stats.video_decoder_info.decoder_type));
OnReceivedRpc(std::move(rpc));
RunPendingTasks();
}
// Issue RPC_RC_ONBUFFERINGSTATECHANGE RPC message.
void IssuesBufferingStateRpc(BufferingState state) {
base::Optional<pb::RendererClientOnBufferingStateChange::State> pb_state =
ToProtoMediaBufferingState(state);
if (!pb_state.has_value())
return;
std::unique_ptr<remoting::pb::RpcMessage> rpc(
new remoting::pb::RpcMessage());
rpc->set_handle(5);
rpc->set_proc(remoting::pb::RpcMessage::RPC_RC_ONBUFFERINGSTATECHANGE);
auto* buffering_state =
rpc->mutable_rendererclient_onbufferingstatechange_rpc();
buffering_state->set_state(pb_state.value());
OnReceivedRpc(std::move(rpc));
RunPendingTasks();
}
base::test::SingleThreadTaskEnvironment task_environment_;
std::unique_ptr<RendererController> controller_;
std::unique_ptr<RendererClientImpl> render_client_;
std::unique_ptr<FakeMediaResource> media_resource_;
std::unique_ptr<CourierRenderer> renderer_;
base::SimpleTestTickClock clock_;
// RPC handles.
const int receiver_renderer_handle_{10};
const int receiver_audio_demuxer_callback_handle_{11};
const int receiver_video_demuxer_callback_handle_{12};
int sender_renderer_handle_;
int sender_client_handle_{RpcBroker::kInvalidHandle};
int sender_renderer_callback_handle_{RpcBroker::kInvalidHandle};
int sender_audio_demuxer_handle_{RpcBroker::kInvalidHandle};
int sender_video_demuxer_handle_{RpcBroker::kInvalidHandle};
// Indicates whether the test runs in backward-compatible mode.
bool is_backward_compatible_mode_ = false;
// Indicates whether the demuxer at receiver is initialized or not.
bool is_receiver_demuxer_initialized_ = false;
// Indicate whether RPC_DS_INITIALIZE_CALLBACK RPC messages are received.
bool received_audio_ds_init_cb_ = false;
bool received_video_ds_init_cb_ = false;
// Indicates whether the test wants to simulate successful initialization in
// the renderer on the receiver side.
bool is_successfully_initialized_ = true;
// Stores RPC messages that are sending to remote sink.
std::vector<std::unique_ptr<pb::RpcMessage>> received_rpc_;
private:
DISALLOW_COPY_AND_ASSIGN(CourierRendererTest);
};
TEST_F(CourierRendererTest, Initialize) {
InitializeRenderer();
RunPendingTasks();
ASSERT_TRUE(IsRendererInitialized());
ASSERT_EQ(render_client_->status(), PIPELINE_OK);
}
TEST_F(CourierRendererTest, InitializeBackwardCompatible) {
InitializeRendererBackwardsCompatible();
RunPendingTasks();
ASSERT_TRUE(IsRendererInitialized());
ASSERT_EQ(render_client_->status(), PIPELINE_OK);
}
TEST_F(CourierRendererTest, InitializeFailed) {
is_successfully_initialized_ = false;
InitializeRenderer();
RunPendingTasks();
ASSERT_FALSE(IsRendererInitialized());
ASSERT_TRUE(DidEncounterFatalError());
// Don't report error to prevent breaking the pipeline.
ASSERT_EQ(render_client_->status(), PIPELINE_OK);
// The CourierRenderer should act as a no-op renderer from this point.
ResetReceivedRpcMessage();
EXPECT_CALL(*render_client_, OnFlushCallback()).Times(1);
renderer_->Flush(base::BindOnce(&RendererClientImpl::OnFlushCallback,
base::Unretained(render_client_.get())));
RunPendingTasks();
ASSERT_EQ(0, ReceivedRpcMessageCount());
base::TimeDelta seek = base::TimeDelta::FromMicroseconds(100);
renderer_->StartPlayingFrom(seek);
RunPendingTasks();
ASSERT_EQ(0, ReceivedRpcMessageCount());
renderer_->SetVolume(3.0);
RunPendingTasks();
ASSERT_EQ(0, ReceivedRpcMessageCount());
renderer_->SetPlaybackRate(2.5);
RunPendingTasks();
ASSERT_EQ(0, ReceivedRpcMessageCount());
}
TEST_F(CourierRendererTest, Flush) {
// Initialize Renderer.
InitializeRenderer();
RunPendingTasks();
ASSERT_TRUE(IsRendererInitialized());
ASSERT_EQ(render_client_->status(), PIPELINE_OK);
// Flush Renderer.
// Redirect RPC message for simulate receiver scenario
controller_->GetRpcBroker()->SetMessageCallbackForTesting(base::BindRepeating(
&CourierRendererTest::RpcMessageResponseBot, base::Unretained(this)));
RunPendingTasks();
EXPECT_CALL(*render_client_, OnFlushCallback()).Times(1);
renderer_->Flush(base::BindOnce(&RendererClientImpl::OnFlushCallback,
base::Unretained(render_client_.get())));
RunPendingTasks();
}
TEST_F(CourierRendererTest, StartPlayingFrom) {
// Initialize Renderer
InitializeRenderer();
RunPendingTasks();
ASSERT_TRUE(IsRendererInitialized());
ASSERT_EQ(render_client_->status(), PIPELINE_OK);
// StartPlaying from
base::TimeDelta seek = base::TimeDelta::FromMicroseconds(100);
renderer_->StartPlayingFrom(seek);
RunPendingTasks();
// Checks if it sends out RPC message with correct value.
ASSERT_EQ(1, ReceivedRpcMessageCount());
const pb::RpcMessage* rpc =
PeekRpcMessage(pb::RpcMessage::RPC_R_STARTPLAYINGFROM);
ASSERT_TRUE(rpc);
ASSERT_EQ(rpc->integer64_value(), 100);
}
TEST_F(CourierRendererTest, SetVolume) {
// Initialize Renderer because, as of this writing, the pipeline guarantees it
// will not call SetVolume() until after the media::Renderer is initialized.
InitializeRenderer();
RunPendingTasks();
ASSERT_EQ(0, ReceivedRpcMessageCount());
// SetVolume() will send pb::RpcMessage::RPC_R_SETVOLUME RPC.
renderer_->SetVolume(3.0);
RunPendingTasks();
// Checks if it sends out RPC message with correct value.
ASSERT_EQ(1, ReceivedRpcMessageCount());
const pb::RpcMessage* rpc = PeekRpcMessage(pb::RpcMessage::RPC_R_SETVOLUME);
ASSERT_TRUE(rpc);
ASSERT_TRUE(rpc->double_value() == 3.0);
}
TEST_F(CourierRendererTest, SetPlaybackRate) {
// Initialize Renderer because, as of this writing, the pipeline guarantees it
// will not call SetPlaybackRate() until after the media::Renderer is
// initialized.
InitializeRenderer();
RunPendingTasks();
ASSERT_EQ(0, ReceivedRpcMessageCount());
renderer_->SetPlaybackRate(2.5);
RunPendingTasks();
ASSERT_EQ(1, ReceivedRpcMessageCount());
// Checks if it sends out RPC message with correct value.
const pb::RpcMessage* rpc =
PeekRpcMessage(pb::RpcMessage::RPC_R_SETPLAYBACKRATE);
ASSERT_TRUE(rpc);
ASSERT_TRUE(rpc->double_value() == 2.5);
}
TEST_F(CourierRendererTest, OnTimeUpdate) {
base::TimeDelta media_time = base::TimeDelta::FromMicroseconds(100);
base::TimeDelta max_media_time = base::TimeDelta::FromMicroseconds(500);
IssueTimeUpdateRpc(media_time, max_media_time);
ValidateCurrentTime(media_time, max_media_time);
// Issues RPC_RC_ONTIMEUPDATE RPC message with invalid time
base::TimeDelta media_time2 = base::TimeDelta::FromMicroseconds(-100);
base::TimeDelta max_media_time2 = base::TimeDelta::FromMicroseconds(500);
IssueTimeUpdateRpc(media_time2, max_media_time2);
// Because of invalid value, the time will not be updated and remain the same.
ValidateCurrentTime(media_time, max_media_time);
}
TEST_F(CourierRendererTest, OnBufferingStateChange) {
InitializeRenderer();
EXPECT_CALL(*render_client_,
OnBufferingStateChange(BUFFERING_HAVE_NOTHING, _))
.Times(1);
IssuesBufferingStateRpc(BufferingState::BUFFERING_HAVE_NOTHING);
}
TEST_F(CourierRendererTest, OnAudioConfigChange) {
const AudioDecoderConfig kNewAudioConfig(
kCodecVorbis, kSampleFormatPlanarF32, CHANNEL_LAYOUT_STEREO, 44100,
EmptyExtraData(), EncryptionScheme::kUnencrypted);
InitializeRenderer();
// Make sure initial audio config does not match the one we intend to send.
ASSERT_FALSE(render_client_->audio_decoder_config().Matches(kNewAudioConfig));
// Issues RPC_RC_ONVIDEOCONFIGCHANGE RPC message.
EXPECT_CALL(*render_client_,
OnAudioConfigChange(DecoderConfigEq(kNewAudioConfig)))
.Times(1);
std::unique_ptr<pb::RpcMessage> rpc(new pb::RpcMessage());
rpc->set_handle(5);
rpc->set_proc(pb::RpcMessage::RPC_RC_ONAUDIOCONFIGCHANGE);
auto* audio_config_change_message =
rpc->mutable_rendererclient_onaudioconfigchange_rpc();
pb::AudioDecoderConfig* proto_audio_config =
audio_config_change_message->mutable_audio_decoder_config();
ConvertAudioDecoderConfigToProto(kNewAudioConfig, proto_audio_config);
OnReceivedRpc(std::move(rpc));
RunPendingTasks();
ASSERT_TRUE(render_client_->audio_decoder_config().Matches(kNewAudioConfig));
}
TEST_F(CourierRendererTest, OnVideoConfigChange) {
const auto kNewVideoConfig = TestVideoConfig::Normal();
InitializeRenderer();
// Make sure initial video config does not match the one we intend to send.
ASSERT_FALSE(render_client_->video_decoder_config().Matches(kNewVideoConfig));
// Issues RPC_RC_ONVIDEOCONFIGCHANGE RPC message.
EXPECT_CALL(*render_client_,
OnVideoConfigChange(DecoderConfigEq(kNewVideoConfig)))
.Times(1);
std::unique_ptr<pb::RpcMessage> rpc(new pb::RpcMessage());
rpc->set_handle(5);
rpc->set_proc(pb::RpcMessage::RPC_RC_ONVIDEOCONFIGCHANGE);
auto* video_config_change_message =
rpc->mutable_rendererclient_onvideoconfigchange_rpc();
pb::VideoDecoderConfig* proto_video_config =
video_config_change_message->mutable_video_decoder_config();
ConvertVideoDecoderConfigToProto(kNewVideoConfig, proto_video_config);
OnReceivedRpc(std::move(rpc));
RunPendingTasks();
ASSERT_TRUE(render_client_->video_decoder_config().Matches(kNewVideoConfig));
}
TEST_F(CourierRendererTest, OnVideoNaturalSizeChange) {
InitializeRenderer();
// Makes sure initial value of video natural size is not set to
// gfx::Size(100, 200).
ASSERT_NE(render_client_->size().width(), 100);
ASSERT_NE(render_client_->size().height(), 200);
// Issues RPC_RC_ONVIDEONATURALSIZECHANGE RPC message.
EXPECT_CALL(*render_client_, OnVideoNaturalSizeChange(gfx::Size(100, 200)))
.Times(1);
std::unique_ptr<pb::RpcMessage> rpc(new pb::RpcMessage());
rpc->set_handle(5);
rpc->set_proc(pb::RpcMessage::RPC_RC_ONVIDEONATURALSIZECHANGE);
auto* size_message =
rpc->mutable_rendererclient_onvideonatualsizechange_rpc();
size_message->set_width(100);
size_message->set_height(200);
OnReceivedRpc(std::move(rpc));
RunPendingTasks();
ASSERT_EQ(render_client_->size().width(), 100);
ASSERT_EQ(render_client_->size().height(), 200);
}
TEST_F(CourierRendererTest, OnVideoNaturalSizeChangeWithInvalidValue) {
InitializeRenderer();
// Issues RPC_RC_ONVIDEONATURALSIZECHANGE RPC message.
EXPECT_CALL(*render_client_, OnVideoNaturalSizeChange(_)).Times(0);
std::unique_ptr<pb::RpcMessage> rpc(new pb::RpcMessage());
rpc->set_handle(5);
rpc->set_proc(pb::RpcMessage::RPC_RC_ONVIDEONATURALSIZECHANGE);
auto* size_message =
rpc->mutable_rendererclient_onvideonatualsizechange_rpc();
size_message->set_width(-100);
size_message->set_height(0);
OnReceivedRpc(std::move(rpc));
RunPendingTasks();
}
TEST_F(CourierRendererTest, OnVideoOpacityChange) {
InitializeRenderer();
ASSERT_FALSE(render_client_->opaque());
// Issues RPC_RC_ONVIDEOOPACITYCHANGE RPC message.
EXPECT_CALL(*render_client_, OnVideoOpacityChange(true)).Times(1);
std::unique_ptr<pb::RpcMessage> rpc(new pb::RpcMessage());
rpc->set_handle(5);
rpc->set_proc(pb::RpcMessage::RPC_RC_ONVIDEOOPACITYCHANGE);
rpc->set_boolean_value(true);
OnReceivedRpc(std::move(rpc));
RunPendingTasks();
ASSERT_TRUE(render_client_->opaque());
}
TEST_F(CourierRendererTest, OnStatisticsUpdate) {
InitializeRenderer();
EXPECT_NE(DefaultStats(), render_client_->stats());
IssueStatisticsUpdateRpc();
EXPECT_EQ(DefaultStats(), render_client_->stats());
}
TEST_F(CourierRendererTest, OnPacingTooSlowly) {
InitializeRenderer();
controller_->GetRpcBroker()->SetMessageCallbackForTesting(base::BindRepeating(
&CourierRendererTest::OnSendMessageToSink, base::Unretained(this)));
// There should be no error reported with this playback rate.
renderer_->SetPlaybackRate(0.8);
RunPendingTasks();
EXPECT_CALL(*render_client_, OnBufferingStateChange(BUFFERING_HAVE_ENOUGH, _))
.Times(1);
IssuesBufferingStateRpc(BufferingState::BUFFERING_HAVE_ENOUGH);
clock_.Advance(base::TimeDelta::FromSeconds(3));
VerifyAndReportTimeUpdates(0, 15);
ASSERT_FALSE(DidEncounterFatalError());
// Change playback rate. Pacing keeps same as above. Should report error when
// playback was continuously delayed for 10 times.
renderer_->SetPlaybackRate(1);
RunPendingTasks();
clock_.Advance(base::TimeDelta::FromSeconds(3));
VerifyAndReportTimeUpdates(15, 30);
ASSERT_TRUE(DidEncounterFatalError());
}
TEST_F(CourierRendererTest, OnFrameDropRateHigh) {
InitializeRenderer();
for (int i = 0; i < 7; ++i) {
ASSERT_FALSE(DidEncounterFatalError()); // Not enough measurements.
IssueStatisticsUpdateRpc();
clock_.Advance(base::TimeDelta::FromSeconds(1));
RunPendingTasks();
}
ASSERT_TRUE(DidEncounterFatalError());
}
} // namespace remoting
} // namespace media
| 39.78866 | 80 | 0.730859 | [
"vector"
] |
edb8d4feb3a708176c79dd2e0c15d765271297ed | 34,787 | cpp | C++ | ke_mode/winnt/ntke_cpprtl/eh/table_based/eh_engine.cpp | 133a/project_ntke_cpprtl | f2d3fd36a2c44f968f7b10c344abe7e0b7aa2e4c | [
"MIT"
] | 12 | 2016-08-02T19:22:26.000Z | 2022-02-28T21:20:18.000Z | ke_mode/winnt/ntke_cpprtl/eh/table_based/eh_engine.cpp | 133a/project_ntke_cpprtl | f2d3fd36a2c44f968f7b10c344abe7e0b7aa2e4c | [
"MIT"
] | null | null | null | ke_mode/winnt/ntke_cpprtl/eh/table_based/eh_engine.cpp | 133a/project_ntke_cpprtl | f2d3fd36a2c44f968f7b10c344abe7e0b7aa2e4c | [
"MIT"
] | 6 | 2018-04-15T16:51:40.000Z | 2021-04-23T19:32:34.000Z | /////////////////////////////////////////////////////////////////////////////
//// copyright (c) 2012-2017 project_ntke_cpprtl
//// mailto:kt133a@seznam.cz
//// license: the MIT license
/////////////////////////////////////////////////////////////////////////////
#include "eh_config.h"
#include "eh_framework_specific_header.h"
#include "eh_msvc_internal_data.h"
#include "eh_msvc_internal_data_aux.h"
#include "eh_engine.h"
#include "eh_engine_defs.h"
#include "eh_stack_walker.h"
#include "eh_aux.h"
#include "eh_exception_code.h"
#include "eh_invoke_funclet.h"
namespace cpprtl
{
namespace eh
{
namespace eh_engine
{
typedef int ehstate_t;
}
namespace eh_state
{
using eh_engine::ehstate_t;
using eh_engine::frame_ptr_t;
using eh_engine::funcframe_ptr_t;
enum
{
INVALID = -2,
EMPTY = -1,
};
ehstate_t from_ip
(
func_descriptor_iterator const& func_dsc
, ::size_t const& ip
, ::DISPATCHER_CONTEXT const& dc
)
{
ehstate_t state = EMPTY;
rva_t ip_rva = static_cast<rva_t>(ip - dc.ImageBase);
ip2state_iterator ip2state(*func_dsc, dc.ImageBase);
for ( ; ip2state.valid(); ip2state.next() )
{
if (ip_rva < ip2state->ip)
{
break;
}
}
if ( ip2state.prev() )
{
state = ip2state->state;
}
return state;
}
ehstate_t from_dc
(
func_descriptor_iterator const& func_dsc
, ::DISPATCHER_CONTEXT const& dc
)
{
::size_t pc = dc.ControlPc;
#if defined (_M_ARM)
if ( dc.ControlPcIsUnwound )
{
pc -= 2; // rewind the forwarded execution point
}
#elif defined (_M_ARM64)
if ( dc.ControlPcIsUnwound )
{
pc -= 4; // rewind the forwarded execution point
}
#endif
return from_ip(func_dsc, pc, dc);
}
void try_range
(
func_descriptor_iterator const& func_dsc
, ehstate_t const& state
, try_iterator & try_begin
, try_iterator & try_end
, ::DISPATCHER_CONTEXT const& dc
)
{
ehstate_t const cs = from_dc(func_dsc, dc);
msvc_internal_data::eh::try_descriptor const* in_catch = 0;
for ( try_rev_iterator try_dsc(*func_dsc, dc.ImageBase); try_dsc.valid(); try_dsc.next() )
{
if ( cs > try_dsc->high_level && cs <= try_dsc->catch_level )
{
in_catch = *try_dsc;
break;
}
}
try_begin.deface();
try_end.deface();
for ( try_iterator try_dsc(*func_dsc, dc.ImageBase); try_dsc.valid(); try_dsc.next() )
{
if
(
in_catch
&&
( try_dsc->low_level <= in_catch->high_level || try_dsc->high_level > in_catch->catch_level )
)
{
continue;
}
if
(
state >= try_dsc->low_level
&&
state <= try_dsc->high_level
)
{
if ( !try_begin.valid() )
{
try_begin = try_dsc;
}
try_end = try_dsc;
}
}
if ( try_end.valid() )
{
try_end.next();
}
}
funcframe_ptr_t function_frame
(
func_descriptor_iterator const& func_dsc
, frame_ptr_t const& frame
, ::DISPATCHER_CONTEXT const& dc
)
{
ehstate_t state = from_dc(func_dsc, dc);
::size_t func_frame = reinterpret_cast< ::size_t>(frame);
for ( try_rev_iterator try_dsc(*func_dsc, dc.ImageBase); try_dsc.valid(); try_dsc.next() )
{
if
(
state > try_dsc->high_level
&&
state <= try_dsc->catch_level
)
{
image_base_t img_base;
IRQL_CHECK ( <=DISPATCH_LEVEL ) // ::RtlLookupFunctionEntry()
::RUNTIME_FUNCTION const* prf = ::RtlLookupFunctionEntry(dc.ControlPc, &img_base, 0);
catch_iterator catch_block(*try_dsc, dc.ImageBase);
while ( catch_block.valid() && prf->BeginAddress != catch_block->handler_address )
{
catch_block.next();
}
if ( catch_block.valid() )
{
#if defined (_M_AMD64) || defined (_M_X64)
func_frame = *reinterpret_cast< ::size_t*>(func_frame + catch_block->frame_offset);
#elif defined (_M_ARM) || defined (_M_ARM64)
func_frame = *reinterpret_cast< ::size_t*>(func_frame);
#else
# error check $(target.arch)
#endif
break;
}
}
}
return reinterpret_cast<funcframe_ptr_t>(func_frame);
}
namespace aux_
{
struct FRAME_POINTERS
{
int fp1; // contains the current function state
int fp2;
static FRAME_POINTERS* get
(
func_descriptor_iterator const& func_dsc
, funcframe_ptr_t const& func_frame
)
{
return reinterpret_cast<eh_state::aux_::FRAME_POINTERS*>(reinterpret_cast< ::size_t>(func_frame) + func_dsc->frame_ptrs);
}
};
}
ehstate_t saved_state
(
func_descriptor_iterator const& func_dsc
, funcframe_ptr_t const& func_frame
)
{
return static_cast<ehstate_t>(aux_::FRAME_POINTERS::get(func_dsc, func_frame)->fp1);
}
void save_state
(
func_descriptor_iterator const& func_dsc
, funcframe_ptr_t const& func_frame
, ehstate_t const& state
)
{
aux_::FRAME_POINTERS::get(func_dsc, func_frame)->fp1 = state;
}
ehstate_t saved_unwind_try_block
(
func_descriptor_iterator const& func_dsc
, funcframe_ptr_t const& func_frame
)
{
return static_cast<ehstate_t>(aux_::FRAME_POINTERS::get(func_dsc, func_frame)->fp2);
}
void save_unwind_try_block
(
func_descriptor_iterator const& func_dsc
, funcframe_ptr_t const& func_frame
, ehstate_t const& state
)
{
aux_::FRAME_POINTERS::get(func_dsc, func_frame)->fp2 = state;
}
} // namespace eh_state
namespace eh_type
{
using eh_engine::funcframe_ptr_t;
msvc_internal_data::eh::exception_descriptor const* get_exception_descriptor(::EXCEPTION_RECORD const& exc_rec)
{
if ( eh_engine::EXCEPTION_OPCODE_THROW == exc_rec.ExceptionInformation[eh_engine::EXCPTR_OPCODE] )
{
return reinterpret_cast<msvc_internal_data::eh::exception_descriptor*>(exc_rec.ExceptionInformation[eh_engine::EXCPTR_THR_THROWINFO]);
}
return 0;
}
void* get_exception_object(::EXCEPTION_RECORD const& exc_rec)
{
if ( eh_engine::EXCEPTION_OPCODE_THROW == exc_rec.ExceptionInformation[eh_engine::EXCPTR_OPCODE] )
{
return reinterpret_cast<void*>(exc_rec.ExceptionInformation[eh_engine::EXCPTR_THR_THROWOBJECT]);
}
return 0;
}
bool match
(
msvc_internal_data::eh::exception_descriptor const& exc_dsc
, catchable_type_iterator const& catchable_type
, catchable_typeinfo_iterator const& catchable_typeinfo
, catch_typeinfo_iterator const& catch_typeinfo
, unsigned const& catch_attr
)
{
if
(
0 == *catch_typeinfo
||
0 == catch_typeinfo->name
) // (...) check
{
return true;
}
if
(
*catchable_typeinfo != *catch_typeinfo
&&
!aux_::strzcmp(&catchable_typeinfo->name, &catch_typeinfo->name)
) // type_info equality check
{
return false;
}
if
(
( (catchable_type->attributes & msvc_internal_data::eh::EXCEP_REFERENCE) && !(catch_attr & msvc_internal_data::eh::CATCH_REFERENCE) )
||
( (exc_dsc.attributes & msvc_internal_data::eh::EXCEP_CONST) && !(catch_attr & msvc_internal_data::eh::CATCH_CONST) )
||
( (exc_dsc.attributes & msvc_internal_data::eh::EXCEP_VOLATILE) && !(catch_attr & msvc_internal_data::eh::CATCH_VOLATILE) )
)
{
return false;
}
return true;
}
void* pointer_cast
(
void const* const complete_obj
, msvc_internal_data::eh::subtype_cast_info const& cast_info
)
{
::size_t ptr = reinterpret_cast< ::size_t>(complete_obj);
if ( cast_info.vbase_table_offset >= 0 )
{
ptr += cast_info.vbase_table_offset;
ptr += *reinterpret_cast<int*>(*reinterpret_cast< ::size_t*>(ptr) + cast_info.vbase_disp_offset);
}
ptr += cast_info.subtype_offset;
return reinterpret_cast<void*>(ptr);
}
void copy_exception_object
(
void const* const exc_object
, funcframe_ptr_t const& func_frame
, catch_iterator const& catch_block
, catchable_type_iterator const& catchable_type
, ::DISPATCHER_CONTEXT const& dc
)
{
if ( exc_object && catch_block->exc_offset )
{
__try
{
catch_typeinfo_iterator type_dsc(*catch_block, dc.ImageBase);
if ( type_dsc.valid() && type_dsc->name )
{
::size_t dst_addr = reinterpret_cast< ::size_t>(func_frame) + catch_block->exc_offset;
if ( catch_block->attributes & msvc_internal_data::eh::CATCH_REFERENCE )
{
*reinterpret_cast<void**>(dst_addr) = pointer_cast(exc_object, catchable_type->cast_info);
}
else if ( catchable_type->attributes & msvc_internal_data::eh::EXCEP_SIMPLE_TYPE )
{
aux_::memcpy(reinterpret_cast<void*>(dst_addr), exc_object, catchable_type->size);
if ( sizeof(void*) == catchable_type->size )
{
*reinterpret_cast<void**>(dst_addr) = pointer_cast(*reinterpret_cast<void**>(dst_addr), catchable_type->cast_info);
}
}
else // UDT
{
void* casted_exc_object = pointer_cast(exc_object, catchable_type->cast_info);
if ( !catchable_type->cctor )
{
aux_::memcpy(reinterpret_cast<void*>(dst_addr), casted_exc_object, catchable_type->size);
}
else
{
if ( catchable_type->attributes & msvc_internal_data::eh::EXCEP_VIRTUAL_BASE )
{
(*cctorvb_iterator(*catchable_type, dc.ImageBase))(reinterpret_cast<void*>(dst_addr), casted_exc_object, 1);
}
else
{
(*cctor_iterator(*catchable_type, dc.ImageBase))(reinterpret_cast<void*>(dst_addr), casted_exc_object);
}
}
}
}
}
__except ( eh::aux_::invalid_exception(GetExceptionCode(), eh::EXCEPTION_SUBCODE_CCTOR_THROW) , EXCEPTION_CONTINUE_SEARCH )
{
}
}
}
void destroy_exception_object(::EXCEPTION_RECORD const& exc_rec)
{
if
(
eh::EXCEPTION_CODE_CPP == exc_rec.ExceptionCode
&&
eh_engine::EXCEPTION_OPCODE_THROW == exc_rec.ExceptionInformation[eh_engine::EXCPTR_OPCODE]
)
{
msvc_internal_data::eh::exception_descriptor const* const exc_dsc = eh_type::get_exception_descriptor(exc_rec);
void* const exc_object = eh_type::get_exception_object(exc_rec);
if ( exc_object && exc_dsc )
{
dtor_iterator dtor(exc_dsc, exc_rec.ExceptionInformation[eh_engine::EXCPTR_THR_IMAGEBASE]);
if ( dtor.valid() )
{
__try
{
(*dtor)(exc_object);
}
__except ( eh::aux_::invalid_exception(GetExceptionCode(), eh::EXCEPTION_SUBCODE_DTOR_THROW) , EXCEPTION_CONTINUE_SEARCH )
{
}
}
}
}
}
} // namespace eh_type
namespace eh_engine
{
void unwind_frame
(
func_descriptor_iterator const& func_dsc
, funcframe_ptr_t const& func_frame
, ehstate_t const& target_state
, ::DISPATCHER_CONTEXT const& dc
)
{
ehstate_t current_state = eh_state::saved_state(func_dsc, func_frame);
if ( eh_state::INVALID == current_state )
{
current_state = eh_state::from_dc(func_dsc, dc);
}
unwind_iterator unwind_entry(*func_dsc, dc.ImageBase);
while
(
current_state > eh_state::EMPTY
&&
current_state != target_state
&&
unwind_entry[current_state].valid()
)
{
current_state = unwind_entry->prev_state;
unwind_action_iterator unwind_action(*unwind_entry, dc.ImageBase);
if ( unwind_action.valid() )
{
eh_state::save_state(func_dsc, func_frame, current_state);
__try
{
#if defined (_M_X64) || defined (_M_AMD64)
_CPPRTL_invoke_funclet(*unwind_action, func_frame);
#elif defined (_M_ARM) || defined (_M_ARM64)
_CPPRTL_invoke_funclet(*unwind_action, func_frame, dc.NonVolatileRegisters);
#else
# error check $(target.arch)
#endif
}
__except ( eh::aux_::invalid_exception(GetExceptionCode(), eh::EXCEPTION_SUBCODE_UNWIND_THROW) , EXCEPTION_CONTINUE_SEARCH )
{
}
}
}
eh_state::save_state(func_dsc, func_frame, current_state);
}
namespace aux_
{
int call_catch_block_rethrow_seh_filter
(
::EXCEPTION_POINTERS * xp
, ::EXCEPTION_RECORD * const cur_exc
)
{
if ( eh::EXCEPTION_CODE_CPP == xp->ExceptionRecord->ExceptionCode )
{
::EXCEPTION_RECORD* new_exc = xp->ExceptionRecord;
if ( new_exc )
{
if ( EXCEPTION_OPCODE_THROW == new_exc->ExceptionInformation[EXCPTR_OPCODE] )
{
if ( 0 == new_exc->ExceptionInformation[EXCPTR_THR_THROWOBJECT] )
{
new_exc->ExceptionInformation[EXCPTR_THR_THROWOBJECT] = cur_exc->ExceptionInformation[EXCPTR_THR_THROWOBJECT];
new_exc->ExceptionInformation[EXCPTR_THR_THROWINFO] = cur_exc->ExceptionInformation[EXCPTR_THR_THROWINFO];
new_exc->ExceptionInformation[EXCPTR_THR_IMAGEBASE] = cur_exc->ExceptionInformation[EXCPTR_THR_IMAGEBASE];
new_exc->ExceptionInformation[EXCPTR_THR_PREV_EXCEPTION] = reinterpret_cast< ::ULONG_PTR>(cur_exc);
// our exception object is propagated to the outer scope so we are no longer responsible for its' destruction.
cur_exc->ExceptionInformation[EXCPTR_FLAGS] |= EXCEPTION_FLAG_OBJECT_RETHROWED;
// delegate the exception object's destruction to the outer scope's catch-block caller finally handler
new_exc->ExceptionInformation[EXCPTR_FLAGS] &= ~EXCEPTION_FLAG_OBJECT_RETHROWED;
}
else if (cur_exc->ExceptionInformation[EXCPTR_THR_THROWOBJECT] == new_exc->ExceptionInformation[EXCPTR_THR_THROWOBJECT])
{
new_exc->ExceptionInformation[EXCPTR_THR_PREV_EXCEPTION] = reinterpret_cast< ::ULONG_PTR>(cur_exc);
new_exc->ExceptionInformation[EXCPTR_THR_IMAGEBASE] = cur_exc->ExceptionInformation[EXCPTR_THR_IMAGEBASE];
// our exception object is propagated to the outer scope so we are no longer responsible for its' destruction.
cur_exc->ExceptionInformation[EXCPTR_FLAGS] |= EXCEPTION_FLAG_OBJECT_RETHROWED;
// delegate the exception object's destruction to the outer scope's catch-block caller finally handler
new_exc->ExceptionInformation[EXCPTR_FLAGS] &= ~EXCEPTION_FLAG_OBJECT_RETHROWED;
}
return EXCEPTION_CONTINUE_SEARCH;
}
if ( EXCEPTION_OPCODE_NO_EXC_OBJ == new_exc->ExceptionInformation[EXCPTR_OPCODE] )
{
::EXCEPTION_RECORD* const rec_patch = reinterpret_cast< ::EXCEPTION_RECORD*>(new_exc->ExceptionInformation[EXCPTR_NOOBJ_EXCREC_PTR]);
if ( rec_patch && EXCEPTION_OPCODE_THROW == rec_patch->ExceptionInformation[EXCPTR_OPCODE] )
{
rec_patch->ExceptionInformation[EXCPTR_THR_THROWOBJECT] = cur_exc->ExceptionInformation[EXCPTR_THR_THROWOBJECT];
rec_patch->ExceptionInformation[EXCPTR_THR_THROWINFO] = cur_exc->ExceptionInformation[EXCPTR_THR_THROWINFO];
rec_patch->ExceptionInformation[EXCPTR_THR_IMAGEBASE] = cur_exc->ExceptionInformation[EXCPTR_THR_IMAGEBASE];
rec_patch->ExceptionInformation[EXCPTR_THR_PREV_EXCEPTION] = reinterpret_cast< ::ULONG_PTR>(cur_exc);
// put the flag that our scope (and may be outer ones) is responsible of the exception object's lifetime
rec_patch->ExceptionInformation[EXCPTR_FLAGS] |= EXCEPTION_FLAG_OBJECT_RETHROWED;
}
return EXCEPTION_CONTINUE_EXECUTION;
}
}
}
return EXCEPTION_CONTINUE_SEARCH;
}
} // namespace aux_
void* call_catch_block(::EXCEPTION_RECORD const& unwind_exc_rec)
{
::EXCEPTION_RECORD& cur_exc = *reinterpret_cast< ::EXCEPTION_RECORD*>(unwind_exc_rec.ExceptionInformation[EXCPTR_UNW_CURRENT_EXCEPTION]);
void* ret_addr = 0;
__try
{
__try
{
ret_addr =
#if defined (_M_X64) || defined (_M_AMD64)
_CPPRTL_invoke_funclet
(
reinterpret_cast<msvc_internal_data::eh::catch_handler_ft> (unwind_exc_rec.ExceptionInformation[EXCPTR_UNW_HANDLER_ADDR])
, reinterpret_cast<void*> (unwind_exc_rec.ExceptionInformation[EXCPTR_UNW_FUNCTION_FRAME])
);
#elif defined (_M_ARM) || defined (_M_ARM64)
_CPPRTL_invoke_funclet
(
reinterpret_cast<msvc_internal_data::eh::catch_handler_ft> (unwind_exc_rec.ExceptionInformation[EXCPTR_UNW_HANDLER_ADDR])
, reinterpret_cast<void*> (unwind_exc_rec.ExceptionInformation[EXCPTR_UNW_FUNCTION_FRAME])
, reinterpret_cast<void*> (unwind_exc_rec.ExceptionInformation[EXCPTR_UNW_ARM_NV_CONTEXT])
);
#else
# error check $(target.arch)
#endif
}
__except ( aux_::call_catch_block_rethrow_seh_filter(GetExceptionInformation(), &cur_exc) )
{
}
}
__finally
{
if ( !(cur_exc.ExceptionInformation[EXCPTR_FLAGS] & EXCEPTION_FLAG_OBJECT_RETHROWED) )
{
eh_type::destroy_exception_object(cur_exc);
}
}
eh_state::save_unwind_try_block
(
func_descriptor_iterator(reinterpret_cast<msvc_internal_data::eh::func_descriptor*>(unwind_exc_rec.ExceptionInformation[EXCPTR_UNW_FUNC_DESCRIPTOR]))
, reinterpret_cast<funcframe_ptr_t>(unwind_exc_rec.ExceptionInformation[EXCPTR_UNW_FUNCTION_FRAME])
, eh_state::INVALID
);
return ret_addr;
}
namespace aux_
{
void init_unwind_exception_record
(
::EXCEPTION_RECORD & unwind_exc_rec
, ::EXCEPTION_RECORD const& exc_rec
, func_descriptor_iterator const& func_dsc
, funcframe_ptr_t const& func_frame
, frame_ptr_t const& target_frame
, ehstate_t const& target_state
, catch_handler_iterator const& handler
)
{
unwind_exc_rec.ExceptionCode = STATUS_UNWIND_CONSOLIDATE;
unwind_exc_rec.ExceptionFlags |= EXCEPTION_NONCONTINUABLE;
unwind_exc_rec.ExceptionRecord = 0;
unwind_exc_rec.ExceptionAddress = 0;
unwind_exc_rec.ExceptionInformation[EXCPTR_OPCODE] = EXCEPTION_OPCODE_STACK_CONSOLIDATE; // operation sub-code
unwind_exc_rec.ExceptionInformation[EXCPTR_UNW_CALLBACK_ADDR] = reinterpret_cast< ::ULONG_PTR>(&call_catch_block); // Address of callback function
unwind_exc_rec.ExceptionInformation[EXCPTR_UNW_FUNCTION_FRAME] = reinterpret_cast< ::ULONG_PTR>(func_frame); // Used by callback funciton
unwind_exc_rec.ExceptionInformation[EXCPTR_UNW_HANDLER_ADDR] = reinterpret_cast< ::ULONG_PTR>(*handler); // Used by callback function to call catch block
unwind_exc_rec.ExceptionInformation[EXCPTR_UNW_TARGET_STATE] = target_state; // Used by CxxFrameHandler to unwind to target_state
unwind_exc_rec.ExceptionInformation[EXCPTR_UNW_TARGET_FRAME] = reinterpret_cast< ::ULONG_PTR>(target_frame); // used by CFG_EH_STACK_WALKER
unwind_exc_rec.ExceptionInformation[EXCPTR_UNW_FUNC_DESCRIPTOR] = reinterpret_cast< ::ULONG_PTR>(*func_dsc); // Used in callback function to set state on stack to -2
unwind_exc_rec.ExceptionInformation[EXCPTR_UNW_CURRENT_EXCEPTION] = reinterpret_cast< ::ULONG_PTR>(&exc_rec); // Used for passing current Exception
unwind_exc_rec.ExceptionInformation[EXCPTR_UNW_ARM_NV_CONTEXT] = -1; // _M_ARM specific
unwind_exc_rec.NumberParameters = ARRAYSIZE_EXCPTR_UNW;
}
void unwind_stack_helper
(
::EXCEPTION_RECORD const& exc_rec
, func_descriptor_iterator const& func_dsc
, funcframe_ptr_t const& func_frame
, frame_ptr_t const& target_frame
, ehstate_t const& target_state
, catch_handler_iterator const& handler
, ::DISPATCHER_CONTEXT const& dc
)
{
::EXCEPTION_RECORD unwind_exc_rec = { 0 };
init_unwind_exception_record
(
unwind_exc_rec
, exc_rec
, func_dsc
, func_frame
, target_frame
, target_state
, handler
);
::RtlUnwindEx(target_frame, reinterpret_cast<void*>(dc.ControlPc), &unwind_exc_rec, 0, dc.ContextRecord, dc.HistoryTable);
}
} // namespace aux_
void unwind_stack
(
::EXCEPTION_RECORD const& exc_rec
, func_descriptor_iterator const& func_dsc
, funcframe_ptr_t const& func_frame
, frame_ptr_t const& target_frame
, ehstate_t const& target_state
, catch_handler_iterator const& handler
, ::DISPATCHER_CONTEXT const& dc
)
{
if
(
eh::EXCEPTION_CODE_CPP == exc_rec.ExceptionCode
&&
EXCEPTION_OPCODE_THROW == exc_rec.ExceptionInformation[EXCPTR_OPCODE]
)
{
if ( exc_rec.ExceptionInformation[EXCPTR_FLAGS] & EXCEPTION_FLAG_STACKWALKER_UNWIND )
{
::EXCEPTION_RECORD& unwind_exc_rec = *reinterpret_cast< ::EXCEPTION_RECORD*>(exc_rec.ExceptionInformation[EXCPTR_THR_UNWIND_EXCREC]);
aux_::init_unwind_exception_record
(
unwind_exc_rec
, exc_rec
, func_dsc
, func_frame
, target_frame
, target_state
, handler
);
return; // back into the stack walker
}
}
aux_::unwind_stack_helper
(
exc_rec
, func_dsc
, func_frame
, target_frame
, target_state
, handler
, dc
);
}
void throw_exception_no_exception_object(::EXCEPTION_RECORD const* const rec)
{
::EXCEPTION_RECORD exc_rec = { 0 };
exc_rec.ExceptionCode = eh::EXCEPTION_CODE_CPP;
exc_rec.ExceptionFlags = 0; // this is a continuable exception - if catchblock-handler would fill the necessary ptrs it will return ExceptionContinueExecution
exc_rec.ExceptionRecord = 0;
exc_rec.ExceptionAddress = 0;
exc_rec.ExceptionInformation[EXCPTR_OPCODE] = EXCEPTION_OPCODE_NO_EXC_OBJ;
exc_rec.ExceptionInformation[EXCPTR_NOOBJ_EXCREC_PTR] = reinterpret_cast< ::ULONG_PTR>(rec);
exc_rec.NumberParameters = ARRAYSIZE_EXCPTR_NOOBJ;
#ifdef CFG_EH_STACK_WALKER
eh::eh_engine::stack_walk(exc_rec);
#else
eh::aux_::raise_exception(exc_rec);
#endif
}
void throw_exception
(
void const* const exc_object
, msvc_internal_data::eh::exception_descriptor const* const exc_descr
)
{
::EXCEPTION_RECORD exc_rec = { 0 };
exc_rec.ExceptionCode = eh::EXCEPTION_CODE_CPP;
exc_rec.ExceptionFlags |= EXCEPTION_NONCONTINUABLE;
exc_rec.ExceptionRecord = 0;
exc_rec.ExceptionAddress = 0;
exc_rec.ExceptionInformation[EXCPTR_OPCODE] = EXCEPTION_OPCODE_THROW;
exc_rec.ExceptionInformation[EXCPTR_THR_THROWOBJECT] = reinterpret_cast< ::ULONG_PTR>(exc_object);
exc_rec.ExceptionInformation[EXCPTR_THR_THROWINFO] = reinterpret_cast< ::ULONG_PTR>(exc_descr);
if ( exc_descr )
{
IRQL_CHECK ( <=DISPATCH_LEVEL ) // RtlPcToFileHeader()
exc_rec.ExceptionInformation[EXCPTR_THR_IMAGEBASE] =
reinterpret_cast< ::ULONG_PTR>
(
::RtlPcToFileHeader
(
reinterpret_cast<void*> (const_cast<msvc_internal_data::eh::exception_descriptor*>(exc_descr))
, reinterpret_cast<void**> (&exc_rec.ExceptionInformation[EXCPTR_THR_IMAGEBASE])
)
);
}
exc_rec.NumberParameters = ARRAYSIZE_EXCPTR_THROW;
if ( !exc_object || !exc_descr )
{
// if we are here the 'throw;' statement has occured and we are to try getting the exception info from the previous scope's rethrow-seh-filter by continuable seh-exception
throw_exception_no_exception_object(&exc_rec);
}
#ifdef CFG_EH_STACK_WALKER
eh::eh_engine::stack_walk(exc_rec);
#else
eh::aux_::raise_exception(exc_rec);
#endif
}
void find_matching_catch_block
(
::EXCEPTION_RECORD const& exc_rec
, func_descriptor_iterator const& func_dsc
, frame_ptr_t const& frame
, ::DISPATCHER_CONTEXT const& dc
)
{
funcframe_ptr_t const func_frame = eh_state::function_frame(func_dsc, frame, dc);
ehstate_t state = eh_state::from_dc(func_dsc, dc);
if ( state > eh_state::saved_unwind_try_block(func_dsc, func_frame) )
{
eh_state::save_state(func_dsc, func_frame, state);
eh_state::save_unwind_try_block(func_dsc, func_frame, state);
}
else
{
state = eh_state::saved_unwind_try_block(func_dsc, func_frame);
}
try_iterator try_cur(*func_dsc, dc.ImageBase);
try_iterator try_end(*func_dsc, dc.ImageBase);
eh_state::try_range(func_dsc, state, try_cur, try_end, dc);
if ( eh::EXCEPTION_CODE_CPP == exc_rec.ExceptionCode ) // ...for cpp-exception
{
if ( EXCEPTION_OPCODE_THROW == exc_rec.ExceptionInformation[EXCPTR_OPCODE] )
{
msvc_internal_data::eh::exception_descriptor const* const exc_dsc = eh_type::get_exception_descriptor(exc_rec);
void const* const exc_object = eh_type::get_exception_object(exc_rec);
if ( exc_object && exc_dsc )
{
for ( ; try_cur != try_end; try_cur.next() )
{
if ( try_cur->low_level <= state && state <= try_cur->high_level )
{
for ( catch_iterator catch_block(*try_cur, dc.ImageBase); catch_block.valid(); catch_block.next() )
{
for ( catchable_type_iterator catchable_type(*catchable_table_iterator(exc_dsc, dc.ImageBase), dc.ImageBase); catchable_type.valid(); catchable_type.next() )
{
if
(
eh_type::match
(
*exc_dsc
, catchable_type
, catchable_typeinfo_iterator(*catchable_type, dc.ImageBase)
, catch_typeinfo_iterator(*catch_block, dc.ImageBase)
, catch_block->attributes
)
)
{
eh_type::copy_exception_object
(
exc_object
, func_frame
, catch_block
, catchable_type
, dc
);
unwind_stack
(
exc_rec
, func_dsc
, func_frame
, frame
, try_cur->low_level
, catch_handler_iterator(*catch_block, dc.ImageBase)
, dc
);
#if defined ( CFG_EH_STACK_WALKER )
if ( exc_rec.ExceptionInformation[EXCPTR_FLAGS] & EXCEPTION_FLAG_STACKWALKER_UNWIND )
{
return; // delegate the unwind duties back to the stack_walker
}
#endif
goto next_try_block; // don't come here if unwound properly
}
}
}
}
next_try_block : ;
}
}
}
}
else // ...for remaining SEH-exceptions
{
if ( STATUS_BREAKPOINT != exc_rec.ExceptionCode ) //// wouldn't touch this code
{
//// TODO SEH translator
#if !( defined (NT_KERNEL_MODE) && defined (_M_ARM) )
// WinRT (at least 6.2.9200) ke-mode RtlUnwindEx()-->RtlRestoreContext() doesn't support stack consolidation mode, so let's skip
// the SEH catching by (...) facility
for ( ; try_cur != try_end; try_cur.next() )
{
if ( try_cur->low_level <= state && state <= try_cur->high_level )
{
catch_rev_iterator catch_block(*try_cur, dc.ImageBase);
if
(
catch_block.valid()
&&
!catch_typeinfo_iterator(*catch_block, dc.ImageBase).valid()
) // check the last catch in the corresponding try is the '(...)'
{
unwind_stack
(
exc_rec
, func_dsc
, func_frame
, frame
, try_cur->low_level
, catch_handler_iterator(*catch_block, dc.ImageBase)
, dc
);
#if defined ( CFG_EH_STACK_WALKER )
return; // could anyone achieve here ? hardly... but hell knows... let's just delegate the decision back to the stack_walker
#endif
}
}
}
#endif
}
}
}
namespace aux_
{
msvc_internal_data::eh::func_descriptor const* const get_function_descriptor(::DISPATCHER_CONTEXT const& dc)
{
return reinterpret_cast<msvc_internal_data::eh::func_descriptor const*>(dc.ImageBase + *reinterpret_cast<rva_t*>(dc.HandlerData));
}
}
::EXCEPTION_DISPOSITION frame_handler3
(
::EXCEPTION_RECORD const& exc_rec
, frame_ptr_t const& frame
, ::CONTEXT const& context
, ::DISPATCHER_CONTEXT const& dc
)
{
// the function this handler is invoked on behalf of
func_descriptor_iterator const func_dsc(aux_::get_function_descriptor(dc));
//// check if this frame handler is responsible for the incoming EXCEPTION_RECORD
if ( eh::EXCEPTION_CODE_CPP == exc_rec.ExceptionCode ) // cpp-exception
{
if
(
ARRAYSIZE_EXCPTR_NOOBJ <= exc_rec.NumberParameters
&&
EXCEPTION_OPCODE_NO_EXC_OBJ == exc_rec.ExceptionInformation[EXCPTR_OPCODE]
)
{
// no duties for this frame handler, the catch block handler is responsible for an exception object searching
return ::ExceptionContinueSearch;
}
}
else if ( STATUS_UNWIND_CONSOLIDATE != exc_rec.ExceptionCode ) // filter out other no cpp-exceptions
{
if
(
func_dsc->magic_number >= msvc_internal_data::eh::EH_VC8
&&
(func_dsc->flags & msvc_internal_data::eh::FLAG_EHs)
)
{
// compiled with -EHs option - nothing to do with foreign structured exception codes (besides EXCEPTION_CODE_CPP)
return ::ExceptionContinueSearch;
}
}
//// proceed the unwind and return
if ( exc_rec.ExceptionFlags & EXCEPTION_UNWIND )
{
if ( func_dsc->unwind_array_size )
{
if
(
(exc_rec.ExceptionFlags & EXCEPTION_TARGET_UNWIND)
&&
STATUS_UNWIND_CONSOLIDATE == exc_rec.ExceptionCode
)
{
// unwinding the target frame
if
(
ARRAYSIZE_EXCPTR_UNW == exc_rec.NumberParameters
&&
EXCEPTION_OPCODE_STACK_CONSOLIDATE == exc_rec.ExceptionInformation[EXCPTR_OPCODE]
)
{
unwind_frame
(
func_dsc
, reinterpret_cast<funcframe_ptr_t const> (exc_rec.ExceptionInformation[EXCPTR_UNW_FUNCTION_FRAME])
, static_cast<ehstate_t> (exc_rec.ExceptionInformation[EXCPTR_UNW_TARGET_STATE])
, dc
);
}
}
else
{
// unwinding the nested frames
funcframe_ptr_t func_frame = eh_state::function_frame(func_dsc, frame, dc);
ehstate_t target_state = -1;
ehstate_t const state = eh_state::from_dc(func_dsc, dc);
for ( try_rev_iterator try_block(*func_dsc, dc.ImageBase); try_block.valid(); try_block.next() )
{
if ( state > try_block->high_level && state <= try_block->catch_level )
{
target_state = try_block->high_level;
break;
}
}
unwind_frame(func_dsc, func_frame, target_state, dc);
}
}
return ::ExceptionContinueSearch;
}
//// else find and invoke the handler
find_matching_catch_block
(
exc_rec
, func_dsc
, frame
, dc
);
// does not return if matching catch-block has been found (if the standard NT exception dispatcher is used)
// or returns and delegates the unwinding duties to a custom dispatching routine
return ::ExceptionContinueSearch;
}
} // namespace eh_engine
} // namespace eh
} // namespace cpprtl
| 33.905458 | 190 | 0.593469 | [
"object"
] |
edb9463c408a339fae7962d87198865e08ecad0b | 23,146 | cpp | C++ | src/nio/Channel.cpp | krzydyn/jacpp | ab9b5bfcca1774198c05d9187e5891de1fdf4759 | [
"Apache-2.0"
] | 5 | 2019-01-01T14:55:58.000Z | 2021-01-31T14:55:59.000Z | src/nio/Channel.cpp | krzydyn/jacpp | ab9b5bfcca1774198c05d9187e5891de1fdf4759 | [
"Apache-2.0"
] | null | null | null | src/nio/Channel.cpp | krzydyn/jacpp | ab9b5bfcca1774198c05d9187e5891de1fdf4759 | [
"Apache-2.0"
] | null | null | null | #include <nio/channels/Channel.hpp>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
namespace nio {
namespace channels {
class IOStatus {
#undef EOF
public:
static const int EOF = -1; // End of file
static const int UNAVAILABLE = -2; // Nothing available (non-blocking)
static const int INTERRUPTED = -3; // System call interrupted
static const int UNSUPPORTED = -4; // Operation not supported
static const int THROWN = -5; // Exception thrown in JNI code
static const int UNSUPPORTED_CASE = -6; // This case not supported
};
#undef SHUT_RD
#undef SHUT_WR
#undef SHUT_RDWR
//http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/sun/nio/ch/Net.java
class Net {
public:
static const int SHUT_RD = 0;
static const int SHUT_WR = 1;
static const int SHUT_RDWR = 2;
static const InetSocketAddress& getRevealedLocalAddress(const InetSocketAddress& addr);
static InetSocketAddress checkAddress(const SocketAddress& sa);
static int connect(int fd, const InetAddress& remote, int remotePort);
static int connect(const ProtocolFamily& family, int fd, const InetAddress& remote, int remotePort);
static void bind(const ProtocolFamily& family, int fd, const InetAddress& local, int localPort);
static void shutdown(int fdVal, int how);
};
const InetSocketAddress& Net::getRevealedLocalAddress(const InetSocketAddress& addr) { return addr; }
int Net::connect(int fd, const InetAddress& remote, int remotePort) {
return -1;
}
int Net::connect(const ProtocolFamily& family, int fd, const InetAddress& remote, int remotePort) {
if (family == StandardProtocolFamily::INET) return 1;
return -1;
}
void Net::bind(const ProtocolFamily& family, int fd, const InetAddress& local, int localPort) {
struct sockaddr_in addr_bind;
/*
socklen_t slen = sizeof(addr_bind);
if (getsockname(fd, (struct sockaddr*)&addr_bind, &slen) != -1) {
throw io::IOException(String("getsockname: socket already bound to an address"));
}
LOGD("fd not bound, err = %s", strerror(errno));
*/
memset(&addr_bind, 0, sizeof(addr_bind));
addr_bind.sin_family = AF_INET;//(short)family;
addr_bind.sin_port = htons((short)localPort);
//Array<byte> addr = local.getAddress();
//memcpy(&addr_bind.sin_addr.s_addr, &addr[0], addr.length);
addr_bind.sin_addr.s_addr = htonl(INADDR_ANY);
if (::bind(fd, (struct sockaddr*)&addr_bind, sizeof(addr_bind)) == -1) {
if (errno == EINVAL) io::IOException(String("bind: socket already bound to an address"));
throw io::IOException(String("bind: ")+strerror(errno)+" on :"+String::valueOf(localPort));
}
LOGD("fd=%d: bound to port %s:%d", fd, local.toString().cstr(), localPort);
}
void Net::shutdown(int fdVal, int how) {
::shutdown(fdVal, how);
}
InetSocketAddress Net::checkAddress(const SocketAddress& sa) {
if (sa == null) throw NullPointerException();
if (!(instanceof<InetSocketAddress>(&sa))) {
throw UnsupportedAddressTypeException(sa.getClass().getName());
}
InetSocketAddress& isa = (InetSocketAddress&)sa;
if (isa.isUnresolved()) throw UnresolvedAddressException(isa.getHostName());
//const InetAddress& addr = isa.getAddress();
return (InetSocketAddress&)sa;
}
Shared<SelectorProvider> SelectorProvider::mProvider = null;
class SelectorImpl : extends AbstractSelector {
private:
int lockAndDoSelect(long timeout) {
synchronized (*this) {
if (!isOpen()) throw ClosedSelectorException();
return doSelect(timeout);
}
return -1;
}
protected:
SelectorImpl(Shared<SelectorProvider> sp) : AbstractSelector(sp) {
}
virtual int doSelect(long timeout) = 0;
public:
virtual int selectNow() {
return lockAndDoSelect(0);
}
void implCloseSelector() {
wakeup();
synchronized (*this) {
}
}
int select(long timeout) {
if (timeout < 0) throw IllegalArgumentException("Negative timeout");
return lockAndDoSelect((timeout == 0) ? -1 : timeout);
}
int select() {
return select(0);
}
Selector& wakeup() = 0;
};
class AbstractPollSelectorImpl : extends SelectorImpl {
protected:
int totalChannels;
int channelOffset;
AbstractPollSelectorImpl(Shared<SelectorProvider> sp, int channels, int offset) : SelectorImpl(sp),
totalChannels(channels), channelOffset(offset) {
}
virtual int doSelect(long timeout) = 0;
int updateSelectedKeys() {
return 0;
}
public:
Selector& wakeup() {
return *this;
}
};
// http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/sun/nio/ch/PollSelectorImpl.java
class PollSelectorImpl : extends AbstractPollSelectorImpl {
private:
protected:
int doSelect(long timeout) {
int numKeysUpdated = updateSelectedKeys();
return numKeysUpdated;
}
public:
PollSelectorImpl(Shared<SelectorProvider> p) : AbstractPollSelectorImpl(p, 1, 1) {
}
};
class DatagramChannelImpl : extends DatagramChannel {
private:
static const int ST_UNINITIALIZED = -1;
static const int ST_UNCONNECTED = 0;
static const int ST_CONNECTED = 1;
static const int ST_KILLED = 2;
int fdVal = -1;
const ProtocolFamily& family;
long readerThread = 0;
long writerThread = 0;
Object readLock;
Object writeLock;
Object stateLock;
int state = ST_UNINITIALIZED;
InetSocketAddress mLocalAddress;
InetSocketAddress mRemoteAddress;
boolean reuseAddressEmulated;
boolean isReuseAddress;
int poll(int events, long timeout) {
return 0;
}
void ensureOpen() const {
if (!isOpen()) throw ClosedChannelException();
}
void ensureOpenAndUnconnected() const {
synchronized (stateLock) {
if (!isOpen()) throw ClosedChannelException();
if (state != ST_UNCONNECTED) throw IllegalStateException("Connect already invoked");
}
}
void kill() { }
int read(int fd, ByteBuffer& dst) {
int pos = dst.position();
int lim = dst.limit();
int rem = (pos <= lim ? lim - pos : 0);
if (rem == 0) return 0;
int flags = 0; //MSG_NOSIGNAL; // MSG_DONTWAIT | MSG_DONTROUTE
int n = (int)::recv(fd, &dst.array()[pos], rem, flags);
if (n == -1) LOGD("recv(fd=%d) error=%d (%s)", fd, errno, strerror(errno));
else {
dst.position(pos + n);
}
return n;
}
// only for connected descriptor, but Datagram is not connected
/*
int write(int fd, ByteBuffer& src) {
int pos = src.position();
int lim = src.limit();
int rem = (pos <= lim ? lim - pos : 0);
LOGD("writing %d bytes into fd=%d", rem, fd);
if (rem == 0) return 0;
int flags = MSG_NOSIGNAL; // MSG_DONTWAIT | MSG_DONTROUTE
int n = (int)::send(fd, &src.array()[pos], rem, flags);
if (n == -1) {
LOGD("writing to fd=%d error=%d (%s)", fd, errno, strerror(errno));
}
else {
LOGD("wrote %d bytes to fd=%d", n, fd);
src.position(pos + n);
}
return n;
}
*/
int receive(int fd, ByteBuffer& dst, InetSocketAddress& sender) {
int pos = dst.position();
int lim = dst.limit();
int rem = (pos <= lim ? lim - pos : 0);
if (rem == 0) return 0;
struct sockaddr_in addr_remote;
socklen_t slen = sizeof(addr_remote);
int flags = 0; //MSG_NOSIGNAL; // | MSG_DONTWAIT;// | MSG_DONTROUTE
int n = (int)::recvfrom(fd, &dst.array()[pos], rem, flags, (struct sockaddr *)&addr_remote, &slen);
if (n == -1) LOGD("recvfrom(fd=%d) error=%d (%s)", fd, errno, strerror(errno));
else {
dst.position(pos + n);
int port = ntohs(addr_remote.sin_port);
sender = InetSocketAddress(makeShared<Inet4Address>(), port);
}
return n;
}
int send(int fd, ByteBuffer& src, InetSocketAddress& target) {
int pos = src.position();
int lim = src.limit();
int rem = (pos <= lim ? lim - pos : 0);
if (rem == 0) return 0;
struct sockaddr_in addr_remote;
memset(&addr_remote, 0, sizeof(addr_remote));
addr_remote.sin_family = (char)family;
addr_remote.sin_port = htons((short)target.getPort());
Array<byte> addr = target.getAddress().getAddress();
memcpy(&addr_remote.sin_addr.s_addr, &addr[0], addr.length);
int flags = 0; //MSG_NOSIGNAL; // MSG_DONTWAIT | MSG_DONTROUTE
int n = (int)::sendto(fd, &src.array()[pos], rem, flags, (struct sockaddr *)&addr_remote, sizeof(addr_remote));
if (n == -1) LOGD("sendto(fd=%d) error=%d (%s)", fd, errno, strerror(errno));
else src.position(pos + n);
return n;
}
//void drop(MembershipKeyImpl& key) { }
InetSocketAddress last_sender;
protected:
void implCloseSelectableChannel() {}
void implConfigureBlocking(boolean block) {}
public:
DatagramChannelImpl(Shared<SelectorProvider> p, const ProtocolFamily& family = StandardProtocolFamily::INET) :
DatagramChannel(p), family(family) {
fdVal = ::socket(family, SOCK_DGRAM, 0);
if (fdVal == -1) throw io::IOException(String("Create datagram: ")+strerror(errno));
LOGD("Datagram socket created, fd=%d", fdVal);
state = ST_UNCONNECTED;
}
~DatagramChannelImpl() {
if (fdVal != -1) {
LOGD("%s: socket closing, fd=%d", __FUNCTION__, fdVal);
::close(fdVal);
fdVal = -1;
}
else {
LOGD("%s: socket never opened", __FUNCTION__);
}
}
int getFDVal() { return fdVal; }
DatagramSocket& socket() {
return (DatagramSocket&)null_obj;
}
const SocketAddress& getLocalAddress() const {
synchronized (stateLock) {
if (!isOpen()) throw ClosedChannelException();
return Net::getRevealedLocalAddress(mLocalAddress);
}
return (SocketAddress&)null_obj;
}
const SocketAddress& getRemoteAddress() const {
synchronized (stateLock) {
if (!isOpen()) throw ClosedChannelException();
return mRemoteAddress;
}
return (SocketAddress&)null_obj;
}
DatagramChannel& setOption(const SocketOption& name, Object *value) {
//if (name == null) throw NullPointerException();
synchronized (stateLock) {
ensureOpen();
}
return *this;
}
Object* getOption(const SocketOption& name) const {
//if (name == null) throw NullPointerException();
synchronized (stateLock) {
ensureOpen();
}
return null;
}
const SocketAddress& receive(ByteBuffer& dst) {
if (dst.isReadOnly()) throw IllegalArgumentException("Read-only buffer");
synchronized (readLock) {
ensureOpen();
if (!isOpen()) return (const SocketAddress&)null_obj;
//if (localAddress() == null) bind(null); //bind to random address
int n = 0;
Finalize(readerThread = 0;end((n > 0) || (n == IOStatus::UNAVAILABLE)););
begin();
n = receive(fdVal, dst, last_sender);
if (n == -1) return (const SocketAddress&)null_obj;
}
return last_sender;
}
int send(ByteBuffer& src, const SocketAddress& target) {
synchronized (writeLock) {
ensureOpen();
InetSocketAddress isa = Net::checkAddress(target);
synchronized (stateLock) {
if (!isConnected()) {
if (target == null) throw NullPointerException();
}
else {
if (!target.equals(mRemoteAddress)) {
throw IllegalArgumentException("Connected address not equal to target address");
}
return write(src);
}
}
int n = 0;
Finalize(writerThread = 0;end((n > 0) || (n == IOStatus::UNAVAILABLE)););
begin();
if (!isOpen()) return 0;
n = send(fdVal, src, isa);
}
return 0;
}
int read(ByteBuffer& buf) {
synchronized (readLock) {
synchronized (stateLock) {
ensureOpen();
if (!isConnected()) throw NotYetConnectedException();
}
int n = 0;
Finalize(readerThread = 0;end((n > 0) || (n == IOStatus::UNAVAILABLE)););
begin();
if (!isOpen()) return 0;
n = read(fdVal, buf);
return n;
}
return -1;
}
long read(Array<ByteBuffer>& dsts, int offset, int length) {
return -1;
}
int write(ByteBuffer& buf) {
synchronized (writeLock) {
synchronized (stateLock) {
ensureOpen();
if (!isConnected()) throw NotYetConnectedException();
}
int n = 0;
Finalize(writerThread = 0;end((n > 0) || (n == IOStatus::UNAVAILABLE)););
begin();
if (!isOpen()) return 0;
n = send(fdVal, buf, mRemoteAddress);
return n;
}
return -1;
}
long write(Array<ByteBuffer>& srcs, int offset, int length) {
return -1;
}
DatagramChannel& bind(const SocketAddress& local) {
synchronized(readLock) {
synchronized(writeLock) {
synchronized (stateLock) {
ensureOpen();
if (mLocalAddress.getPort() != 0) throw AlreadyBoundException(mLocalAddress.toString());
InetSocketAddress isa;
if (local == null) {
if (family == StandardProtocolFamily::INET) {
isa = InetSocketAddress(InetAddress::getByName("0.0.0.0"), 0);
}
else {
isa = InetSocketAddress(0);
}
}
else {
isa = Net::checkAddress(local);
if (family == StandardProtocolFamily::INET) {
const InetAddress& addr = isa.getAddress();
if (!(instanceof<Inet4Address>(&addr))) {
throw UnsupportedAddressTypeException(addr.getClass().getName() + " is not Inet4Address");
}
}
else {
throw UnsupportedAddressTypeException("Family is not supported");
}
}
Net::bind(family, fdVal, isa.getAddress(), isa.getPort());
mLocalAddress = isa;
//mLocalAddress = Net::localAddress(fd);
}
}
}
return *this;
}
boolean isConnected() {
synchronized (stateLock) {
return (state == ST_CONNECTED);
}
return false;
}
DatagramChannel& connect(const SocketAddress& sa) {
synchronized(readLock) {
synchronized(writeLock) {
synchronized (stateLock) {
ensureOpenAndUnconnected();
InetSocketAddress isa = Net::checkAddress(sa);
int n = Net::connect(family, fdVal, isa.getAddress(), isa.getPort());
if (n <= 0) throw Error();
state = ST_CONNECTED;
mRemoteAddress = isa;
LOGD("fd=%d: connected to %s", fdVal, mRemoteAddress.toString().cstr());
//sender = isa;
//localAddress = Net::localAddress(fd);
}
}
}
return *this;
}
DatagramChannel& disconnect() {
synchronized(readLock) {
synchronized(writeLock) {
synchronized (stateLock) {
if (!isConnected() || !isOpen()) return *this;
mRemoteAddress = InetSocketAddress(0);
state = ST_UNCONNECTED;
}
}
}
return *this;
}
Shared<MembershipKey> join(const InetAddress& group, const NetworkInterface& interf) {
throw UnsupportedOperationException(__FUNCTION__);
}
Shared<MembershipKey> join(const InetAddress& group, const NetworkInterface& interf, const InetAddress& source) {
throw UnsupportedOperationException(__FUNCTION__);
}
//boolean translateReadyOps(int ops, int initialOps, SelectionKeyImpl sk) { }
};
class SocketChannelImpl : extends SocketChannel {
private:
static const int ST_UNINITIALIZED = -1;
static const int ST_UNCONNECTED = 0;
static const int ST_PENDING = 1;
static const int ST_CONNECTED = 2;
static const int ST_KILLPENDING = 3;
static const int ST_KILLED = 4;
int fdVal = -1;
long readerThread = 0;
long writerThread = 0;
Object readLock;
Object writeLock;
Object stateLock;
int state = ST_UNINITIALIZED;
InetSocketAddress mLocalAddress;
InetSocketAddress mRemoteAddress;
boolean reuseAddressEmulated;
boolean isReuseAddress;
// Input/Output open
boolean isInputOpen = true;
boolean isOutputOpen = true;
boolean readyToConnect = false;
boolean ensureReadOpen() {
synchronized (stateLock) {
if (!isOpen()) throw ClosedChannelException();
if (!isConnected()) throw NotYetConnectedException();
//if (!isInputOpen) return false;
return isInputOpen;
}
return false;
}
boolean ensureWriteOpen() {
synchronized (stateLock) {
if (!isOpen()) throw ClosedChannelException();
if (!isConnected()) throw NotYetConnectedException();
//if (!isInputOpen) return false;
return isOutputOpen;
}
return false;
}
void ensureOpenAndUnconnected() {
synchronized (stateLock) {
if (!isOpen()) throw ClosedChannelException();
if (state == ST_CONNECTED) throw AlreadyConnectedException();
if (state == ST_PENDING) throw ConnectionPendingException();
}
}
void readerCleanup() {
synchronized (stateLock) {
readerThread = 0;
if (state == ST_KILLPENDING) kill();
}
}
void writerCleanup() {
synchronized (stateLock) {
writerThread = 0;
if (state == ST_KILLPENDING) kill();
}
}
int sendOutOfBandData(byte b) {
return -1;
}
int read(int fd, ByteBuffer& dst) {
return -1;
}
int write(int fd, ByteBuffer& src) {
return -1;
}
protected:
void implConfigureBlocking(boolean block) {}
void implCloseSelectableChannel() {
synchronized (stateLock) {
}
}
public:
SocketChannelImpl(Shared<SelectorProvider> p) : SocketChannel(p) {
fdVal = ::socket(AF_INET, SOCK_STREAM, 0);
if (fdVal == -1) throw io::IOException(String("Create socket: ")+strerror(errno));
LOGD("Socket created, fd=%d", fdVal);
state = ST_UNCONNECTED;
}
SocketChannelImpl(Shared<SelectorProvider> p, const InetSocketAddress& remote) : SocketChannel(p) {
fdVal = ::socket(AF_INET, SOCK_DGRAM, 0);
if (fdVal == -1) throw io::IOException(String("Create socket: ")+strerror(errno));
LOGD("Socket created, fd=%d", fdVal);
mRemoteAddress = remote;
state = ST_CONNECTED;
}
~SocketChannelImpl() {
if (fdVal != -1) {
LOGD("%s: socket closing, fd=%d", __FUNCTION__, fdVal);
::close(fdVal);
fdVal = -1;
}
else {
LOGD("%s: socket never opened", __FUNCTION__);
}
}
const SocketAddress& getLocalAddress() const {
synchronized (stateLock) {
if (!isOpen()) throw ClosedChannelException();
return mLocalAddress;
}
return (SocketAddress&)null_obj;
}
const SocketAddress& getRemoteAddress() const {
synchronized (stateLock) {
if (!isOpen()) throw ClosedChannelException();
return mRemoteAddress;
}
return (SocketAddress&)null_obj;
}
SocketChannel& setOption(const SocketOption& name, Object *value) {
//if (name == null) throw NullPointerException();
synchronized (stateLock) {
if (!isOpen()) throw ClosedChannelException();
}
return *this;
}
Object* getOption(const SocketOption& name) const {
//if (name == null) throw NullPointerException();
synchronized (stateLock) {
if (!isOpen()) throw ClosedChannelException();
}
return null;
}
void kill() {
synchronized (stateLock) {
if (state == ST_KILLED) return;
if (state == ST_UNINITIALIZED) {
state = ST_KILLED;
return;
}
::close(fdVal); fdVal=-1;
state = ST_KILLED;
}
}
SocketChannel& shutdownInput() {
synchronized (stateLock) {
if (!isOpen()) throw new ClosedChannelException();
if (!isConnected()) throw new NotYetConnectedException();
if (isInputOpen) {
Net::shutdown(fdVal, Net::SHUT_RD);
isInputOpen = false;
}
}
return *this;
}
SocketChannel& shutdownOutput() {
synchronized (stateLock) {
if (!isOpen()) throw new ClosedChannelException();
if (!isConnected()) throw new NotYetConnectedException();
if (isOutputOpen) {
Net::shutdown(fdVal, Net::SHUT_WR);
isOutputOpen = false;
}
}
return *this;
}
Shared<Socket> socket() {return null;}
boolean isConnected() {
synchronized (stateLock) {
return state == ST_CONNECTED;
}
return false;
}
boolean isConnectionPending() {
synchronized (stateLock) {
return state == ST_PENDING;
}
}
boolean connect(const SocketAddress& sa) {
synchronized (readLock) {
synchronized (writeLock) {
ensureOpenAndUnconnected();
InetSocketAddress isa = Net::checkAddress(sa);
synchronized (blockingLock()) {
int n = 0;
try {
Finalize(readerCleanup();end((n > 0) || (n == IOStatus::UNAVAILABLE)););
begin();
synchronized (stateLock) {
if (!isOpen()) return false;
}
for (;;) {
Shared<InetAddress> sia;
const InetAddress* ia = &isa.getAddress();
if ((*ia).isAnyLocalAddress()) {
sia = InetAddress::getLocalHost();
ia = &(*sia);
}
n = Net::connect(fdVal, *ia, isa.getPort());
if ((n == IOStatus::INTERRUPTED) && isOpen()) continue;
break;
}
}
catch (const io::IOException& e) {
close();
throw;
}
synchronized (stateLock) {
mRemoteAddress = isa;
if (n > 0) {
state = ST_CONNECTED;
//if (isOpen()) localAddress = Net.localAddress(fd);
return true;
}
if (!isBlocking()) state = ST_PENDING;
}
}
}
}
return false;
}
boolean finishConnect() {
return true;
}
int read(ByteBuffer& buf) {
synchronized (readLock) {
if (!ensureReadOpen()) return -1;
int n = 0;
Finalize(end((n > 0) || (n == IOStatus::UNAVAILABLE)););
begin();
synchronized (stateLock) {
if (!isOpen()) return 0;
}
n = read(fdVal, buf);
return n;
}
return -1;
}
long read(Array<ByteBuffer>& dsts, int offset, int length) {
return -1;
}
int write(ByteBuffer& buf) {
synchronized (writeLock) {
ensureWriteOpen();
int n = 0;
Finalize(writerCleanup();end((n > 0) || (n == IOStatus::UNAVAILABLE)););
begin();
synchronized (stateLock) {
if (!isOpen()) return 0;
// writerThread = NativeThread.current();
}
n = write(fdVal, buf);
return n;
}
return -1;
}
long write(Array<ByteBuffer>& srcs, int offset, int length) {
return -1;
}
SocketChannel& bind(const SocketAddress& local) {
return *this;
}
boolean isConnected() const {
synchronized (stateLock) {
return (state == ST_CONNECTED);
}
return false;
}
boolean isConnectionPending() const {
synchronized (stateLock) {
return (state == ST_PENDING);
}
return false;
}
};
class PollSelectorProviderImpl : extends SelectorProvider {
public:
Shared<SelectorProvider> self;
virtual Shared<DatagramChannel> openDatagramChannel() {
return makeShared<DatagramChannelImpl>(self);
}
virtual Shared<DatagramChannel> openDatagramChannel(const ProtocolFamily& family) {
return makeShared<DatagramChannelImpl>(self, family);
}
virtual Shared<Pipe> openPipe() {
throw UnsupportedOperationException(__FUNCTION__);
}
virtual Shared<AbstractSelector> openSelector() {
return makeShared<PollSelectorImpl>(self);
}
virtual Shared<ServerSocketChannel> openServerSocketChannel() {
throw UnsupportedOperationException(__FUNCTION__);
}
virtual Shared<SocketChannel> openSocketChannel() {
return makeShared<SocketChannelImpl>(self);
}
virtual Shared<Channel> inheritedChannel() {
//return InheritedChannel::getChannel();
throw UnsupportedOperationException(__FUNCTION__);
}
};
class DefaultSelectorProvider {
public:
static Shared<SelectorProvider> create();
};
Shared<SelectorProvider> DefaultSelectorProvider::create() {
//String osname = System::getProperty("os.name");
//if (osname.equals("SunOS")) return createProvider("sun.nio.ch.DevPollSelectorProvider");
//if (osname.equals("Linux")) return createProvider("sun.nio.ch.EPollSelectorProvider");
Shared<PollSelectorProviderImpl> p = makeShared<PollSelectorProviderImpl>();
p->self = p;
return p;
}
Shared<SelectorProvider> SelectorProvider::provider() {
synchronized (lock) {
if (mProvider != null) return mProvider;
mProvider = DefaultSelectorProvider::create();
}
return mProvider;
}
Shared<Selector> Selector::open() {
return SelectorProvider::provider()->openSelector();
}
Shared<DatagramChannel> DatagramChannel::open() {
return SelectorProvider::provider()->openDatagramChannel();
}
Shared<SocketChannel> SocketChannel::open() {
return SelectorProvider::provider()->openSocketChannel();
}
}}
| 28.365196 | 115 | 0.678778 | [
"object"
] |
edc4d36c483720b5ad01f165dc767dc4d99ca976 | 3,219 | cpp | C++ | Scrabble.cpp | FRCTeamPhoenix/CMDGames2021 | 8112fb0ced2ec5a8ce0add77060dbb7e85290458 | [
"MIT"
] | null | null | null | Scrabble.cpp | FRCTeamPhoenix/CMDGames2021 | 8112fb0ced2ec5a8ce0add77060dbb7e85290458 | [
"MIT"
] | 5 | 2021-11-16T16:32:29.000Z | 2021-11-18T23:46:48.000Z | Scrabble.cpp | FRCTeamPhoenix/CMDGames2021 | 8112fb0ced2ec5a8ce0add77060dbb7e85290458 | [
"MIT"
] | 2 | 2021-11-01T23:46:16.000Z | 2021-11-04T22:46:03.000Z | #include <vector>
#include <string>
#include <iostream>
#include "scrabble.h"
#include <fstream>
#include <stdlib.h>
#include <time.h>
#include <climits>
#include <algorithm>
Scrabble::Scrabble() {
//adds the dictionary txt to list
std::ifstream f;
f.open("words_alpha.txt");
std::string line;
if (f.is_open()) {
while (std::getline(f, line)) {
m_words.push_back(line);
}
}
f.close();
}
char Scrabble::RandChar() {
//randomly generates a letter (ascii values 97 to 122)
return (char)(rand() % (122 - 97 + 1) + 97);
}
bool Scrabble::IsInt(std::string str) {
//checks if a string is an integer
for (int i = 0; i < str.length();i++) {
int asciiValue = (int)str[i] - 48;
if ((asciiValue >= 0) && (asciiValue <= 9)) {
}
else {return false;}
}
return true;
}
void Scrabble::Run() {
//randomizes seed
srand (time(NULL));
//main game loop
while (true) {
//generates given letters
std::string givenLetters = "";
for (int i = 0; i < 7; i++) {
givenLetters += RandChar();
}
//word quessing loop
while (true) {
std::cout << "Given letters: " << givenLetters << std::endl;
std::cout << " 1234567\n";
std::cout << "Word: ";
std::string wordGuess;
std::cin >> wordGuess;
bool notWord = true;
//checks if input was character to reroll or a word to guess
if (IsInt(wordGuess)) {
//reroll
int iReroll = std::stoi(wordGuess) - 1;
givenLetters[iReroll] = RandChar();
}
else {
//searches for the list of words to check if the guess was a recognized word
if (std::count(m_words.begin(), m_words.end(), wordGuess)) {
//checks if the guessed word is possible to make with the givin letters
std::string remainingLetters = givenLetters;
for (int i = 0; i < wordGuess.length(); i++) {
notWord = true;
for (int j = 0; j < remainingLetters.length(); j++) {
if (wordGuess[i] == remainingLetters[j]) {
remainingLetters.erase(j, 1);
notWord = false;
break;
}
}
if ((remainingLetters == "") || (false)) {
notWord = false;
break;
}
if (notWord) {
break;
}
}
if (notWord) {
std::cout << "Invalid\n";
}
else {
break;
}
}
else {
std::cout << "Invalid\n";
}
}
}
std::cout << "You found a word.\n\n";
}
std::cout << "Done.\n";
} | 29.53211 | 92 | 0.425598 | [
"vector"
] |
edc6cd0e6a6707979b88ccce70c529cba4e0900b | 50,063 | cpp | C++ | src/Loaders/NFS3Loader.cpp | Keiiko/OpenNFS | 9824ca7cb9025346d7d88837ff94d8b06cfdc324 | [
"MIT"
] | 1 | 2020-12-17T11:47:51.000Z | 2020-12-17T11:47:51.000Z | src/Loaders/NFS3Loader.cpp | Keiiko/OpenNFS | 9824ca7cb9025346d7d88837ff94d8b06cfdc324 | [
"MIT"
] | null | null | null | src/Loaders/NFS3Loader.cpp | Keiiko/OpenNFS | 9824ca7cb9025346d7d88837ff94d8b06cfdc324 | [
"MIT"
] | null | null | null | #include "NFS3Loader.h"
#include "../Util/Raytracer.h"
using namespace Utils;
using namespace TrackUtils;
// CAR
std::shared_ptr<Car> NFS3::LoadCar(const std::string &car_base_path) {
boost::filesystem::path p(car_base_path);
std::string car_name = p.filename().string();
std::stringstream viv_path, car_out_path, fce_path;
viv_path << car_base_path << "/car.viv";
car_out_path << CAR_PATH << ToString(NFS_3) << "/" << car_name << "/";
fce_path << CAR_PATH << ToString(NFS_3) << "/" << car_name << "/car.fce";
ASSERT(ExtractVIV(viv_path.str(), car_out_path.str()),
"Unable to extract " << viv_path.str() << " to " << car_out_path.str());
return std::make_shared<Car>(LoadFCE(fce_path.str()), NFS_3, car_name);
}
void NFS3::ConvertFCE(const std::string &fce_path, const std::string &obj_out_path) {
std::shared_ptr<Car> car(new Car(LoadFCE(fce_path), NFS_3, "Converted"));
car->writeObj(obj_out_path, car->data.meshes);
}
CarData NFS3::LoadFCE(const std::string &fce_path) {
LOG(INFO) << "Parsing FCE File located at " << fce_path;
glm::quat rotationMatrix = glm::normalize(glm::quat(glm::vec3(glm::radians(90.f), 0, glm::radians(180.f)))); // All Vertices are stored so that the model is rotated 90 degs on X, 180 on Z. Remove this at Vert load time.
CarData carData;
std::ifstream fce(fce_path, std::ios::in | std::ios::binary);
auto fceHeader = std::make_shared<FCE::NFS3::HEADER>();
fce.read((char *) fceHeader.get(), sizeof(FCE::NFS3::HEADER));
// Grab colours
for(uint8_t colourIdx = 0; colourIdx < fceHeader->nPriColours; ++colourIdx){
FCE::NFS3::COLOUR primaryColour = fceHeader->primaryColours[colourIdx];
CarColour originalPrimaryColour("", HSLToRGB(glm::vec4(primaryColour.H, primaryColour.S, primaryColour.B, primaryColour.T)));
carData.colours.emplace_back(originalPrimaryColour);
}
for(uint32_t dummyIdx = 0; dummyIdx < fceHeader->nDummies; ++dummyIdx){
Dummy dummy(fceHeader->dummyNames[dummyIdx], rotationMatrix * glm::vec3(fceHeader->dummyCoords[dummyIdx].x /10,fceHeader->dummyCoords[dummyIdx].y /10, fceHeader->dummyCoords[dummyIdx].z /10));
carData.dummies.emplace_back(dummy);
}
for (uint32_t part_Idx = 0; part_Idx < fceHeader->nParts; ++part_Idx) {
float specularDamper = 0.2f;
float specularReflectivity = 0.02f;
float envReflectivity = 0.4f;
std::vector<uint32_t> indices;
std::vector<uint32_t> polygonFlags;
std::vector<glm::vec3> vertices;
std::vector<glm::vec3> normals;
std::vector<glm::vec2> uvs;
std::string part_name(fceHeader->partNames[part_Idx]);
glm::vec3 center = rotationMatrix *
glm::vec3(fceHeader->partCoords[part_Idx].x / 10, fceHeader->partCoords[part_Idx].y / 10,
fceHeader->partCoords[part_Idx].z / 10);
auto *partVertices = new FLOATPT[fceHeader->partNumVertices[part_Idx]];
auto *partNormals = new FLOATPT[fceHeader->partNumVertices[part_Idx]];
auto *partTriangles = new FCE::TRIANGLE[fceHeader->partNumTriangles[part_Idx]];
fce.seekg(sizeof(FCE::NFS3::HEADER) + fceHeader->vertTblOffset +
(fceHeader->partFirstVertIndices[part_Idx] * sizeof(FLOATPT)), std::ios_base::beg);
fce.read((char *) partVertices, fceHeader->partNumVertices[part_Idx] * sizeof(FLOATPT));
for (uint32_t vert_Idx = 0; vert_Idx < fceHeader->partNumVertices[part_Idx]; ++vert_Idx) {
vertices.emplace_back(rotationMatrix *
glm::vec3(partVertices[vert_Idx].x / 10, partVertices[vert_Idx].y / 10,
partVertices[vert_Idx].z / 10));
}
fce.seekg(sizeof(FCE::NFS3::HEADER) + fceHeader->normTblOffset +
(fceHeader->partFirstVertIndices[part_Idx] * sizeof(FLOATPT)), std::ios_base::beg);
fce.read((char *) partNormals, fceHeader->partNumVertices[part_Idx] * sizeof(FLOATPT));
for (uint32_t normal_Idx = 0; normal_Idx < fceHeader->partNumVertices[part_Idx]; ++normal_Idx) {
normals.emplace_back(rotationMatrix * glm::vec3(partNormals[normal_Idx].x, partNormals[normal_Idx].y,
partNormals[normal_Idx].z));
}
fce.seekg(sizeof(FCE::NFS3::HEADER) + fceHeader->triTblOffset +
(fceHeader->partFirstTriIndices[part_Idx] * sizeof(FCE::TRIANGLE)), std::ios_base::beg);
fce.read((char *) partTriangles, fceHeader->partNumTriangles[part_Idx] * sizeof(FCE::TRIANGLE));
for (uint32_t tri_Idx = 0; tri_Idx < fceHeader->partNumTriangles[part_Idx]; ++tri_Idx) {
polygonFlags.emplace_back(partTriangles[tri_Idx].polygonFlags);
polygonFlags.emplace_back(partTriangles[tri_Idx].polygonFlags);
polygonFlags.emplace_back(partTriangles[tri_Idx].polygonFlags);
indices.emplace_back(partTriangles[tri_Idx].vertex[0]);
indices.emplace_back(partTriangles[tri_Idx].vertex[1]);
indices.emplace_back(partTriangles[tri_Idx].vertex[2]);
uvs.emplace_back(glm::vec2(partTriangles[tri_Idx].uvTable[0], 1.0f- partTriangles[tri_Idx].uvTable[3]));
uvs.emplace_back(glm::vec2(partTriangles[tri_Idx].uvTable[1], 1.0f- partTriangles[tri_Idx].uvTable[4]));
uvs.emplace_back(glm::vec2(partTriangles[tri_Idx].uvTable[2], 1.0f- partTriangles[tri_Idx].uvTable[5]));
}
carData.meshes.emplace_back(CarModel(part_name, vertices, uvs, normals, indices, polygonFlags, center, specularDamper, specularReflectivity, envReflectivity));
LOG(INFO) << "Loaded Mesh: " << carData.meshes[part_Idx].m_name << " UVs: " << carData.meshes[part_Idx].m_uvs.size()
<< " Verts: " << carData.meshes[part_Idx].m_vertices.size() << " Indices: "
<< carData.meshes[part_Idx].m_vertex_indices.size() << " Normals: " << carData.meshes[part_Idx].m_normals.size();
delete[] partNormals;
delete[] partVertices;
delete[] partTriangles;
}
fce.close();
// Go get car metadata from FEDATA
boost::filesystem::path fcePath(fce_path);
boost::filesystem::path fceBaseDir = fcePath.parent_path();
std::ifstream fedata(fceBaseDir.string() + "/fedata.eng", std::ios::in | std::ios::binary);
// Go get the offset of car name
fedata.seekg(FEDATA::NFS3::MENU_NAME_FILEPOS_OFFSET, std::ios::beg);
uint32_t menuNameOffset = 0;
fedata.read((char*) &menuNameOffset, sizeof(uint32_t));
fedata.seekg(menuNameOffset, std::ios::beg);
char carMenuName[64];
fedata.read((char*) carMenuName, 64u);
std::string carMenuNameStr(carMenuName);
carData.carName = carMenuNameStr;
// Jump to location of FILEPOS table for car colour names
fedata.seekg(FEDATA::NFS3::COLOUR_TABLE_OFFSET, std::ios::beg);
// Read that table in
auto *colourNameOffsets = new uint32_t[fceHeader->nPriColours];
fedata.read((char*) colourNameOffsets, fceHeader->nPriColours * sizeof(uint32_t));
for(uint8_t colourIdx = 0; colourIdx < fceHeader->nPriColours; ++colourIdx){
fedata.seekg(colourNameOffsets[colourIdx]);
uint32_t colourNameLength = colourIdx < (fceHeader->nPriColours - 1) ? (colourNameOffsets[colourIdx+1] - colourNameOffsets[colourIdx]) : 32;
char *colourName = new char[colourNameLength];
fedata.read((char*) colourName, colourNameLength);
std::string colourNameStr(colourName);
carData.colours[colourIdx].colourName =colourNameStr;
delete []colourName;
}
delete []colourNameOffsets;
return carData;
}
// TRACK
std::shared_ptr<TRACK> NFS3::LoadTrack(const std::string &track_base_path) {
LOG(INFO) << "Loading Track located at " << track_base_path;
auto track = std::make_shared<TRACK>(TRACK());
boost::filesystem::path p(track_base_path);
track->name = p.filename().string();
std::stringstream frd_path, col_path, can_path, hrz_path;
std::string strip = "k0";
size_t pos = track->name.find(strip);
if (pos != std::string::npos)
track->name.replace(pos, strip.size(), "");
frd_path << track_base_path << "/" << track->name << ".frd";
col_path << track_base_path << "/" << track->name << ".col";
can_path << track_base_path << "/" << track->name << "00a.can";
hrz_path << track_base_path << "/3" << track->name << ".hrz";
ASSERT(ExtractTrackTextures(track_base_path, track->name, NFSVer::NFS_3),
"Could not extract " << track->name << " QFS texture pack.");
ASSERT(LoadFRD(frd_path.str(), track->name, track),
"Could not load FRD file: " << frd_path.str()); // Load FRD file to get track block specific data
ASSERT(LoadCOL(col_path.str(), track), "Could not load COL file: "
<< col_path.str()); // Load Catalogue file to get global (non trkblock specific) data
ASSERT(LoadCAN(can_path.str(), track->cameraAnimation),
"Could not load CAN file (camera animation): " << can_path.str()); // Load camera intro/outro animation data
ASSERT(LoadHRZ(hrz_path.str(), track),
"Could not load HRZ file (skybox/lighting):" << hrz_path.str()); // Load HRZ Data
track->textureArrayID = MakeTextureArray(track->textures, false);
track->track_blocks = ParseTRKModels(track);
track->global_objects = ParseCOLModels(track);
LOG(INFO) << "Track loaded successfully";
return track;
}
bool NFS3::LoadFFN(const std::string &ffn_path) {
std::ifstream ffn(ffn_path, std::ios::in | std::ios::binary);
if (!ffn.is_open()) {
return false;
}
LOG(INFO) << "Loading FFN File located at " << ffn_path;
// Get filesize so can check have parsed all bytes
FFN::HEADER *header = new FFN::HEADER;
ffn.read((char *) header, sizeof(FFN::HEADER));
if (memcmp(header->fntfChk, "FNTF", sizeof(header->fntfChk)) != 0) {
LOG(WARNING) << "Invalid FFN Header.";
delete header;
return false;
}
FFN::CHAR_TABLE_ENTRY *charTable = new FFN::CHAR_TABLE_ENTRY[header->numChars];
ffn.read((char *) charTable, sizeof(FFN::CHAR_TABLE_ENTRY) * header->numChars);
uint32_t predictedAFontOffset = header->fontMapOffset;
for (uint8_t char_Idx = 0; char_Idx < header->numChars; ++char_Idx) {
FFN::CHAR_TABLE_ENTRY character = charTable[char_Idx];
}
header->numChars = 400;
header->version = 164;
//streamoff readBytes = ffn.tellg();
//ASSERT(readBytes == header->fileSize, "Missing " << header->fileSize - readBytes << " bytes from loaded FFN file: " << ffn_path);
ffn.seekg(header->fontMapOffset, std::ios_base::beg);
uint32_t *pixels = new uint32_t[header->version * header->numChars];
uint16_t *paletteColours = new uint16_t[0xFF];
uint8_t *indexes = new uint8_t[header->version * header->numChars]; // Only used if indexed
for(int pal_Idx = 0; pal_Idx < 255; ++pal_Idx){
paletteColours[pal_Idx] = 65535;
}
for (int y = 0; y < header->numChars; y++) {
for (int x = 0; x < header->version; x++) {
ffn.read((char *) &indexes[(x + y * header->version)], sizeof(uint8_t));
}
}
// Rewrite the pixels using the palette data
for (int y = 0; y < header->numChars; y++) {
for (int x = 0; x < header->version; x++) {
uint32_t pixel = ImageLoader::abgr1555ToARGB8888(paletteColours[indexes[(x + y * header->version)]]);
pixels[(x + y * header->version)] = pixel;
}
}
ImageLoader::SaveImage("C:/Users/Amrik/Desktop/test.bmp", pixels, header->version, header->numChars);
delete[]pixels;
delete header;
//ASSERT(readBytes == header->fileSize, "Missing " << header->fileSize - readBytes << " bytes from loaded FFN file: " << ffn_path);
return true;
}
void NFS3::FreeTrack(const std::shared_ptr<TRACK> &track) {
FreeFRD(track);
FreeCOL(track);
}
bool NFS3::LoadFRD(std::string frd_path, const std::string &track_name, const std::shared_ptr<TRACK> &track) {
std::ifstream ar(frd_path, std::ios::in | std::ios::binary);
char header[28]; /* file header */
SAFE_READ(ar, header, 28); // header & numblocks
SAFE_READ(ar, &track->nBlocks, 4);
track->nBlocks++;
if ((track->nBlocks < 1) || (track->nBlocks > 500)) return false; // 1st sanity check
LOG(INFO) << "Loading FRD File located at " << frd_path;
track->trk = new TRKBLOCK[track->nBlocks]();
track->poly = new POLYGONBLOCK[track->nBlocks]();
track->xobj = new XOBJBLOCK[4 * track->nBlocks + 1]();
int l;
SAFE_READ(ar, &l, 4); // choose between NFS3 & NFSHS
if ((l < 0) || (l > 5000)) track->bHSMode = false;
else if (((l + 7) / 8) == track->nBlocks) track->bHSMode = true;
else return false; // unknown file type
memcpy(track->trk, &l, 4);
if (ar.read(((char *) track->trk) + 4, 80).gcount() != 80) return false;
// TRKBLOCKs
for (uint32_t block_Idx = 0; block_Idx < track->nBlocks; block_Idx++) {
TRKBLOCK *trackBlock = &(track->trk[block_Idx]);
// ptCentre, ptBounding, 6 nVertices == 84 bytes
if (block_Idx != 0) { SAFE_READ(ar, trackBlock, 84); }
if (trackBlock->nVertices == 0) return false;
trackBlock->vert = new FLOATPT[trackBlock->nVertices];;
SAFE_READ(ar, trackBlock->vert, 12 * trackBlock->nVertices);
trackBlock->unknVertices = new uint32_t[trackBlock->nVertices];
SAFE_READ(ar, trackBlock->unknVertices, 4 * trackBlock->nVertices);
SAFE_READ(ar, trackBlock->nbdData, 4 * 0x12c);
// nStartPos & various blk sizes == 32 bytes
SAFE_READ(ar, &(trackBlock->nStartPos), 32);
if (block_Idx > 0)
if (trackBlock->nStartPos !=
track->trk[block_Idx - 1].nStartPos + track->trk[block_Idx - 1].nPositions)
return false;
trackBlock->posData = new POSITIONDATA[trackBlock->nPositions];
SAFE_READ(ar, trackBlock->posData, 8 * trackBlock->nPositions);
trackBlock->polyData = new POLYVROADDATA[trackBlock->nPolygons];
for (uint32_t j = 0; j < trackBlock->nPolygons; j++)
SAFE_READ(ar, trackBlock->polyData + j, 8);
trackBlock->vroadData = new VROADDATA[trackBlock->nVRoad];
SAFE_READ(ar, trackBlock->vroadData, 12 * trackBlock->nVRoad);
if (trackBlock->nXobj > 0) {
trackBlock->xobj = new REFXOBJ[trackBlock->nXobj];
SAFE_READ(ar, trackBlock->xobj, 20 * trackBlock->nXobj);
}
if (trackBlock->nPolyobj > 0) {
ar.seekg(20 * trackBlock->nPolyobj, std::ios_base::cur);
}
trackBlock->nPolyobj = 0;
if (trackBlock->nSoundsrc > 0) {
trackBlock->soundsrc = new SOUNDSRC[trackBlock->nSoundsrc];
SAFE_READ(ar, trackBlock->soundsrc, 16 * trackBlock->nSoundsrc);
}
if (trackBlock->nLightsrc > 0) {
trackBlock->lightsrc = new LIGHTSRC[trackBlock->nLightsrc];
SAFE_READ(ar, trackBlock->lightsrc, 16 * trackBlock->nLightsrc);
}
}
// POLYGONBLOCKs
for (uint32_t block_Idx = 0; block_Idx < track->nBlocks; block_Idx++) {
POLYGONBLOCK *p = &(track->poly[block_Idx]);
for (uint32_t j = 0; j < 7; j++) {
SAFE_READ(ar, &(p->sz[j]), 0x4);
if (p->sz[j] != 0) {
SAFE_READ(ar, &(p->szdup[j]), 0x4);
if (p->szdup[j] != p->sz[j]) return false;
p->poly[j] = static_cast<LPPOLYGONDATA>(calloc(p->sz[j], sizeof(POLYGONDATA)));
SAFE_READ(ar, p->poly[j], 14 * p->sz[j]);
}
}
if (p->sz[4] != track->trk[block_Idx].nPolygons) return false; // sanity check
for (uint32_t obj_Idx = 0; obj_Idx < 4; obj_Idx++) {
OBJPOLYBLOCK *o = &(p->obj[obj_Idx]);
SAFE_READ(ar, &(o->n1), 0x4);
if (o->n1 > 0) {
SAFE_READ(ar, &(o->n2), 0x4);
o->types = new uint32_t[o->n2];
o->numpoly = new uint32_t[o->n2];
o->poly = new LPPOLYGONDATA[o->n2];
o->nobj = 0;
l = 0;
for (uint32_t k = 0; k < o->n2; k++) {
SAFE_READ(ar, o->types + k, 0x4);
if (o->types[k] == 1) {
SAFE_READ(ar, o->numpoly + o->nobj, 0x4);
o->poly[o->nobj] = static_cast<LPPOLYGONDATA>(calloc(o->numpoly[o->nobj], sizeof(POLYGONDATA)));
SAFE_READ(ar, o->poly[o->nobj], 14 * o->numpoly[o->nobj]);
l += o->numpoly[o->nobj];
o->nobj++;
}
}
if (l != o->n1) return false; // n1 == total nb polygons
}
}
}
// XOBJBLOCKs
for (uint32_t xblock_Idx = 0; xblock_Idx <= 4 * track->nBlocks; xblock_Idx++) {
SAFE_READ(ar, &(track->xobj[xblock_Idx].nobj), 4);
if (track->xobj[xblock_Idx].nobj > 0) {
track->xobj[xblock_Idx].obj = new XOBJDATA[track->xobj[xblock_Idx].nobj];
}
for (uint32_t xobj_Idx = 0; xobj_Idx < track->xobj[xblock_Idx].nobj; xobj_Idx++) {
XOBJDATA *x = &(track->xobj[xblock_Idx].obj[xobj_Idx]);
// 3 headers == 12 bytes
SAFE_READ(ar, x, 12);
if (x->crosstype == 4) { // basic objects
SAFE_READ(ar, &(x->ptRef), 12);
SAFE_READ(ar, &(x->AnimMemory), 4);
} else if (x->crosstype == 3) { // animated objects
// unkn3, type3, objno, nAnimLength, unkn4 == 24 bytes
SAFE_READ(ar, x->unknown3, 24);
if (x->type3 != 3) return false;
x->animData = new ANIMDATA[x->nAnimLength];
SAFE_READ(ar, x->animData, 20 * x->nAnimLength);
// make a ref point from first anim position
x->ptRef.x = (float) (x->animData->pt.x / 65536.0);
x->ptRef.z = (float) (x->animData->pt.z / 65536.0);
x->ptRef.y = (float) (x->animData->pt.y / 65536.0);
} else return false; // unknown object type
// common part : vertices & polygons
SAFE_READ(ar, &(x->nVertices), 4);
x->vert = new FLOATPT[x->nVertices];
SAFE_READ(ar, x->vert, 12 * x->nVertices);
x->unknVertices = new uint32_t[x->nVertices];
SAFE_READ(ar, x->unknVertices, 4 * x->nVertices);
SAFE_READ(ar, &(x->nPolygons), 4);
x->polyData = new POLYGONDATA[x->nPolygons];
SAFE_READ(ar, x->polyData, 14 * x->nPolygons);
}
}
// TEXTUREBLOCKs
SAFE_READ(ar, &track->nTextures, 4);
track->texture = new TEXTUREBLOCK[track->nTextures];
for (uint32_t tex_Idx = 0; tex_Idx < track->nTextures; tex_Idx++) {
SAFE_READ(ar, &(track->texture[tex_Idx]), 47);
track->textures[track->texture[tex_Idx].texture] = LoadTexture(track->texture[tex_Idx], track_name);
}
uint32_t pad;
return ar.read((char *) &pad, 4).gcount() == 0; // we ought to be at EOF now
}
bool NFS3::LoadCOL(std::string col_path, const std::shared_ptr<TRACK> &track) {
std::ifstream coll(col_path, std::ios::in | std::ios::binary);
COLOBJECT *o;
track->col.hs_extra = NULL;
if (coll.read((char *) &track->col, 16).gcount() != 16) return false;
if (memcmp(track->col.collID, "COLL", sizeof(track->col.collID[0])) != 0) {
LOG(WARNING) << "Invalid COL file";
return false;
}
LOG(INFO) << "Loading COL File located at " << col_path;
if (track->col.version != 11) return false;
if ((track->col.nBlocks != 2) && (track->col.nBlocks != 4) && (track->col.nBlocks != 5)) return false;
SAFE_READ(coll, track->col.xbTable, 4 * track->col.nBlocks);
// texture XB
SAFE_READ(coll, &track->col.textureHead, 8);
if (track->col.textureHead.xbid != XBID_TEXTUREINFO) return false;
track->col.texture = new COLTEXTUREINFO[track->col.textureHead.nrec];
SAFE_READ(coll, track->col.texture, 8 * track->col.textureHead.nrec);
// struct3D XB
if (track->col.nBlocks >= 4) {
SAFE_READ(coll, &track->col.struct3DHead, 8);
if (track->col.struct3DHead.xbid != XBID_STRUCT3D) return false;
COLSTRUCT3D *s = track->col.struct3D = new COLSTRUCT3D[track->col.struct3DHead.nrec];
int delta;
for (uint32_t colRec_Idx = 0; colRec_Idx < track->col.struct3DHead.nrec; colRec_Idx++, s++) {
SAFE_READ(coll, s, 8);
delta = (8 + 16 * s->nVert + 6 * s->nPoly) % 4;
delta = (4 - delta) % 4;
if (s->size != 8 + 16 * s->nVert + 6 * s->nPoly + delta) return false;
s->vertex = new COLVERTEX[s->nVert];
SAFE_READ(coll, s->vertex, 16 * s->nVert);
s->polygon = new COLPOLYGON[s->nPoly];
SAFE_READ(coll, s->polygon, 6 * s->nPoly);
int dummy;
if (delta > 0) SAFE_READ(coll, &dummy, delta);
}
// object XB
SAFE_READ(coll, &track->col.objectHead, 8);
if ((track->col.objectHead.xbid != XBID_OBJECT) && (track->col.objectHead.xbid != XBID_OBJECT2))
return false;
o = track->col.object = new COLOBJECT[track->col.objectHead.nrec];
for (uint32_t colRec_Idx = 0; colRec_Idx < track->col.objectHead.nrec; colRec_Idx++, o++) {
SAFE_READ(coll, o, 4);
if (o->type == 1) {
if (o->size != 16) return false;
SAFE_READ(coll, &(o->ptRef), 12);
} else if (o->type == 3) {
SAFE_READ(coll, &(o->animLength), 4);
if (o->size != 8 + 20 * o->animLength) return false;
o->animData = new ANIMDATA[o->animLength];
SAFE_READ(coll, o->animData, 20 * o->animLength);
o->ptRef.x = o->animData->pt.x;
o->ptRef.z = o->animData->pt.z;
o->ptRef.y = o->animData->pt.y;
} else return false; // unknown object type
}
}
// object2 XB
if (track->col.nBlocks == 5) {
SAFE_READ(coll, &track->col.object2Head, 8);
if ((track->col.object2Head.xbid != XBID_OBJECT) && (track->col.object2Head.xbid != XBID_OBJECT2))
return false;
o = track->col.object2 = new COLOBJECT[track->col.object2Head.nrec];
for (uint32_t colRec_Idx = 0; colRec_Idx < track->col.object2Head.nrec; colRec_Idx++, o++) {
SAFE_READ(coll, o, 4);
if (o->type == 1) {
if (o->size != 16) return false;
SAFE_READ(coll, &(o->ptRef), 12);
} else if (o->type == 3) {
SAFE_READ(coll, &(o->animLength), 4);
if (o->size != 8 + 20 * o->animLength) return false;
o->animData = new ANIMDATA[o->animLength];
SAFE_READ(coll, o->animData, 20 * o->animLength);
o->ptRef.x = o->animData->pt.x;
o->ptRef.z = o->animData->pt.z;
o->ptRef.y = o->animData->pt.y;
} else return false; // unknown object type
}
}
// vroad XB
SAFE_READ(coll, &track->col.vroadHead, 8);
if (track->col.vroadHead.xbid != XBID_VROAD) return false;
if (track->col.vroadHead.size != 8 + 36 * track->col.vroadHead.nrec) return false;
track->col.vroad = new COLVROAD[track->col.vroadHead.nrec];
SAFE_READ(coll, track->col.vroad, 36 * track->col.vroadHead.nrec);
uint32_t pad;
return coll.read((char *) &pad, 4).gcount() == 0; // we ought to be at EOF now
}
bool NFS3::LoadHRZ(std::string hrz_path, const std::shared_ptr<TRACK> &track) {
std::ifstream hrz(hrz_path, std::ios::in | std::ios::binary);
if (!hrz.is_open()) return false;
LOG(INFO) << "Loading HRZ File located at " << hrz_path;
std::string str, skyTopColour, skyBottomColour;
while (std::getline(hrz, str))
{
if (str.find("/* r,g,b value at top of Gourad shaded SKY area */") != std::string::npos) {
std::getline(hrz, skyTopColour);
}
if (str.find("/* r,g,b values for base of Gourad shaded SKY area */") != std::string::npos) {
std::getline(hrz, skyBottomColour);
}
}
track->sky_top_colour = ParseRGBString(skyTopColour);
track->sky_bottom_colour = ParseRGBString(skyBottomColour);
hrz.close();
return true;
}
std::vector<TrackBlock> NFS3::ParseTRKModels(const std::shared_ptr<TRACK> &track) {
LOG(INFO) << "Parsing TRK file into ONFS GL structures";
std::vector<TrackBlock> track_blocks = std::vector<TrackBlock>();
glm::quat rotationMatrix = glm::normalize(glm::quat(glm::vec3(-SIMD_PI / 2, 0, 0))); // All Vertices are stored so that the model is rotated 90 degs on X. Remove this at Vert load time.
/* TRKBLOCKS - BASE TRACK GEOMETRY */
for (uint32_t i = 0; i < track->nBlocks; i++) {
// Get Verts from Trk block, indices from associated polygon block
TRKBLOCK trk_block = track->trk[i];
POLYGONBLOCK polygon_block = track->poly[i];
TrackBlock current_track_block(i, rotationMatrix *
glm::vec3(trk_block.ptCentre.x / 10, trk_block.ptCentre.y / 10,
trk_block.ptCentre.z / 10));
glm::vec3 trk_block_center = rotationMatrix * glm::vec3(0, 0, 0);
// Light sources
for (uint32_t j = 0; j < trk_block.nLightsrc; j++) {
glm::vec3 light_center = rotationMatrix * glm::vec3((trk_block.lightsrc[j].refpoint.x / 65536.0) / 10,
(trk_block.lightsrc[j].refpoint.y / 65536.0) / 10,
(trk_block.lightsrc[j].refpoint.z / 65536.0) / 10);
current_track_block.lights.emplace_back(
Entity(i, j, NFS_3, LIGHT, MakeLight(light_center, trk_block.lightsrc[j].type)));
}
for (uint32_t s = 0; s < trk_block.nSoundsrc; s++) {
glm::vec3 sound_center = rotationMatrix * glm::vec3((trk_block.soundsrc[s].refpoint.x / 65536.0) / 10,
(trk_block.soundsrc[s].refpoint.y / 65536.0) / 10,
(trk_block.soundsrc[s].refpoint.z / 65536.0) / 10);
current_track_block.sounds.emplace_back(
Entity(i, s, NFS_3, SOUND, Sound(sound_center, trk_block.soundsrc[s].type)));
}
// Get Object vertices
std::vector<glm::vec3> obj_verts;
std::vector<glm::vec4> obj_shading_verts;
for (uint32_t v = 0; v < trk_block.nObjectVert; v++) {
obj_verts.emplace_back(rotationMatrix * glm::vec3(trk_block.vert[v].x / 10, trk_block.vert[v].y / 10,
trk_block.vert[v].z / 10));
uint32_t shading_data = trk_block.unknVertices[v];
obj_shading_verts.emplace_back(
glm::vec4(((shading_data >> 16) & 0xFF) / 255.0f, ((shading_data >> 8) & 0xFF) / 255.0f,
(shading_data & 0xFF) / 255.0f, ((shading_data >> 24) & 0xFF) / 255.0f));
}
// 4 OBJ Poly blocks
for (uint32_t j = 0; j < 4; j++) {
OBJPOLYBLOCK obj_polygon_block = polygon_block.obj[j];
if (obj_polygon_block.n1 > 0) {
// Iterate through objects in objpoly block up to num objects
for (uint32_t k = 0; k < obj_polygon_block.nobj; k++) {
//TODO: Animated objects here, obj_polygon_block.types
// Mesh Data
std::vector<unsigned int> vertex_indices;
std::vector<glm::vec2> uvs;
std::vector<unsigned int> texture_indices;
std::vector<glm::vec3> norms;
uint32_t accumulatedObjectFlags = 0u;
// Get Polygons in object
LPPOLYGONDATA object_polys = obj_polygon_block.poly[k];
for (uint32_t p = 0; p < obj_polygon_block.numpoly[k]; p++) {
TEXTUREBLOCK texture_for_block = track->texture[object_polys[p].texture];
Texture gl_texture = track->textures[texture_for_block.texture];
glm::vec3 normal = rotationMatrix *
CalculateQuadNormal(PointToVec(trk_block.vert[object_polys[p].vertex[0]]),
PointToVec(trk_block.vert[object_polys[p].vertex[1]]),
PointToVec(trk_block.vert[object_polys[p].vertex[2]]),
PointToVec(trk_block.vert[object_polys[p].vertex[3]]));
norms.emplace_back(normal);
norms.emplace_back(normal);
norms.emplace_back(normal);
norms.emplace_back(normal);
norms.emplace_back(normal);
norms.emplace_back(normal);
vertex_indices.emplace_back(object_polys[p].vertex[0]);
vertex_indices.emplace_back(object_polys[p].vertex[1]);
vertex_indices.emplace_back(object_polys[p].vertex[2]);
vertex_indices.emplace_back(object_polys[p].vertex[0]);
vertex_indices.emplace_back(object_polys[p].vertex[2]);
vertex_indices.emplace_back(object_polys[p].vertex[3]);
std::vector<glm::vec2> transformedUVs = GenerateUVs(NFS_3, OBJ_POLY,
object_polys[p].hs_texflags, gl_texture,
texture_for_block);
uvs.insert(uvs.end(), transformedUVs.begin(), transformedUVs.end());
texture_indices.emplace_back(texture_for_block.texture);
texture_indices.emplace_back(texture_for_block.texture);
texture_indices.emplace_back(texture_for_block.texture);
texture_indices.emplace_back(texture_for_block.texture);
texture_indices.emplace_back(texture_for_block.texture);
texture_indices.emplace_back(texture_for_block.texture);
accumulatedObjectFlags |= object_polys[p].flags;
}
current_track_block.objects.emplace_back(Entity(i, (j + 1) * (k + 1), NFS_3, OBJ_POLY,
Track(obj_verts, norms, uvs, texture_indices,
vertex_indices, obj_shading_verts,
trk_block_center), accumulatedObjectFlags));
}
}
}
/* XOBJS - EXTRA OBJECTS */
for (uint32_t l = (i * 4); l < (i * 4) + 4; l++) {
for (uint32_t j = 0; j < track->xobj[l].nobj; j++) {
XOBJDATA *x = &(track->xobj[l].obj[j]);
if (x->crosstype == 4) { // basic objects
} else if (x->crosstype == 3) { // animated objects
}
// common part : vertices & polygons
std::vector<glm::vec3> verts;
std::vector<glm::vec4> xobj_shading_verts;
for (uint32_t k = 0; k < x->nVertices; k++, x->vert++) {
verts.emplace_back(rotationMatrix * glm::vec3(x->vert->x / 10, x->vert->y / 10, x->vert->z / 10));
uint32_t shading_data = x->unknVertices[k];
//RGBA
xobj_shading_verts.emplace_back(
glm::vec4(((shading_data >> 16) & 0xFF) / 255.0f, ((shading_data >> 8) & 0xFF) / 255.0f,
(shading_data & 0xFF) / 255.0f, ((shading_data >> 24) & 0xFF) / 255.0f));
}
std::vector<unsigned int> vertex_indices;
std::vector<glm::vec2> uvs;
std::vector<unsigned int> texture_indices;
std::vector<glm::vec3> norms;
uint32_t accumulatedObjectFlags = 0u;
for (uint32_t k = 0; k < x->nPolygons; k++, x->polyData++) {
TEXTUREBLOCK texture_for_block = track->texture[x->polyData->texture];
Texture gl_texture = track->textures[texture_for_block.texture];
glm::vec3 normal = rotationMatrix * CalculateQuadNormal(PointToVec(verts[x->polyData->vertex[0]]),
PointToVec(verts[x->polyData->vertex[1]]),
PointToVec(verts[x->polyData->vertex[2]]),
PointToVec(verts[x->polyData->vertex[3]]));
norms.emplace_back(normal);
norms.emplace_back(normal);
norms.emplace_back(normal);
norms.emplace_back(normal);
norms.emplace_back(normal);
norms.emplace_back(normal);
vertex_indices.emplace_back(x->polyData->vertex[0]);
vertex_indices.emplace_back(x->polyData->vertex[1]);
vertex_indices.emplace_back(x->polyData->vertex[2]);
vertex_indices.emplace_back(x->polyData->vertex[0]);
vertex_indices.emplace_back(x->polyData->vertex[2]);
vertex_indices.emplace_back(x->polyData->vertex[3]);
std::vector<glm::vec2> transformedUVs = GenerateUVs(NFS_3, XOBJ, x->polyData->hs_texflags,
gl_texture, texture_for_block);
uvs.insert(uvs.end(), transformedUVs.begin(), transformedUVs.end());
texture_indices.emplace_back(texture_for_block.texture);
texture_indices.emplace_back(texture_for_block.texture);
texture_indices.emplace_back(texture_for_block.texture);
texture_indices.emplace_back(texture_for_block.texture);
texture_indices.emplace_back(texture_for_block.texture);
texture_indices.emplace_back(texture_for_block.texture);
accumulatedObjectFlags |= x->polyData->flags;
}
glm::vec3 xobj_center = rotationMatrix * glm::vec3(x->ptRef.x / 10, x->ptRef.y / 10, x->ptRef.z / 10);
current_track_block.objects.emplace_back(Entity(i, l, NFS_3, XOBJ,
Track(verts, norms, uvs, texture_indices,
vertex_indices, xobj_shading_verts, xobj_center),
accumulatedObjectFlags));
}
}
// Mesh Data
std::vector<unsigned int> vertex_indices;
std::vector<glm::vec2> uvs;
std::vector<unsigned int> texture_indices;
std::vector<glm::vec3> verts;
std::vector<glm::vec4> trk_block_shading_verts;
std::vector<glm::vec3> norms;
uint32_t accumulatedObjectFlags = 0u;
for (int32_t j = 0; j < trk_block.nVertices; j++) {
verts.emplace_back(rotationMatrix *
glm::vec3(trk_block.vert[j].x / 10, trk_block.vert[j].y / 10, trk_block.vert[j].z / 10));
// Break uint32_t of RGB into 4 normalised floats and store into vec4
uint32_t shading_data = trk_block.unknVertices[j];
trk_block_shading_verts.emplace_back(
glm::vec4(((shading_data >> 16) & 0xFF) / 255.0f, ((shading_data >> 8) & 0xFF) / 255.0f,
(shading_data & 0xFF) / 255.0f, ((shading_data >> 24) & 0xFF) / 255.0f));
}
// Get indices from Chunk 4 and 5 for High Res polys, Chunk 6 for Road Lanes
for (uint32_t chnk = 4; chnk <= 6; chnk++) {
if ((chnk == 6) && (trk_block.nVertices <= trk_block.nHiResVert))
continue;
LPPOLYGONDATA poly_chunk = polygon_block.poly[chnk];
for (uint32_t k = 0; k < polygon_block.sz[chnk]; k++) {
TEXTUREBLOCK texture_for_block = track->texture[poly_chunk[k].texture];
Texture gl_texture = track->textures[texture_for_block.texture];
glm::vec3 normal = rotationMatrix *
CalculateQuadNormal(PointToVec(trk_block.vert[poly_chunk[k].vertex[0]]),
PointToVec(trk_block.vert[poly_chunk[k].vertex[1]]),
PointToVec(trk_block.vert[poly_chunk[k].vertex[2]]),
PointToVec(trk_block.vert[poly_chunk[k].vertex[3]]));
norms.emplace_back(normal);
norms.emplace_back(normal);
norms.emplace_back(normal);
norms.emplace_back(normal);
norms.emplace_back(normal);
norms.emplace_back(normal);
vertex_indices.emplace_back(poly_chunk[k].vertex[0]);
vertex_indices.emplace_back(poly_chunk[k].vertex[1]);
vertex_indices.emplace_back(poly_chunk[k].vertex[2]);
vertex_indices.emplace_back(poly_chunk[k].vertex[0]);
vertex_indices.emplace_back(poly_chunk[k].vertex[2]);
vertex_indices.emplace_back(poly_chunk[k].vertex[3]);
std::vector<glm::vec2> transformedUVs = GenerateUVs(NFS_3, chnk == 6 ? LANE : ROAD,
poly_chunk[k].hs_texflags, gl_texture,
texture_for_block);
uvs.insert(uvs.end(), transformedUVs.begin(), transformedUVs.end());
texture_indices.emplace_back(texture_for_block.texture);
texture_indices.emplace_back(texture_for_block.texture);
texture_indices.emplace_back(texture_for_block.texture);
texture_indices.emplace_back(texture_for_block.texture);
texture_indices.emplace_back(texture_for_block.texture);
texture_indices.emplace_back(texture_for_block.texture);
accumulatedObjectFlags |= poly_chunk[k].flags;
}
if (chnk == 6) {
current_track_block.lanes.emplace_back(Entity(i, -1, NFS_3, LANE,
Track(verts, norms, uvs, texture_indices, vertex_indices,
trk_block_shading_verts, trk_block_center),
accumulatedObjectFlags));
} else {
current_track_block.track.emplace_back(Entity(i, -1, NFS_3, ROAD,
Track(verts, norms, uvs, texture_indices, vertex_indices,
trk_block_shading_verts, trk_block_center),
accumulatedObjectFlags));
}
}
track_blocks.emplace_back(current_track_block);
}
return track_blocks;
}
std::vector<Entity> NFS3::ParseCOLModels(const std::shared_ptr<TRACK> &track) {
LOG(INFO) << "Parsing COL file into ONFS GL structures";
std::vector<Entity> col_entities;
glm::quat rotationMatrix = glm::normalize(glm::quat(glm::vec3(-SIMD_PI / 2, 0,
0))); // All Vertices are stored so that the model is rotated 90 degs on X. Remove this at Vert load time.
COLOBJECT *o = track->col.object;
/* COL DATA - TODO: Come back for VROAD AI/Collision data */
for (uint32_t i = 0; i < track->col.objectHead.nrec; i++, o++) {
COLSTRUCT3D s = track->col.struct3D[o->struct3D];
std::vector<unsigned int> indices;
std::vector<glm::vec2> uvs;
std::vector<unsigned int> texture_indices;
std::vector<glm::vec3> verts;
std::vector<glm::vec4> shading_data;
std::vector<glm::vec3> norms;
for (uint32_t j = 0; j < s.nVert; j++, s.vertex++) {
verts.emplace_back(
rotationMatrix * glm::vec3(s.vertex->pt.x / 10, s.vertex->pt.y / 10, s.vertex->pt.z / 10));
shading_data.emplace_back(glm::vec4(1.0, 1.0f, 1.0f, 1.0f));
}
for (uint32_t k = 0; k < s.nPoly; k++, s.polygon++) {
// Remap the COL TextureID's using the COL texture block (XBID2)
COLTEXTUREINFO col_texture = track->col.texture[s.polygon->texture];
TEXTUREBLOCK texture_for_block;
// Find the texture by it's file name, but use the Texture table to get the block. TODO: Not mapping this so, must do a manual search.
for (uint32_t t = 0; t < track->nTextures; t++) {
if (track->texture[t].texture == col_texture.texture) {
texture_for_block = track->texture[t];
}
}
Texture gl_texture = track->textures[texture_for_block.texture];
indices.emplace_back(s.polygon->v[0]);
indices.emplace_back(s.polygon->v[1]);
indices.emplace_back(s.polygon->v[2]);
indices.emplace_back(s.polygon->v[0]);
indices.emplace_back(s.polygon->v[2]);
indices.emplace_back(s.polygon->v[3]);
glm::vec3 normal = rotationMatrix * CalculateQuadNormal(PointToVec(verts[s.polygon->v[0]]),
PointToVec(verts[s.polygon->v[1]]),
PointToVec(verts[s.polygon->v[2]]),
PointToVec(verts[s.polygon->v[3]]));
norms.emplace_back(normal);
norms.emplace_back(normal);
norms.emplace_back(normal);
norms.emplace_back(normal);
norms.emplace_back(normal);
norms.emplace_back(normal);
uvs.emplace_back(texture_for_block.corners[0] * gl_texture.max_u,
(1.0f - texture_for_block.corners[1]) * gl_texture.max_v);
uvs.emplace_back(texture_for_block.corners[2] * gl_texture.max_u,
(1.0f - texture_for_block.corners[3]) * gl_texture.max_v);
uvs.emplace_back(texture_for_block.corners[4] * gl_texture.max_u,
(1.0f - texture_for_block.corners[5]) * gl_texture.max_v);
uvs.emplace_back(texture_for_block.corners[0] * gl_texture.max_u,
(1.0f - texture_for_block.corners[1]) * gl_texture.max_v);
uvs.emplace_back(texture_for_block.corners[4] * gl_texture.max_u,
(1.0f - texture_for_block.corners[5]) * gl_texture.max_v);
uvs.emplace_back(texture_for_block.corners[6] * gl_texture.max_u,
(1.0f - texture_for_block.corners[7]) * gl_texture.max_v);
texture_indices.emplace_back(texture_for_block.texture);
texture_indices.emplace_back(texture_for_block.texture);
texture_indices.emplace_back(texture_for_block.texture);
texture_indices.emplace_back(texture_for_block.texture);
texture_indices.emplace_back(texture_for_block.texture);
texture_indices.emplace_back(texture_for_block.texture);
}
glm::vec3 position = rotationMatrix * glm::vec3(static_cast<float>(o->ptRef.x / 65536.0) / 10,
static_cast<float>(o->ptRef.y / 65536.0) / 10,
static_cast<float>(o->ptRef.z / 65536.0) / 10);
col_entities.emplace_back(Entity(-1, i, NFS_3, GLOBAL,
Track(verts, norms, uvs, texture_indices, indices, shading_data, position)));
}
return col_entities;
}
Texture NFS3::LoadTexture(TEXTUREBLOCK track_texture, const std::string &track_name) {
std::stringstream filename;
std::stringstream filename_alpha;
if (track_texture.islane) {
filename << "../resources/sfx/" << std::setfill('0') << std::setw(4) << track_texture.texture + 9 << ".BMP";
filename_alpha << "../resources/sfx/" << std::setfill('0') << std::setw(4) << track_texture.texture + 9 << "-a.BMP";
} else {
filename << TRACK_PATH << ToString(NFS_3) << "/" << track_name << "/textures/" << std::setfill('0') << std::setw(4)
<< track_texture.texture << ".BMP";
filename_alpha << TRACK_PATH << ToString(NFS_3) << "/" << track_name << "/textures/" << std::setfill('0') << std::setw(4)
<< track_texture.texture << "-a.BMP";
}
GLubyte *data;
GLsizei width = track_texture.width;
GLsizei height = track_texture.height;
if (!ImageLoader::LoadBmpWithAlpha(filename.str().c_str(), filename_alpha.str().c_str(), &data, &width, &height)) {
LOG(WARNING) << "Texture " << filename.str() << " or " << filename_alpha.str() << " did not load succesfully!";
// If the texture is missing, load a "MISSING" texture of identical size.
ASSERT(ImageLoader::LoadBmpWithAlpha("../resources/misc/missing.bmp", "../resources/misc/missing-a.bmp", &data,
&width, &height), "Even the 'missing' texture is missing!");
return Texture((unsigned int) track_texture.texture, data, static_cast<unsigned int>(width),
static_cast<unsigned int>(height));
}
return Texture((unsigned int) track_texture.texture, data, static_cast<unsigned int>(track_texture.width),
static_cast<unsigned int>(track_texture.height));
}
void NFS3::FreeFRD(const std::shared_ptr<TRACK> &track) {
// Free FRD data
// TRKBLOCKs
for (uint32_t block_Idx = 0; block_Idx < track->nBlocks; block_Idx++) {
TRKBLOCK *trackBlock = &(track->trk[block_Idx]);
delete[]trackBlock->vert;
delete[]trackBlock->unknVertices;
delete[]trackBlock->posData;
delete[] trackBlock->polyData;
delete[] trackBlock->vroadData;
if (trackBlock->nXobj > 0) {
delete[]trackBlock->xobj;
}
if (trackBlock->nSoundsrc > 0) {
delete[]trackBlock->soundsrc;
}
if (trackBlock->nLightsrc > 0) {
delete[]trackBlock->lightsrc;
}
//delete trackBlock;
}
//delete []track->trk;
// POLYGONBLOCKs
for (uint32_t block_Idx = 0; block_Idx < track->nBlocks; block_Idx++) {
POLYGONBLOCK *p = &(track->poly[block_Idx]);
for (uint32_t j = 0; j < 7; j++) {
if (p->sz[j] != 0) {
free(p->poly[j]);
}
}
for (uint32_t obj_Idx = 0; obj_Idx < 4; obj_Idx++) {
OBJPOLYBLOCK *o = &(p->obj[obj_Idx]);
if (o->n1 > 0) {
delete[]o->types;
delete[]o->numpoly;
for (uint32_t k = 0; k < o->n2; k++) {
if (o->types[k] == 1) {
// free(o->poly[o->nobj]);
}
}
}
}
}
// XOBJBLOCKs
for (uint32_t xblock_Idx = 0; xblock_Idx <= 4 * track->nBlocks; xblock_Idx++) {
if (track->xobj[xblock_Idx].nobj > 0) {
delete[]track->xobj[xblock_Idx].obj;
}
for (uint32_t xobj_Idx = 0; xobj_Idx < track->xobj[xblock_Idx].nobj; xobj_Idx++) {
XOBJDATA *x = &(track->xobj[xblock_Idx].obj[xobj_Idx]);
if (x->crosstype == 3) { // animated objects
delete[]x->animData;
}
//delete[]x->vert;
delete[]x->unknVertices;
delete[]x->polyData;
//delete x;
}
}
// TEXTUREBLOCKs
delete[]track->texture;
delete[]track->trk;
delete[]track->poly;
delete[]track->xobj;
}
void NFS3::FreeCOL(const std::shared_ptr<TRACK> &track) {
// Free COL Data
delete[]track->col.texture;
// struct3D XB
if (track->col.nBlocks >= 4) {
COLSTRUCT3D *s = track->col.struct3D;
for (uint32_t colRec_Idx = 0; colRec_Idx < track->col.struct3DHead.nrec; colRec_Idx++, s++) {
delete[]s->vertex;
delete[]s->polygon;
}
delete[] track->col.struct3D;
// Object XB
COLOBJECT *o = track->col.object;
for (uint32_t colRec_Idx = 0; colRec_Idx < track->col.objectHead.nrec; colRec_Idx++, o++) {
if (o->type == 3) {
delete[]o->animData;
}
}
delete[]track->col.object;
}
// object2 XB
if (track->col.nBlocks == 5) {
COLOBJECT *o = track->col.object2;
for (uint32_t colRec_Idx = 0; colRec_Idx < track->col.object2Head.nrec; colRec_Idx++, o++) {
if (o->type == 3) {
delete[]o->animData;
}
}
delete[]track->col.object2;
}
delete track->col.vroad;
}
| 49.963074 | 223 | 0.561113 | [
"mesh",
"geometry",
"object",
"vector",
"model"
] |
edc72a9f57be62263e28934fc07c981ae5f93842 | 1,916 | hpp | C++ | include/note.hpp | Terodom/termNote | d4165a4897af74f06c443f4c27f126f36d5caaf2 | [
"MIT"
] | 3 | 2019-01-19T20:49:06.000Z | 2019-01-20T07:36:47.000Z | include/note.hpp | Terodom/termNote | d4165a4897af74f06c443f4c27f126f36d5caaf2 | [
"MIT"
] | 13 | 2019-01-20T10:39:02.000Z | 2019-01-30T19:31:55.000Z | include/note.hpp | Terodom/termNote | d4165a4897af74f06c443f4c27f126f36d5caaf2 | [
"MIT"
] | 3 | 2018-11-27T17:41:38.000Z | 2019-01-23T14:48:19.000Z | #pragma once
#define GCC_VERSION (__GNUC__ * 10000 \
+ __GNUC_MINOR__ * 100 \
+ __GNUC_PATCHLEVEL__)
#if GCC_VERSION < 80000
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
#else
#include <filesystem>
namespace fs = std::filesystem;
#endif
#include <memory>
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib> /* getenv */
#include <vector>
#include "./config.hpp"
#define HOME std::getenv("HOME")
#define XDG_CONFIG_HOME std::getenv("XDG_CONFIG_HOME")
#define XDG_DATA_HOME std::getenv("XDG_DATA_HOME")
class todoTxtNote {
private:
static tm * parseTime(std::string s, const char* format);
std::vector<std::string> words;
public:
bool completed = false;
char priority = 'z';
tm * createdAt = nullptr;
tm * completedAt = nullptr;
std::string description;
std::string toString();
std::vector<std::vector<tm>> getNotificationSpecs();
std::vector<std::string> getProjects(), getContexts();
todoTxtNote(std::string raw);
~todoTxtNote();
};
class Note {
private:
// Filestreams
std::fstream noteStream;
std::fstream tempStream;
// Files and Directories
std::string configDir = XDG_CONFIG_HOME ? std::string(XDG_CONFIG_HOME) + "/termNote/" : std::string(HOME) + "/.config/termNote/";
std::string noteDir = XDG_DATA_HOME ? std::string(XDG_DATA_HOME) + "/termNote/" : std::string(HOME) + "/.termNote/";
std::string tempFile = noteDir + "tempNotes";
std::string file = noteDir + "notes";
std::string configFile = configDir + "config";
std::string line;
public:
Note();
~Note();
void add(char* note);
void del(std::vector<int> numbers);
void list(bool show_completed);
void show(int n);
void complete(int n);
std::vector<todoTxtNote> getList();
};
| 26.985915 | 133 | 0.644572 | [
"vector"
] |
edc7d58bc6f93903889c6e91d280031c80bf387d | 3,121 | cpp | C++ | src/algorithm/algorithm.cpp | AALEKH/hpx-dataflow | 5fe19bad51f2bbf7161ca79f005f04f53133ba3d | [
"BSL-1.0"
] | 4 | 2016-12-26T06:24:09.000Z | 2020-10-06T23:48:22.000Z | src/algorithm/algorithm.cpp | AALEKH/hpx-dataflow | 5fe19bad51f2bbf7161ca79f005f04f53133ba3d | [
"BSL-1.0"
] | 18 | 2016-06-15T11:06:49.000Z | 2016-08-18T12:58:51.000Z | src/algorithm/algorithm.cpp | AALEKH/hpx-dataflow | 5fe19bad51f2bbf7161ca79f005f04f53133ba3d | [
"BSL-1.0"
] | 1 | 2016-08-17T13:48:59.000Z | 2016-08-17T13:48:59.000Z | ////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2016 Aalekh Nigam
//
// 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)
////////////////////////////////////////////////////////////////////////////////
/**
* @file algorithm.h
* @author Aalekh Nigam
* @brief This file contains some fundamental helper algorithm for the help of library users
*/
#include <regex>
#include <map>
#include <array>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <math.h>
#include <iostream>
#include <vector>
#include <string>
#include <list>
#include <limits>
#include <set>
#include <utility>
#include <algorithm>
#include <iterator>
#include "algorithm.h"
/**
* @brief Wrapper for dynamic function execution.
* returns fluent interface onject, used just to execute the function
* @param fn
*
*/
template < typename T >
hpx::flow::Algorithm & hpx::flow::Algorithm::dymcFunc (T fn)
{
fn (buffer);
return *this;
}
/**
* @brief Comparator operator between two data types
* returns the boolean value for denoting if the two are equal
* @param first_value
* @param second_value
*/
template < typename T >
bool hpx::flow::Algorithm::equal (const T & first_value,
const T & second_value)
{
return first_value == second_value;
}
/**
* Checks for the greater value, for ex: s > c
* returns the boolean value for denoting if first value is greater than the second
* @param first_value
* @param second_value
*/
template < typename T >
bool hpx::flow::Algorithm::grt (const T & first_value,
const T & second_value)
{
return first_value > second_value;
}
/**
* @brief Checks for the greater value, for ex: s < c
* returns the boolean value for denoting if first value is smaller than the second
* @param first_value
* @param second_value
*/
template < typename T >
bool hpx::flow::Algorithm::lst (const T & first_value,
const T & second_value)
{
return first_value < second_value;
}
/**
* @brief Checks for the greater value, for ex: s >= c
* returns the boolean value for denoting if first value is greater than or equal to the second
* @param first_value
* @param second_value
*/
template < typename T >
bool hpx::flow::Algorithm::grt_equal (const T & first_value,
const T & second_value)
{
return first_value >= second_value;
}
/**
* @brief Checks for the greater value, for ex: s =< c
* returns the boolean value for denoting if first value is less than or equal to the second
* @param first_value
* @param second_value
*/
template < typename T >
bool hpx::flow::Algorithm::lst_equal (const T & first_value,
const T & second_value)
{
return first_value <= second_value;
}
/**
* @brief Summation of two values
* returns sum of the two parameters
* @param first_value
* @param second_value
*/
// template<typename T>
// T const& hpx::flow::Algorithm::summation(const T &first_value, const T &second_value) {
// return first_value + second_value;
// }
| 24.007692 | 95 | 0.665812 | [
"vector"
] |
edcbc5067c50f974f0a65102cdb3a127b0c92126 | 1,244 | cpp | C++ | problems/016.3Sum_Closest/AC_two_points_n2.cpp | subramp-prep/leetcode | d125201d9021ab9b1eea5e5393c2db4edd84e740 | [
"Unlicense"
] | null | null | null | problems/016.3Sum_Closest/AC_two_points_n2.cpp | subramp-prep/leetcode | d125201d9021ab9b1eea5e5393c2db4edd84e740 | [
"Unlicense"
] | null | null | null | problems/016.3Sum_Closest/AC_two_points_n2.cpp | subramp-prep/leetcode | d125201d9021ab9b1eea5e5393c2db4edd84e740 | [
"Unlicense"
] | null | null | null | /*
* Author: illuz <iilluzen[at]gmail.com>
* File: AC_two_points_n2.cpp
* Create Date: 2015-01-10 13:47:11
* Descripton: Just like 3Sum.
*/
#include <bits/stdc++.h>
using namespace std;
const int N = 0;
class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
int ret = num[0] + num[1] + num[2];
int len = num.size();
sort(num.begin(), num.end());
for (int i = 0; i <= len - 3; i++) {
// first number : num[i]
int j = i + 1; // second number
int k = len - 1; // third number
while (j < k) {
int sum = num[i] + num[j] + num[k];
if (abs(sum - target) < abs(ret - target))
ret = sum;
if (sum < target) {
++j;
} else if (sum > target) {
--k;
} else {
++j;
--k;
}
}
}
return ret;
}
};
int main() {
vector<int> num;
int n, tar;
cin >> tar;
while (~scanf("%d", &n))
num.push_back(n);
Solution s;
cout << s.threeSumClosest(num, tar) << endl;
return 0;
}
| 23.037037 | 58 | 0.415595 | [
"vector"
] |
edd8ee35cb460e8372ff363aa123545483f94550 | 5,084 | cpp | C++ | inference-engine/src/low_precision_transformations/src/fuse_subtract_to_fake_quantize.cpp | hanchengyao/openvino | 81c8cd711bb9f8dc48e5f288e77dc0d80cedebd8 | [
"Apache-2.0"
] | 1 | 2021-12-30T05:47:43.000Z | 2021-12-30T05:47:43.000Z | inference-engine/src/low_precision_transformations/src/fuse_subtract_to_fake_quantize.cpp | hanchengyao/openvino | 81c8cd711bb9f8dc48e5f288e77dc0d80cedebd8 | [
"Apache-2.0"
] | 42 | 2020-11-23T08:09:57.000Z | 2022-02-21T13:03:34.000Z | inference-engine/src/low_precision_transformations/src/fuse_subtract_to_fake_quantize.cpp | tsocha/openvino | 3081fac7581933568b496a3c4e744d1cee481619 | [
"Apache-2.0"
] | 2 | 2020-09-08T17:12:23.000Z | 2021-12-21T07:58:09.000Z | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "low_precision/fuse_subtract_to_fake_quantize.hpp"
#include <memory>
#include <ngraph/ngraph.hpp>
#include <ngraph/pattern/op/wrap_type.hpp>
#include "low_precision/fake_quantize.hpp"
#include "low_precision/network_helper.hpp"
namespace ngraph {
namespace pass {
namespace low_precision {
NGRAPH_RTTI_DEFINITION(ngraph::pass::low_precision::FuseSubtractToFakeQuantizeTransformation, "FuseSubtractToFakeQuantizeTransformation", 0);
FuseSubtractToFakeQuantizeTransformation::FuseSubtractToFakeQuantizeTransformation(const Params& params) : LayerTransformation(params) {
auto matcher = pattern::wrap_type<opset1::Subtract>();
ngraph::graph_rewrite_callback callback = [this](pattern::Matcher& m) {
auto op = m.get_match_root();
if (transformation_callback(op)) {
return false;
}
return transform(*context, m);
};
auto m = std::make_shared<ngraph::pattern::Matcher>(matcher, "FuseSubtractToFakeQuantizeTransformation");
this->register_matcher(m, callback);
}
bool FuseSubtractToFakeQuantizeTransformation::transform(TransformationContext& context, ngraph::pattern::Matcher &m) {
const auto subtract = m.get_match_root();
if (!canBeTransformed(context, subtract)) {
return false;
}
const auto parent = subtract->get_input_node_shared_ptr(0);
auto fakeQuantize = ov::as_type_ptr<opset1::FakeQuantize>(parent);
const auto convert = ov::as_type_ptr<opset1::Convert>(parent);
if (convert) {
fakeQuantize = ov::as_type_ptr<opset1::FakeQuantize>(convert->get_input_node_shared_ptr(0));
}
const auto subtractConstant = subtract->get_input_node_shared_ptr(1);
auto outputLowConst_f32 = foldConvert(fakeQuantize->get_input_node_shared_ptr(3), deqPrecision);
auto outputHighConst_f32 = foldConvert(fakeQuantize->get_input_node_shared_ptr(4), deqPrecision);
const auto value = subtractConstant->get_output_element_type(0) == element::f32 ?
subtractConstant :
foldConvert(subtractConstant, deqPrecision);
outputLowConst_f32 = fold<opset1::Subtract>(outputLowConst_f32, value);
outputHighConst_f32 = fold<opset1::Subtract>(outputHighConst_f32, value);
const auto fakeQuantizeParent = fakeQuantize->get_input_node_shared_ptr(0);
const size_t parentIndex = NetworkHelper::getParentOutputIndex(fakeQuantizeParent, fakeQuantize);
const auto inputLow = foldConvert(fakeQuantize->input_value(1), deqPrecision);
const auto inputHigh = foldConvert(fakeQuantize->input_value(2), deqPrecision);
NetworkHelper::copyInfo(fakeQuantize->get_input_node_shared_ptr(1), inputLow);
NetworkHelper::copyInfo(fakeQuantize->get_input_node_shared_ptr(2), inputHigh);
NetworkHelper::copyInfo(fakeQuantize->get_input_node_shared_ptr(3), outputLowConst_f32);
NetworkHelper::copyInfo(fakeQuantize->get_input_node_shared_ptr(4), outputHighConst_f32);
auto newFakeQuantize = std::make_shared<op::TypeRelaxed<opset1::FakeQuantize>>(
opset1::FakeQuantize(
fakeQuantizeParent->output(parentIndex),
inputLow,
inputHigh,
outputLowConst_f32,
outputHighConst_f32,
fakeQuantize->get_levels()),
subtract->get_output_element_type(0));
replace_node(subtract, newFakeQuantize);
NetworkHelper::copyInfo(fakeQuantize, newFakeQuantize);
updateOutput(context, newFakeQuantize, subtract);
return true;
}
bool FuseSubtractToFakeQuantizeTransformation::canBeTransformed(const TransformationContext& context, std::shared_ptr<Node> operation) const {
if (!ov::is_type<opset1::Constant>(operation->get_input_node_shared_ptr(1))) {
return false;
}
if (!FakeQuantizeTransformation::checkElementwise(operation)) {
return false;
}
const auto children = operation->get_output_target_inputs(0);
for (const auto& target : children) {
const auto convolution = ov::is_type<opset1::Convolution>(target.get_node());
const auto groupConvolution = ov::is_type<opset1::GroupConvolution>(target.get_node());
const auto convolutionBackpropData = ov::is_type<opset1::ConvolutionBackpropData>(target.get_node());
if (convolution || groupConvolution || convolutionBackpropData) {
return false;
}
}
const auto parent = operation->get_input_node_shared_ptr(0);
auto fq = ov::as_type_ptr<opset1::FakeQuantize>(parent);
const auto convert = ov::as_type_ptr<opset1::Convert>(parent);
if (convert) {
fq = ov::as_type_ptr<opset1::FakeQuantize>(convert->get_input_node_shared_ptr(0));
}
if (!fq) {
return false;
}
if (fq->get_output_target_inputs(0).size() != 1) {
return false;
}
return true;
}
bool FuseSubtractToFakeQuantizeTransformation::isPrecisionPreserved(std::shared_ptr<Node> layer) const noexcept {
return false;
}
} // namespace low_precision
} // namespace pass
} // namespace ngraph
| 38.515152 | 142 | 0.730724 | [
"transform"
] |
edd9fe2e290821460ab6f91e9604a217526dd057 | 1,341 | cpp | C++ | Communication/TextualSearchResultsImpl.cpp | Dudi119/SearchYA | a3468dedcd3fc8d63350a2c79b16b6949fdc7e41 | [
"MIT"
] | 5 | 2017-08-29T15:33:16.000Z | 2020-12-09T08:34:02.000Z | Communication/TextualSearchResultsImpl.cpp | Dudi119/MesosBenchMark | a3468dedcd3fc8d63350a2c79b16b6949fdc7e41 | [
"MIT"
] | 1 | 2017-09-26T11:44:01.000Z | 2017-09-27T06:40:01.000Z | Communication/TextualSearchResultsImpl.cpp | Dudi119/MesosBenchMark | a3468dedcd3fc8d63350a2c79b16b6949fdc7e41 | [
"MIT"
] | 2 | 2017-08-19T04:41:16.000Z | 2020-07-21T17:38:16.000Z | #include "TextualSearchResultsImpl.h"
#include "ITextualSearchService.h"
using namespace std;
TextualSearchResultsImpl::TextualSearchResultsImpl(grpc::ServerCompletionQueue& completionQueue, ITextualSearchService& consumer):
m_completionQueue(completionQueue), m_consumer(consumer){
m_service = shared_ptr<grpc::Service>(new TextualSearchResultsAsyncService());
m_responder.reset(new Responder(&m_serverContex));
}
void TextualSearchResultsImpl::Connect(void* tag) {
TextualSearchResultsAsyncService& service = static_cast<TextualSearchResultsAsyncService&>(*m_service);
service.RequestGetTopKDocuments(&m_serverContex, &m_request, m_responder.get(), &m_completionQueue,
&m_completionQueue, tag);
m_state = AsyncService::State ::NotConnected;
}
void TextualSearchResultsImpl::Invoke(void *tag) {
m_state = AsyncService::State::Connected;
int k = m_request.k();
string word = m_request.word();
m_consumer.GetTopKDocuments(word, k, this);
}
void TextualSearchResultsImpl::ProvideResult(const vector<string>& documentsNames){
::TextualSearchResultsService::TopKDocumentsReply reply;
for(const string& documentName : documentsNames)
reply.add_documentname(documentName);
m_responder->Finish(reply, grpc::Status::OK, this);
m_state = AsyncService::State::Completed;
}
| 39.441176 | 130 | 0.773304 | [
"vector"
] |
ede5700d86bb6175540e588394ac619767bccc5c | 44,954 | cc | C++ | tests/third_party/poppler/utils/HtmlOutputDev.cc | albertobarri/idk | a250884f79e2a484251fc750bb915ecbc962be58 | [
"MIT"
] | 9,724 | 2015-01-01T02:06:30.000Z | 2019-01-17T15:13:51.000Z | tests/third_party/poppler/utils/HtmlOutputDev.cc | albertobarri/idk | a250884f79e2a484251fc750bb915ecbc962be58 | [
"MIT"
] | 7,584 | 2019-01-17T22:58:27.000Z | 2022-03-31T23:10:22.000Z | tests/third_party/poppler/utils/HtmlOutputDev.cc | albertobarri/idk | a250884f79e2a484251fc750bb915ecbc962be58 | [
"MIT"
] | 1,519 | 2015-01-01T18:11:12.000Z | 2019-01-17T14:16:02.000Z | //========================================================================
//
// HtmlOutputDev.cc
//
// Copyright 1997-2002 Glyph & Cog, LLC
//
// Changed 1999-2000 by G.Ovtcharov
//
// Changed 2002 by Mikhail Kruk
//
//========================================================================
//========================================================================
//
// Modified under the Poppler project - http://poppler.freedesktop.org
//
// All changes made under the Poppler project to this file are licensed
// under GPL version 2 or later
//
// Copyright (C) 2005-2010 Albert Astals Cid <aacid@kde.org>
// Copyright (C) 2008 Kjartan Maraas <kmaraas@gnome.org>
// Copyright (C) 2008 Boris Toloknov <tlknv@yandex.ru>
// Copyright (C) 2008 Haruyuki Kawabe <Haruyuki.Kawabe@unisys.co.jp>
// Copyright (C) 2008 Tomas Are Haavet <tomasare@gmail.com>
// Copyright (C) 2009 Warren Toomey <wkt@tuhs.org>
// Copyright (C) 2009 Carlos Garcia Campos <carlosgc@gnome.org>
// Copyright (C) 2009 Reece Dunn <msclrhd@gmail.com>
// Copyright (C) 2010 Adrian Johnson <ajohnson@redneon.com>
// Copyright (C) 2010 Hib Eris <hib@hiberis.nl>
// Copyright (C) 2010 OSSD CDAC Mumbai by Leena Chourey (leenac@cdacmumbai.in) and Onkar Potdar (onkar@cdacmumbai.in)
//
// To see a description of the changes please see the Changelog file that
// came with your tarball or type make ChangeLog if you are building from git
//
//========================================================================
#ifdef __GNUC__
#pragma implementation
#endif
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stddef.h>
#include <ctype.h>
#include <math.h>
#include "goo/GooString.h"
#include "goo/GooList.h"
#include "UnicodeMap.h"
#include "goo/gmem.h"
#include "Error.h"
#include "GfxState.h"
#include "Page.h"
#include "PNGWriter.h"
#ifdef ENABLE_LIBJPEG
#include "DCTStream.h"
#endif
#include "GlobalParams.h"
#include "HtmlOutputDev.h"
#include "HtmlFonts.h"
int HtmlPage::pgNum=0;
int HtmlOutputDev::imgNum=1;
GooList *HtmlOutputDev::imgList=new GooList();
extern GBool complexMode;
extern GBool singleHtml;
extern GBool ignore;
extern GBool printCommands;
extern GBool printHtml;
extern GBool noframes;
extern GBool stout;
extern GBool xml;
extern GBool showHidden;
extern GBool noMerge;
static GooString* basename(GooString* str){
char *p=str->getCString();
int len=str->getLength();
for (int i=len-1;i>=0;i--)
if (*(p+i)==SLASH)
return new GooString((p+i+1),len-i-1);
return new GooString(str);
}
#if 0
static GooString* Dirname(GooString* str){
char *p=str->getCString();
int len=str->getLength();
for (int i=len-1;i>=0;i--)
if (*(p+i)==SLASH)
return new GooString(p,i+1);
return new GooString();
}
#endif
//------------------------------------------------------------------------
// HtmlString
//------------------------------------------------------------------------
HtmlString::HtmlString(GfxState *state, double fontSize, HtmlFontAccu* fonts) {
GfxFont *font;
double x, y;
state->transform(state->getCurX(), state->getCurY(), &x, &y);
if ((font = state->getFont())) {
double ascent = font->getAscent();
double descent = font->getDescent();
if( ascent > 1.05 ){
//printf( "ascent=%.15g is too high, descent=%.15g\n", ascent, descent );
ascent = 1.05;
}
if( descent < -0.4 ){
//printf( "descent %.15g is too low, ascent=%.15g\n", descent, ascent );
descent = -0.4;
}
yMin = y - ascent * fontSize;
yMax = y - descent * fontSize;
GfxRGB rgb;
state->getFillRGB(&rgb);
GooString *name = state->getFont()->getName();
if (!name) name = HtmlFont::getDefaultFont(); //new GooString("default");
HtmlFont hfont=HtmlFont(name, static_cast<int>(fontSize-1), rgb);
fontpos = fonts->AddFont(hfont);
} else {
// this means that the PDF file draws text without a current font,
// which should never happen
yMin = y - 0.95 * fontSize;
yMax = y + 0.35 * fontSize;
fontpos=0;
}
if (yMin == yMax) {
// this is a sanity check for a case that shouldn't happen -- but
// if it does happen, we want to avoid dividing by zero later
yMin = y;
yMax = y + 1;
}
col = 0;
text = NULL;
xRight = NULL;
link = NULL;
len = size = 0;
yxNext = NULL;
xyNext = NULL;
htext=new GooString();
dir = textDirUnknown;
}
HtmlString::~HtmlString() {
gfree(text);
delete htext;
gfree(xRight);
}
void HtmlString::addChar(GfxState *state, double x, double y,
double dx, double dy, Unicode u) {
if (dir == textDirUnknown) {
//dir = UnicodeMap::getDirection(u);
dir = textDirLeftRight;
}
if (len == size) {
size += 16;
text = (Unicode *)grealloc(text, size * sizeof(Unicode));
xRight = (double *)grealloc(xRight, size * sizeof(double));
}
text[len] = u;
if (len == 0) {
xMin = x;
}
xMax = xRight[len] = x + dx;
//printf("added char: %f %f xright = %f\n", x, dx, x+dx);
++len;
}
void HtmlString::endString()
{
if( dir == textDirRightLeft && len > 1 )
{
//printf("will reverse!\n");
for (int i = 0; i < len / 2; i++)
{
Unicode ch = text[i];
text[i] = text[len - i - 1];
text[len - i - 1] = ch;
}
}
}
//------------------------------------------------------------------------
// HtmlPage
//------------------------------------------------------------------------
HtmlPage::HtmlPage(GBool rawOrder, char *imgExtVal) {
this->rawOrder = rawOrder;
curStr = NULL;
yxStrings = NULL;
xyStrings = NULL;
yxCur1 = yxCur2 = NULL;
fonts=new HtmlFontAccu();
links=new HtmlLinks();
pageWidth=0;
pageHeight=0;
fontsPageMarker = 0;
DocName=NULL;
firstPage = -1;
imgExt = new GooString(imgExtVal);
}
HtmlPage::~HtmlPage() {
clear();
if (DocName) delete DocName;
if (fonts) delete fonts;
if (links) delete links;
if (imgExt) delete imgExt;
}
void HtmlPage::updateFont(GfxState *state) {
GfxFont *font;
double *fm;
char *name;
int code;
double w;
// adjust the font size
fontSize = state->getTransformedFontSize();
if ((font = state->getFont()) && font->getType() == fontType3) {
// This is a hack which makes it possible to deal with some Type 3
// fonts. The problem is that it's impossible to know what the
// base coordinate system used in the font is without actually
// rendering the font. This code tries to guess by looking at the
// width of the character 'm' (which breaks if the font is a
// subset that doesn't contain 'm').
for (code = 0; code < 256; ++code) {
if ((name = ((Gfx8BitFont *)font)->getCharName(code)) &&
name[0] == 'm' && name[1] == '\0') {
break;
}
}
if (code < 256) {
w = ((Gfx8BitFont *)font)->getWidth(code);
if (w != 0) {
// 600 is a generic average 'm' width -- yes, this is a hack
fontSize *= w / 0.6;
}
}
fm = font->getFontMatrix();
if (fm[0] != 0) {
fontSize *= fabs(fm[3] / fm[0]);
}
}
}
void HtmlPage::beginString(GfxState *state, GooString *s) {
curStr = new HtmlString(state, fontSize, fonts);
}
void HtmlPage::conv(){
HtmlString *tmp;
int linkIndex = 0;
HtmlFont* h;
for(tmp=yxStrings;tmp;tmp=tmp->yxNext){
int pos=tmp->fontpos;
// printf("%d\n",pos);
h=fonts->Get(pos);
if (tmp->htext) delete tmp->htext;
tmp->htext=HtmlFont::simple(h,tmp->text,tmp->len);
if (links->inLink(tmp->xMin,tmp->yMin,tmp->xMax,tmp->yMax, linkIndex)){
tmp->link = links->getLink(linkIndex);
/*GooString *t=tmp->htext;
tmp->htext=links->getLink(k)->Link(tmp->htext);
delete t;*/
}
}
}
void HtmlPage::addChar(GfxState *state, double x, double y,
double dx, double dy,
double ox, double oy, Unicode *u, int uLen) {
double x1, y1, w1, h1, dx2, dy2;
int n, i;
state->transform(x, y, &x1, &y1);
n = curStr->len;
// check that new character is in the same direction as current string
// and is not too far away from it before adding
//if ((UnicodeMap::getDirection(u[0]) != curStr->dir) ||
// XXX
if (
(n > 0 &&
fabs(x1 - curStr->xRight[n-1]) > 0.1 * (curStr->yMax - curStr->yMin))) {
endString();
beginString(state, NULL);
}
state->textTransformDelta(state->getCharSpace() * state->getHorizScaling(),
0, &dx2, &dy2);
dx -= dx2;
dy -= dy2;
state->transformDelta(dx, dy, &w1, &h1);
if (uLen != 0) {
w1 /= uLen;
h1 /= uLen;
}
for (i = 0; i < uLen; ++i) {
curStr->addChar(state, x1 + i*w1, y1 + i*h1, w1, h1, u[i]);
}
}
void HtmlPage::endString() {
HtmlString *p1, *p2;
double h, y1, y2;
// throw away zero-length strings -- they don't have valid xMin/xMax
// values, and they're useless anyway
if (curStr->len == 0) {
delete curStr;
curStr = NULL;
return;
}
curStr->endString();
#if 0 //~tmp
if (curStr->yMax - curStr->yMin > 20) {
delete curStr;
curStr = NULL;
return;
}
#endif
// insert string in y-major list
h = curStr->yMax - curStr->yMin;
y1 = curStr->yMin + 0.5 * h;
y2 = curStr->yMin + 0.8 * h;
if (rawOrder) {
p1 = yxCur1;
p2 = NULL;
} else if ((!yxCur1 ||
(y1 >= yxCur1->yMin &&
(y2 >= yxCur1->yMax || curStr->xMax >= yxCur1->xMin))) &&
(!yxCur2 ||
(y1 < yxCur2->yMin ||
(y2 < yxCur2->yMax && curStr->xMax < yxCur2->xMin)))) {
p1 = yxCur1;
p2 = yxCur2;
} else {
for (p1 = NULL, p2 = yxStrings; p2; p1 = p2, p2 = p2->yxNext) {
if (y1 < p2->yMin || (y2 < p2->yMax && curStr->xMax < p2->xMin))
break;
}
yxCur2 = p2;
}
yxCur1 = curStr;
if (p1)
p1->yxNext = curStr;
else
yxStrings = curStr;
curStr->yxNext = p2;
curStr = NULL;
}
static const char *strrstr( const char *s, const char *ss )
{
const char *p = strstr( s, ss );
for( const char *pp = p; pp != NULL; pp = strstr( p+1, ss ) ){
p = pp;
}
return p;
}
static void CloseTags( GooString *htext, GBool &finish_a, GBool &finish_italic, GBool &finish_bold )
{
const char *last_italic = finish_italic && ( finish_bold || finish_a ) ? strrstr( htext->getCString(), "<i>" ) : NULL;
const char *last_bold = finish_bold && ( finish_italic || finish_a ) ? strrstr( htext->getCString(), "<b>" ) : NULL;
const char *last_a = finish_a && ( finish_italic || finish_bold ) ? strrstr( htext->getCString(), "<a " ) : NULL;
if( finish_a && ( finish_italic || finish_bold ) && last_a > ( last_italic > last_bold ? last_italic : last_bold ) ){
htext->append("</a>", 4);
finish_a = false;
}
if( finish_italic && finish_bold && last_italic > last_bold ){
htext->append("</i>", 4);
finish_italic = false;
}
if( finish_bold )
htext->append("</b>", 4);
if( finish_italic )
htext->append("</i>", 4);
if( finish_a )
htext->append("</a>");
}
void HtmlPage::coalesce() {
HtmlString *str1, *str2;
HtmlFont *hfont1, *hfont2;
double space, horSpace, vertSpace, vertOverlap;
GBool addSpace, addLineBreak;
int n, i;
double curX, curY;
#if 0 //~ for debugging
for (str1 = yxStrings; str1; str1 = str1->yxNext) {
printf("x=%f..%f y=%f..%f size=%2d '",
str1->xMin, str1->xMax, str1->yMin, str1->yMax,
(int)(str1->yMax - str1->yMin));
for (i = 0; i < str1->len; ++i) {
fputc(str1->text[i] & 0xff, stdout);
}
printf("'\n");
}
printf("\n------------------------------------------------------------\n\n");
#endif
str1 = yxStrings;
if( !str1 ) return;
//----- discard duplicated text (fake boldface, drop shadows)
if( !complexMode )
{ /* if not in complex mode get rid of duplicate strings */
HtmlString *str3;
GBool found;
while (str1)
{
double size = str1->yMax - str1->yMin;
double xLimit = str1->xMin + size * 0.2;
found = gFalse;
for (str2 = str1, str3 = str1->yxNext;
str3 && str3->xMin < xLimit;
str2 = str3, str3 = str2->yxNext)
{
if (str3->len == str1->len &&
!memcmp(str3->text, str1->text, str1->len * sizeof(Unicode)) &&
fabs(str3->yMin - str1->yMin) < size * 0.2 &&
fabs(str3->yMax - str1->yMax) < size * 0.2 &&
fabs(str3->xMax - str1->xMax) < size * 0.2)
{
found = gTrue;
//printf("found duplicate!\n");
break;
}
}
if (found)
{
str2->xyNext = str3->xyNext;
str2->yxNext = str3->yxNext;
delete str3;
}
else
{
str1 = str1->yxNext;
}
}
} /*- !complexMode */
str1 = yxStrings;
hfont1 = getFont(str1);
if( hfont1->isBold() )
str1->htext->insert(0,"<b>",3);
if( hfont1->isItalic() )
str1->htext->insert(0,"<i>",3);
if( str1->getLink() != NULL ) {
GooString *ls = str1->getLink()->getLinkStart();
str1->htext->insert(0, ls);
delete ls;
}
curX = str1->xMin; curY = str1->yMin;
while (str1 && (str2 = str1->yxNext)) {
hfont2 = getFont(str2);
space = str1->yMax - str1->yMin;
horSpace = str2->xMin - str1->xMax;
addLineBreak = !noMerge && (fabs(str1->xMin - str2->xMin) < 0.4);
vertSpace = str2->yMin - str1->yMax;
//printf("coalesce %d %d %f? ", str1->dir, str2->dir, d);
if (str2->yMin >= str1->yMin && str2->yMin <= str1->yMax)
{
vertOverlap = str1->yMax - str2->yMin;
} else
if (str2->yMax >= str1->yMin && str2->yMax <= str1->yMax)
{
vertOverlap = str2->yMax - str1->yMin;
} else
{
vertOverlap = 0;
}
if (
(
(
(
(rawOrder && vertOverlap > 0.5 * space)
||
(!rawOrder && str2->yMin < str1->yMax)
) &&
(horSpace > -0.5 * space && horSpace < space)
) ||
(vertSpace >= 0 && vertSpace < 0.5 * space && addLineBreak)
) &&
(!complexMode || (hfont1->isEqualIgnoreBold(*hfont2))) && // in complex mode fonts must be the same, in other modes fonts do not metter
str1->dir == str2->dir // text direction the same
)
{
// printf("yes\n");
n = str1->len + str2->len;
if ((addSpace = horSpace > 0.1 * space)) {
++n;
}
if (addLineBreak) {
++n;
}
str1->size = (n + 15) & ~15;
str1->text = (Unicode *)grealloc(str1->text,
str1->size * sizeof(Unicode));
str1->xRight = (double *)grealloc(str1->xRight,
str1->size * sizeof(double));
if (addSpace) {
str1->text[str1->len] = 0x20;
str1->htext->append(xml?" ":" ");
str1->xRight[str1->len] = str2->xMin;
++str1->len;
}
if (addLineBreak) {
str1->text[str1->len] = '\n';
str1->htext->append("<br>");
str1->xRight[str1->len] = str2->xMin;
++str1->len;
str1->yMin = str2->yMin;
str1->yMax = str2->yMax;
str1->xMax = str2->xMax;
int fontLineSize = hfont1->getLineSize();
int curLineSize = (int)(vertSpace + space);
if( curLineSize != fontLineSize )
{
HtmlFont *newfnt = new HtmlFont(*hfont1);
newfnt->setLineSize(curLineSize);
str1->fontpos = fonts->AddFont(*newfnt);
delete newfnt;
hfont1 = getFont(str1);
// we have to reget hfont2 because it's location could have
// changed on resize
hfont2 = getFont(str2);
}
}
for (i = 0; i < str2->len; ++i) {
str1->text[str1->len] = str2->text[i];
str1->xRight[str1->len] = str2->xRight[i];
++str1->len;
}
/* fix <i>, <b> if str1 and str2 differ and handle switch of links */
HtmlLink *hlink1 = str1->getLink();
HtmlLink *hlink2 = str2->getLink();
bool switch_links = !hlink1 || !hlink2 || !hlink1->isEqualDest(*hlink2);
GBool finish_a = switch_links && hlink1 != NULL;
GBool finish_italic = hfont1->isItalic() && ( !hfont2->isItalic() || finish_a );
GBool finish_bold = hfont1->isBold() && ( !hfont2->isBold() || finish_a || finish_italic );
CloseTags( str1->htext, finish_a, finish_italic, finish_bold );
if( switch_links && hlink2 != NULL ) {
GooString *ls = hlink2->getLinkStart();
str1->htext->append(ls);
delete ls;
}
if( ( !hfont1->isItalic() || finish_italic ) && hfont2->isItalic() )
str1->htext->append("<i>", 3);
if( ( !hfont1->isBold() || finish_bold ) && hfont2->isBold() )
str1->htext->append("<b>", 3);
str1->htext->append(str2->htext);
// str1 now contains href for link of str2 (if it is defined)
str1->link = str2->link;
hfont1 = hfont2;
if (str2->xMax > str1->xMax) {
str1->xMax = str2->xMax;
}
if (str2->yMax > str1->yMax) {
str1->yMax = str2->yMax;
}
str1->yxNext = str2->yxNext;
delete str2;
} else { // keep strings separate
// printf("no\n");
GBool finish_a = str1->getLink() != NULL;
GBool finish_bold = hfont1->isBold();
GBool finish_italic = hfont1->isItalic();
CloseTags( str1->htext, finish_a, finish_italic, finish_bold );
str1->xMin = curX; str1->yMin = curY;
str1 = str2;
curX = str1->xMin; curY = str1->yMin;
hfont1 = hfont2;
if( hfont1->isBold() )
str1->htext->insert(0,"<b>",3);
if( hfont1->isItalic() )
str1->htext->insert(0,"<i>",3);
if( str1->getLink() != NULL ) {
GooString *ls = str1->getLink()->getLinkStart();
str1->htext->insert(0, ls);
delete ls;
}
}
}
str1->xMin = curX; str1->yMin = curY;
GBool finish_bold = hfont1->isBold();
GBool finish_italic = hfont1->isItalic();
GBool finish_a = str1->getLink() != NULL;
CloseTags( str1->htext, finish_a, finish_italic, finish_bold );
#if 0 //~ for debugging
for (str1 = yxStrings; str1; str1 = str1->yxNext) {
printf("x=%3d..%3d y=%3d..%3d size=%2d ",
(int)str1->xMin, (int)str1->xMax, (int)str1->yMin, (int)str1->yMax,
(int)(str1->yMax - str1->yMin));
printf("'%s'\n", str1->htext->getCString());
}
printf("\n------------------------------------------------------------\n\n");
#endif
}
void HtmlPage::dumpAsXML(FILE* f,int page){
fprintf(f, "<page number=\"%d\" position=\"absolute\"", page);
fprintf(f," top=\"0\" left=\"0\" height=\"%d\" width=\"%d\">\n", pageHeight,pageWidth);
for(int i=fontsPageMarker;i < fonts->size();i++) {
GooString *fontCSStyle = fonts->CSStyle(i);
fprintf(f,"\t%s\n",fontCSStyle->getCString());
delete fontCSStyle;
}
GooString *str, *str1 = NULL;
for(HtmlString *tmp=yxStrings;tmp;tmp=tmp->yxNext){
if (tmp->htext){
str=new GooString(tmp->htext);
fprintf(f,"<text top=\"%d\" left=\"%d\" ",xoutRound(tmp->yMin),xoutRound(tmp->xMin));
fprintf(f,"width=\"%d\" height=\"%d\" ",xoutRound(tmp->xMax-tmp->xMin),xoutRound(tmp->yMax-tmp->yMin));
fprintf(f,"font=\"%d\">", tmp->fontpos);
str1=fonts->getCSStyle(tmp->fontpos, str);
fputs(str1->getCString(),f);
delete str;
delete str1;
fputs("</text>\n",f);
}
}
fputs("</page>\n",f);
}
void HtmlPage::dumpComplex(FILE *file, int page){
FILE* pageFile;
GooString* tmp;
char* htmlEncoding;
if( firstPage == -1 ) firstPage = page;
if( !noframes )
{
GooString* pgNum=GooString::fromInt(page);
tmp = new GooString(DocName);
if (!singleHtml){
tmp->append('-')->append(pgNum)->append(".html");
pageFile = fopen(tmp->getCString(), "w");
} else {
tmp->append("-html")->append(".html");
pageFile = fopen(tmp->getCString(), "a");
}
delete pgNum;
if (!pageFile) {
error(-1, "Couldn't open html file '%s'", tmp->getCString());
delete tmp;
return;
}
if (!singleHtml)
fprintf(pageFile,"%s\n<HTML>\n<HEAD>\n<TITLE>Page %d</TITLE>\n\n", DOCTYPE, page);
else
fprintf(pageFile,"%s\n<HTML>\n<HEAD>\n<TITLE>%s</TITLE>\n\n", DOCTYPE, tmp->getCString());
delete tmp;
htmlEncoding = HtmlOutputDev::mapEncodingToHtml
(globalParams->getTextEncodingName());
if (!singleHtml)
fprintf(pageFile, "<META http-equiv=\"Content-Type\" content=\"text/html; charset=%s\">\n", htmlEncoding);
else
fprintf(pageFile, "<META http-equiv=\"Content-Type\" content=\"text/html; charset=%s\">\n <br>\n", htmlEncoding);
}
else
{
pageFile = file;
fprintf(pageFile,"<!-- Page %d -->\n", page);
fprintf(pageFile,"<a name=\"%d\"></a>\n", page);
}
fprintf(pageFile,"<DIV style=\"position:relative;width:%d;height:%d;\">\n",
pageWidth, pageHeight);
tmp=basename(DocName);
fputs("<STYLE type=\"text/css\">\n<!--\n",pageFile);
for(int i=fontsPageMarker;i!=fonts->size();i++) {
GooString *fontCSStyle;
if (!singleHtml)
fontCSStyle = fonts->CSStyle(i);
else
fontCSStyle = fonts->CSStyle(i,page);
fprintf(pageFile,"\t%s\n",fontCSStyle->getCString());
delete fontCSStyle;
}
fputs("-->\n</STYLE>\n",pageFile);
if( !noframes )
{
fputs("</HEAD>\n<BODY bgcolor=\"#A0A0A0\" vlink=\"blue\" link=\"blue\">\n",pageFile);
}
if( !ignore )
{
fprintf(pageFile,
"<IMG width=\"%d\" height=\"%d\" src=\"%s%03d.%s\" alt=\"background image\">\n",
pageWidth, pageHeight, tmp->getCString(),
(page-firstPage+1), imgExt->getCString());
}
delete tmp;
GooString *str, *str1 = NULL;
for(HtmlString *tmp1=yxStrings;tmp1;tmp1=tmp1->yxNext){
if (tmp1->htext){
str=new GooString(tmp1->htext);
fprintf(pageFile,
"<DIV style=\"position:absolute;top:%d;left:%d\">",
xoutRound(tmp1->yMin),
xoutRound(tmp1->xMin));
fputs("<nobr>",pageFile);
if (!singleHtml)
str1=fonts->getCSStyle(tmp1->fontpos, str);
else
str1=fonts->getCSStyle(tmp1->fontpos, str, page);
fputs(str1->getCString(),pageFile);
delete str;
delete str1;
fputs("</nobr></DIV>\n",pageFile);
}
}
fputs("</DIV>\n", pageFile);
if( !noframes )
{
fputs("</BODY>\n</HTML>\n",pageFile);
fclose(pageFile);
}
}
void HtmlPage::dump(FILE *f, int pageNum)
{
if (complexMode || singleHtml)
{
if (xml) dumpAsXML(f, pageNum);
if (!xml) dumpComplex(f, pageNum);
}
else
{
fprintf(f,"<A name=%d></a>",pageNum);
// Loop over the list of image names on this page
int listlen=HtmlOutputDev::imgList->getLength();
for (int i = 0; i < listlen; i++) {
GooString *fName= (GooString *)HtmlOutputDev::imgList->del(0);
fprintf(f,"<IMG src=\"%s\"><br>\n",fName->getCString());
delete fName;
}
HtmlOutputDev::imgNum=1;
GooString* str;
for(HtmlString *tmp=yxStrings;tmp;tmp=tmp->yxNext){
if (tmp->htext){
str=new GooString(tmp->htext);
fputs(str->getCString(),f);
delete str;
fputs("<br>\n",f);
}
}
fputs("<hr>\n",f);
}
}
void HtmlPage::clear() {
HtmlString *p1, *p2;
if (curStr) {
delete curStr;
curStr = NULL;
}
for (p1 = yxStrings; p1; p1 = p2) {
p2 = p1->yxNext;
delete p1;
}
yxStrings = NULL;
xyStrings = NULL;
yxCur1 = yxCur2 = NULL;
if( !noframes )
{
delete fonts;
fonts=new HtmlFontAccu();
fontsPageMarker = 0;
}
else
{
fontsPageMarker = fonts->size();
}
delete links;
links=new HtmlLinks();
}
void HtmlPage::setDocName(char *fname){
DocName=new GooString(fname);
}
//------------------------------------------------------------------------
// HtmlMetaVar
//------------------------------------------------------------------------
HtmlMetaVar::HtmlMetaVar(char *_name, char *_content)
{
name = new GooString(_name);
content = new GooString(_content);
}
HtmlMetaVar::~HtmlMetaVar()
{
delete name;
delete content;
}
GooString* HtmlMetaVar::toString()
{
GooString *result = new GooString("<META name=\"");
result->append(name);
result->append("\" content=\"");
result->append(content);
result->append("\">");
return result;
}
//------------------------------------------------------------------------
// HtmlOutputDev
//------------------------------------------------------------------------
static char* HtmlEncodings[][2] = {
{"Latin1", "ISO-8859-1"},
{NULL, NULL}
};
char* HtmlOutputDev::mapEncodingToHtml(GooString* encoding)
{
char* enc = encoding->getCString();
for(int i = 0; HtmlEncodings[i][0] != NULL; i++)
{
if( strcmp(enc, HtmlEncodings[i][0]) == 0 )
{
return HtmlEncodings[i][1];
}
}
return enc;
}
void HtmlOutputDev::doFrame(int firstPage){
GooString* fName=new GooString(Docname);
char* htmlEncoding;
fName->append(".html");
if (!(fContentsFrame = fopen(fName->getCString(), "w"))){
error(-1, "Couldn't open html file '%s'", fName->getCString());
delete fName;
return;
}
delete fName;
fName=basename(Docname);
fputs(DOCTYPE_FRAMES, fContentsFrame);
fputs("\n<HTML>",fContentsFrame);
fputs("\n<HEAD>",fContentsFrame);
fprintf(fContentsFrame,"\n<TITLE>%s</TITLE>",docTitle->getCString());
htmlEncoding = mapEncodingToHtml(globalParams->getTextEncodingName());
fprintf(fContentsFrame, "\n<META http-equiv=\"Content-Type\" content=\"text/html; charset=%s\">\n", htmlEncoding);
dumpMetaVars(fContentsFrame);
fprintf(fContentsFrame, "</HEAD>\n");
fputs("<FRAMESET cols=\"100,*\">\n",fContentsFrame);
fprintf(fContentsFrame,"<FRAME name=\"links\" src=\"%s_ind.html\">\n",fName->getCString());
fputs("<FRAME name=\"contents\" src=",fContentsFrame);
if (complexMode)
fprintf(fContentsFrame,"\"%s-%d.html\"",fName->getCString(), firstPage);
else
fprintf(fContentsFrame,"\"%ss.html\"",fName->getCString());
fputs(">\n</FRAMESET>\n</HTML>\n",fContentsFrame);
delete fName;
fclose(fContentsFrame);
}
HtmlOutputDev::HtmlOutputDev(char *fileName, char *title,
char *author, char *keywords, char *subject, char *date,
char *extension,
GBool rawOrder, int firstPage, GBool outline)
{
char *htmlEncoding;
fContentsFrame = NULL;
docTitle = new GooString(title);
pages = NULL;
dumpJPEG=gTrue;
//write = gTrue;
this->rawOrder = rawOrder;
this->doOutline = outline;
ok = gFalse;
imgNum=1;
//this->firstPage = firstPage;
//pageNum=firstPage;
// open file
needClose = gFalse;
pages = new HtmlPage(rawOrder, extension);
glMetaVars = new GooList();
glMetaVars->append(new HtmlMetaVar("generator", "pdftohtml 0.36"));
if( author ) glMetaVars->append(new HtmlMetaVar("author", author));
if( keywords ) glMetaVars->append(new HtmlMetaVar("keywords", keywords));
if( date ) glMetaVars->append(new HtmlMetaVar("date", date));
if( subject ) glMetaVars->append(new HtmlMetaVar("subject", subject));
maxPageWidth = 0;
maxPageHeight = 0;
pages->setDocName(fileName);
Docname=new GooString (fileName);
// for non-xml output (complex or simple) with frames generate the left frame
if(!xml && !noframes)
{
if (!singleHtml)
{
GooString* left=new GooString(fileName);
left->append("_ind.html");
doFrame(firstPage);
if (!(fContentsFrame = fopen(left->getCString(), "w")))
{
error(-1, "Couldn't open html file '%s'", left->getCString());
delete left;
return;
}
delete left;
fputs(DOCTYPE, fContentsFrame);
fputs("<HTML>\n<HEAD>\n<TITLE></TITLE>\n</HEAD>\n<BODY>\n",fContentsFrame);
if (doOutline)
{
GooString *str = basename(Docname);
fprintf(fContentsFrame, "<A href=\"%s%s\" target=\"contents\">Outline</a><br>", str->getCString(), complexMode ? "-outline.html" : "s.html#outline");
delete str;
}
}
if (!complexMode)
{ /* not in complex mode */
GooString* right=new GooString(fileName);
right->append("s.html");
if (!(page=fopen(right->getCString(),"w"))){
error(-1, "Couldn't open html file '%s'", right->getCString());
delete right;
return;
}
delete right;
fputs(DOCTYPE, page);
fputs("<HTML>\n<HEAD>\n<TITLE></TITLE>\n</HEAD>\n<BODY>\n",page);
}
}
if (noframes) {
if (stout) page=stdout;
else {
GooString* right=new GooString(fileName);
if (!xml) right->append(".html");
if (xml) right->append(".xml");
if (!(page=fopen(right->getCString(),"w"))){
error(-1, "Couldn't open html file '%s'", right->getCString());
delete right;
return;
}
delete right;
}
htmlEncoding = mapEncodingToHtml(globalParams->getTextEncodingName());
if (xml)
{
fprintf(page, "<?xml version=\"1.0\" encoding=\"%s\"?>\n", htmlEncoding);
fputs("<!DOCTYPE pdf2xml SYSTEM \"pdf2xml.dtd\">\n\n", page);
fputs("<pdf2xml>\n",page);
}
else
{
fprintf(page,"%s\n<HTML>\n<HEAD>\n<TITLE>%s</TITLE>\n",
DOCTYPE, docTitle->getCString());
fprintf(page, "<META http-equiv=\"Content-Type\" content=\"text/html; charset=%s\">\n", htmlEncoding);
dumpMetaVars(page);
fprintf(page,"</HEAD>\n");
fprintf(page,"<BODY bgcolor=\"#A0A0A0\" vlink=\"blue\" link=\"blue\">\n");
}
}
ok = gTrue;
}
HtmlOutputDev::~HtmlOutputDev() {
HtmlFont::clear();
delete Docname;
delete docTitle;
deleteGooList(glMetaVars, HtmlMetaVar);
if (fContentsFrame){
fputs("</BODY>\n</HTML>\n",fContentsFrame);
fclose(fContentsFrame);
}
if (xml) {
fputs("</pdf2xml>\n",page);
fclose(page);
} else
if ( !complexMode || xml || noframes )
{
fputs("</BODY>\n</HTML>\n",page);
fclose(page);
}
if (pages)
delete pages;
}
void HtmlOutputDev::startPage(int pageNum, GfxState *state) {
#if 0
if (mode&&!xml){
if (write){
write=gFalse;
GooString* fname=Dirname(Docname);
fname->append("image.log");
if((tin=fopen(getFileNameFromPath(fname->getCString(),fname->getLength()),"w"))==NULL){
printf("Error : can not open %s",fname);
exit(1);
}
delete fname;
// if(state->getRotation()!=0)
// fprintf(tin,"ROTATE=%d rotate %d neg %d neg translate\n",state->getRotation(),state->getX1(),-state->getY1());
// else
fprintf(tin,"ROTATE=%d neg %d neg translate\n",state->getX1(),state->getY1());
}
}
#endif
this->pageNum = pageNum;
GooString *str=basename(Docname);
pages->clear();
if(!noframes)
{
if (fContentsFrame)
{
if (complexMode)
fprintf(fContentsFrame,"<A href=\"%s-%d.html\"",str->getCString(),pageNum);
else
fprintf(fContentsFrame,"<A href=\"%ss.html#%d\"",str->getCString(),pageNum);
fprintf(fContentsFrame," target=\"contents\" >Page %d</a><br>\n",pageNum);
}
}
pages->pageWidth=static_cast<int>(state->getPageWidth());
pages->pageHeight=static_cast<int>(state->getPageHeight());
delete str;
}
void HtmlOutputDev::endPage() {
Links *linksList = docPage->getLinks(catalog);
for (int i = 0; i < linksList->getNumLinks(); ++i)
{
doProcessLink(linksList->getLink(i));
}
delete linksList;
pages->conv();
pages->coalesce();
pages->dump(page, pageNum);
// I don't yet know what to do in the case when there are pages of different
// sizes and we want complex output: running ghostscript many times
// seems very inefficient. So for now I'll just use last page's size
maxPageWidth = pages->pageWidth;
maxPageHeight = pages->pageHeight;
//if(!noframes&&!xml) fputs("<br>\n", fContentsFrame);
if(!stout && !globalParams->getErrQuiet()) printf("Page-%d\n",(pageNum));
}
void HtmlOutputDev::updateFont(GfxState *state) {
pages->updateFont(state);
}
void HtmlOutputDev::beginString(GfxState *state, GooString *s) {
pages->beginString(state, s);
}
void HtmlOutputDev::endString(GfxState *state) {
pages->endString();
}
void HtmlOutputDev::drawChar(GfxState *state, double x, double y,
double dx, double dy,
double originX, double originY,
CharCode code, int /*nBytes*/, Unicode *u, int uLen)
{
if ( !showHidden && (state->getRender() & 3) == 3) {
return;
}
pages->addChar(state, x, y, dx, dy, originX, originY, u, uLen);
}
void HtmlOutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str,
int width, int height, GBool invert,
GBool interpolate, GBool inlineImg) {
if (ignore||complexMode) {
OutputDev::drawImageMask(state, ref, str, width, height, invert, interpolate, inlineImg);
return;
}
FILE *f1;
int c;
int x0, y0; // top left corner of image
int w0, h0, w1, h1; // size of image
double xt, yt, wt, ht;
GBool rotate, xFlip, yFlip;
// get image position and size
state->transform(0, 0, &xt, &yt);
state->transformDelta(1, 1, &wt, &ht);
if (wt > 0) {
x0 = xoutRound(xt);
w0 = xoutRound(wt);
} else {
x0 = xoutRound(xt + wt);
w0 = xoutRound(-wt);
}
if (ht > 0) {
y0 = xoutRound(yt);
h0 = xoutRound(ht);
} else {
y0 = xoutRound(yt + ht);
h0 = xoutRound(-ht);
}
state->transformDelta(1, 0, &xt, &yt);
rotate = fabs(xt) < fabs(yt);
if (rotate) {
w1 = h0;
h1 = w0;
xFlip = ht < 0;
yFlip = wt > 0;
} else {
w1 = w0;
h1 = h0;
xFlip = wt < 0;
yFlip = ht > 0;
}
// dump JPEG file
if (dumpJPEG && str->getKind() == strDCT) {
GooString *fName=new GooString(Docname);
fName->append("-");
GooString *pgNum=GooString::fromInt(pageNum);
GooString *imgnum=GooString::fromInt(imgNum);
// open the image file
fName->append(pgNum)->append("_")->append(imgnum)->append(".jpg");
delete pgNum;
delete imgnum;
++imgNum;
if (!(f1 = fopen(fName->getCString(), "wb"))) {
error(-1, "Couldn't open image file '%s'", fName->getCString());
delete fName;
return;
}
// initialize stream
str = ((DCTStream *)str)->getRawStream();
str->reset();
// copy the stream
while ((c = str->getChar()) != EOF)
fputc(c, f1);
fclose(f1);
if (fName) imgList->append(fName);
}
else {
OutputDev::drawImageMask(state, ref, str, width, height, invert, interpolate, inlineImg);
}
}
void HtmlOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
int width, int height, GfxImageColorMap *colorMap,
GBool interpolate, int *maskColors, GBool inlineImg) {
if (ignore||complexMode) {
OutputDev::drawImage(state, ref, str, width, height, colorMap, interpolate,
maskColors, inlineImg);
return;
}
FILE *f1;
int c;
int x0, y0; // top left corner of image
int w0, h0, w1, h1; // size of image
double xt, yt, wt, ht;
GBool rotate, xFlip, yFlip;
// get image position and size
state->transform(0, 0, &xt, &yt);
state->transformDelta(1, 1, &wt, &ht);
if (wt > 0) {
x0 = xoutRound(xt);
w0 = xoutRound(wt);
} else {
x0 = xoutRound(xt + wt);
w0 = xoutRound(-wt);
}
if (ht > 0) {
y0 = xoutRound(yt);
h0 = xoutRound(ht);
} else {
y0 = xoutRound(yt + ht);
h0 = xoutRound(-ht);
}
state->transformDelta(1, 0, &xt, &yt);
rotate = fabs(xt) < fabs(yt);
if (rotate) {
w1 = h0;
h1 = w0;
xFlip = ht < 0;
yFlip = wt > 0;
} else {
w1 = w0;
h1 = h0;
xFlip = wt < 0;
yFlip = ht > 0;
}
/*if( !globalParams->getErrQuiet() )
printf("image stream of kind %d\n", str->getKind());*/
// dump JPEG file
if (dumpJPEG && str->getKind() == strDCT) {
GooString *fName=new GooString(Docname);
fName->append("-");
GooString *pgNum= GooString::fromInt(pageNum);
GooString *imgnum= GooString::fromInt(imgNum);
// open the image file
fName->append(pgNum)->append("_")->append(imgnum)->append(".jpg");
delete pgNum;
delete imgnum;
++imgNum;
if (!(f1 = fopen(fName->getCString(), "wb"))) {
error(-1, "Couldn't open image file '%s'", fName->getCString());
delete fName;
return;
}
// initialize stream
str = ((DCTStream *)str)->getRawStream();
str->reset();
// copy the stream
while ((c = str->getChar()) != EOF)
fputc(c, f1);
fclose(f1);
if (fName) imgList->append(fName);
}
else {
#ifdef ENABLE_LIBPNG
// Dump the image as a PNG file. Much of the PNG code
// comes from an example by Guillaume Cottenceau.
Guchar *p;
GfxRGB rgb;
png_byte *row = (png_byte *) malloc(3 * width); // 3 bytes/pixel: RGB
png_bytep *row_pointer= &row;
// Create the image filename
GooString *fName=new GooString(Docname);
fName->append("-");
GooString *pgNum= GooString::fromInt(pageNum);
GooString *imgnum= GooString::fromInt(imgNum);
fName->append(pgNum)->append("_")->append(imgnum)->append(".png");
delete pgNum;
delete imgnum;
// Open the image file
if (!(f1 = fopen(fName->getCString(), "wb"))) {
error(-1, "Couldn't open image file '%s'", fName->getCString());
delete fName;
return;
}
PNGWriter *writer = new PNGWriter();
// TODO can we calculate the resolution of the image?
if (!writer->init(f1, width, height, 72, 72)) {
delete writer;
fclose(f1);
return;
}
// Initialize the image stream
ImageStream *imgStr = new ImageStream(str, width,
colorMap->getNumPixelComps(), colorMap->getBits());
imgStr->reset();
// For each line...
for (int y = 0; y < height; y++) {
// Convert into a PNG row
p = imgStr->getLine();
for (int x = 0; x < width; x++) {
colorMap->getRGB(p, &rgb);
// Write the RGB pixels into the row
row[3*x]= colToByte(rgb.r);
row[3*x+1]= colToByte(rgb.g);
row[3*x+2]= colToByte(rgb.b);
p += colorMap->getNumPixelComps();
}
if (!writer->writeRow(row_pointer)) {
delete writer;
fclose(f1);
return;
}
}
writer->close();
delete writer;
fclose(f1);
free(row);
imgList->append(fName);
++imgNum;
imgStr->close();
delete imgStr;
#else
OutputDev::drawImage(state, ref, str, width, height, colorMap, interpolate,
maskColors, inlineImg);
#endif
}
}
void HtmlOutputDev::doProcessLink(Link* link){
double _x1,_y1,_x2,_y2;
int x1,y1,x2,y2;
link->getRect(&_x1,&_y1,&_x2,&_y2);
cvtUserToDev(_x1,_y1,&x1,&y1);
cvtUserToDev(_x2,_y2,&x2,&y2);
GooString* _dest=getLinkDest(link,catalog);
HtmlLink t((double) x1,(double) y2,(double) x2,(double) y1,_dest);
pages->AddLink(t);
delete _dest;
}
GooString* HtmlOutputDev::getLinkDest(Link *link,Catalog* catalog){
char *p;
switch(link->getAction()->getKind())
{
case actionGoTo:
{
GooString* file=basename(Docname);
int page=1;
LinkGoTo *ha=(LinkGoTo *)link->getAction();
LinkDest *dest=NULL;
if (ha->getDest()!=NULL)
dest=ha->getDest()->copy();
else if (ha->getNamedDest()!=NULL)
dest=catalog->findDest(ha->getNamedDest());
if (dest){
if (dest->isPageRef()){
Ref pageref=dest->getPageRef();
page=catalog->findPage(pageref.num,pageref.gen);
}
else {
page=dest->getPageNum();
}
delete dest;
GooString *str=GooString::fromInt(page);
/* complex simple
frames file-4.html files.html#4
noframes file.html#4 file.html#4
*/
if (noframes)
{
file->append(".html#");
file->append(str);
}
else
{
if( complexMode )
{
file->append("-");
file->append(str);
file->append(".html");
}
else
{
file->append("s.html#");
file->append(str);
}
}
if (printCommands) printf(" link to page %d ",page);
delete str;
return file;
}
else
{
return new GooString();
}
}
case actionGoToR:
{
LinkGoToR *ha=(LinkGoToR *) link->getAction();
LinkDest *dest=NULL;
int page=1;
GooString *file=new GooString();
if (ha->getFileName()){
delete file;
file=new GooString(ha->getFileName()->getCString());
}
if (ha->getDest()!=NULL) dest=ha->getDest()->copy();
if (dest&&file){
if (!(dest->isPageRef())) page=dest->getPageNum();
delete dest;
if (printCommands) printf(" link to page %d ",page);
if (printHtml){
p=file->getCString()+file->getLength()-4;
if (!strcmp(p, ".pdf") || !strcmp(p, ".PDF")){
file->del(file->getLength()-4,4);
file->append(".html");
}
file->append('#');
file->append(GooString::fromInt(page));
}
}
if (printCommands && file) printf("filename %s\n",file->getCString());
return file;
}
case actionURI:
{
LinkURI *ha=(LinkURI *) link->getAction();
GooString* file=new GooString(ha->getURI()->getCString());
// printf("uri : %s\n",file->getCString());
return file;
}
case actionLaunch:
{
LinkLaunch *ha=(LinkLaunch *) link->getAction();
GooString* file=new GooString(ha->getFileName()->getCString());
if (printHtml) {
p=file->getCString()+file->getLength()-4;
if (!strcmp(p, ".pdf") || !strcmp(p, ".PDF")){
file->del(file->getLength()-4,4);
file->append(".html");
}
if (printCommands) printf("filename %s",file->getCString());
return file;
}
}
default:
return new GooString();
}
}
void HtmlOutputDev::dumpMetaVars(FILE *file)
{
GooString *var;
for(int i = 0; i < glMetaVars->getLength(); i++)
{
HtmlMetaVar *t = (HtmlMetaVar*)glMetaVars->get(i);
var = t->toString();
fprintf(file, "%s\n", var->getCString());
delete var;
}
}
GBool HtmlOutputDev::dumpDocOutline(Catalog* catalog)
{
FILE * output = NULL;
GBool bClose = gFalse;
if (!ok || xml)
return gFalse;
Object *outlines = catalog->getOutline();
if (!outlines->isDict())
return gFalse;
if (!complexMode && !xml)
{
output = page;
}
else if (complexMode && !xml)
{
if (noframes)
{
output = page;
fputs("<hr>\n", output);
}
else
{
GooString *str = Docname->copy();
str->append("-outline.html");
output = fopen(str->getCString(), "w");
if (output == NULL)
return gFalse;
delete str;
bClose = gTrue;
fputs("<HTML>\n<HEAD>\n<TITLE>Document Outline</TITLE>\n</HEAD>\n<BODY>\n", output);
}
}
GBool done = newOutlineLevel(output, outlines, catalog);
if (done && !complexMode)
fputs("<hr>\n", output);
if (bClose)
{
fputs("</BODY>\n</HTML>\n", output);
fclose(output);
}
return done;
}
GBool HtmlOutputDev::newOutlineLevel(FILE *output, Object *node, Catalog* catalog, int level)
{
Object curr, next;
GBool atLeastOne = gFalse;
if (node->dictLookup("First", &curr)->isDict()) {
if (level == 1)
{
fputs("<A name=\"outline\"></a>", output);
fputs("<h1>Document Outline</h1>\n", output);
}
fputs("<ul>",output);
do {
// get title, give up if not found
Object title;
if (curr.dictLookup("Title", &title)->isNull()) {
title.free();
break;
}
GooString *titleStr = new GooString(title.getString());
title.free();
// get corresponding link
// Note: some code duplicated from HtmlOutputDev::getLinkDest().
GooString *linkName = NULL;;
Object dest;
if (!curr.dictLookup("Dest", &dest)->isNull()) {
LinkGoTo *link = new LinkGoTo(&dest);
LinkDest *linkdest=NULL;
if (link->getDest()!=NULL)
linkdest=link->getDest()->copy();
else if (link->getNamedDest()!=NULL)
linkdest=catalog->findDest(link->getNamedDest());
delete link;
if (linkdest) {
int page;
if (linkdest->isPageRef()) {
Ref pageref=linkdest->getPageRef();
page=catalog->findPage(pageref.num,pageref.gen);
} else {
page=linkdest->getPageNum();
}
delete linkdest;
/* complex simple
frames file-4.html files.html#4
noframes file.html#4 file.html#4
*/
linkName=basename(Docname);
GooString *str=GooString::fromInt(page);
if (noframes) {
linkName->append(".html#");
linkName->append(str);
} else {
if( complexMode ) {
linkName->append("-");
linkName->append(str);
linkName->append(".html");
} else {
linkName->append("s.html#");
linkName->append(str);
}
}
delete str;
}
}
dest.free();
fputs("<li>",output);
if (linkName)
fprintf(output,"<A href=\"%s\">", linkName->getCString());
fputs(titleStr->getCString(),output);
if (linkName) {
fputs("</A>",output);
delete linkName;
}
fputs("\n",output);
delete titleStr;
atLeastOne = gTrue;
newOutlineLevel(output, &curr, catalog, level+1);
curr.dictLookup("Next", &next);
curr.free();
curr = next;
} while(curr.isDict());
fputs("</ul>",output);
}
curr.free();
return atLeastOne;
}
| 26.694774 | 162 | 0.57461 | [
"object",
"transform",
"3d"
] |
ede8a4892d7a841b24676fea3ed1360e881f934e | 292 | hh | C++ | build/ARM/params/FUPool.hh | magnuram/edelsten5 | 63de812a22142f07fa48c253636e5c96156d4da9 | [
"BSD-3-Clause"
] | 5 | 2019-12-12T16:26:09.000Z | 2022-03-17T03:23:33.000Z | build/X86/params/FUPool.hh | zhoushuxin/impl_of_HPCA2018 | 594d807fb0c0712bb7766122c4efe3321d012687 | [
"BSD-3-Clause"
] | 1 | 2020-08-20T05:53:30.000Z | 2020-08-20T05:53:30.000Z | build/X86/params/FUPool.hh | zhoushuxin/impl_of_HPCA2018 | 594d807fb0c0712bb7766122c4efe3321d012687 | [
"BSD-3-Clause"
] | null | null | null | #ifndef __PARAMS__FUPool__
#define __PARAMS__FUPool__
class FUPool;
#include <vector>
#include "params/FUDesc.hh"
#include "params/SimObject.hh"
struct FUPoolParams
: public SimObjectParams
{
FUPool * create();
std::vector< FUDesc * > FUList;
};
#endif // __PARAMS__FUPool__
| 15.368421 | 35 | 0.726027 | [
"vector"
] |
edeabb3717258d4f50169845406f4be3e34fe34b | 21,810 | cpp | C++ | contrib/imgui/ImGuiFileDialog.cpp | Khirion/nau | 47a2ad8e0355a264cd507da5e7bba1bf7abbff95 | [
"MIT"
] | 29 | 2015-09-16T22:28:30.000Z | 2022-03-11T02:57:36.000Z | contrib/imgui/ImGuiFileDialog.cpp | Khirion/nau | 47a2ad8e0355a264cd507da5e7bba1bf7abbff95 | [
"MIT"
] | 1 | 2017-03-29T13:32:58.000Z | 2017-03-31T13:56:03.000Z | contrib/imgui/ImGuiFileDialog.cpp | Khirion/nau | 47a2ad8e0355a264cd507da5e7bba1bf7abbff95 | [
"MIT"
] | 10 | 2015-10-15T14:20:15.000Z | 2022-02-17T10:37:29.000Z | // This is an independent project of an individual developer. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
// From https://github.com/aiekick/ImGuiFileDialog
#include "ImGuiFileDialog.h"
#include "imgui.h"
#ifdef WIN32
#include <dirent.h>
#define PATH_SEP '\\'
#ifndef PATH_MAX
#define PATH_MAX 260
#endif
#elif defined(LINUX) or defined(APPLE)
#include <sys/types.h>
#include <dirent.h>
#define PATH_SEP '/'
#endif
#include "imgui.h"
#ifndef IMGUI_DEFINE_MATH_OPERATORS
#define IMGUI_DEFINE_MATH_OPERATORS
#endif
#include "imgui_internal.h"
#include <cstdlib>
#include <algorithm>
#include <iostream>
static std::string s_fs_root(1u, PATH_SEP);
inline bool replaceString(::std::string& str, const ::std::string& oldStr, const ::std::string& newStr)
{
bool found = false;
size_t pos = 0;
while ((pos = str.find(oldStr, pos)) != ::std::string::npos)
{
found = true;
str.replace(pos, oldStr.length(), newStr);
pos += newStr.length();
}
return found;
}
inline std::vector<std::string> splitStringToVector(const ::std::string& text, char delimiter, bool pushEmpty)
{
std::vector<std::string> arr;
if (text.size() > 0)
{
std::string::size_type start = 0;
std::string::size_type end = text.find(delimiter, start);
while (end != std::string::npos)
{
std::string token = text.substr(start, end - start);
if (token.size() > 0 || (token.size() == 0 && pushEmpty))
arr.push_back(token);
start = end + 1;
end = text.find(delimiter, start);
}
arr.push_back(text.substr(start));
}
return arr;
}
inline std::vector<std::string> GetDrivesList()
{
std::vector<std::string> res;
#ifdef WIN32
DWORD mydrives = 2048;
char lpBuffer[2048];
DWORD countChars = GetLogicalDriveStrings(mydrives, lpBuffer);
if (countChars > 0)
{
std::string var = std::string(lpBuffer, countChars);
replaceString(var, "\\", "");
res = splitStringToVector(var, '\0', false);
}
#endif
return res;
}
inline bool IsDirectoryExist(const std::string& name)
{
bool bExists = false;
if (name.size() > 0)
{
DIR *pDir = 0;
pDir = opendir(name.c_str());
if (pDir != NULL)
{
bExists = true;
(void)closedir(pDir);
}
}
return bExists; // this is not a directory!
}
inline bool CreateDirectoryIfNotExist(const std::string& name)
{
bool res = false;
if (name.size() > 0)
{
if (!IsDirectoryExist(name))
{
res = true;
#ifdef WIN32
CreateDirectory(name.c_str(), NULL);
#elif defined(LINUX) or defined(APPLE)
char buffer[PATH_MAX] = {};
snprintf(buffer, PATH_MAX, "mkdir -p %s", name.c_str());
const int dir_err = std::system(buffer);
if (dir_err == -1)
{
std::cout << "Error creating directory " << name << std::endl;
res = false;
}
#endif
}
}
return res;
}
struct PathStruct
{
std::string path;
std::string name;
std::string ext;
bool isOk;
PathStruct()
{
isOk = false;
}
};
inline PathStruct ParsePathFileName(const std::string& vPathFileName)
{
PathStruct res;
if (vPathFileName.size() > 0)
{
std::string pfn = vPathFileName;
std::string separator(1u, PATH_SEP);
replaceString(pfn, "\\", separator);
replaceString(pfn, "/", separator);
size_t lastSlash = pfn.find_last_of(separator);
if (lastSlash != std::string::npos)
{
res.name = pfn.substr(lastSlash + 1);
res.path = pfn.substr(0, lastSlash);
res.isOk = true;
}
size_t lastPoint = pfn.find_last_of('.');
if (lastPoint != std::string::npos)
{
if (!res.isOk)
{
res.name = pfn;
res.isOk = true;
}
res.ext = pfn.substr(lastPoint + 1);
replaceString(res.name, "." + res.ext, "");
}
}
return res;
}
inline void AppendToBuffer(char* vBuffer, size_t vBufferLen, std::string vStr)
{
std::string st = vStr;
size_t len = vBufferLen - 1u;
size_t slen = strlen(vBuffer);
if (st != "" && st != "\n")
{
replaceString(st, "\n", "");
replaceString(st, "\r", "");
}
vBuffer[slen] = '\0';
std::string str = std::string(vBuffer);
if (str.size() > 0) str += "\n";
str += vStr;
if (len > str.size()) len = str.size();
#ifdef MSVC
strncpy_s(vBuffer, vBufferLen, str.c_str(), len);
#else
strncpy(vBuffer, str.c_str(), len);
#endif
vBuffer[len] = '\0';
}
inline void ResetBuffer(char* vBuffer)
{
vBuffer[0] = '\0';
}
char ImGuiFileDialog::FileNameBuffer[MAX_FILE_DIALOG_NAME_BUFFER] = "";
char ImGuiFileDialog::DirectoryNameBuffer[MAX_FILE_DIALOG_NAME_BUFFER] = "";
char ImGuiFileDialog::SearchBuffer[MAX_FILE_DIALOG_NAME_BUFFER] = "";
int ImGuiFileDialog::FilterIndex = 0;
ImGuiFileDialog::ImGuiFileDialog()
{
m_AnyWindowsHovered = false;
IsOk = false;
m_ShowDialog = false;
m_ShowDrives = false;
m_CreateDirectoryMode = false;
dlg_optionsPane = 0;
dlg_optionsPaneWidth = 250;
dlg_filters = "";
}
ImGuiFileDialog::~ImGuiFileDialog()
{
}
/* Alphabetical sorting */
/*#ifdef WIN32
static int alphaSort(const void *a, const void *b)
{
return strcoll(((dirent*)a)->d_name, ((dirent*)b)->d_name);
}
#elif defined(LINUX) or defined(APPLE)*/
static int alphaSort(const struct dirent **a, const struct dirent **b)
{
return strcoll((*a)->d_name, (*b)->d_name);
}
//#endif
static bool stringComparator(const FileInfoStruct& a, const FileInfoStruct& b)
{
bool res;
if (a.type != b.type) res = (a.type < b.type);
else res = (a.fileName < b.fileName);
return res;
}
void ImGuiFileDialog::ScanDir(const std::string& vPath)
{
struct dirent **files = NULL;
int i = 0;
int n = 0;
std::string path = vPath;
#if defined(LINUX) || defined(APPLE)
if (path.size()>0)
{
if (path[0] != PATH_SEP)
{
//path = PATH_SEP + path;
}
}
#endif
if (0u == m_CurrentPath_Decomposition.size())
{
SetCurrentDir(path);
}
if (0u != m_CurrentPath_Decomposition.size())
{
#ifdef WIN32
if (path == s_fs_root)
{
path += PATH_SEP;
}
#endif
n = scandir(path.c_str(), &files, NULL, alphaSort);
if (n > 0)
{
m_FileList.clear();
for (i = 0; i < n; i++)
{
struct dirent *ent = files[i];
FileInfoStruct infos;
infos.fileName = ent->d_name;
if (("." != infos.fileName)/* && (".." != infos.fileName)*/)
{
switch (ent->d_type)
{
case DT_REG: infos.type = 'f'; break;
case DT_DIR: infos.type = 'd'; break;
case DT_LNK: infos.type = 'l'; break;
}
if (infos.type == 'f')
{
size_t lpt = infos.fileName.find_last_of('.');
if (lpt != std::string::npos)
{
infos.ext = infos.fileName.substr(lpt);
}
}
m_FileList.push_back(infos);
}
}
for (i = 0; i < n; i++)
{
free(files[i]);
}
free(files);
}
std::sort(m_FileList.begin(), m_FileList.end(), stringComparator);
}
}
void ImGuiFileDialog::SetCurrentDir(const std::string& vPath)
{
std::string path = vPath;
#ifdef WIN32
if (s_fs_root == path)
path += PATH_SEP;
#endif
DIR *dir = opendir(path.c_str());
char real_path[PATH_MAX];
if (NULL == dir)
{
path = ".";
dir = opendir(path.c_str());
}
if (NULL != dir)
{
#ifdef WIN32
size_t numchar = GetFullPathName(path.c_str(), PATH_MAX-1, real_path, 0);
#elif defined(LINUX) or defined(APPLE)
char *numchar = realpath(path.c_str(), real_path);
#endif
if (numchar != 0)
{
m_CurrentPath = real_path;
if (m_CurrentPath[m_CurrentPath.size()-1] == PATH_SEP)
{
m_CurrentPath = m_CurrentPath.substr(0, m_CurrentPath.size() - 1);
}
m_CurrentPath_Decomposition = splitStringToVector(m_CurrentPath, PATH_SEP, false);
#if defined(LINUX) || defined(APPLE)
m_CurrentPath_Decomposition.insert(m_CurrentPath_Decomposition.begin(), std::string(1u, PATH_SEP));
#endif
if (m_CurrentPath_Decomposition.size()>0)
{
#ifdef WIN32
s_fs_root = m_CurrentPath_Decomposition[0];
#endif
}
}
closedir(dir);
}
}
bool ImGuiFileDialog::CreateDir(const std::string& vPath)
{
bool res = false;
if (vPath.size())
{
std::string path = m_CurrentPath + PATH_SEP + vPath;
res = CreateDirectoryIfNotExist(path);
}
return res;
}
void ImGuiFileDialog::ComposeNewPath(std::vector<std::string>::iterator vIter)
{
m_CurrentPath = "";
while (true)
{
if (!m_CurrentPath.empty())
{
#ifdef WIN32
m_CurrentPath = *vIter + PATH_SEP + m_CurrentPath;
#elif defined(LINUX) or defined(APPLE)
if (*vIter == s_fs_root)
{
m_CurrentPath = *vIter + m_CurrentPath;
}
else
{
m_CurrentPath = *vIter + PATH_SEP + m_CurrentPath;
}
#endif
}
else
{
m_CurrentPath = *vIter;
}
if (vIter == m_CurrentPath_Decomposition.begin())
{
#if defined(LINUX) || defined(APPLE)
if (m_CurrentPath[0] != PATH_SEP)
m_CurrentPath = PATH_SEP + m_CurrentPath;
#endif
break;
}
vIter--;
}
}
void ImGuiFileDialog::GetDrives()
{
auto res = GetDrivesList();
if (res.size() > 0)
{
m_CurrentPath = "";
m_CurrentPath_Decomposition.clear();
m_FileList.clear();
for (auto it = res.begin(); it != res.end(); ++it)
{
FileInfoStruct infos;
infos.fileName = *it;
infos.type = 'd';
if (infos.fileName.size() > 0)
{
m_FileList.push_back(infos);
}
}
m_ShowDrives = true;
}
}
void ImGuiFileDialog::OpenDialog(const std::string& vKey, const char* vName, const char* vFilters,
const std::string& vPath, const std::string& vDefaultFileName,
std::function<void(std::string, bool*)> vOptionsPane, size_t vOptionsPaneWidth, const std::string& vUserString)
{
if (m_ShowDialog) // si deja ouvert on ne fou pas la merde en voulant en ecrire une autre
return;
dlg_key = vKey;
dlg_name = std::string(vName);
dlg_filters = vFilters;
dlg_path = vPath;
dlg_defaultFileName = vDefaultFileName;
dlg_optionsPane = vOptionsPane;
dlg_userString = vUserString;
dlg_optionsPaneWidth = vOptionsPaneWidth;
dlg_defaultExt = "";
m_ShowDialog = true;
}
void ImGuiFileDialog::OpenDialog(const std::string& vKey, const char* vName, const char* vFilters,
const std::string& vFilePathName,
std::function<void(std::string, bool*)> vOptionsPane, size_t vOptionsPaneWidth, const std::string& vUserString)
{
if (m_ShowDialog) // si deja ouvert on ne fou pas la merde en voulant en ecrire une autre
return;
dlg_key = vKey;
dlg_name = std::string(vName);
dlg_filters = vFilters;
auto ps = ParsePathFileName(vFilePathName);
if (ps.isOk)
{
dlg_path = ps.path;
dlg_defaultFileName = vFilePathName;
dlg_defaultExt = "." + ps.ext;
}
else
{
dlg_path = ".";
dlg_defaultFileName = "";
dlg_defaultExt = "";
}
dlg_optionsPane = vOptionsPane;
dlg_userString = vUserString;
dlg_optionsPaneWidth = vOptionsPaneWidth;
m_ShowDialog = true;
}
void ImGuiFileDialog::OpenDialog(const std::string& vKey, const char* vName, const char* vFilters,
const std::string& vFilePathName, const std::string& vUserString)
{
if (m_ShowDialog) // si deja ouvert on ne fou pas la merde en voulant en ecrire une autre
return;
dlg_key = vKey;
dlg_name = std::string(vName);
dlg_filters = vFilters;
auto ps = ParsePathFileName(vFilePathName);
if (ps.isOk)
{
dlg_path = ps.path;
dlg_defaultFileName = vFilePathName;
dlg_defaultExt = "." + ps.ext;
}
else
{
dlg_path = ".";
dlg_defaultFileName = "";
dlg_defaultExt = "";
}
dlg_optionsPane = 0;
dlg_userString = vUserString;
dlg_optionsPaneWidth = 0;
ScanDir(m_CurrentPath);
m_ShowDialog = true;
}
void ImGuiFileDialog::OpenDialog(const std::string& vKey, const char* vName, const char* vFilters,
const std::string& vPath, const std::string& vDefaultFileName, const std::string& vUserString)
{
if (m_ShowDialog) // si deja ouvert on ne fou pas la merde en voulant en ecrire une autre
return;
dlg_key = vKey;
dlg_name = std::string(vName);
dlg_filters = vFilters;
dlg_path = vPath;
dlg_defaultFileName = vDefaultFileName;
dlg_optionsPane = 0;
dlg_userString = vUserString;
dlg_optionsPaneWidth = 0;
dlg_defaultExt = "";
m_ShowDialog = true;
}
void ImGuiFileDialog::CloseDialog(const std::string& vKey)
{
if (dlg_key == vKey)
{
dlg_key.clear();
m_ShowDialog = false;
}
}
void ImGuiFileDialog::SetPath(const std::string& vPath)
{
m_ShowDrives = false;
m_CurrentPath = vPath;
m_FileList.clear();
m_CurrentPath_Decomposition.clear();
ScanDir(m_CurrentPath);
}
bool ImGuiFileDialog::FileDialog(const std::string& vKey)
{
if (m_ShowDialog && dlg_key == vKey)
{
bool res = false;
std::string name = dlg_name + "##" + dlg_key;
if (m_Name != name)
{
m_FileList.clear();
m_CurrentPath_Decomposition.clear();
}
IsOk = false;
if (ImGui::Begin(name.c_str(), (bool*)0, ImGuiWindowFlags_Modal |
ImGuiWindowFlags_NoCollapse /*| ImGuiWindowFlags_NoDocking*/))
{
m_Name = name;
m_AnyWindowsHovered |= ImGui::IsWindowHovered();
if (dlg_path.size() == 0) dlg_path = ".";
if (m_FileList.size() == 0 && !m_ShowDrives)
{
replaceString(dlg_defaultFileName, dlg_path, ""); // local path
if (dlg_defaultFileName.size() > 0)
{
ResetBuffer(FileNameBuffer);
AppendToBuffer(FileNameBuffer, MAX_FILE_DIALOG_NAME_BUFFER, dlg_defaultFileName);
m_SelectedFileName = dlg_defaultFileName;
if (dlg_defaultExt.size() > 0)
{
m_SelectedExt = dlg_defaultExt;
ImGuiFileDialog::FilterIndex = 0;
size_t size = 0;
const char* p = dlg_filters; // FIXME-OPT: Avoid computing this, or at least only when combo is open
while (*p)
{
size += strlen(p) + 1;
p += size;
}
int idx = 0;
auto arr = splitStringToVector(std::string(dlg_filters, size), '\0', false);
for (auto it = arr.begin(); it != arr.end(); ++it)
{
if (m_SelectedExt == *it)
{
ImGuiFileDialog::FilterIndex = idx;
break;
}
idx++;
}
}
}
ScanDir(dlg_path);
}
if (ImGui::Button("+"))
{
if (!m_CreateDirectoryMode)
{
m_CreateDirectoryMode = true;
ResetBuffer(DirectoryNameBuffer);
}
}
if (m_CreateDirectoryMode)
{
ImGui::SameLine();
ImGui::PushItemWidth(100.0f);
ImGui::InputText("##DirectoryFileName", DirectoryNameBuffer, MAX_FILE_DIALOG_NAME_BUFFER);
ImGui::PopItemWidth();
ImGui::SameLine();
if (ImGui::Button("OK"))
{
std::string newDir = std::string(DirectoryNameBuffer);
if (CreateDir(newDir))
{
SetPath(m_CurrentPath + PATH_SEP + newDir);
}
m_CreateDirectoryMode = false;
}
ImGui::SameLine();
if (ImGui::Button("Cancel"))
{
m_CreateDirectoryMode = false;
}
}
ImGui::SameLine();
//ImGui::SeparatorEx(ImGuiSeparatorFlags_Vertical);
ImGui::SameLine();
if (ImGui::Button("R"))
{
SetPath(".");
}
bool drivesClick = false;
#ifdef WIN32
ImGui::SameLine();
if (ImGui::Button("Drives"))
{
drivesClick = true;
}
#endif
ImGui::SameLine();
//ImGui::SeparatorEx(ImGuiSeparatorFlags_Vertical);
// show current path
bool pathClick = false;
if (m_CurrentPath_Decomposition.size() > 0)
{
ImGui::SameLine();
for (std::vector<std::string>::iterator itPathDecomp = m_CurrentPath_Decomposition.begin();
itPathDecomp != m_CurrentPath_Decomposition.end(); ++itPathDecomp)
{
if (itPathDecomp != m_CurrentPath_Decomposition.begin())
ImGui::SameLine();
if (ImGui::Button((*itPathDecomp).c_str()))
{
ComposeNewPath(itPathDecomp);
pathClick = true;
break;
}
}
}
ImVec2 size = ImGui::GetContentRegionMax() - ImVec2((float)dlg_optionsPaneWidth, 120.0f);
// search field
if (ImGui::Button("R##ImGuiFileDialogSearchFiled"))
{
ResetBuffer(SearchBuffer);
searchTag.clear();
}
ImGui::SameLine();
ImGui::Text("Search : ");
ImGui::SameLine();
if (ImGui::InputText("##ImGuiFileDialogSearchFiled", SearchBuffer, MAX_FILE_DIALOG_NAME_BUFFER))
{
searchTag = SearchBuffer;
}
ImGui::BeginChild("##FileDialog_FileList", size);
for (std::vector<FileInfoStruct>::iterator it = m_FileList.begin(); it != m_FileList.end(); ++it)
{
const FileInfoStruct& infos = *it;
bool show = true;
std::string str;
if (infos.type == 'd') str = "[Dir] " + infos.fileName;
if (infos.type == 'l') str = "[Link] " + infos.fileName;
if (infos.type == 'f') str = "[File] " + infos.fileName;
if (infos.type == 'f' && m_SelectedExt.size() > 0 && (infos.ext != m_SelectedExt && m_SelectedExt != ".*"))
{
show = false;
}
if (searchTag.size() > 0 && infos.fileName.find(searchTag) == std::string::npos)
{
show = false;
}
if (show == true)
{
ImVec4 c;
bool showColor = GetFilterColor(infos.ext, &c);
if (showColor)
ImGui::PushStyleColor(ImGuiCol_Text, c);
if (ImGui::Selectable(str.c_str(), (infos.fileName == m_SelectedFileName)))
{
if (infos.type == 'd')
{
if ((*it).fileName == "..")
{
if (m_CurrentPath_Decomposition.size() > 1)
{
ComposeNewPath(m_CurrentPath_Decomposition.end() - 2);
pathClick = true;
}
}
else
{
std::string newPath;
if (m_ShowDrives)
{
newPath = infos.fileName + PATH_SEP;
}
else
{
#ifdef LINUX
if (s_fs_root == m_CurrentPath)
{
newPath = m_CurrentPath + infos.fileName;
}
else
{
#endif
newPath = m_CurrentPath + PATH_SEP + infos.fileName;
#ifdef LINUX
}
#endif
}
if (IsDirectoryExist(newPath))
{
if (m_ShowDrives)
{
m_CurrentPath = infos.fileName;
s_fs_root = m_CurrentPath;
}
else
{
m_CurrentPath = newPath;
}
pathClick = true;
}
}
}
else
{
m_SelectedFileName = infos.fileName;
ResetBuffer(FileNameBuffer);
AppendToBuffer(FileNameBuffer, MAX_FILE_DIALOG_NAME_BUFFER, m_SelectedFileName);
}
if (showColor)
ImGui::PopStyleColor();
break;
}
if (showColor)
ImGui::PopStyleColor();
}
}
// changement de repertoire
if (pathClick == true)
{
SetPath(m_CurrentPath);
}
if (drivesClick == true)
{
GetDrives();
}
ImGui::EndChild();
bool _CanWeContinue = true;
if (dlg_optionsPane)
{
ImGui::SameLine();
size.x = (float)dlg_optionsPaneWidth;
ImGui::BeginChild("##FileTypes", size);
dlg_optionsPane(m_SelectedExt, &_CanWeContinue);
ImGui::EndChild();
}
ImGui::Text("File Name : ");
ImGui::SameLine();
float width = ImGui::GetContentRegionAvail().x;
if (dlg_filters) width -= 120.0f;
ImGui::PushItemWidth(width);
ImGui::InputText("##FileName", FileNameBuffer, MAX_FILE_DIALOG_NAME_BUFFER);
ImGui::PopItemWidth();
if (dlg_filters)
{
ImGui::SameLine();
ImGui::PushItemWidth(100.0f);
bool comboClick = ImGui::Combo("##Filters", &FilterIndex, dlg_filters) || m_SelectedExt.size() == 0;
ImGui::PopItemWidth();
if (comboClick == true)
{
int itemIdx = 0;
const char* p = dlg_filters;
while (*p)
{
if (FilterIndex == itemIdx)
{
m_SelectedExt = std::string(p);
break;
}
p += strlen(p) + 1;
itemIdx++;
}
}
}
if (ImGui::Button("Cancel"))
{
IsOk = false;
res = true;
}
if (_CanWeContinue)
{
ImGui::SameLine();
if (ImGui::Button("Ok"))
{
if ('\0' != FileNameBuffer[0])
{
IsOk = true;
res = true;
}
}
}
}
ImGui::End();
if (res == true)
{
m_FileList.clear();
}
return res;
}
return false;
}
std::string ImGuiFileDialog::GetFilepathName()
{
std::string result = m_CurrentPath;
if (s_fs_root != result)
{
result += PATH_SEP;
}
result += GetCurrentFileName();
return result;
}
std::string ImGuiFileDialog::GetCurrentPath()
{
return m_CurrentPath;
}
std::string ImGuiFileDialog::GetCurrentFileName()
{
std::string result = FileNameBuffer;
size_t lastPoint = result.find_last_of('.');
if (lastPoint != std::string::npos)
{
result = result.substr(0, lastPoint);
}
result += m_SelectedExt;
return result;
}
std::string ImGuiFileDialog::GetFinalFileName()
{
std::string result = m_CurrentPath + "/" + FileNameBuffer;
return result;
}
std::string ImGuiFileDialog::GetCurrentFilter()
{
return m_SelectedExt;
}
std::string ImGuiFileDialog::GetUserString()
{
return dlg_userString;
}
void ImGuiFileDialog::SetFilterColor(std::string vFilter, ImVec4 vColor)
{
m_FilterColor[vFilter] = vColor;
}
bool ImGuiFileDialog::GetFilterColor(std::string vFilter, ImVec4 *vColor)
{
if (vColor)
{
if (m_FilterColor.find(vFilter) != m_FilterColor.end()) // found
{
*vColor = m_FilterColor[vFilter];
return true;
}
}
return false;;
}
void ImGuiFileDialog::ClearFilterColor()
{
m_FilterColor.clear();
}
| 21.723108 | 112 | 0.610912 | [
"vector"
] |
edec0177a253b964b3cc03f1136c0a350f997116 | 2,438 | cpp | C++ | tests/rho/ip/tAddrTest.cpp | Rhobota/librho | d540cba6227e15ac6ef3dcb6549ed9557f6fee04 | [
"BSD-3-Clause"
] | 1 | 2016-09-22T03:27:33.000Z | 2016-09-22T03:27:33.000Z | tests/rho/ip/tAddrTest.cpp | Rhobota/librho | d540cba6227e15ac6ef3dcb6549ed9557f6fee04 | [
"BSD-3-Clause"
] | null | null | null | tests/rho/ip/tAddrTest.cpp | Rhobota/librho | d540cba6227e15ac6ef3dcb6549ed9557f6fee04 | [
"BSD-3-Clause"
] | null | null | null | #include <rho/ip/tAddr.h>
#include <rho/ip/tAddrGroup.h>
#include <rho/tCrashReporter.h>
#include <rho/tTest.h>
#include <iostream>
#include <string>
#include <vector>
/*
* Note: tAddr isn't constructable by client code, so to test it we'll have
* to use tAddrGroup to get some tAddr objects.
*/
using namespace rho;
using std::cout;
using std::endl;
void ipv4Test(const tTest& t)
{
std::string ipStr = "2.3.4.5";
std::vector<u8> correctIpBytes;
correctIpBytes.push_back(2);
correctIpBytes.push_back(3);
correctIpBytes.push_back(4);
correctIpBytes.push_back(5);
{
ip::tAddrGroup g(ipStr, false);
t.iseq(g.size(), 1);
ip::tAddr addr = g[0];
t.iseq(addr.getVersion(), ip::kIPv4);
t.iseq(addr.toString(), ipStr);
t.iseq(addr.getAddress(), correctIpBytes);
}
{
ip::tAddrGroup g(ipStr, true);
t.iseq(g.size(), 1);
ip::tAddr addr = g[0];
t.iseq(addr.getVersion(), ip::kIPv4);
t.iseq(addr.toString(), ipStr);
t.iseq(addr.getAddress(), correctIpBytes);
}
}
void ipv6Test(const tTest& t)
{
std::string ipStr = "1122:3344:5566:7788:99aa:bbcc:ddee:11ff";
std::vector<u8> correctIpBytes;
correctIpBytes.push_back(0x11);
correctIpBytes.push_back(0x22);
correctIpBytes.push_back(0x33);
correctIpBytes.push_back(0x44);
correctIpBytes.push_back(0x55);
correctIpBytes.push_back(0x66);
correctIpBytes.push_back(0x77);
correctIpBytes.push_back(0x88);
correctIpBytes.push_back(0x99);
correctIpBytes.push_back(0xAA);
correctIpBytes.push_back(0xBB);
correctIpBytes.push_back(0xCC);
correctIpBytes.push_back(0xDD);
correctIpBytes.push_back(0xEE);
correctIpBytes.push_back(0x11);
correctIpBytes.push_back(0xFF);
{
ip::tAddrGroup g(ipStr, false);
t.iseq(g.size(), 1);
ip::tAddr addr = g[0];
t.iseq(addr.getVersion(), ip::kIPv6);
t.iseq(addr.toString(), ipStr);
t.iseq(addr.getAddress(), correctIpBytes);
}
{
ip::tAddrGroup g(ipStr, true);
t.iseq(g.size(), 1);
ip::tAddr addr = g[0];
t.iseq(addr.getVersion(), ip::kIPv6);
t.iseq(addr.toString(), ipStr);
t.iseq(addr.getAddress(), correctIpBytes);
}
}
int main()
{
tCrashReporter::init();
tTest("ipv4 test", ipv4Test);
tTest("ipv6 test", ipv6Test);
return 0;
}
| 24.626263 | 75 | 0.626743 | [
"vector"
] |
edf42469dc6f3d080b5720b968583d1221a77460 | 3,855 | cpp | C++ | src/libv/update/update_client/network_client.cpp | cpplibv/libv | 293e382f459f0acbc540de8ef6283782b38d2e63 | [
"Zlib"
] | 2 | 2018-04-11T03:07:03.000Z | 2019-03-29T15:24:12.000Z | src/libv/update/update_client/network_client.cpp | cpplibv/libv | 293e382f459f0acbc540de8ef6283782b38d2e63 | [
"Zlib"
] | null | null | null | src/libv/update/update_client/network_client.cpp | cpplibv/libv | 293e382f459f0acbc540de8ef6283782b38d2e63 | [
"Zlib"
] | 1 | 2021-06-13T06:39:06.000Z | 2021-06-13T06:39:06.000Z | // Project: libv.update, File: src/libv/update/update_client/network_client.cpp, Author: Császár Mátyás [Vader]
// hpp
#include <libv/update/update_client/network_client.hpp>
// libv
#include <libv/mt/binary_latch.hpp>
#include <libv/net/mtcp/connection_he.hpp>
#include <libv/serial/archive/binary.hpp>
#include <libv/serial/codec.hpp>
#include <libv/utility/hex_dump.hpp> // <<< hex_dump_with_ascii
//#include <libv/net/error.hpp>
// std
// pro
#include <libv/update/common/protocol_upd.hpp>
#include <libv/update/log.hpp>
namespace libv {
namespace update {
// -------------------------------------------------------------------------------------------------
class aux_UpdateNetworkClient : public libv::net::mtcp::ConnectionHandler<aux_UpdateNetworkClient> {
public:
libv::mt::binary_latch latch;
error_code error;
std::vector<std::byte> response;
msg_upd::UpdateRoute info;
bool version_not_supported = false;
bool version_outdated = false;
bool version_up_to_date = false;
public:
inline explicit aux_UpdateNetworkClient(libv::net::Address address, std::vector<std::byte> message) {
connection.connect_async(std::move(address));
connection.send_async(std::move(message));
}
public:
void receive(const msg_upd::VersionNotSupported&) {
version_not_supported = true;
}
void receive(msg_upd::UpdateRoute info_) {
version_outdated = true;
info = std::move(info_);
}
void receive(const msg_upd::VersionUpToDate&) {
version_up_to_date = true;
}
private:
virtual void on_connect(error_code ec) override {
if (ec) {
error = ec;
latch.raise();
}
}
virtual void on_receive(error_code ec, message m) override {
if (!ec) {
response = std::vector<std::byte>(m.begin(), m.end());
connection.disconnect_async();
}
}
virtual void on_send(error_code ec, message m) override {
}
virtual void on_disconnect(error_code ec) override {
error = ec;
latch.raise();
}
};
namespace { // -------------------------------------------------------------------------------------
static auto codec = libv::serial::CodecClient<aux_UpdateNetworkClient, libv::archive::Binary>{msg_upd{}};
} // namespace -------------------------------------------------------------------------------------
UpdateNetworkClient::UpdateNetworkClient(net::IOContext& ioContext, net::Address serverAddress) :
io_context(ioContext),
server_address(std::move(serverAddress)) {}
update_check_result UpdateNetworkClient::check_version(std::string program_name, std::string program_variant, version_number current_version) {
const auto report = msg_upd::ReportVersion(program_name, program_variant, current_version);
const auto message = codec.encode(report);
log_update.debug("Report: \n{}", libv::hex_dump_with_ascii(message)); // <<< hex_dump_with_ascii
const auto connection = libv::net::mtcp::Connection<aux_UpdateNetworkClient>(io_context, server_address, message);
// No need to limit for version checking
// connection.read_limit(100); // bytes per second
// connection.write_limit(100); // bytes per second
connection->latch.wait();
if (connection->error)
return update_check_result::communication_error;
log_update.debug("Response: \n{}", libv::hex_dump_with_ascii(connection->response)); // <<< hex_dump_with_ascii
codec.decode(*connection, connection->response);
if (connection->version_up_to_date)
return update_check_result::version_up_to_date;
if (connection->version_not_supported)
return update_check_result::version_not_supported;
if (connection->version_outdated) {
update_info_ = connection->info;
return update_check_result::version_outdated;
}
assert(false && "Internal error");
return update_check_result::communication_error;
}
// -------------------------------------------------------------------------------------------------
} // namespace update
} // namespace libv
| 30.84 | 143 | 0.680156 | [
"vector"
] |
edf71c44322a34a94eaa4bf4bf3f5d4e3e40be8d | 3,302 | hh | C++ | src/cpu/o3/hash.hh | dskarlatos/JamaisVu | bb3e072b594673f492dc3d612ff185c2c9bd91da | [
"MIT",
"BSD-3-Clause"
] | 4 | 2020-12-11T18:48:36.000Z | 2021-11-08T20:11:51.000Z | src/cpu/o3/hash.hh | dskarlatos/JamaisVu | bb3e072b594673f492dc3d612ff185c2c9bd91da | [
"MIT",
"BSD-3-Clause"
] | null | null | null | src/cpu/o3/hash.hh | dskarlatos/JamaisVu | bb3e072b594673f492dc3d612ff185c2c9bd91da | [
"MIT",
"BSD-3-Clause"
] | null | null | null | /* Copyright (c) 2016, Matthias Vallentin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
GitHub: https://github.com/mavam/libbf */
#ifndef BF_HASH_POLICY_HPP
#define BF_HASH_POLICY_HPP
#include <functional>
#include "cpu/o3/h3.hh"
#include "cpu/o3/object.hh"
namespace bf {
/// The hash digest type.
typedef size_t digest;
/// The hash function type.
typedef std::function<digest(object const&)> hash_function;
/// A function that hashes an object *k* times.
typedef std::function<std::vector<digest>(object const&)> hasher;
class default_hash_function
{
public:
constexpr static size_t max_obj_size = 36;
default_hash_function(size_t seed);
size_t operator()(object const& o) const;
private:
h3<size_t, max_obj_size> h3_;
};
/// A hasher which hashes an object *k* times.
class default_hasher
{
public:
default_hasher(std::vector<hash_function> fns);
std::vector<digest> operator()(object const& o) const;
private:
std::vector<hash_function> fns_;
};
/// A hasher which hashes an object two times and generates *k* digests through
/// a linear combinations of the two digests.
class double_hasher
{
public:
double_hasher(size_t k, hash_function h1, hash_function h2);
std::vector<digest> operator()(object const& o) const;
private:
size_t k_;
hash_function h1_;
hash_function h2_;
};
/// Creates a default or double hasher with the default hash function, using
/// seeds from a linear congruential PRNG.
///
/// @param k The number of hash functions to use.
///
/// @param seed The initial seed of the PRNG.
///
/// @param double_hashing If `true`, the function constructs a ::double_hasher
/// and a ::default_hasher otherwise.
///
/// @return A ::hasher with the *k* hash functions.
///
/// @pre `k > 0`
hasher make_hasher(size_t k, size_t seed = 0, bool double_hashing = false);
} // namespace bf
#endif
| 30.574074 | 79 | 0.753786 | [
"object",
"vector"
] |
edf9945076d0362af100becca4ce7c56ac588580 | 4,574 | hpp | C++ | include/GlobalNamespace/OVRBoneCapsule.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/OVRBoneCapsule.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/OVRBoneCapsule.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Rigidbody
class Rigidbody;
// Forward declaring type: CapsuleCollider
class CapsuleCollider;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Size: 0x28
#pragma pack(push, 1)
// Autogenerated type: OVRBoneCapsule
class OVRBoneCapsule : public ::Il2CppObject {
public:
// [CompilerGeneratedAttribute] Offset: 0xDD12FC
// private System.Int16 <BoneIndex>k__BackingField
// Size: 0x2
// Offset: 0x10
int16_t BoneIndex;
// Field size check
static_assert(sizeof(int16_t) == 0x2);
// Padding between fields: BoneIndex and: CapsuleRigidbody
char __padding0[0x6] = {};
// [CompilerGeneratedAttribute] Offset: 0xDD130C
// private UnityEngine.Rigidbody <CapsuleRigidbody>k__BackingField
// Size: 0x8
// Offset: 0x18
UnityEngine::Rigidbody* CapsuleRigidbody;
// Field size check
static_assert(sizeof(UnityEngine::Rigidbody*) == 0x8);
// [CompilerGeneratedAttribute] Offset: 0xDD131C
// private UnityEngine.CapsuleCollider <CapsuleCollider>k__BackingField
// Size: 0x8
// Offset: 0x20
UnityEngine::CapsuleCollider* CapsuleCollider;
// Field size check
static_assert(sizeof(UnityEngine::CapsuleCollider*) == 0x8);
// Creating value type constructor for type: OVRBoneCapsule
OVRBoneCapsule(int16_t BoneIndex_ = {}, UnityEngine::Rigidbody* CapsuleRigidbody_ = {}, UnityEngine::CapsuleCollider* CapsuleCollider_ = {}) noexcept : BoneIndex{BoneIndex_}, CapsuleRigidbody{CapsuleRigidbody_}, CapsuleCollider{CapsuleCollider_} {}
// public System.Int16 get_BoneIndex()
// Offset: 0x125E5D4
int16_t get_BoneIndex();
// public System.Void set_BoneIndex(System.Int16 value)
// Offset: 0x125E5DC
void set_BoneIndex(int16_t value);
// public UnityEngine.Rigidbody get_CapsuleRigidbody()
// Offset: 0x125E5E4
UnityEngine::Rigidbody* get_CapsuleRigidbody();
// public System.Void set_CapsuleRigidbody(UnityEngine.Rigidbody value)
// Offset: 0x125E5EC
void set_CapsuleRigidbody(UnityEngine::Rigidbody* value);
// public UnityEngine.CapsuleCollider get_CapsuleCollider()
// Offset: 0x125E5F4
UnityEngine::CapsuleCollider* get_CapsuleCollider();
// public System.Void set_CapsuleCollider(UnityEngine.CapsuleCollider value)
// Offset: 0x125E5FC
void set_CapsuleCollider(UnityEngine::CapsuleCollider* value);
// public System.Void .ctor(System.Int16 boneIndex, UnityEngine.Rigidbody capsuleRigidBody, UnityEngine.CapsuleCollider capsuleCollider)
// Offset: 0x125E60C
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static OVRBoneCapsule* New_ctor(int16_t boneIndex, UnityEngine::Rigidbody* capsuleRigidBody, UnityEngine::CapsuleCollider* capsuleCollider) {
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::OVRBoneCapsule::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<OVRBoneCapsule*, creationType>(boneIndex, capsuleRigidBody, capsuleCollider)));
}
// public System.Void .ctor()
// Offset: 0x125E604
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static OVRBoneCapsule* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::OVRBoneCapsule::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<OVRBoneCapsule*, creationType>()));
}
}; // OVRBoneCapsule
#pragma pack(pop)
static check_size<sizeof(OVRBoneCapsule), 32 + sizeof(UnityEngine::CapsuleCollider*)> __GlobalNamespace_OVRBoneCapsuleSizeCheck;
static_assert(sizeof(OVRBoneCapsule) == 0x28);
}
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::OVRBoneCapsule*, "", "OVRBoneCapsule");
| 49.182796 | 253 | 0.721906 | [
"object"
] |
edfa66c0a7dc1ed69fa342637de3a44d46ceb90c | 4,883 | cpp | C++ | Parser.cpp | taraldv/MazeSolve | a110118f608aa087a8ee38d4723e073042a7c136 | [
"MIT"
] | 1 | 2020-12-07T10:55:35.000Z | 2020-12-07T10:55:35.000Z | Parser.cpp | taraldv/MazeSolve | a110118f608aa087a8ee38d4723e073042a7c136 | [
"MIT"
] | null | null | null | Parser.cpp | taraldv/MazeSolve | a110118f608aa087a8ee38d4723e073042a7c136 | [
"MIT"
] | null | null | null | /*
* A simple libpng example program
* http://zarb.org/~gc/html/libpng.html
*
* Modified by Yoshimasa Niwa to make it much simpler
* and support all defined color_type.
*
* To build, use the next instruction on OS X.
* $ brew install libpng
* $ clang -lz -lpng15 libpng_test.c
*
* Copyright 2002-2010 Guillaume Cottenceau.
*
* This software may be freely redistributed under the terms
* of the X11 license.
*
*/
#include "Parser.h"
using namespace std;
int Parser::getHeight(){
return height;
}
int Parser::getWidth(){
return width;
}
Parser::Parser(char* fname){
FILE *fp = fopen(fname, "rb");
png_structp png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if(!png) abort();
png_infop info = png_create_info_struct(png);
if(!info) abort();
if(setjmp(png_jmpbuf(png))) abort();
png_init_io(png, fp);
png_read_info(png, info);
width = png_get_image_width(png, info);
height = png_get_image_height(png, info);
color_type = png_get_color_type(png, info);
bit_depth = png_get_bit_depth(png, info);
// Read any color_type into 8bit depth, RGBA format.
// See http://www.libpng.org/pub/png/libpng-manual.txt
if(bit_depth == 16)
png_set_strip_16(png);
if(color_type == PNG_COLOR_TYPE_PALETTE)
png_set_palette_to_rgb(png);
// PNG_COLOR_TYPE_GRAY_ALPHA is always 8 or 16bit depth.
if(color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
png_set_expand_gray_1_2_4_to_8(png);
if(png_get_valid(png, info, PNG_INFO_tRNS))
png_set_tRNS_to_alpha(png);
// These color_type don't have an alpha channel then fill it with 0xff.
if(color_type == PNG_COLOR_TYPE_RGB ||
color_type == PNG_COLOR_TYPE_GRAY ||
color_type == PNG_COLOR_TYPE_PALETTE)
png_set_filler(png, 0xFF, PNG_FILLER_AFTER);
if(color_type == PNG_COLOR_TYPE_GRAY ||
color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
png_set_gray_to_rgb(png);
png_read_update_info(png, info);
row_pointers = (png_bytep*)malloc(sizeof(png_bytep) * height);
for(int y = 0; y < height; y++) {
row_pointers[y] = (png_byte*)malloc(png_get_rowbytes(png,info));
}
png_read_image(png, row_pointers);
fclose(fp);
}
/*void Parser::write(char *filename) {
int y;
FILE *fp = fopen(filename, "wb");
if(!fp) abort();
png_structp png = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!png) abort();
png_infop info = png_create_info_struct(png);
if (!info) abort();
if (setjmp(png_jmpbuf(png))) abort();
png_init_io(png, fp);
// Output is 8bit depth, RGBA format.
png_set_IHDR(
png,
info,
width, height,
8,
PNG_COLOR_TYPE_RGBA,
PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT,
PNG_FILTER_TYPE_DEFAULT
);
png_write_info(png, info);
// To remove the alpha channel for PNG_COLOR_TYPE_RGB format,
// Use png_set_filler().
//png_set_filler(png, 0, PNG_FILLER_AFTER);
png_write_image(png, row_pointers);
png_write_end(png, NULL);
fclose(fp);
}*/
void Parser::process() {
for(int y = 0; y < 18; y++) {
for(int x = 0; x < 18; x++) {
png_bytep px = &(row_pointers[y][x * 4]);
//cout << (int)px[0] << (int)px[1] << (int)px[2] << endl;
printf("%4d, %4d = RGBA(%3d, %3d, %3d, %3d)\n", x, y, px[0], px[1], px[2], px[3]);
}
}
}
//true hvis svart
int* Parser::getPixels(int col, int row){
png_bytep px = &(row_pointers[row][col * 4]);
int* arr = new int(3);
for(int i=0;i<3;i++){
arr[i] = (int)px[i];
}
return arr;
}
Square** Parser::parse(){
int side = 16;
int border = 1;
int numberOfSquareRows = (height-border*2)/side;
// cout << "numberOfSquareRows: "<< numberOfSquareRows << endl;
int numberOfSquareColumns = (width-border*2)/side;
//cout << "numberOfSquareColumns" << numberOfSquareColumns << endl;
squares = numberOfSquareRows*numberOfSquareColumns;
Square** squareArr = new Square*[squares];
//int count = 0;
for(int i=0;i<numberOfSquareRows;i++){
for(int j=0;j<numberOfSquareColumns;j++){
//count++;
int** pixelArr = new int*[side*side];
//cout << "square row: " << i << endl;
//cout << "square col: " << j << endl;
for(int x=0;x<side;x++){
int row = i*side+x;
for(int y=0;y<side;y++){
int col = j*side+y;
//cout << "pixel row&col: " << row+1 << "&" << col+1 << endl;
pixelArr[x*side+y] = getPixels(col+1,row+1);
}
}
int squareIndex = i*numberOfSquareColumns+j;
//cout << "new Square på index:" << squareIndex << " row:" << i << " col:" << j << endl;
squareArr[squareIndex] = new Square(pixelArr,j,i);
}
}
//cout << "count: " << count << endl;
return squareArr;
}
int Parser::getSquareNumber(){
return squares;
}
Parser::~Parser(){
for(int y = 0; y < height; y++) {
free(row_pointers[y]);
}
free(row_pointers);
} | 25.7 | 94 | 0.641614 | [
"3d"
] |
edfac8e975a6143d58bd0dafd4170869aa45efbe | 9,622 | cpp | C++ | VideojuegoIPOO/Game.cpp | AlonsoCerpa/IPOO | 269082c967feac4e46f120d0a031917a024a6826 | [
"MIT"
] | null | null | null | VideojuegoIPOO/Game.cpp | AlonsoCerpa/IPOO | 269082c967feac4e46f120d0a031917a024a6826 | [
"MIT"
] | null | null | null | VideojuegoIPOO/Game.cpp | AlonsoCerpa/IPOO | 269082c967feac4e46f120d0a031917a024a6826 | [
"MIT"
] | null | null | null | #include "Game.h"
#include <iostream>
#include <random>
#include <SFML/Audio.hpp>
Game *Game::uniqueGame = nullptr;
///////////////////////////////////////////////////////////////////////////////
Game *Game::getInstance()
{
if (uniqueGame == nullptr)
uniqueGame = new Game();
return uniqueGame;
}
Game::Game() : ventana{sf::VideoMode{800, 600}, "Videojuego de carros"},
arrObstacle{{&redCar, &policeCar, &truck1, &blackCar,
&taxi, &truck2, &motorcycle, &bicycle}},
arrCarPlayer{{&mainCar}},
obs{{&obs1, &obs2, &obs3}}
{
}
///////////////////////////////////////////////////////////////////////////////
int Game::inicializar(){
topPlayersFile.open("topPlayers.txt");
for (int i = 0; i <= 4; ++i)
{
topPlayersFile.getline(arrChar, 24);
inputAux = string{arrChar};
posRead = static_cast<int>(inputAux[0]) - 48;
nameRead = inputAux.substr(2, 16);
scoreRead = std::stoi(inputAux.substr(19, 4));
arrPly.arrPtrPlayers.push_back(new PlayerScore{posRead, nameRead, scoreRead});
std::cout << arrPly.arrPtrPlayers[i]->getInfo();
}
score = 0;
ventana.setFramerateLimit(60);
ventana.setVerticalSyncEnabled(false);
timeFloat = clock.getElapsedTime().asSeconds();
timeInt = static_cast<int>(timeFloat);
localPosition = sf::Mouse::getPosition(ventana);
/*
text.setFont(font);
text.setString("exitB");
text.setCharacterSize(150);
text.setColor(sf::Color::Red);
text.setStyle(sf::Text::Bold);
text.setPosition(sf::Vector2f{70.f, 20.f});
*/
namePlayerT.setFont(font);
namePlayerT.setCharacterSize(40);
namePlayerT.setColor(sf::Color::Red);
namePlayerT.setStyle(sf::Text::Bold);
namePlayerT.setPosition(sf::Vector2f{240.f, 20.f});
scoreText.setFont(font);
scoreText.setCharacterSize(40);
scoreText.setColor(sf::Color::Red);
scoreText.setStyle(sf::Text::Bold);
scoreText.setPosition(sf::Vector2f{610.f, 20.f});
std::srand(std::time(0));
if(!loadSounds())
return 1;
if(!loadImages())
return 1;
setSounds();
setTextures();
iniMusicNoEnd.play();
menu.setScreenPosition(sf::Vector2f{195.f, 0.f});
fondoMenu.setScreenPosition(sf::Vector2f{195.f, 102.f});
options.setScreenPosition(sf::Vector2f(195.f, 0.f));
topPlayers.setScreenPosition(sf::Vector2f(195.f, 0.f));
credits.setScreenPosition(sf::Vector2f(195.f, 0.f));
newGameB.setScreenPosition(sf::Vector2f{195.f, 200.f});
optionsB.setScreenPosition(sf::Vector2f{195.f, 280.f});
topPlayersB.setScreenPosition(sf::Vector2f{195.f, 360.f});
creditsB.setScreenPosition(sf::Vector2f{195.f, 440.f});
exitB.setScreenPosition(sf::Vector2f{195.f, 520.f});
pista.setFondoPosition(sf::Vector2f{118.f, 0.f});
treesL.setFondoPosition(sf::Vector2f{0.f, 0.f});
treesR.setFondoPosition(sf::Vector2f{681.f, 0.f});
mainCar.setVehiclePosition(sf::Vector2f(365.f, 463.f));
return 0;
}
/////////////////////////////////////////////////////////////////////////////
void Game::eventos(){
while (ventana.pollEvent(miEvento)){
switch (miEvento.type)
{
case sf::Event::Closed:
isPlaying = false;
break;
case sf::Event::KeyPressed:
switchKeyPressed();
break;
case sf::Event::KeyReleased:
switchKeyReleased();
break;
case sf::Event::TextEntered:
if (topPlayersB.buttonPressed())
{
if (miEvento.text.unicode >= 32 && miEvento.text.unicode <= 126 && numCharEnter <= 15)
{
namePlayerS.insert(namePlayerS.getSize(),
miEvento.text.unicode);
++numCharEnter;
}
else if (miEvento.text.unicode == 8)
{
namePlayerS = namePlayerS.substring(0, namePlayerS.getSize() - 1);
--numCharEnter;
}
}
break;
default:
break;
}
}
}
/////////////////////////////////////////////////////////////////////////////
void Game::update(){
if (enterReleased)
{
//topPlayersFile.open("topPlayers.txt");
aux = namePlayerS.toAnsiString();
int sizeAux = aux.size();
for (int i = 0; i < 16 - sizeAux; ++i)
aux.push_back(' ');
arrPly.insertPlayer(new PlayerScore{aux, score});
for (unsigned i = 0; i <= 4; ++i)
{
std::cout << (arrPly.getPlayer(i))->getInfo();
topPlayersFile << (arrPly.getPlayer(i))->getInfo();
}
//topPlayersFile.close();
}
localPosition = sf::Mouse::getPosition(ventana);
posX = static_cast<float>(localPosition.x);
posY = static_cast<float>(localPosition.y);
timeFloat = clock.getElapsedTime().asSeconds();
timeInt = static_cast<int>(timeFloat);
//std::cout << timeFloat << std::endl;
if(menu.ScreenIsOpen())
{
checkMenu();
if(!bodyMusicStart && iniMusicNoEnd.getStatus() == 0){
bodyMusicStart = true;
iniMusicNoEnd.stop();
bodyMusic.play();
bodyMusic.setLoop(true);
}
newGameB.updateButton();
optionsB.updateButton();
topPlayersB.updateButton();
creditsB.updateButton();
exitB.updateButton();
}
else if(newGameB.buttonPressed())
{
++score;
scoreString = std::to_string(score/20);
scoreText.setString(scoreString);
if(numPitch < 1)
numPitch += 0.0002;
//std::cout << numPitch << std::endl;
if (!newGameBMusicStart){
newGameBMusicStart = true;
if(!bodyMusicStart)
iniMusicNoEnd.stop();
else{
bodyMusic.stop();
bodyMusicStart = false;
}
iniMusicNoEnd.play();
}
iniMusicNoEnd.setPitch(numPitch);
if (!bodyMusicStart && iniMusicNoEnd.getStatus() == 0)
{
bodyMusicStart = true;
bodyMusic.play();
bodyMusic.setLoop(true);
}
if(bodyMusicStart)
bodyMusic.setPitch(numPitch);
if (upReleased)
upDone = false;
if (downReleased)
downDone = false;
if (leftReleased)
leftDone = false;
if (rightReleased)
rightDone = false;
if (UP && !upDone)
{
mainCar.movement(1);
upDone = true;
}
else if (DOWN && !downDone)
{
mainCar.movement(2);
downDone = true;
}
else if (LEFT && !leftDone)
{
mainCar.movement(3);
leftDone = true;
}
else if (RIGHT && !rightDone)
{
mainCar.movement(4);
rightDone = true;
}
Obstacle::setVehicleSpeed(0.003f);
pista.moveFondo(1);
treesL.moveFondo(2);
treesR.moveFondo(2);
//Movement
if (finishMove){
key = minInt + (rand() % (int)(maxInt - minInt + 1));
rand1 = minPos + (rand() % (int)(maxPos - minPos + 1));
rand2 = minPos + (rand() % (int)(maxPos - minPos + 1));
rand3 = minPos + (rand() % (int)(maxPos - minPos + 1));
finishMove = false;
newMovement = true;
}
else
movementSchemeUpdate();
if (mainCar.getVehicleBounds().intersects(obs1.getVehicleBounds()))
isPlaying = false;
if (mainCar.getVehicleBounds().intersects(obs2.getVehicleBounds()))
isPlaying = false;
if (mainCar.getVehicleBounds().intersects(obs3.getVehicleBounds()))
isPlaying = false;
}
else if(topPlayersB.buttonPressed())
{
namePlayerT.setString(namePlayerS);
}
updateKeyStates();
}
/////////////////////////////////////////////////////////////////////////////
void Game::render(){
ventana.clear();
if(menu.ScreenIsOpen()){
//ventana.draw(text);
ventana.draw(fondoMenu.getScreenSprite());
ventana.draw(menu.getScreenSprite());
ventana.draw(newGameB.ScreenSprite);
ventana.draw(optionsB.ScreenSprite);
ventana.draw(topPlayersB.ScreenSprite);
ventana.draw(creditsB.ScreenSprite);
ventana.draw(exitB.ScreenSprite);
}
else if(optionsB.buttonPressed())
ventana.draw(options.getScreenSprite());
else if(topPlayersB.buttonPressed()){
ventana.draw(topPlayers.getScreenSprite());
ventana.draw(namePlayerT);
}
else if(creditsB.buttonPressed())
ventana.draw(credits.getScreenSprite());
else if (newGameB.buttonPressed()){
ventana.draw(treesL.getFondoSprite());
ventana.draw(treesR.getFondoSprite());
ventana.draw(pista.getFondoSprite());
ventana.draw(scoreText);
ventana.draw(mainCar.getVehicleSprite());
if (!finishMove)
obstacleRender();
}
ventana.display();
}
/////////////////////////////////////////////////////////////////////////////
void Game::cleared(){
ventana.close();
}
/////////////////////////////////////////////////////////////////////////////
void Game::run(){
inicializar();
while(isPlaying){
eventos();
update();
render();
}
topPlayersFile.close();
cleared();
}
| 27.25779 | 102 | 0.530555 | [
"render"
] |
61020899cbc4a7e433b151dccaebfe90764d3e2d | 4,832 | cpp | C++ | 3rdparty/webkit/Source/WebCore/Modules/gamepad/NavigatorGamepad.cpp | mchiasson/PhaserNative | f867454602c395484bf730a7c43b9c586c102ac2 | [
"MIT"
] | null | null | null | 3rdparty/webkit/Source/WebCore/Modules/gamepad/NavigatorGamepad.cpp | mchiasson/PhaserNative | f867454602c395484bf730a7c43b9c586c102ac2 | [
"MIT"
] | 9 | 2020-04-18T18:47:18.000Z | 2020-04-18T18:52:41.000Z | Source/WebCore/Modules/gamepad/NavigatorGamepad.cpp | ijsf/DeniseEmbeddableWebKit | 57dfc6783d60f8f59b7129874e60f84d8c8556c9 | [
"BSD-3-Clause"
] | 1 | 2019-01-25T13:55:25.000Z | 2019-01-25T13:55:25.000Z | /*
* Copyright (C) 2014 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "NavigatorGamepad.h"
#if ENABLE(GAMEPAD)
#include "Gamepad.h"
#include "GamepadManager.h"
#include "GamepadProvider.h"
#include "Navigator.h"
#include "PlatformGamepad.h"
namespace WebCore {
NavigatorGamepad::NavigatorGamepad()
{
GamepadManager::singleton().registerNavigator(this);
}
NavigatorGamepad::~NavigatorGamepad()
{
GamepadManager::singleton().unregisterNavigator(this);
}
const char* NavigatorGamepad::supplementName()
{
return "NavigatorGamepad";
}
NavigatorGamepad* NavigatorGamepad::from(Navigator* navigator)
{
NavigatorGamepad* supplement = static_cast<NavigatorGamepad*>(Supplement<Navigator>::from(navigator, supplementName()));
if (!supplement) {
auto newSupplement = std::make_unique<NavigatorGamepad>();
supplement = newSupplement.get();
provideTo(navigator, supplementName(), WTFMove(newSupplement));
}
return supplement;
}
Ref<Gamepad> NavigatorGamepad::gamepadFromPlatformGamepad(PlatformGamepad& platformGamepad)
{
unsigned index = platformGamepad.index();
if (index >= m_gamepads.size() || !m_gamepads[index])
return Gamepad::create(platformGamepad);
return *m_gamepads[index];
}
const Vector<RefPtr<Gamepad>>& NavigatorGamepad::getGamepads(Navigator& navigator)
{
return NavigatorGamepad::from(&navigator)->gamepads();
}
const Vector<RefPtr<Gamepad>>& NavigatorGamepad::gamepads()
{
if (m_gamepads.isEmpty())
return m_gamepads;
const Vector<PlatformGamepad*>& platformGamepads = GamepadProvider::singleton().platformGamepads();
for (unsigned i = 0; i < platformGamepads.size(); ++i) {
if (!platformGamepads[i]) {
ASSERT(!m_gamepads[i]);
continue;
}
ASSERT(m_gamepads[i]);
m_gamepads[i]->updateFromPlatformGamepad(*platformGamepads[i]);
}
return m_gamepads;
}
void NavigatorGamepad::gamepadsBecameVisible()
{
const Vector<PlatformGamepad*>& platformGamepads = GamepadProvider::singleton().platformGamepads();
m_gamepads.resize(platformGamepads.size());
for (unsigned i = 0; i < platformGamepads.size(); ++i) {
if (!platformGamepads[i])
continue;
m_gamepads[i] = Gamepad::create(*platformGamepads[i]);
}
}
void NavigatorGamepad::gamepadConnected(PlatformGamepad& platformGamepad)
{
// If this is the first gamepad this Navigator object has seen, then all gamepads just became visible.
if (m_gamepads.isEmpty()) {
gamepadsBecameVisible();
return;
}
unsigned index = platformGamepad.index();
ASSERT(GamepadProvider::singleton().platformGamepads()[index] == &platformGamepad);
// The new index should already fit in the existing array, or should be exactly one past-the-end of the existing array.
ASSERT(index <= m_gamepads.size());
if (index < m_gamepads.size())
m_gamepads[index] = Gamepad::create(platformGamepad);
else if (index == m_gamepads.size())
m_gamepads.append(Gamepad::create(platformGamepad));
}
void NavigatorGamepad::gamepadDisconnected(PlatformGamepad& platformGamepad)
{
// If this Navigator hasn't seen any gamepads yet its Vector will still be empty.
if (!m_gamepads.size())
return;
ASSERT(platformGamepad.index() < m_gamepads.size());
ASSERT(m_gamepads[platformGamepad.index()]);
m_gamepads[platformGamepad.index()] = nullptr;
}
} // namespace WebCore
#endif // ENABLE(GAMEPAD)
| 32.870748 | 124 | 0.720199 | [
"object",
"vector"
] |
61022a877c334ff9778584dac904ba89c45d1b18 | 1,495 | cpp | C++ | PathfindingSandbox/Scenario.cpp | SgtWiggles/PathfindingSandbox | 8c247b52d2888ee0b5345163b45559283123c9c1 | [
"MIT"
] | null | null | null | PathfindingSandbox/Scenario.cpp | SgtWiggles/PathfindingSandbox | 8c247b52d2888ee0b5345163b45559283123c9c1 | [
"MIT"
] | null | null | null | PathfindingSandbox/Scenario.cpp | SgtWiggles/PathfindingSandbox | 8c247b52d2888ee0b5345163b45559283123c9c1 | [
"MIT"
] | null | null | null | #include "Scenario.h"
#include <fstream>
#include <iostream>
#include <sstream>
void Scenario::loadScenario(const std::string_view path) {
auto file = std::fstream(path.data());
std::string line;
std::string map;
int w, h;
std::getline(file, line);
while (std::getline(file, line)) {
ScenarioCase c;
auto iss = std::istringstream(line);
if (!(iss >> c.bucket >> map >> w >> h >> c.sx >> c.sy >> c.gx >> c.gy >>
c.optimal)) {
// TODO complain
break;
}
addCase(c);
}
}
const std::vector<ScenarioCase> &Scenario::getBucket(int bucket) const {
return m_buckets[bucket];
}
int Scenario::getTotalBuckets() const { return m_buckets.size(); }
void Scenario::addCase(ScenarioCase cas) {
if (m_buckets.size() <= cas.bucket)
m_buckets.resize(cas.bucket + 1);
m_buckets[cas.bucket].push_back(cas);
}
#define COUT_PAIR(LEFT, RIGHT) "(" << LEFT << "," << RIGHT << ")"
void Scenario::print() const {
for (int i = 0, end = m_buckets.size(); i < end; ++i) {
const auto &bucket = m_buckets[i];
for (int j = 0, end2 = bucket.size(); j < end2; ++j) {
const auto &cbucket = bucket[j];
std::cout << i << COUT_PAIR(cbucket.sx, cbucket.sy) << "->"
<< COUT_PAIR(cbucket.gx, cbucket.gy) << "\n";
}
}
}
std::tuple<Map, Scenario> loadMapAndScenario(std::string mapPath) {
Map map;
map.loadMap(mapPath);
Scenario scen;
scen.loadScenario(mapPath + ".scen");
return std::make_tuple(map, scen);
}
| 25.338983 | 77 | 0.608696 | [
"vector"
] |
6102d445589afe2efc321559d1b754ec4cff034e | 13,519 | hpp | C++ | RapidXML/RapidXMLSTD.hpp | Fe-Bell/RapidXML | 5c97748913e2a7f48496ed44fb26bbf797c9d796 | [
"MIT"
] | 1 | 2020-07-25T16:48:44.000Z | 2020-07-25T16:48:44.000Z | RapidXML/RapidXMLSTD.hpp | Fe-Bell/RapidXML | 5c97748913e2a7f48496ed44fb26bbf797c9d796 | [
"MIT"
] | null | null | null | RapidXML/RapidXMLSTD.hpp | Fe-Bell/RapidXML | 5c97748913e2a7f48496ed44fb26bbf797c9d796 | [
"MIT"
] | null | null | null | #ifndef RAPIDXMLSTD
#define RAPIDXMLSTD
#include "rapidxml.hpp"
#include "rapidxml_utils.hpp"
#include "rapidxml_ext.hpp"
#include <string>
#define XML_XSI_TYPE "xsi:type"
#define XML_XMLNS_XSI "xmlns:xsi"
#define XML_XMLNS_XSD "xmlns:xsd"
/**Defines basic RapidXML types with friendly names**/
typedef rapidxml::xml_document<> XMLDocument;
typedef rapidxml::xml_node<> XMLElement;
typedef rapidxml::xml_attribute<> XMLAttributte;
typedef rapidxml::file<> XMLFile;
#if defined _WIN32 || defined _WIN64
/*If windows based*/
#define DLL_EX __declspec(dllexport)
extern "C"
{
/**Searches for a named element
* @param parent - A xml element object
* @param elementName - The name of the element
* @param error - An error message
* @returns The element, if success*/
DLL_EX XMLElement* FirstOrDefaultElement(XMLElement* parent, const std::string& elementName, std::string& error);
/**Searches for a named element
* @param parent - A xml document object
* @param elementName - The name of the element
* @param error - An error message
* @returns The element, if success*/
DLL_EX XMLElement* FirstOrDefaultElementA(XMLDocument* parent, const std::string& elementName, std::string& error);
/**Searches for a named attribute
* @param parent - A xml document object
* @param attributeName - The name of the attribute
* @param error - An error message
* @returns The attribute, if success*/
DLL_EX XMLAttributte* FirstOrDefaultAttribute(XMLElement* parent, const std::string& attributeName, std::string& error);
/**Sets the value of an attribute
* @param attribute - The attribute
* @param attributeValue - The value of the attribute
* @param error - An error message
* @returns True if success*/
DLL_EX const bool SetAttributeValue(XMLAttributte* attribute, const std::string& attributeValue, std::string& error);
/**Sets the value of an attribute
* @param element - The attribute parent
* @param attributeName - The attribute name
* @param attributeValue - The value of the attribute
* @param error - An error message
* @returns True if success*/
DLL_EX const bool SetAttributeValueA(XMLElement* element, const std::string& attributeName, const std::string& attributeValue, std::string& error);
/**Sets the value of an attribute
* @param parent - The element's parent
* @param child - The element
* @param error - An error message
* @returns True if success*/
DLL_EX const bool SetElementValue(XMLElement* parent, XMLElement* child, std::string& error);
/**Sets the value of an attribute
* @param element - The element
* @param elementValue - The element value
* @param error - An error message
* @returns True if success*/
DLL_EX const bool SetElementValueA(XMLElement* element, const std::string& elementValue, std::string& error);
/**Opens a new XML file
* @param filePath - The path to a file
* @param error - An error message
* @returns A xml file object*/
DLL_EX XMLFile* OpenXMLFile(const std::string& filePath, std::string& error);
/**Disposes resources.
* @param doc - A xml object file
* @returns True if success*/
DLL_EX const bool DisposeXMLFile(XMLFile* file);
/**Creates a new XML file
* @param file - The xml object file
* @param error - An error message
* @returns A xml document*/
DLL_EX XMLDocument* CreateXMLFromFile(XMLFile* file, std::string& error);
/**Creates a new XML file
* @param version - the version of the XML format
* @param encoding - The Encoding of the XML file (eg: utf-8, utf-16)
* @param error - An error message
* @returns A xml document*/
DLL_EX XMLDocument* CreateXML(const uint8_t& version, const std::string& encoding, std::string& error);
/**Disposes resources.
* @param doc - A xml document object
* @returns True if success*/
DLL_EX const bool DisposeXMLObject(XMLDocument* doc);
/**Saves and XML object to a file
* @param doc - A xml document object
* @param filePath - The path to an xml file
* @param error - An error message
* @returns True if success*/
DLL_EX const bool SaveXML(const XMLDocument& doc, const std::string& filePath);
/**Writes the header of an xml file
* @param doc - A xml document object
* @param version - the version of the XML format
* @param encoding = The Encoding of the XML file (eg: utf-8, utf-16)
* @param error - An error message
* @returns True if success*/
DLL_EX const bool SetHeader(XMLDocument* doc, const uint8_t& version, const std::string& encoding, std::string& error);
/**Sets the default xsi and xsd namespaces
* @param doc - A xml document object
* @param element - The element to set the namespace
* @param error - An error message
* @returns True if success*/
DLL_EX const bool SetElementDefaultNamespaces(XMLDocument* doc, XMLElement* element, std::string& error);
/**Sets the xmlns:xsi and xmlns:xsd namespaces
* @param doc - A xml document object
* @param element - The element to set the namespace
* @param xsi - The xsi address
* @param xsd - The xds address
* @param error - An error message
* @returns True if success*/
DLL_EX const bool SetElementNamespaces(XMLDocument* doc, XMLElement* element, const std::string& xsi, const std::string& xsd, std::string& error);
/**Adds an element to a xml document
* @param doc - A xml document object
* @param element - The element add
* @param error - An error message
* @returns True if success*/
DLL_EX const bool AddElementToDocument(XMLDocument* doc, XMLElement* element, std::string& error);
/**Adds a element to another element
* @param parent - The parent element
* @param child - The child element
* @param error - An error message
* @returns True if success*/
DLL_EX const bool AddElementToElement(XMLElement* parent, XMLElement* child, std::string& error);
/**Adds an attribute to a element
* @param parent - The parent element
* @param child - The child element
* @param error - An error message
* @returns True if success*/
DLL_EX const bool AddAttributeToElement(XMLElement* parent, XMLAttributte* child, std::string& error);
/**Creates an attribute
* @param doc - A xml document object
* @param attributeName - The name of the attribute
* @param attributeValue - The value of the attribute
* @param error - An error message
* @returns True if success*/
DLL_EX XMLAttributte* CreateAttribute(XMLDocument* doc, const std::string& attributeName, const std::string& attributeValue, std::string& error);
/**Creates a element
* @param doc - A xml document object
* @param elementName - The name of the element
* @param elementValue - The value of the element
* @param error - An error message
* @returns True if success*/
DLL_EX XMLElement* CreateElement(XMLDocument* doc, const std::string& elementName, const std::string& elementValue, std::string& error);
/**Creates a element
* @param doc - A xml document object
* @param elementName - The name of the element
* @param subElements - An array of elements
* @param subElementCount - The number of elements to add
* @param error - An error message
* @returns True if success*/
DLL_EX XMLElement* CreateElementA(XMLDocument* doc, const std::string& elementName, XMLElement** subElements, const size_t& subElementCount, std::string& error);
};
/*If unix based*/
#else
/**Searches for a named element
* @param parent - A xml element object
* @param elementName - The name of the element
* @param error - An error message
* @returns The element, if success*/
XMLElement* FirstOrDefaultElement(XMLElement* parent, const std::string& elementName, std::string& error);
/**Searches for a named element
* @param parent - A xml document object
* @param elementName - The name of the element
* @param error - An error message
* @returns The element, if success*/
XMLElement* FirstOrDefaultElementA(XMLDocument* parent, const std::string& elementName, std::string& error);
/**Searches for a named attribute
* @param parent - A xml document object
* @param attributeName - The name of the attribute
* @param error - An error message
* @returns The attribute, if success*/
XMLAttributte* FirstOrDefaultAttribute(XMLElement* parent, const std::string& attributeName, std::string& error);
/**Sets the value of an attribute
* @param attribute - The attribute
* @param attributeValue - The value of the attribute
* @param error - An error message
* @returns True if success*/
const bool SetAttributeValue(XMLAttributte* attribute, const std::string& attributeValue, std::string& error);
/**Sets the value of an attribute
* @param element - The attribute parent
* @param attributeName - The attribute name
* @param attributeValue - The value of the attribute
* @param error - An error message
* @returns True if success*/
const bool SetAttributeValueA(XMLElement* element, const std::string& attributeName, const std::string& attributeValue, std::string& error);
/**Sets the value of an attribute
* @param parent - The element's parent
* @param child - The element
* @param error - An error message
* @returns True if success*/
const bool SetElementValue(XMLElement* parent, XMLElement* child, std::string& error);
/**Sets the value of an attribute
* @param element - The element
* @param elementValue - The element value
* @param error - An error message
* @returns True if success*/
const bool SetElementValueA(XMLElement* element, const std::string& elementValue, std::string& error);
/**Opens a new XML file
* @param filePath - The path to a file
* @param error - An error message
* @returns A xml file object*/
XMLFile* OpenXMLFile(const std::string& filePath, std::string& error);
/**Disposes resources.
* @param doc - A xml object file
* @returns True if success*/
const bool DisposeXMLFile(XMLFile* file);
/**Creates a new XML file
* @param file - The xml object file
* @param error - An error message
* @returns A xml document*/
XMLDocument* CreateXMLFromFile(XMLFile* file, std::string& error);
/**Creates a new XML file
* @param version - the version of the XML format
* @param encoding - The Encoding of the XML file (eg: utf-8, utf-16)
* @param error - An error message
* @returns A xml document*/
XMLDocument* CreateXML(const uint8_t& version, const std::string& encoding, std::string& error);
/**Disposes resources.
* @param doc - A xml document object
* @returns True if success*/
const bool DisposeXMLObject(XMLDocument* doc);
/**Saves and XML object to a file
* @param doc - A xml document object
* @param filePath - The path to an xml file
* @param error - An error message
* @returns True if success*/
const bool SaveXML(const XMLDocument& doc, const std::string& filePath);
/**Writes the header of an xml file
* @param doc - A xml document object
* @param version - the version of the XML format
* @param encoding = The Encoding of the XML file (eg: utf-8, utf-16)
* @param error - An error message
* @returns True if success*/
const bool SetHeader(XMLDocument* doc, const uint8_t& version, const std::string& encoding, std::string& error);
/**Sets the default xsi and xsd namespaces
* @param doc - A xml document object
* @param element - The element to set the namespace
* @param error - An error message
* @returns True if success*/
const bool SetElementDefaultNamespaces(XMLDocument* doc, XMLElement* element, std::string& error);
/**Sets the xmlns:xsi and xmlns:xsd namespaces
* @param doc - A xml document object
* @param element - The element to set the namespace
* @param xsi - The xsi address
* @param xsd - The xds address
* @param error - An error message
* @returns True if success*/
const bool SetElementNamespaces(XMLDocument* doc, XMLElement* element, const std::string& xsi, const std::string& xsd, std::string& error);
/**Adds an element to a xml document
* @param doc - A xml document object
* @param element - The element add
* @param error - An error message
* @returns True if success*/
const bool AddElementToDocument(XMLDocument* doc, XMLElement* element, std::string& error);
/**Adds a element to another element
* @param parent - The parent element
* @param child - The child element
* @param error - An error message
* @returns True if success*/
const bool AddElementToElement(XMLElement* parent, XMLElement* child, std::string& error);
/**Adds an attribute to a element
* @param parent - The parent element
* @param child - The child element
* @param error - An error message
* @returns True if success*/
const bool AddAttributeToElement(XMLElement* parent, XMLAttributte* child, std::string& error);
/**Creates an attribute
* @param doc - A xml document object
* @param attributeName - The name of the attribute
* @param attributeValue - The value of the attribute
* @param error - An error message
* @returns True if success*/
XMLAttributte* CreateAttribute(XMLDocument* doc, const std::string& attributeName, const std::string& attributeValue, std::string& error);
/**Creates a element
* @param doc - A xml document object
* @param elementName - The name of the element
* @param elementValue - The value of the element
* @param error - An error message
* @returns True if success*/
XMLElement* CreateElement(XMLDocument* doc, const std::string& elementName, const std::string& elementValue, std::string& error);
/**Creates a element
* @param doc - A xml document object
* @param elementName - The name of the element
* @param subElements - An array of elements
* @param subElementCount - The number of elements to add
* @param error - An error message
* @returns True if success*/
XMLElement* CreateElementA(XMLDocument* doc, const std::string& elementName, XMLElement** subElements, const size_t& subElementCount, std::string& error);
#endif
#endif | 44.913621 | 162 | 0.740809 | [
"object"
] |
61043d9b64e540afce1f14f46f3255f0def86b6e | 5,193 | cpp | C++ | deps/gwen/src/Controls/TreeNode.cpp | haileys/battlecars | e6cf3ca50d7695ce89ab2acab8a276279db508e6 | [
"Zlib"
] | 1 | 2022-02-06T10:36:59.000Z | 2022-02-06T10:36:59.000Z | deps/gwen/src/Controls/TreeNode.cpp | haileys/battlecars | e6cf3ca50d7695ce89ab2acab8a276279db508e6 | [
"Zlib"
] | null | null | null | deps/gwen/src/Controls/TreeNode.cpp | haileys/battlecars | e6cf3ca50d7695ce89ab2acab8a276279db508e6 | [
"Zlib"
] | null | null | null | /*
GWEN
Copyright (c) 2010 Facepunch Studios
See license in Gwen.h
*/
#include "Gwen/Controls/TreeNode.h"
#include "Gwen/Controls/TreeControl.h"
#include "Gwen/Utility.h"
using namespace Gwen;
using namespace Gwen::Controls;
class OpenToggleButton : public Button
{
GWEN_CONTROL_INLINE ( OpenToggleButton, Button )
{
SetIsToggle( true );
SetTabable( false );
}
virtual void RenderFocus( Skin::Base* /*skin*/ ) {}
virtual void Render( Skin::Base* skin )
{
skin->DrawTreeButton( this, GetToggleState() );
}
};
class TreeNodeText : public Button
{
GWEN_CONTROL_INLINE ( TreeNodeText, Button )
{
SetAlignment( Pos::Left | Pos::CenterV );
SetShouldDrawBackground( false );
SetHeight( 16 );
}
void UpdateColours()
{
if ( IsDisabled() ) return SetTextColor( GetSkin()->Colors.Button.Disabled );
if ( IsDepressed() || GetToggleState() ) return SetTextColor( GetSkin()->Colors.Tree.Selected );
if ( IsHovered() ) return SetTextColor( GetSkin()->Colors.Tree.Hover );
SetTextColor( GetSkin()->Colors.Tree.Normal );
}
};
const int TreeIndentation = 14;
GWEN_CONTROL_CONSTRUCTOR( TreeNode )
{
m_TreeControl = NULL;
m_ToggleButton = new OpenToggleButton( this );
m_ToggleButton->SetBounds( 0, 0, 15, 15 );
m_ToggleButton->onToggle.Add( this, &TreeNode::OnToggleButtonPress );
m_Title = new TreeNodeText( this );
m_Title->Dock( Pos::Top );
m_Title->SetMargin( Margin( 16, 0, 0, 0 ) );
m_Title->onDoubleClick.Add( this, &TreeNode::OnDoubleClickName );
m_Title->onDown.Add( this, &TreeNode::OnClickName );
m_Title->onRightPress.Add( this, &TreeNode::OnRightPress );
m_InnerPanel = new Base( this );
m_InnerPanel->Dock( Pos::Top );
m_InnerPanel->SetHeight( 100 );
m_InnerPanel->SetMargin( Margin( TreeIndentation, 1, 0, 0 ) );
m_InnerPanel->Hide();
m_bRoot = false;
m_bSelected = false;
m_bSelectable = true;
}
void TreeNode::Render( Skin::Base* skin )
{
int iBottom = 0;
if ( m_InnerPanel->Children.size() > 0 )
{
iBottom = m_InnerPanel->Children.back()->Y() + m_InnerPanel->Y();
}
skin->DrawTreeNode( this, m_InnerPanel->Visible(), IsSelected(), m_Title->Height(), m_Title->TextRight(), m_ToggleButton->Y() + m_ToggleButton->Height() * 0.5, iBottom, GetParent() == m_TreeControl );
}
TreeNode* TreeNode::AddNode( const UnicodeString& strLabel )
{
TreeNode* node = new TreeNode( this );
node->SetText( strLabel );
node->Dock( Pos::Top );
node->SetRoot( gwen_cast<TreeControl>( this ) != NULL );
node->SetTreeControl( m_TreeControl );
if ( m_TreeControl )
{
m_TreeControl->OnNodeAdded( node );
}
return node;
}
TreeNode* TreeNode::AddNode( const String& strLabel )
{
return AddNode( Utility::StringToUnicode( strLabel ) );
}
void TreeNode::Layout( Skin::Base* skin )
{
if ( m_ToggleButton )
{
if ( m_Title )
{
m_ToggleButton->SetPos( 0, (m_Title->Height() - m_ToggleButton->Height()) * 0.5 );
}
if ( m_InnerPanel->NumChildren() == 0 )
{
m_ToggleButton->Hide();
m_ToggleButton->SetToggleState( false );
m_InnerPanel->Hide();
}
else
{
m_ToggleButton->Show();
m_InnerPanel->SizeToChildren( false, true );
}
}
BaseClass::Layout( skin );
}
void TreeNode::PostLayout( Skin::Base* /*skin*/ )
{
if ( SizeToChildren( false, true ) )
{
InvalidateParent();
}
}
void TreeNode::SetText( const UnicodeString& text ){ m_Title->SetText( text ); };
void TreeNode::SetText( const String& text ){ m_Title->SetText( text ); };
void TreeNode::Open()
{
m_InnerPanel->Show();
if ( m_ToggleButton ) m_ToggleButton->SetToggleState( true );
Invalidate();
}
void TreeNode::Close()
{
m_InnerPanel->Hide();
if ( m_ToggleButton ) m_ToggleButton->SetToggleState( false );
Invalidate();
}
void TreeNode::ExpandAll()
{
Open();
Base::List& children = m_InnerPanel->GetChildren();
for ( Base::List::iterator iter = children.begin(); iter != children.end(); ++iter )
{
TreeNode* pChild = gwen_cast<TreeNode>(*iter);
if ( !pChild ) continue;
pChild->ExpandAll();
}
}
Button* TreeNode::GetButton(){ return m_Title; }
void TreeNode::OnToggleButtonPress( Base* /*control*/ )
{
if ( m_ToggleButton->GetToggleState() )
{
Open();
}
else
{
Close();
}
}
void TreeNode::OnDoubleClickName( Base* /*control*/ )
{
if ( !m_ToggleButton->Visible() ) return;
m_ToggleButton->Toggle();
}
void TreeNode::OnClickName( Base* /*control*/ )
{
onNamePress.Call( this );
SetSelected( !IsSelected() );
}
void TreeNode::OnRightPress( Base* control )
{
onRightPress.Call( this );
}
void TreeNode::SetSelected( bool b )
{
if ( !m_bSelectable ) return;
if ( m_bSelected == b ) return;
m_bSelected = b;
if ( m_Title )
m_Title->SetToggleState( m_bSelected );
onSelectChange.Call( this );
if ( m_bSelected )
{
onSelect.Call( this );
}
else
{
onUnselect.Call( this );
}
Redraw();
}
void TreeNode::DeselectAll()
{
m_bSelected = false;
if ( m_Title )
m_Title->SetToggleState( m_bSelected );
Base::List& children = m_InnerPanel->GetChildren();
for ( Base::List::iterator iter = children.begin(); iter != children.end(); ++iter )
{
TreeNode* pChild = gwen_cast<TreeNode>(*iter);
if ( !pChild ) continue;
pChild->DeselectAll( );
}
}
| 20.689243 | 201 | 0.675332 | [
"render"
] |
6104eb301693ea026af93234c824e446050ee0fe | 1,397 | hpp | C++ | src/netspeak/util/Vec.hpp | netspeak/netspeak4-application-cpp | b322c19e22c71f39be95b37b14f43daab1cb9024 | [
"MIT"
] | null | null | null | src/netspeak/util/Vec.hpp | netspeak/netspeak4-application-cpp | b322c19e22c71f39be95b37b14f43daab1cb9024 | [
"MIT"
] | 7 | 2020-06-02T18:37:02.000Z | 2021-02-17T11:04:22.000Z | src/netspeak/util/Vec.hpp | netspeak/netspeak4-application-ngrams | b322c19e22c71f39be95b37b14f43daab1cb9024 | [
"MIT"
] | null | null | null | #ifndef NETSPEAK_UTIL_VEC_HPP
#define NETSPEAK_UTIL_VEC_HPP
#include <vector>
namespace netspeak {
namespace util {
/**
* @brief A simple function that appends all elements of \c other to \c base.
*
* @tparam T
* @param base
* @param other
*/
template <typename T, typename I>
inline void vec_append(std::vector<T>& base, const I& other) {
base.insert(base.end(), other.begin(), other.end());
}
template <typename T>
inline bool vec_contains(std::vector<T>& base, const T& item) {
const auto it = std::find(base.begin(), base.end(), item);
return it != base.end();
}
/**
* @brief A move version of vector<T>.pop_back().
*
* @tparam T
* @param base
* @return T
*/
template <typename T>
inline T vec_pop(std::vector<T>& base) {
auto back = std::move(base.back());
base.pop_back();
return back;
}
/**
* @brief Assuming a sorted vector, this will remove all duplicate elements in
* the vector.
*
* Elements are compared using the standard != operator.
*/
template <typename T>
void vec_sorted_filter_dups(std::vector<T>& base) {
if (base.size() < 2) {
return;
}
size_t write_i = 0;
for (size_t read_i = 1; read_i != base.size(); read_i++) {
if (base[read_i] != base[write_i]) {
write_i++;
base[write_i] = base[read_i];
}
}
write_i++;
base.erase(base.begin() + write_i);
}
} // namespace util
} // namespace netspeak
#endif
| 19.957143 | 78 | 0.647817 | [
"vector"
] |
610abbab5dcaf959939218ba7cd099c1c00846aa | 17,464 | cpp | C++ | src/execution/operator/aggregate/physical_hash_aggregate.cpp | ChuyingHe/duckdb-master-rl | 28edfc40bd012d4094442c0dfa7339a0c52a4ee8 | [
"MIT"
] | 1 | 2021-09-15T10:29:20.000Z | 2021-09-15T10:29:20.000Z | src/execution/operator/aggregate/physical_hash_aggregate.cpp | ChuyingHe/duckdb-master-rl | 28edfc40bd012d4094442c0dfa7339a0c52a4ee8 | [
"MIT"
] | null | null | null | src/execution/operator/aggregate/physical_hash_aggregate.cpp | ChuyingHe/duckdb-master-rl | 28edfc40bd012d4094442c0dfa7339a0c52a4ee8 | [
"MIT"
] | null | null | null | #include "duckdb/execution/operator/aggregate/physical_hash_aggregate.hpp"
#include "duckdb/catalog/catalog_entry/aggregate_function_catalog_entry.hpp"
#include "duckdb/common/vector_operations/vector_operations.hpp"
#include "duckdb/execution/aggregate_hashtable.hpp"
#include "duckdb/execution/partitionable_hashtable.hpp"
#include "duckdb/main/client_context.hpp"
#include "duckdb/parallel/pipeline.hpp"
#include "duckdb/parallel/task_scheduler.hpp"
#include "duckdb/planner/expression/bound_aggregate_expression.hpp"
#include "duckdb/planner/expression/bound_constant_expression.hpp"
#include "duckdb/common/atomic.hpp"
namespace duckdb {
PhysicalHashAggregate::PhysicalHashAggregate(ClientContext &context, vector<LogicalType> types,
vector<unique_ptr<Expression>> expressions, idx_t estimated_cardinality,
PhysicalOperatorType type)
: PhysicalHashAggregate(context, move(types), move(expressions), {}, estimated_cardinality, type) {
}
PhysicalHashAggregate::PhysicalHashAggregate(ClientContext &context, vector<LogicalType> types,
vector<unique_ptr<Expression>> expressions,
vector<unique_ptr<Expression>> groups_p, idx_t estimated_cardinality,
PhysicalOperatorType type)
: PhysicalSink(type, move(types), estimated_cardinality), groups(move(groups_p)), all_combinable(true),
any_distinct(false) {
// get a list of all aggregates to be computed
// fake a single group with a constant value for aggregation without groups
if (this->groups.empty()) {
group_types.push_back(LogicalType::TINYINT);
is_implicit_aggr = true;
} else {
is_implicit_aggr = false;
}
for (auto &expr : groups) {
group_types.push_back(expr->return_type);
}
vector<LogicalType> payload_types_filters;
for (auto &expr : expressions) {
D_ASSERT(expr->expression_class == ExpressionClass::BOUND_AGGREGATE);
D_ASSERT(expr->IsAggregate());
auto &aggr = (BoundAggregateExpression &)*expr;
bindings.push_back(&aggr);
if (aggr.distinct) {
any_distinct = true;
}
aggregate_return_types.push_back(aggr.return_type);
for (auto &child : aggr.children) {
payload_types.push_back(child->return_type);
}
if (aggr.filter) {
payload_types_filters.push_back(aggr.filter->return_type);
}
if (!aggr.function.combine) {
all_combinable = false;
}
aggregates.push_back(move(expr));
}
for (const auto &pay_filters : payload_types_filters) {
payload_types.push_back(pay_filters);
}
// 10000 seems like a good compromise here
radix_limit = 10000;
// filter_indexes must be pre-built, not lazily instantiated in parallel...
idx_t aggregate_input_idx = 0;
for (auto &aggregate : aggregates) {
auto &aggr = (BoundAggregateExpression &)*aggregate;
aggregate_input_idx += aggr.children.size();
}
for (auto &aggregate : aggregates) {
auto &aggr = (BoundAggregateExpression &)*aggregate;
if (aggr.filter) {
auto &bound_ref_expr = (BoundReferenceExpression &)*aggr.filter;
auto it = filter_indexes.find(aggr.filter.get());
if (it == filter_indexes.end()) {
filter_indexes[aggr.filter.get()] = bound_ref_expr.index;
bound_ref_expr.index = aggregate_input_idx++;
} else {
++aggregate_input_idx;
}
}
}
}
//===--------------------------------------------------------------------===//
// Sink
//===--------------------------------------------------------------------===//
class HashAggregateGlobalState : public GlobalOperatorState {
public:
HashAggregateGlobalState(PhysicalHashAggregate &op_p, ClientContext &context)
: op(op_p), is_empty(true), total_groups(0),
partition_info((idx_t)TaskScheduler::GetScheduler(context).NumberOfThreads()) {
}
PhysicalHashAggregate &op;
vector<unique_ptr<PartitionableHashTable>> intermediate_hts;
vector<unique_ptr<GroupedAggregateHashTable>> finalized_hts;
//! Whether or not any tuples were added to the HT
bool is_empty;
//! The lock for updating the global aggregate state
mutex lock;
//! a counter to determine if we should switch over to p
atomic<idx_t> total_groups;
RadixPartitionInfo partition_info;
};
class HashAggregateLocalState : public LocalSinkState {
public:
explicit HashAggregateLocalState(PhysicalHashAggregate &op_p) : op(op_p), is_empty(true) {
group_chunk.InitializeEmpty(op.group_types);
if (!op.payload_types.empty()) {
aggregate_input_chunk.InitializeEmpty(op.payload_types);
}
// if there are no groups we create a fake group so everything has the same group
if (op.groups.empty()) {
group_chunk.data[0].Reference(Value::TINYINT(42));
}
}
PhysicalHashAggregate &op;
DataChunk group_chunk;
DataChunk aggregate_input_chunk;
//! The aggregate HT
unique_ptr<PartitionableHashTable> ht;
//! Whether or not any tuples were added to the HT
bool is_empty;
};
unique_ptr<GlobalOperatorState> PhysicalHashAggregate::GetGlobalState(ClientContext &context) {
return make_unique<HashAggregateGlobalState>(*this, context);
}
unique_ptr<LocalSinkState> PhysicalHashAggregate::GetLocalSinkState(ExecutionContext &context) {
return make_unique<HashAggregateLocalState>(*this);
}
void PhysicalHashAggregate::Sink(ExecutionContext &context, GlobalOperatorState &state, LocalSinkState &lstate,
DataChunk &input) const {
auto &llstate = (HashAggregateLocalState &)lstate;
auto &gstate = (HashAggregateGlobalState &)state;
DataChunk &group_chunk = llstate.group_chunk;
DataChunk &aggregate_input_chunk = llstate.aggregate_input_chunk;
for (idx_t group_idx = 0; group_idx < groups.size(); group_idx++) {
auto &group = groups[group_idx];
D_ASSERT(group->type == ExpressionType::BOUND_REF);
auto &bound_ref_expr = (BoundReferenceExpression &)*group;
group_chunk.data[group_idx].Reference(input.data[bound_ref_expr.index]);
}
idx_t aggregate_input_idx = 0;
for (auto &aggregate : aggregates) {
auto &aggr = (BoundAggregateExpression &)*aggregate;
for (auto &child_expr : aggr.children) {
D_ASSERT(child_expr->type == ExpressionType::BOUND_REF);
auto &bound_ref_expr = (BoundReferenceExpression &)*child_expr;
aggregate_input_chunk.data[aggregate_input_idx++].Reference(input.data[bound_ref_expr.index]);
}
}
for (auto &aggregate : aggregates) {
auto &aggr = (BoundAggregateExpression &)*aggregate;
if (aggr.filter) {
auto it = filter_indexes.find(aggr.filter.get());
D_ASSERT(it != filter_indexes.end());
aggregate_input_chunk.data[aggregate_input_idx++].Reference(input.data[it->second]);
}
}
group_chunk.SetCardinality(input.size());
aggregate_input_chunk.SetCardinality(input.size());
group_chunk.Verify();
aggregate_input_chunk.Verify();
D_ASSERT(aggregate_input_chunk.ColumnCount() == 0 || group_chunk.size() == aggregate_input_chunk.size());
// if we have non-combinable aggregates (e.g. string_agg) or any distinct aggregates we cannot keep parallel hash
// tables
if (ForceSingleHT(state)) {
lock_guard<mutex> glock(gstate.lock);
gstate.is_empty = gstate.is_empty && group_chunk.size() == 0;
if (gstate.finalized_hts.empty()) {
gstate.finalized_hts.push_back(
make_unique<GroupedAggregateHashTable>(BufferManager::GetBufferManager(context.client), group_types,
payload_types, bindings, HtEntryType::HT_WIDTH_64));
}
D_ASSERT(gstate.finalized_hts.size() == 1);
gstate.total_groups += gstate.finalized_hts[0]->AddChunk(group_chunk, aggregate_input_chunk);
return;
}
D_ASSERT(all_combinable);
D_ASSERT(!any_distinct);
if (group_chunk.size() > 0) {
llstate.is_empty = false;
}
if (!llstate.ht) {
llstate.ht = make_unique<PartitionableHashTable>(BufferManager::GetBufferManager(context.client),
gstate.partition_info, group_types, payload_types, bindings);
}
gstate.total_groups +=
llstate.ht->AddChunk(group_chunk, aggregate_input_chunk,
gstate.total_groups > radix_limit && gstate.partition_info.n_partitions > 1);
}
class PhysicalHashAggregateState : public PhysicalOperatorState {
public:
PhysicalHashAggregateState(PhysicalOperator &op, vector<LogicalType> &group_types,
vector<LogicalType> &aggregate_types, PhysicalOperator *child)
: PhysicalOperatorState(op, child), ht_index(0), ht_scan_position(0) {
auto scan_chunk_types = group_types;
for (auto &aggr_type : aggregate_types) {
scan_chunk_types.push_back(aggr_type);
}
scan_chunk.Initialize(scan_chunk_types);
}
//! Materialized GROUP BY expressions & aggregates
DataChunk scan_chunk;
//! The current position to scan the HT for output tuples
idx_t ht_index;
idx_t ht_scan_position;
};
void PhysicalHashAggregate::Combine(ExecutionContext &context, GlobalOperatorState &state, LocalSinkState &lstate) {
auto &gstate = (HashAggregateGlobalState &)state;
auto &llstate = (HashAggregateLocalState &)lstate;
// this actually does not do a lot but just pushes the local HTs into the global state so we can later combine them
// in parallel
if (ForceSingleHT(state)) {
D_ASSERT(gstate.finalized_hts.size() <= 1);
return;
}
if (!llstate.ht) {
return; // no data
}
if (!llstate.ht->IsPartitioned() && gstate.partition_info.n_partitions > 1 && gstate.total_groups > radix_limit) {
llstate.ht->Partition();
}
lock_guard<mutex> glock(gstate.lock);
D_ASSERT(all_combinable);
D_ASSERT(!any_distinct);
if (!llstate.is_empty) {
gstate.is_empty = false;
}
// we will never add new values to these HTs so we can drop the first part of the HT
llstate.ht->Finalize();
// at this point we just collect them the PhysicalHashAggregateFinalizeTask (below) will merge them in parallel
gstate.intermediate_hts.push_back(move(llstate.ht));
}
// this task is run in multiple threads and combines the radix-partitioned hash tables into a single onen and then
// folds them into the global ht finally.
class PhysicalHashAggregateFinalizeTask : public Task {
public:
PhysicalHashAggregateFinalizeTask(Pipeline &parent_p, HashAggregateGlobalState &state_p, idx_t radix_p)
: parent(parent_p), state(state_p), radix(radix_p) {
}
static void FinalizeHT(HashAggregateGlobalState &gstate, idx_t radix) {
D_ASSERT(gstate.finalized_hts[radix]);
for (auto &pht : gstate.intermediate_hts) {
for (auto &ht : pht->GetPartition(radix)) {
gstate.finalized_hts[radix]->Combine(*ht);
ht.reset();
}
}
gstate.finalized_hts[radix]->Finalize();
}
void Execute() override {
FinalizeHT(state, radix);
lock_guard<mutex> glock(state.lock);
parent.finished_tasks++;
// finish the whole pipeline
if (parent.total_tasks == parent.finished_tasks) {
parent.Finish();
}
}
private:
Pipeline &parent;
HashAggregateGlobalState &state;
idx_t radix;
};
bool PhysicalHashAggregate::Finalize(Pipeline &pipeline, ClientContext &context,
unique_ptr<GlobalOperatorState> state) {
return FinalizeInternal(context, move(state), false, &pipeline);
}
void PhysicalHashAggregate::FinalizeImmediate(ClientContext &context, unique_ptr<GlobalOperatorState> state) {
FinalizeInternal(context, move(state), true, nullptr);
}
bool PhysicalHashAggregate::FinalizeInternal(ClientContext &context, unique_ptr<GlobalOperatorState> state,
bool immediate, Pipeline *pipeline) {
this->sink_state = move(state);
auto &gstate = (HashAggregateGlobalState &)*this->sink_state;
// special case if we have non-combinable aggregates
// we have already aggreagted into a global shared HT that does not require any additional finalization steps
if (ForceSingleHT(gstate)) {
D_ASSERT(gstate.finalized_hts.size() <= 1);
return true;
}
// we can have two cases now, non-partitioned for few groups and radix-partitioned for very many groups.
// go through all of the child hts and see if we ever called partition() on any of them
// if we did, its the latter case.
bool any_partitioned = false;
for (auto &pht : gstate.intermediate_hts) {
if (pht->IsPartitioned()) {
any_partitioned = true;
break;
}
}
if (any_partitioned) {
// if one is partitioned, all have to be
// this should mostly have already happened in Combine, but if not we do it here
for (auto &pht : gstate.intermediate_hts) {
if (!pht->IsPartitioned()) {
pht->Partition();
}
}
// schedule additional tasks to combine the partial HTs
if (!immediate) {
D_ASSERT(pipeline);
pipeline->total_tasks += gstate.partition_info.n_partitions;
}
gstate.finalized_hts.resize(gstate.partition_info.n_partitions);
for (idx_t r = 0; r < gstate.partition_info.n_partitions; r++) {
gstate.finalized_hts[r] =
make_unique<GroupedAggregateHashTable>(BufferManager::GetBufferManager(context), group_types,
payload_types, bindings, HtEntryType::HT_WIDTH_64);
if (immediate) {
PhysicalHashAggregateFinalizeTask::FinalizeHT(gstate, r);
} else {
D_ASSERT(pipeline);
auto new_task = make_unique<PhysicalHashAggregateFinalizeTask>(*pipeline, gstate, r);
TaskScheduler::GetScheduler(context).ScheduleTask(pipeline->token, move(new_task));
}
}
return immediate;
} else { // in the non-partitioned case we immediately combine all the unpartitioned hts created by the threads.
// TODO possible optimization, if total count < limit for 32 bit ht, use that one
// create this ht here so finalize needs no lock on gstate
gstate.finalized_hts.push_back(make_unique<GroupedAggregateHashTable>(
BufferManager::GetBufferManager(context), group_types, payload_types, bindings, HtEntryType::HT_WIDTH_64));
for (auto &pht : gstate.intermediate_hts) {
auto unpartitioned = pht->GetUnpartitioned();
for (auto &unpartitioned_ht : unpartitioned) {
D_ASSERT(unpartitioned_ht);
gstate.finalized_hts[0]->Combine(*unpartitioned_ht);
unpartitioned_ht.reset();
}
unpartitioned.clear();
}
gstate.finalized_hts[0]->Finalize();
return true;
}
}
void PhysicalHashAggregate::GetChunkInternal(ExecutionContext &context, DataChunk &chunk,
PhysicalOperatorState *state_p) {
auto &gstate = (HashAggregateGlobalState &)*sink_state;
auto &state = (PhysicalHashAggregateState &)*state_p;
state.scan_chunk.Reset();
// special case hack to sort out aggregating from empty intermediates
// for aggregations without groups
if (gstate.is_empty && is_implicit_aggr) {
D_ASSERT(chunk.ColumnCount() == aggregates.size());
// for each column in the aggregates, set to initial state
chunk.SetCardinality(1);
for (idx_t i = 0; i < chunk.ColumnCount(); i++) {
D_ASSERT(aggregates[i]->GetExpressionClass() == ExpressionClass::BOUND_AGGREGATE);
auto &aggr = (BoundAggregateExpression &)*aggregates[i];
auto aggr_state = unique_ptr<data_t[]>(new data_t[aggr.function.state_size()]);
aggr.function.initialize(aggr_state.get());
Vector state_vector(Value::POINTER((uintptr_t)aggr_state.get()));
aggr.function.finalize(state_vector, aggr.bind_info.get(), chunk.data[i], 1);
if (aggr.function.destructor) {
aggr.function.destructor(state_vector, 1);
}
}
state.finished = true;
return;
}
if (gstate.is_empty && !state.finished) {
state.finished = true;
return;
}
idx_t elements_found = 0;
while (true) {
if (state.ht_index == gstate.finalized_hts.size()) {
state.finished = true;
return;
}
elements_found = gstate.finalized_hts[state.ht_index]->Scan(state.ht_scan_position, state.scan_chunk);
if (elements_found > 0) {
break;
}
gstate.finalized_hts[state.ht_index].reset();
state.ht_index++;
state.ht_scan_position = 0;
}
// compute the final projection list
idx_t chunk_index = 0;
chunk.SetCardinality(elements_found);
if (group_types.size() + aggregates.size() == chunk.ColumnCount()) {
for (idx_t col_idx = 0; col_idx < group_types.size(); col_idx++) {
chunk.data[chunk_index++].Reference(state.scan_chunk.data[col_idx]);
}
} else {
D_ASSERT(aggregates.size() == chunk.ColumnCount());
}
for (idx_t col_idx = 0; col_idx < aggregates.size(); col_idx++) {
chunk.data[chunk_index++].Reference(state.scan_chunk.data[group_types.size() + col_idx]);
}
}
unique_ptr<PhysicalOperatorState> PhysicalHashAggregate::GetOperatorState() {
return make_unique<PhysicalHashAggregateState>(*this, group_types, aggregate_return_types,
children.empty() ? nullptr : children[0].get());
}
bool PhysicalHashAggregate::ForceSingleHT(GlobalOperatorState &state) const {
auto &gstate = (HashAggregateGlobalState &)state;
return !all_combinable || any_distinct || gstate.partition_info.n_partitions < 2;
}
string PhysicalHashAggregate::ParamsToString() const {
string result;
for (idx_t i = 0; i < groups.size(); i++) {
if (i > 0) {
result += "\n";
}
result += groups[i]->GetName();
}
for (idx_t i = 0; i < aggregates.size(); i++) {
auto &aggregate = (BoundAggregateExpression &)*aggregates[i];
if (i > 0 || !groups.empty()) {
result += "\n";
}
result += aggregates[i]->GetName();
if (aggregate.filter) {
result += " Filter: " + aggregate.filter->GetName();
}
}
return result;
}
} // namespace duckdb
| 35.934156 | 117 | 0.712151 | [
"vector"
] |
610bf19458b47a658591b3be72c468b2c6d3af6d | 2,749 | hpp | C++ | src/ttauri/delayed_format.hpp | PinkFlufflyLlama/ttauri | 7badcfbe792932ebb912d54d1062d8fc820c40a7 | [
"BSL-1.0"
] | null | null | null | src/ttauri/delayed_format.hpp | PinkFlufflyLlama/ttauri | 7badcfbe792932ebb912d54d1062d8fc820c40a7 | [
"BSL-1.0"
] | null | null | null | src/ttauri/delayed_format.hpp | PinkFlufflyLlama/ttauri | 7badcfbe792932ebb912d54d1062d8fc820c40a7 | [
"BSL-1.0"
] | null | null | null | // Copyright Take Vos 2021.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
#include <format>
#include <tuple>
#include "forward_value.hpp"
#include "fixed_string.hpp"
#pragma once
namespace tt {
/** Delayed formatting.
* This class will capture all the arguments so that it may be passed
* to another thread. Then call the function operator to do the actual formatting.
*/
template<basic_fixed_string Fmt, typename... Values>
class delayed_format {
public:
static_assert(std::is_same_v<decltype(Fmt)::value_type, char>, "Fmt must be a basic_fixed_string<char>");
delayed_format(delayed_format &&) noexcept = default;
delayed_format(delayed_format const &) noexcept = default;
delayed_format &operator=(delayed_format &&) noexcept = default;
delayed_format &operator=(delayed_format const &) noexcept = default;
/** Construct a delayed format.
*
* All arguments are passed by forwarding-references so that values can be
* moved into the storage of the delayed_format.
*
* Arguments passed by reference will be copied. Arguments passed by std::string_view
* or std::span will be copied into a std::string or std::vector.
*
* Literal strings will not be copied, instead a pointer is taken.
*
* @param args The parameters to std::format, including the fmt paramater,
* but excluding the locale.
*/
template<typename... Args>
delayed_format(Args const &...args) noexcept : _values(args...)
{
}
/** Format now.
* @return The formatted string.
*/
[[nodiscard]] std::string operator()() const noexcept
{
return std::apply(format_wrapper<Values const &...>, std::tuple_cat(std::tuple{Fmt.c_str()}, _values));
}
/** Format now.
* @param loc The locale to use for formatting.
* @return The formatted string.
*/
[[nodiscard]] std::string operator()(std::locale const &loc) const noexcept
{
return std::apply(format_locale_wrapper<Values const &...>, std::tuple_cat(std::tuple{loc, Fmt.c_str()}, _values));
}
private:
std::tuple<Values...> _values;
template<typename... Args>
static std::string format_wrapper(char const *fmt, Args const &...args)
{
return std::format(fmt, args...);
}
template<typename... Args>
static std::string format_locale_wrapper(std::locale const &loc, char const *fmt, Args const &...args)
{
return std::format(loc, fmt, args...);
}
};
template<fixed_string Fmt, typename... Args>
delayed_format(Args &&...) -> delayed_format<Fmt, forward_value_t<Args>...>;
} // namespace tt
| 33.120482 | 123 | 0.671517 | [
"vector"
] |
610c83b837d4f988889753664aab6e450343187b | 9,492 | cpp | C++ | src/Court.cpp | andrefmrocha/MIEIC_18_19_AEDA_PT2 | 4b9c14fbac2ad8c74c3839a33b4d6a469d552bef | [
"MIT"
] | null | null | null | src/Court.cpp | andrefmrocha/MIEIC_18_19_AEDA_PT2 | 4b9c14fbac2ad8c74c3839a33b4d6a469d552bef | [
"MIT"
] | null | null | null | src/Court.cpp | andrefmrocha/MIEIC_18_19_AEDA_PT2 | 4b9c14fbac2ad8c74c3839a33b4d6a469d552bef | [
"MIT"
] | 1 | 2020-02-02T21:20:06.000Z | 2020-02-02T21:20:06.000Z | /*
* Court.cpp
*
* Created on: Oct 21, 2018
* Author: andrefmrocha
*/
#include "Court.h"
using namespace std;
static double courtPrice = 15;
Court::Court(int year):currentYear(Year(year))
{
this->maxUsers = 4;
}
Court::Court() {}
bool Court::isOccupied(int month, int day, double startingHour, int duration)
{
// Checks the schedule for the specified month
return !(this->currentYear.getMonth(month).getDay(day).checkSchedule(startingHour, duration));
}
void Court::unsetReservation(int month, int day, double startingHour, unsigned int duration)
{
this->currentYear.getMonth(month).getDay(day).unsetSchedule(startingHour, duration);
}
void Court::occupied(int month, int day, double startingHour, int duration)
{
// Checks the schedule for the specified month
if(!this->currentYear.getMonth(month).getDay(day).checkSchedule(startingHour, duration))
{
throw(CourtReserved(month, day, startingHour));
}
}
CourtReserved::CourtReserved(int month, int day, double sH)
{
this->month = month;
this->day = day;
this->startingHour = sH;
}
string CourtReserved::what()const{
return "No court is available on the day " + to_string(this->day) + " of the month " + to_string(this->month) + " at "
+ to_string(this->startingHour) + '\n';
}
void Court::reserveCourt(int m, int d, double sH, int dur)
{
this->currentYear.getMonth(m).getDay(d).setSchedule(sH, dur);
}
bool Court::reserveClass(int m, int d, double sH, User &user, Teacher &teacher)
{
// Classes take 1 hour, so duration = 2
int dur = 2;
try{
occupied(m, d, sH, dur); // Check if it's available
}
catch (CourtReserved& court)
{
return false;
}
try
{ // Checks if the User is available
CheckAvailable(user.getReservations(),sH, calculateEndHour(sH, dur),d,m);
}
catch(AlreadyReservedHours &e)
{
cout << "The user is not available at this time!" << endl;
return false;
}
try
{
//Checks if the Teacher is available
CheckAvailable(teacher.getLessons(),sH, calculateEndHour(sH, dur),d,m);
}
catch(AlreadyReservedHours &e)
{
cout << "This user's teacher is not available at this time!" << endl;
return false;
}
reserveCourt(m, d, sH, dur); // Reserves the court
double price = courtPrice * dur;
if(user.getisGold()) // Calculates the price of the lesson, checking if the User is Gold or not
{
price*=0.85;
}
Reservation * lesson = new Lesson(m, d, sH, price, dur,teacher.getName());
Lesson* teacherLesson = new Lesson(m, d, sH, price, dur,teacher.getName());
user.setReservation(lesson); // Saves the reservation in the User
teacher.setLesson(teacherLesson); // Saves the reservation in the Teacher
return true;
}
bool Court::reserveFree(int m, int d, double sH, int dur, User& user)
{
if(dur > 4 ) //Checks if the reservation is too big
{
cout << "You cannot reserve the court for more than 2 hours!" << endl;
return false;
}
try{
occupied(m, d, sH, dur); // Checks if the Court is reserveds
}
catch (CourtReserved& court)
{
return false;
}
try
{ // Checks if the user is available
CheckAvailable(user.getReservations(),sH, calculateEndHour(sH, dur),d,m);
}
catch(AlreadyReservedHours &e)
{
cout << "The user is not available at this time!" << endl;
return false;
}
double price = courtPrice;
price*= dur; // Calculates the price of the reservation
if(user.getisGold())
{
price*=0.85;
}
reserveCourt(m, d, sH, dur); // Reserves the Court
Reservation * reserv = new Free(m, d, sH, price, dur);
user.setReservation(reserv);// Saves the reservation on the user
return true;
}
void Court::storeInfo(ofstream &outfile, int indentation)
{
indent(outfile, indentation);
outfile << "{ " << endl;
indent(outfile, indentation);
outfile << "\"maxUsers\": "<< this->maxUsers <<"," << endl; // Saves the maxUserss
indent(outfile, indentation);
outfile<< "\"months\": [" << endl; // Saves the information of each month
indentation++;
for(unsigned int i = 1; i < 13; i++)
{
indent(outfile,indentation);
outfile << "{ " << endl;
indentation++;
indent(outfile, indentation); // Saves which month it is
outfile << "\"month\": " << to_string(this->currentYear.getMonth(i).getMonth()) << "," << endl;
indent(outfile,indentation);
outfile << " \"days\": [" << endl; //Saves all the days of the month
indentation++;
for(unsigned j = 1; j < this->currentYear.getMonth(i).getNoDays(); j++)
{
indent(outfile,indentation);
outfile << endl;
indent(outfile,indentation);
outfile << "{" << endl;
indentation++;
indent(outfile,indentation); // Saves the startingHour
outfile << "\"startingHour\": " << this->currentYear.getMonth(i).getDay(j).getSH() << "," << endl;
indent(outfile,indentation);
outfile << "\"schedule\": ["; // Saves the vector of each day
indentation++;
// vector<bool>::iterator z = this->currentYear.getMonth(i).getDay(j).getSchedule().begin();
for(unsigned int z = 0 ; z < this->currentYear.getMonth(i).getDay(j).getSchedule().size(); ++z)
{
if(z+1 == this->currentYear.getMonth(i).getDay(j).getSchedule().size())
{
outfile << this->currentYear.getMonth(i).getDay(j).getSchedule()[z];
}
else
{
outfile << this->currentYear.getMonth(i).getDay(j).getSchedule()[z] << ",";
}
}
outfile << "]" << endl;
indentation--;
indentation--;
indent(outfile,indentation);
if(j + 1 == this->currentYear.getMonth(i).getNoDays())
{
outfile << "}" << endl;
}
else
{
outfile << "}," << endl;
}
indent(outfile,indentation);
}
outfile << "]" << endl;
indentation--;
indent(outfile,indentation);
if(i+1 == 13) // Checks when there are no more months to save
{
outfile<< "}" << endl;
}
else
{
outfile<< "}," << endl;
}
indentation--;
indent(outfile,indentation);
// indentation--;
}
outfile << "]" << endl;
indentation--;
indent(outfile,indentation);
outfile << "}";
}
void Court::indent(std::ofstream &outfile, int identation)
{
for(int i = 0; i < identation; i++)
{
outfile << "\t";
}
}
void Court::readInfo(std::ifstream &infile)
{
string savingString;
while (getline(infile, savingString))
{
if(savingString.find("maxUsers") != string::npos) // Reads the maxUsers
{
this->maxUsers = stoi(savingString.substr(savingString.find("maxUsers") + 11,1));
}
if (savingString.find('{') != string::npos)
continue;
if (savingString.find("months") != string::npos) // When it finds the months, it goes
break; // into a different cycle
}
Year year;
vector<Month> months;
int monthCounter = 0;
while (getline(infile, savingString))
{
months.clear();
vector<Day> days;
Month savingMonth;
bool flag;
while (getline(infile, savingString))
{
if (savingString.find("\"month\":") != string::npos) // Starts saving a month
{
monthCounter++; // Adds another month to the Counter
flag = true;
savingString = savingString.substr(
savingString.find("\"month\":") + 9, 2);
if (savingString.find(',') != string::npos)
{
savingString = savingString.substr(0, 1);
}
savingMonth.setMonth(stoi(savingString));
continue;
}
else if (savingString.find("\"days\"") != string::npos) // Starts getting all the days
{
days.clear();
vector<bool> savingSchedule; // Saves the startingHour
while (getline(infile, savingString))
{
Day savingDay;
if (savingString.find("\"startingHour\"") != string::npos)
{
savingString = savingString.substr(savingString.find("\"startingHour\"") + 16);
if (savingString.find(',') != string::npos)
{
savingString = savingString.substr(0, 1);
}
savingDay.setSH(stoi(savingString));
} // Gets the vector of the schedule
else if (savingString.find("\"schedule\"")!= string::npos)
{
savingSchedule.clear();
savingString = savingString.substr(savingString.find("\"schedule\"") + 13);
for (auto i : savingString)
{
if (i == ']')
{
break;
}
else if (i == ',')
{
continue;
}
else if (i == '0')
{
savingSchedule.push_back(false);
}
else
{
savingSchedule.push_back(true);
}
}
savingDay.setSchedule(savingSchedule);
days.push_back(savingDay);
}
else if (savingString.find('}') != string::npos && savingString.find("},") == string::npos)
{
savingDay.setSchedule(savingSchedule);
days.push_back(savingDay);
break;
}
}
}
if (flag) { // Checks the days vector is ready
flag = false;
savingMonth.setDays(days);
months.push_back(savingMonth); //Saves another month
}
if(monthCounter == 12 && savingString.find('\t\t\t\t]') != string::npos) // If 12 months are already stored it stops
{
break;
}
}
break;
}
this->currentYear.setMonths(months);
}
int Court::getMaxUsers() const
{
return maxUsers;
}
void Court::hoursleft(int month, int day)
{
double counter = 0;
for(const auto &i: this->currentYear.getMonth(month).getDay(day).getSchedule())
{
if(i == false)
counter += 1;
}
counter /= 2;
cout << "There are still " << counter << " hours left on this court" << endl;
}
std::string NoCourtfound::what() const
{
return "The Courts have no reservation for the " + to_string(this->day) + " of the month " + to_string(this->month) + " at "
+ to_string(this->startingHour) + '\n';
}
| 26.813559 | 125 | 0.63622 | [
"vector"
] |
610dd3a376beb4f8680dba7b447e57614c24ccfd | 9,110 | cpp | C++ | molequeue/app/queues/remote.cpp | cygwin-lem/molequeue | 0511c9a5d6f7c0aaa728041945b8638dd9232d00 | [
"BSD-3-Clause"
] | 18 | 2017-02-28T13:24:03.000Z | 2022-03-11T17:58:08.000Z | molequeue/app/queues/remote.cpp | cygwin-lem/molequeue | 0511c9a5d6f7c0aaa728041945b8638dd9232d00 | [
"BSD-3-Clause"
] | 14 | 2015-12-28T21:16:21.000Z | 2021-09-11T00:38:40.000Z | molequeue/app/queues/remote.cpp | cygwin-lem/molequeue | 0511c9a5d6f7c0aaa728041945b8638dd9232d00 | [
"BSD-3-Clause"
] | 20 | 2015-01-29T16:35:47.000Z | 2021-04-09T02:05:23.000Z | /******************************************************************************
This source file is part of the MoleQueue project.
Copyright 2011-2012 Kitware, Inc.
This source code is released under the New BSD License, (the "License").
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
******************************************************************************/
#include "remote.h"
#include "../filesystemtools.h"
#include "../job.h"
#include "../jobmanager.h"
#include "../logentry.h"
#include "../logger.h"
#include "../program.h"
#include "../remotequeuewidget.h"
#include "../server.h"
#include <qjsondocument.h>
#include <QtCore/QTimer>
#include <QtCore/QDebug>
#include <QtGui>
namespace MoleQueue {
QueueRemote::QueueRemote(const QString &queueName, QueueManager *parentObject)
: Queue(queueName, parentObject),
m_checkForPendingJobsTimerId(-1),
m_queueUpdateInterval(DEFAULT_REMOTE_QUEUE_UPDATE_INTERVAL),
m_defaultMaxWallTime(DEFAULT_MAX_WALLTIME)
{
// Set remote queue check timer.
m_checkQueueTimerId = startTimer(m_queueUpdateInterval * 60000);
// Check for jobs to submit every 5 seconds
m_checkForPendingJobsTimerId = startTimer(5000);
}
QueueRemote::~QueueRemote()
{
}
bool QueueRemote::writeJsonSettings(QJsonObject &json, bool exportOnly,
bool includePrograms) const
{
if (!Queue::writeJsonSettings(json, exportOnly, includePrograms))
return false;
if (!exportOnly)
json.insert("workingDirectoryBase", m_workingDirectoryBase);
json.insert("queueUpdateInterval",
static_cast<double>(m_queueUpdateInterval));
json.insert("defaultMaxWallTime",
static_cast<double>(m_defaultMaxWallTime));
return true;
}
bool QueueRemote::readJsonSettings(const QJsonObject &json, bool importOnly,
bool includePrograms)
{
// Validate JSON:
if ((!importOnly && !json.value("workingDirectoryBase").isString()) ||
!json.value("queueUpdateInterval").isDouble() ||
!json.value("defaultMaxWallTime").isDouble()) {
Logger::logError(tr("Error reading queue settings: Invalid format:\n%1")
.arg(QString(QJsonDocument(json).toJson())));
return false;
}
if (!Queue::readJsonSettings(json, importOnly, includePrograms))
return false;
if (!importOnly)
m_workingDirectoryBase = json.value("workingDirectoryBase").toString();
m_queueUpdateInterval =
static_cast<int>(json.value("queueUpdateInterval").toDouble() + 0.5);
m_defaultMaxWallTime =
static_cast<int>(json.value("defaultMaxWallTime").toDouble() + 0.5);
return true;
}
void QueueRemote::setQueueUpdateInterval(int interval)
{
if (interval == m_queueUpdateInterval)
return;
m_queueUpdateInterval = interval;
killTimer(m_checkQueueTimerId);
m_checkQueueTimerId = startTimer(m_queueUpdateInterval * 60000);
requestQueueUpdate();
}
void QueueRemote::replaceKeywords(QString &launchScript,
const Job &job, bool addNewline)
{
// If a valid walltime is set, replace all occurances with the appropriate
// string:
int wallTime = job.maxWallTime();
int hours = wallTime / 60;
int minutes = wallTime % 60;
if (wallTime > 0) {
launchScript.replace("$$$maxWallTime$$$",
QString("%1:%2:00")
.arg(hours, 2, 10, QChar('0'))
.arg(minutes, 2, 10, QChar('0')));
}
// Otherwise, erase all lines containing the keyword
else {
QRegExp expr("\\n[^\\n]*\\${3,3}maxWallTime\\${3,3}[^\\n]*\\n");
launchScript.replace(expr, "\n");
}
if (wallTime <= 0) {
wallTime = defaultMaxWallTime();
hours = wallTime / 60;
minutes = wallTime % 60;
}
launchScript.replace("$$maxWallTime$$",
QString("%1:%2:00")
.arg(hours, 2, 10, QChar('0'))
.arg(minutes, 2, 10, QChar('0')));
Queue::replaceKeywords(launchScript, job, addNewline);
}
bool QueueRemote::submitJob(Job job)
{
if (job.isValid()) {
m_pendingSubmission.append(job.moleQueueId());
job.setJobState(MoleQueue::Accepted);
return true;
}
Logger::logError(tr("Refusing to submit job to Queue '%1': Job object is "
"invalid.").arg(m_name), job.moleQueueId());
return false;
}
void QueueRemote::killJob(Job job)
{
if (!job.isValid())
return;
int pendingIndex = m_pendingSubmission.indexOf(job.moleQueueId());
if (pendingIndex >= 0) {
m_pendingSubmission.removeAt(pendingIndex);
job.setJobState(MoleQueue::Canceled);
return;
}
if (job.queue() == m_name && job.queueId() != InvalidId &&
m_jobs.value(job.queueId()) == job.moleQueueId()) {
m_jobs.remove(job.queueId());
beginKillJob(job);
return;
}
Logger::logWarning(tr("Queue '%1' requested to kill unknown job that belongs "
"to queue '%2', queue id '%3'.").arg(m_name)
.arg(job.queue()).arg(idTypeToString(job.queueId())),
job.moleQueueId());
job.setJobState(MoleQueue::Canceled);
}
void QueueRemote::submitPendingJobs()
{
if (m_pendingSubmission.isEmpty())
return;
// lookup job manager:
JobManager *jobManager = NULL;
if (m_server)
jobManager = m_server->jobManager();
if (!jobManager) {
Logger::logError(tr("Internal error: %1\n%2").arg(Q_FUNC_INFO)
.arg("Cannot locate server JobManager!"));
return;
}
foreach (const IdType moleQueueId, m_pendingSubmission) {
Job job = jobManager->lookupJobByMoleQueueId(moleQueueId);
// Kick off the submission process...
beginJobSubmission(job);
}
m_pendingSubmission.clear();
}
void QueueRemote::beginJobSubmission(Job job)
{
if (!writeInputFiles(job)) {
Logger::logError(tr("Error while writing input files."), job.moleQueueId());
job.setJobState(Error);
return;
}
// Attempt to copy the files via scp first. Only call mkdir on the remote
// working directory if the scp call fails.
copyInputFilesToHost(job);
}
void QueueRemote::beginFinalizeJob(IdType queueId)
{
IdType moleQueueId = m_jobs.value(queueId, InvalidId);
if (moleQueueId == InvalidId)
return;
m_jobs.remove(queueId);
// Lookup job
if (!m_server)
return;
Job job = m_server->jobManager()->lookupJobByMoleQueueId(moleQueueId);
if (!job.isValid())
return;
finalizeJobCopyFromServer(job);
}
void QueueRemote::finalizeJobCopyToCustomDestination(Job job)
{
// Skip to next step if needed
if (job.outputDirectory().isEmpty() ||
job.outputDirectory() == job.localWorkingDirectory()) {
finalizeJobCleanup(job);
return;
}
// The copy function will throw errors if needed.
if (!FileSystemTools::recursiveCopyDirectory(job.localWorkingDirectory(),
job.outputDirectory())) {
Logger::logError(tr("Cannot copy '%1' -> '%2'.")
.arg(job.localWorkingDirectory(),
job.outputDirectory()), job.moleQueueId());
job.setJobState(MoleQueue::Error);
return;
}
finalizeJobCleanup(job);
}
void QueueRemote::finalizeJobCleanup(Job job)
{
if (job.cleanLocalWorkingDirectory())
cleanLocalDirectory(job);
if (job.cleanRemoteFiles())
cleanRemoteDirectory(job);
job.setJobState(MoleQueue::Finished);
}
void QueueRemote::jobAboutToBeRemoved(const Job &job)
{
m_pendingSubmission.removeOne(job.moleQueueId());
Queue::jobAboutToBeRemoved(job);
}
void QueueRemote::removeStaleJobs()
{
if (m_server) {
if (JobManager *jobManager = m_server->jobManager()) {
QList<IdType> staleQueueIds;
for (QMap<IdType, IdType>::const_iterator it = m_jobs.constBegin(),
it_end = m_jobs.constEnd(); it != it_end; ++it) {
if (jobManager->lookupJobByMoleQueueId(it.value()).isValid())
continue;
staleQueueIds << it.key();
Logger::logError(tr("Job with MoleQueue id %1 is missing, but the Queue"
" '%2' is still holding a reference to it. Please "
"report this bug and check if the job needs to be "
"resubmitted.").arg(it.value()).arg(name()),
it.value());
}
foreach (IdType queueId, staleQueueIds)
m_jobs.remove(queueId);
}
}
}
void QueueRemote::timerEvent(QTimerEvent *theEvent)
{
if (theEvent->timerId() == m_checkQueueTimerId) {
theEvent->accept();
removeStaleJobs();
if (!m_jobs.isEmpty())
requestQueueUpdate();
return;
}
else if (theEvent->timerId() == m_checkForPendingJobsTimerId) {
theEvent->accept();
submitPendingJobs();
return;
}
QObject::timerEvent(theEvent);
}
} // End namespace
| 28.73817 | 80 | 0.640834 | [
"object"
] |
6112217850c563ad061ede852c3941f5e89fee0e | 4,014 | cpp | C++ | DEM/Low/src/Frame/LightAttribute.cpp | niello/deusexmachina | 2f698054fe82d8b40a0a0e58b86d64ffed0de06c | [
"MIT"
] | 15 | 2019-05-07T11:26:13.000Z | 2022-01-12T18:26:45.000Z | DEM/Low/src/Frame/LightAttribute.cpp | niello/deusexmachina | 2f698054fe82d8b40a0a0e58b86d64ffed0de06c | [
"MIT"
] | 16 | 2021-10-04T17:15:31.000Z | 2022-03-20T09:34:29.000Z | DEM/Low/src/Frame/LightAttribute.cpp | niello/deusexmachina | 2f698054fe82d8b40a0a0e58b86d64ffed0de06c | [
"MIT"
] | 2 | 2019-04-28T23:27:48.000Z | 2019-05-07T11:26:18.000Z | #include "LightAttribute.h"
#include <Scene/SPS.h>
#include <Render/Light.h>
#include <Core/Factory.h>
#include <IO/BinaryReader.h>
namespace Frame
{
FACTORY_CLASS_IMPL(Frame::CLightAttribute, 'LGTA', Scene::CNodeAttribute);
bool CLightAttribute::LoadDataBlocks(IO::CBinaryReader& DataReader, UPTR Count)
{
for (UPTR j = 0; j < Count; ++j)
{
const uint32_t Code = DataReader.Read<uint32_t>();
switch (Code)
{
case 'LGHT':
{
Light.Type = static_cast<Render::ELightType>(DataReader.Read<int>());
break;
}
case 'CSHD':
{
//!!!Light.Flags.SetTo(ShadowCaster, DataReader.Read<bool>());!
DataReader.Read<bool>();
break;
}
case 'LINT':
{
DataReader.Read(Light.Intensity);
break;
}
case 'LCLR':
{
DataReader.Read(Light.Color);
break;
}
case 'LRNG':
{
Light.SetRange(DataReader.Read<float>());
break;
}
case 'LCIN':
{
Light.SetSpotInnerAngle(n_deg2rad(DataReader.Read<float>()));
break;
}
case 'LCOU':
{
Light.SetSpotOuterAngle(n_deg2rad(DataReader.Read<float>()));
break;
}
default: FAIL;
}
}
OK;
}
//---------------------------------------------------------------------
Scene::PNodeAttribute CLightAttribute::Clone()
{
PLightAttribute ClonedAttr = n_new(CLightAttribute());
ClonedAttr->Light = Light;
return ClonedAttr;
}
//---------------------------------------------------------------------
void CLightAttribute::OnActivityChanged(bool Active)
{
if (!Active && pSPS)
{
if (pSPSRecord)
{
pSPS->RemoveRecord(pSPSRecord);
pSPSRecord = nullptr;
}
else pSPS->OversizedObjects.RemoveByValue(this);
pSPS = nullptr;
}
}
//---------------------------------------------------------------------
void CLightAttribute::UpdateInSPS(Scene::CSPS& SPS)
{
if (Light.Type == Render::Light_Directional)
{
if (pSPSRecord)
{
pSPS->RemoveRecord(pSPSRecord);
pSPSRecord = nullptr;
}
if (!pSPS)
{
pSPS = &SPS;
SPS.OversizedObjects.Add(this);
}
}
else
{
if (pSPS != &SPS)
{
if (pSPS)
{
if (pSPSRecord)
{
pSPS->RemoveRecord(pSPSRecord);
pSPSRecord = nullptr;
}
else pSPS->OversizedObjects.RemoveByValue(this);
}
pSPS = &SPS;
}
if (!pSPSRecord)
{
CAABB Box;
GetGlobalAABB(Box); //???calc cached and reuse here?
pSPSRecord = SPS.AddRecord(Box, this);
LastTransformVersion = _pNode->GetTransformVersion();
}
else if (_pNode->GetTransformVersion() != LastTransformVersion) //!!! || Range/Cone changed
{
GetGlobalAABB(pSPSRecord->GlobalBox);
SPS.UpdateRecord(pSPSRecord);
LastTransformVersion = _pNode->GetTransformVersion();
}
}
}
//---------------------------------------------------------------------
//!!!GetGlobalAABB & CalcBox must be separate!
bool CLightAttribute::GetGlobalAABB(CAABB& OutBox) const
{
//!!!If local params changed, recompute AABB
//!!!If transform of host node changed, update global space AABB (rotate, scale)
switch (Light.Type)
{
case Render::Light_Directional: FAIL;
case Render::Light_Point:
{
float Range = Light.GetRange();
OutBox.Set(GetPosition(), vector3(Range, Range, Range));
OK;
}
case Render::Light_Spot:
{
//!!!can cache local box! or HalfFarExtent (1 float instead of 6)
float Range = Light.GetRange();
float ConeOuter = Light.GetSpotOuterAngle();
float HalfFarExtent = Range * n_tan(ConeOuter * 0.5f);
OutBox.Min.set(-HalfFarExtent, -HalfFarExtent, -Range);
OutBox.Max.set(HalfFarExtent, HalfFarExtent, 0.f);
OutBox.Transform(_pNode->GetWorldMatrix());
OK;
}
default: Sys::Error("Invalid light type!");
};
FAIL;
}
//---------------------------------------------------------------------
void CLightAttribute::CalcFrustum(matrix44& OutFrustum) const
{
matrix44 LocalFrustum;
Light.CalcLocalFrustum(LocalFrustum);
_pNode->GetWorldMatrix().invert_simple(OutFrustum);
OutFrustum *= LocalFrustum;
}
//---------------------------------------------------------------------
} | 22.677966 | 93 | 0.594918 | [
"render",
"transform"
] |
6117ed95d4cdde0945dc398dafe1811406e010ec | 7,880 | hxx | C++ | Code/Tools/Standalone/Source/Driller/StripChart.hxx | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-09-13T00:01:12.000Z | 2021-09-13T00:01:12.000Z | Code/Tools/Standalone/Source/Driller/StripChart.hxx | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | null | null | null | Code/Tools/Standalone/Source/Driller/StripChart.hxx | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-07-20T11:07:25.000Z | 2021-07-20T11:07:25.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#ifndef AZ_STRIPCHART_H
#define AZ_STRIPCHART_H
#if !defined(Q_MOC_RUN)
#include <AzCore/base.h>
#include <AzCore/Memory/SystemAllocator.h>
#include <AzCore/std/containers/vector.h>
#include <QWidget>
#include <Source/Driller/ChartTypes.hxx>
#endif
namespace Charts
{
class Axis;
}
namespace StripChart
{
enum TransformResult
{
OUTSIDE_LEFT = -1,
INSIDE_RANGE = 0,
OUTSIDE_RIGHT = 1,
INVALID_RANGE = 2
};
struct Channel
{
AZ_CLASS_ALLOCATOR(Channel,AZ::SystemAllocator,0);
Channel() : m_Color(QColor(255,255,0,255)), m_Style(STYLE_POINT), m_channelID(0), m_highlighted(false), m_highlightSample(false), m_highlightedSampleID(0) {}
enum ChannelStyle
{
STYLE_POINT = 0,
STYLE_CONNECTED_LINE,
STYLE_VERTICAL_LINE,
STYLE_BAR,
STYLE_PLUSMINUS
};
void SetName(QString name) { m_Name = name; }
void SetColor(QColor &color) { m_Color = color; }
void SetStyle(ChannelStyle style) { m_Style = style; }
void SetHighlight(bool highlight) { m_highlighted = highlight; }
void SetHighlightedSample(bool highlight, AZ::u64 sampleID) { m_highlightedSampleID = sampleID; m_highlightSample = highlight; }
void SetID(int id) { m_channelID = id; }
struct Sample
{
float m_domainValue;
float m_dependentValue;
AZ::u64 m_sampleID;
Sample() : m_domainValue(0.0f), m_dependentValue(0.0f), m_sampleID(0) {}
Sample(AZ::u64 sampleID, float domain, float dependent) :
m_sampleID(sampleID),
m_domainValue(domain),
m_dependentValue(dependent) {}
};
int m_channelID;
QString m_Name;
AZStd::vector< Sample > m_Data;
QColor m_Color;
ChannelStyle m_Style;
bool m_highlighted;
AZ::u64 m_highlightedSampleID;
bool m_highlightSample;
};
class DataStrip
: public QWidget
{
Q_OBJECT;
public:
static int s_invalidChannelId;
AZ_CLASS_ALLOCATOR(DataStrip,AZ::SystemAllocator,0);
DataStrip(QWidget* parent = NULL, Qt::WindowFlags flags = Qt::WindowFlags());
virtual ~DataStrip(void);
void Reset();
void SetChannelHighlight(int channelID, bool highlight);
void SetChannelSampleHighlight( int channelID, AZ::u64 sampleID, bool highlight);
bool AddAxis(QString label, float minimum, float maximum, bool lockedZoom = true, bool lockedRange = false);
void ZoomExtents(Charts::AxisType axis);
void ZoomManual(Charts::AxisType axis, float minValue, float maxValue);
int AddChannel(QString name);
// Use AddData when just adding a random point to the graph. This will keep all of
// the axis's in order.
void AddData(int channelID, AZ::u64 sampleID, float h, float v = 0.0f);
// Use AddDataBatch when adding lots of data all at once, this will ignore some calls.
void StartBatchDataAdd();
void AddBatchedData(int channelID, AZ::u64 sampleID, float h, float v = 0.0f);
void EndBatchDataAdd();
void ClearData(int channelID);
void ClearAxisRange();
void SetChannelColor(int channelID, QColor color);
void SetChannelStyle(int channelID, Channel::ChannelStyle style);
void SetViewFull();
void SetLockRight(bool tf);
void SetZoomLimit(float limit);
void SetMarkerColor(QColor qc);
void SetMarkerPosition(float qposn);
bool GetAxisRange(Charts::AxisType whichAxis, float& minValue, float& maxValue);
bool GetWindowRange(Charts::AxisType whichAxis, float &minValue, float &maxValue);
// override for knowledgeable outsiders who want a different range than from the data provided via AddData(...)
void SetWindowRange(Charts::AxisType whichAxis, float minValue, float maxValue);
void AddWindowRange(Charts::AxisType whichAxis, float minValue, float maxValue);
// you may set it to null to clear it.
// the chart will automatically uninstall the text formatter if it is destroyed
// it DOES NOT TAKE OWNERSHIP of the formatter.
void SetAxisTextFormatter(Charts::QAbstractAxisFormatter* target);
void AttachDataSourceWidget(QWidget *widget);
void SetDataDirty();
bool IsValidChannelId(int channelId) const;
signals:
void onMouseOverDataPoint(int channelID, AZ::u64 sampleID, float primaryAxisValue, float dependentAxisValue);
void onMouseOverNothing(float primaryAxisValue, float dependentAxisValue);
void onMouseLeftDownDomainValue(float domainValue);
void onMouseLeftDragDomainValue(float domainValue);
void onMouseLeftUpDomainValue(float domainValue);
void ProcureData(StripChart::DataStrip*);
protected:
virtual void wheelEvent(QWheelEvent * event);
virtual void mouseMoveEvent(QMouseEvent * event);
virtual void mousePressEvent(QMouseEvent * event);
virtual void mouseReleaseEvent(QMouseEvent * event);
virtual void resizeEvent(QResizeEvent * event);
protected slots:
void OnDestroyAxisFormatter(QObject *pDestroyed);
protected:
int m_InsetL;
int m_InsetR;
int m_InsetT;
int m_InsetB;
QRect m_Inset;
float m_ZoomLimit;
bool m_bLeftDown;
bool m_isDataDirty;
typedef AZStd::vector<Channel> Channels;
Channels m_Channels;
QPoint m_DragTracker;
bool m_MouseWasDragged;
Charts::QAbstractAxisFormatter* m_ptrFormatter;
bool m_IsDragging;
bool m_InBatchMode;
// axes dealt with internally as follows:
Charts::Axis* m_Axis;
Charts::Axis* m_DependentAxis; // vertical axis
// first submission = horizontal, for binary state data points
// second submission = vertical, for state with value data points
// third submission = depth, for data grids with value
QColor m_MarkerColor;
float m_MarkerPosition;
// internal ops
virtual void paintEvent(QPaintEvent *event);
void DrawRotatedText(QString text, QPainter *painter, float degrees, int x, int y, float scale = 1.0f);
void RenderVertCallouts(QPainter *painter);
void RenderHorizCallouts(QPainter *painter);
void RecalculateInset();
void Drag(Charts::Axis *axis, int deltaY);
void Drag(Charts::Axis *axis, int deltaX, int deltaY);
QPoint TransformVert(Charts::Axis *axis, float v);
QPoint TransformHoriz(Charts::Axis *axis, float h);
TransformResult Transform(Charts::Axis *axis, float h, float v, QPoint &outQPoint);
class HitArea
{
public:
AZ_CLASS_ALLOCATOR(HitArea, AZ::SystemAllocator, 0);
Channel *m_ptrChannel;
AZ::u64 m_sampleID;
float m_primaryAxisValue;
float m_dependentAxisValue;
QPoint m_hitBoxCenter;
HitArea() : m_ptrChannel(NULL), m_primaryAxisValue(0.0f), m_dependentAxisValue(0.0f) {}
HitArea(float x, float y, QPoint hitBoxCenter, Channel* pChannel, AZ::u64 sampleID) :
m_hitBoxCenter(hitBoxCenter), m_primaryAxisValue(x), m_dependentAxisValue(y), m_ptrChannel(pChannel), m_sampleID(sampleID) {}
};
typedef AZStd::vector<HitArea> HitAreaContainer;
HitAreaContainer m_hitAreas;
};
}
#endif //AZ_STRIPCHART_H
| 35.818182 | 165 | 0.656853 | [
"vector",
"transform",
"3d"
] |
611d5e4e3dfcebf70b39afd6a404c153443ee891 | 1,699 | cpp | C++ | solutions/recover_binary_search_tree.cpp | kmykoh97/My-Leetcode | 0ffdea16c3025805873aafb6feffacaf3411a258 | [
"Apache-2.0"
] | null | null | null | solutions/recover_binary_search_tree.cpp | kmykoh97/My-Leetcode | 0ffdea16c3025805873aafb6feffacaf3411a258 | [
"Apache-2.0"
] | null | null | null | solutions/recover_binary_search_tree.cpp | kmykoh97/My-Leetcode | 0ffdea16c3025805873aafb6feffacaf3411a258 | [
"Apache-2.0"
] | null | null | null | // You are given the root of a binary search tree (BST), where exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure.
// Follow up: A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?
// Example 1:
// Input: root = [1,3,null,null,2]
// Output: [3,1,null,null,2]
// Explanation: 3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes the BST valid.
// Example 2:
// Input: root = [3,1,4,null,null,2]
// Output: [2,1,4,null,null,3]
// Explanation: 2 cannot be in the right subtree of 3 because 2 < 3. Swapping 2 and 3 makes the BST valid.
// Constraints:
// The number of nodes in the tree is in the range [2, 1000].
// -231 <= Node.val <= 231 - 1
// solution: inorder traversal
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<pair<TreeNode*, TreeNode*>> vec;
TreeNode* prev = nullptr;
void inorder(TreeNode* root) {
if (!root) return;
inorder(root->left);
if (prev && prev->val > root->val) vec.push_back({prev, root});
prev = root;
inorder(root->right);
}
void recoverTree(TreeNode* root) {
inorder(root);
if (vec.size() == 1) swap(vec[0].first->val, vec[0].second->val);
if (vec.size() == 2) swap(vec[0].first->val, vec[1].second->val);
}
}; | 29.293103 | 166 | 0.619776 | [
"vector"
] |
6125606d23e9697bb959432bef2b8653387a1844 | 23,590 | cpp | C++ | Src/MainLib/InterceptPluginManager.cpp | vinjn/glintercept | f82166d3a774bfb02459f6b3ae2a03d4c9eaf64f | [
"MIT"
] | 468 | 2015-04-13T19:03:57.000Z | 2022-03-23T00:11:24.000Z | Src/MainLib/InterceptPluginManager.cpp | vinjn/glintercept | f82166d3a774bfb02459f6b3ae2a03d4c9eaf64f | [
"MIT"
] | 12 | 2015-05-25T11:15:21.000Z | 2020-10-26T02:46:50.000Z | Src/MainLib/InterceptPluginManager.cpp | vinjn/glintercept | f82166d3a774bfb02459f6b3ae2a03d4c9eaf64f | [
"MIT"
] | 67 | 2015-04-22T13:22:48.000Z | 2022-03-05T01:11:02.000Z | /*=============================================================================
GLIntercept - OpenGL intercept/debugging tool
Copyright (C) 2004 Damian Trebilco
Licensed under the MIT license - See Docs\license.txt for details.
=============================================================================*/
#include "InterceptPluginManager.h"
#include "InterceptPluginInstance.h"
#include "InterceptPluginDLLInstance.h"
#include "GLDriver.h"
#include <string.h>
USING_ERRORLOG
///////////////////////////////////////////////////////////////////////////////
//
InterceptPluginManager::InterceptPluginManager(GLDriver *ogldriver,FunctionTable * fTable):
driver(ogldriver),
functionDataConverter(NULL),
functionTable(fTable),
isRenderCall(false)
{
//Create the function data log
functionDataConverter = new InterceptLog(functionTable);
}
///////////////////////////////////////////////////////////////////////////////
//
InterceptPluginManager::~InterceptPluginManager()
{
//Destroy all existing plugins
for(uint i=0;i<pluginArray.size();i++)
{
delete pluginArray[i].pluginInstance;
}
pluginArray.clear();
deletePluginArray.clear();
//Destroy the function converter
if(functionDataConverter)
{
delete functionDataConverter;
}
}
///////////////////////////////////////////////////////////////////////////////
//
bool InterceptPluginManager::LoadPlugins(const ConfigData &configData)
{
//Create the initial function array
UpdatePluginFunctionArray();
//Loop for all plugins
for(uint i=0; i<configData.pluginDataArray.size(); i++)
{
//Get the dll/plugin data
string pluginDLLName = configData.pluginBasePath + configData.pluginDataArray[i].pluginDLLName;
const string &pluginName = configData.pluginDataArray[i].pluginName;
const string &configString = configData.pluginDataArray[i].pluginConfigData;
//Load the dll
InterceptPluginDLLInstance * dllInstance = InterceptPluginDLLInstance::CreateDLLInstance(this,pluginDLLName.c_str());
if(dllInstance)
{
//Create a new plugin instance
InterceptPluginInstance *newPlugin = new InterceptPluginInstance(this, driver, dllInstance);
//Add the plugin to the array (In case the plugin does things in its constructor)
AddPluginInstance(newPlugin);
//Attempt to load
if(!newPlugin->Init(pluginName.c_str(),configString))
{
//Remove and delete the attempted plugin
RemovePluginInstance(newPlugin);
}
}
}
//If there are no plugins, return false
if(pluginArray.size() == 0)
{
return false;
}
return true;
}
///////////////////////////////////////////////////////////////////////////////
//
void InterceptPluginManager::LogFunctionPre(const FunctionData *funcData,uint index, const FunctionArgs & args)
{
//Destroy all plugins on the "destroy list"
for(uint i=0; i<deletePluginArray.size(); i++)
{
//Remove from the plugin array
RemovePluginInstance(deletePluginArray[i]);
}
deletePluginArray.clear();
//Update the function call array if necessary
if(functionUpdates.size() < functionTable->GetNumFunctions())
{
//This is a slow method but should only be called during startup
UpdatePluginFunctionArray();
}
//Return now if the function call depth is not 0
if(driver->GetFunctionCallDepth() != 0)
{
return;
}
//Get if there is a valid context
bool isValidContext = (driver->GetCurrentContext() != NULL);
//Determine if the function is a render call
isRenderCall = false;
if(isValidContext &&
driver->GetCurrentContext()->IsRenderFuncion(funcData,index,args))
{
isRenderCall = true;
}
//Get the update array and perform the required updates
if(index < functionUpdates.size())
{
PluginUpdateArray ¬ifyArray = functionUpdates[index];
//Loop for all registered plugins of this function
for(uint i=0; i<notifyArray.size(); i++)
{
uint updateID = notifyArray[i].updateID;
InterceptPluginInstance *pluginInstance = notifyArray[i].pluginInstance;
//Check if calls can be made outside the context
if(isValidContext || !pluginInstance->GetContextFunctionCalls())
{
pluginInstance->GetInterface()->GLFunctionPre(updateID,funcData->GetName().c_str(),index,args);
}
}
}
//If it is a render function, notify all plugins
if(isRenderCall)
{
//Loop for all registered plugins
for(uint i=0; i<pluginArray.size(); i++)
{
pluginArray[i].pluginInstance->GetInterface()->GLRenderPre(funcData->GetName().c_str(),index,args);
}
}
}
///////////////////////////////////////////////////////////////////////////////
//
void InterceptPluginManager::LogFunctionPost(const FunctionData *funcData,uint index, const FunctionRetValue & retVal)
{
//Return now if the function call depth is not 0
if(driver->GetFunctionCallDepth() != 0)
{
return;
}
//Get if there is a valid context (may have changed since "pre" call)
bool isValidContext = (driver->GetCurrentContext() != NULL);
//If it is a render function, notify all plugins
// (This is done first, as in LogFunctionPre, it is done last.)
if(isRenderCall)
{
//Loop for all registered plugins (in reverse order -see below)
for(int i=(int)pluginArray.size()-1; i>=0; i--)
{
pluginArray[i].pluginInstance->GetInterface()->GLRenderPost(funcData->GetName().c_str(),index,retVal);
}
}
//Get the update array for this function
if(index < functionUpdates.size())
{
PluginUpdateArray ¬ifyArray = functionUpdates[index];
//Loop for all registered plugins
// (Notifications are done in reverse order so any OpenGL stage
// changes performed in the plugins can be reset corretly)
for(int i=(int)notifyArray.size()-1; i>=0; i--)
{
uint updateID = notifyArray[i].updateID;
InterceptPluginInstance *pluginInstance = notifyArray[i].pluginInstance;
//Check if calls can be made outside the context
if(isValidContext || !pluginInstance->GetContextFunctionCalls())
{
pluginInstance->GetInterface()->GLFunctionPost(updateID,funcData->GetName().c_str(),index,retVal);
}
}
}
}
///////////////////////////////////////////////////////////////////////////////
//
void InterceptPluginManager::LogFrameEndPre(const FunctionData *funcData,uint index, const FunctionArgs & args)
{
//Loop for all registered plugins
for(uint i=0; i<pluginArray.size(); i++)
{
pluginArray[i].pluginInstance->GetInterface()->GLFrameEndPre(funcData->GetName().c_str(),index,args);
}
}
///////////////////////////////////////////////////////////////////////////////
//
void InterceptPluginManager::LogFrameEndPost(const FunctionData *funcData,uint index, const FunctionRetValue & retVal)
{
//Loop for all registered plugins
// (Notifications are done in reverse order so any OpenGL stage
// changes performed in the plugins can be reset corretly)
for(int i=(int)pluginArray.size()-1; i>=0; i--)
{
pluginArray[i].pluginInstance->GetInterface()->GLFrameEndPost(funcData->GetName().c_str(),index,retVal);
}
}
///////////////////////////////////////////////////////////////////////////////
//
void InterceptPluginManager::OnGLError(const char *funcName, uint funcIndex)
{
//Loop for all registered plugins
for(uint i=0; i<pluginArray.size(); i++)
{
pluginArray[i].pluginInstance->GetInterface()->OnGLError(funcName,funcIndex);
}
}
///////////////////////////////////////////////////////////////////////////////
//
void InterceptPluginManager::OnGLContextCreate(HGLRC rcHandle)
{
//Loop for all registered plugins
for(uint i=0; i<pluginArray.size(); i++)
{
pluginArray[i].pluginInstance->GetInterface()->OnGLContextCreate(rcHandle);
}
}
///////////////////////////////////////////////////////////////////////////////
//
void InterceptPluginManager::OnGLContextDelete(HGLRC rcHandle)
{
//Loop for all registered plugins
for(uint i=0; i<pluginArray.size(); i++)
{
pluginArray[i].pluginInstance->GetInterface()->OnGLContextDelete(rcHandle);
}
}
///////////////////////////////////////////////////////////////////////////////
//
void InterceptPluginManager::OnGLContextSet(HGLRC oldRCHandle, HGLRC newRCHandle)
{
//Loop for all registered plugins
for(uint i=0; i<pluginArray.size(); i++)
{
pluginArray[i].pluginInstance->GetInterface()->OnGLContextSet(oldRCHandle,newRCHandle);
}
}
///////////////////////////////////////////////////////////////////////////////
//
void InterceptPluginManager::OnGLContextShareLists(HGLRC srcHandle, HGLRC dstHandle)
{
//Loop for all registered plugins
for(uint i=0; i<pluginArray.size(); i++)
{
pluginArray[i].pluginInstance->GetInterface()->OnGLContextShareLists(srcHandle,dstHandle);
}
}
///////////////////////////////////////////////////////////////////////////////
//
bool InterceptPluginManager::GetGLArgString(uint funcIndex, const FunctionArgs & args, uint strLength, char *retString) const
{
if(strLength == 0)
{
LOGERR(("GetGLArgString - Zero string length"));
return false;
}
//Look up the function
const FunctionData *funcData = functionTable->GetFunctionData(funcIndex);
if(!funcData)
{
//If the function does not exist, return an empty string
retString[0] = '\0';
return false;
}
//Get the string
string funcString;
functionDataConverter->GetFunctionString(funcData,funcIndex,args,funcString);
//If the string length is greater, crop
uint numCopyChars = (uint)funcString.length();
if(numCopyChars >= strLength)
{
//Save a space for the NULL character
numCopyChars = strLength - 1;
}
//Assign the string
strncpy(retString,funcString.c_str(),numCopyChars);
retString[numCopyChars] = '\0';
return true;
}
///////////////////////////////////////////////////////////////////////////////
//
bool InterceptPluginManager::GetGLReturnString(uint funcIndex, const FunctionRetValue & retVal, uint strLength, char *retString) const
{
if(strLength == 0)
{
LOGERR(("GetGLReturnString - Zero string length"));
return false;
}
//Look up the function
const FunctionData *funcData = functionTable->GetFunctionData(funcIndex);
if(!funcData)
{
//If the function does not exist, return an empty string
retString[0] = '\0';
return false;
}
//Get the string
string convertString;
functionDataConverter->GetReturnString(funcData,funcIndex,retVal,convertString);
//If the string length is greater, crop
uint numCopyChars = (uint)convertString.length();
if(numCopyChars >= strLength)
{
//Save a space for the NULL character
numCopyChars = strLength - 1;
}
//Assign the string
strncpy(retString,convertString.c_str(),numCopyChars);
retString[numCopyChars] = '\0';
return true;
}
///////////////////////////////////////////////////////////////////////////////
//
int InterceptPluginManager::FindPluginIndex(InterceptPluginInstance *searchPlugin)
{
//Search all elements for the plugin
for(uint i=0;i<pluginArray.size();i++)
{
if(pluginArray[i].pluginInstance == searchPlugin)
{
return i;
}
}
return -1;
}
///////////////////////////////////////////////////////////////////////////////
//
bool InterceptPluginManager::AddPluginInstance(InterceptPluginInstance *newPlugin)
{
//Check for NULL
if(newPlugin == NULL)
{
LOGERR(("AddPluginInstance - Cannot add a NULL plugin"));
return false;
}
//Check that the instance does not already exist
if(FindPluginIndex(newPlugin) >= 0)
{
LOGERR(("AddPluginInstance - Plugin already exists in the manager array"));
return false;
}
//Add to the array
pluginArray.push_back(PluginMember(newPlugin));
return true;
}
///////////////////////////////////////////////////////////////////////////////
//
bool InterceptPluginManager::RemovePluginInstance(InterceptPluginInstance *delPlugin)
{
//Check that the instance does not already exist
int pluginIndex = FindPluginIndex(delPlugin);
if(pluginIndex < 0)
{
LOGERR(("RemovePluginInstance - Plugin does not exist in plugin array"));
return false;
}
//Erase the plugin member
pluginArray.erase(pluginArray.begin() + pluginIndex);
//Remove from all the plugin update arrays
for(uint i=0;i<functionUpdates.size();i++)
{
RemovePluginUpdate(i,delPlugin);
}
//Delete the plugin
delete delPlugin;
return true;
}
///////////////////////////////////////////////////////////////////////////////
//
bool InterceptPluginManager::FlagPluginRemoval(InterceptPluginInstance *flagPlugin)
{
//Check if the plugin exists
int foundIndex = FindPluginIndex(flagPlugin);
if(foundIndex < 0)
{
LOGERR(("FlagPluginRemoval - Unknown plugin"));
return false;
}
//Check if already on the removal list
for(uint i=0;i<deletePluginArray.size();i++)
{
//If the plugin is already being deleted, return false now
if(deletePluginArray[i] == flagPlugin)
{
return false;
}
}
//Add to the plugin removal list
deletePluginArray.push_back(flagPlugin);
return true;
}
///////////////////////////////////////////////////////////////////////////////
//
void InterceptPluginManager::RegisterGLFunction(InterceptPluginInstance *plugin,const char *functionName)
{
//Ensure the plugin is registered with this manager?
int foundIndex = FindPluginIndex(plugin);
if(foundIndex < 0)
{
LOGERR(("RegisterGLFunction - Unknown plugin"));
return;
}
//Get the plugin member data
PluginMember &pluginMember = pluginArray[foundIndex];
//If we have registered as "all" return now
if(pluginMember.registerAll)
{
return;
}
//If '*' (all) functions
if(functionName[0] == '*' && functionName[1] == '\0')
{
//Unregister any existing single functions
pluginMember.registeredFunctions.clear();
//Set the 'all' flag and return
pluginMember.registerAll = true;
//Loop and register with all functions
for(uint i=0;i<functionUpdates.size();i++)
{
AddPluginUpdate(i,plugin);
}
return;
}
//Check if this function is currently registered
for(uint i=0;i<pluginMember.registeredFunctions.size();i++)
{
//If already registered, return
if(pluginMember.registeredFunctions[i] == string(functionName))
{
return;
}
}
//Add to the registered list
pluginMember.registeredFunctions.push_back(functionName);
//Get the function index
int functionIndex = functionTable->FindFunction(functionName);
//Register this plugin if the function is currently known
if(functionIndex >= 0)
{
AddPluginUpdate(functionIndex,plugin);
}
}
///////////////////////////////////////////////////////////////////////////////
//
void InterceptPluginManager::UnRegisterGLFunction(InterceptPluginInstance *plugin,const char *functionName)
{
//Ensure the plugin is registered with this manager
int foundIndex = FindPluginIndex(plugin);
if(foundIndex < 0)
{
LOGERR(("UnRegisterGLFunction - Unknown plugin"));
return;
}
//Get the plugin member data
PluginMember &pluginMember = pluginArray[foundIndex];
//If '*' (all) functions
if(functionName[0] == '*' && functionName[1] == '\0')
{
//Remove from the plugin update arrays
for(uint i=0;i<functionUpdates.size();i++)
{
RemovePluginUpdate(i,plugin);
}
//Unregister any existing single functions
pluginMember.updateIDArray.clear();
pluginMember.registeredFunctions.clear();
pluginMember.registerAll = false;
return;
}
//If we have registered as "all" return now
if(pluginMember.registerAll)
{
LOGERR(("UnRegisterGLFunction - Cannot un-register a single function once a plugin has had 'all' functions registered"));
return;
}
//Remove it from the update list
int functionIndex = functionTable->FindFunction(functionName);
if(functionIndex >= 0)
{
RemovePluginUpdate(functionIndex,plugin);
}
//Delete any update ids
uint i;
for(i=0;i<pluginMember.updateIDArray.size();i++)
{
//If found, delete
if(pluginMember.updateIDArray[i].functionName == string(functionName))
{
pluginMember.updateIDArray.erase(pluginMember.updateIDArray.begin() + i);
break;
}
}
//Delete the name of the function to un-register
for(i=0;i<pluginMember.registeredFunctions.size();i++)
{
//If found, un-register it
if(pluginMember.registeredFunctions[i] == string(functionName))
{
pluginMember.registeredFunctions.erase(pluginMember.registeredFunctions.begin() + i);
return;
}
}
//If the function name was not found, log an error
LOGERR(("UnRegisterGLFunction - Function %s was not registered with this plugin",functionName));
}
///////////////////////////////////////////////////////////////////////////////
//
bool InterceptPluginManager::SetFunctionID(InterceptPluginInstance *plugin, const char *functionName, uint newID)
{
//Ensure the plugin is registered with this manager
int foundIndex = FindPluginIndex(plugin);
if(foundIndex < 0)
{
LOGERR(("SetFunctionID - Unknown plugin"));
return false;
}
//Get the plugin member data
PluginMember &pluginMember = pluginArray[foundIndex];
//Serach for the function name.
bool isFunctionRegistered = pluginMember.registerAll;
for(uint i=0; i<pluginMember.registeredFunctions.size(); i++)
{
if(pluginMember.registeredFunctions[i] == functionName)
{
isFunctionRegistered = true;
break;
}
}
if(!isFunctionRegistered)
{
LOGERR(("SetFunctionID - Function %s is not currently registered",functionName));
return false;
}
//If the new id is zero, remove from the list
if(newID == 0)
{
//Loop for all ids
for(uint i=0; i<pluginMember.updateIDArray.size(); i++)
{
//Erase the id
if(pluginMember.updateIDArray[i].functionName == functionName)
{
pluginMember.updateIDArray.erase(pluginMember.updateIDArray.begin() + i);
break;
}
}
}
else
{
//Loop for all ids
bool existingUpdate = false;
for(uint i=0; i<pluginMember.updateIDArray.size(); i++)
{
//If matching, update the id
if(pluginMember.updateIDArray[i].functionName == functionName)
{
pluginMember.updateIDArray[i].updateID = newID;
existingUpdate = true;
break;
}
}
//If the function name did not already exist, add it
if(!existingUpdate)
{
pluginMember.updateIDArray.push_back(UpdateID(newID,functionName));
}
}
//Set the plugin updateID
int funcIndex = functionTable->FindFunction(functionName);
if(funcIndex >= 0)
{
SetFunctionUpdateID(funcIndex, plugin, newID);
}
return true;
}
///////////////////////////////////////////////////////////////////////////////
//
bool InterceptPluginManager::AddPluginUpdate(uint index, InterceptPluginInstance *addPlugin)
{
//Check the index
if(index >= functionUpdates.size())
{
return false;
}
//Get the array to add to
PluginUpdateArray &addArray = functionUpdates[index];
//Loop and check for an existing value
for(uint i=0;i<addArray.size();i++)
{
if(addArray[i].pluginInstance == addPlugin)
{
return false;
}
}
//Add the plugin
addArray.push_back(PluginUpdate(addPlugin));
return true;
}
///////////////////////////////////////////////////////////////////////////////
//
bool InterceptPluginManager::RemovePluginUpdate(uint index, InterceptPluginInstance *delPlugin)
{
//Check the index
if(index >= functionUpdates.size())
{
return false;
}
//Get the array to delete from
PluginUpdateArray &delArray = functionUpdates[index];
//Loop and check for the value to erase
for(uint i=0;i<delArray.size();i++)
{
if(delArray[i].pluginInstance == delPlugin)
{
delArray.erase(delArray.begin() + i);
return true;
}
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
//
void InterceptPluginManager::UpdatePluginFunctionArray()
{
uint oldFunctionArraySize = (uint)functionUpdates.size();
//Loop for all the functions to add
for(uint i=(uint)functionUpdates.size(); i<functionTable->GetNumFunctions(); i++)
{
//Create a new plugin update array
PluginUpdateArray newArray;
//Get the function name at the index
const FunctionData * funcData = functionTable->GetFunctionData(i);
if(!funcData)
{
LOGERR(("UpdatePluginFunctionArray - Invalid function index?")) ;
return;
}
const string &functionName = funcData->GetName();
//Loop for all plugins
for(uint pIndex = 0; pIndex<pluginArray.size(); pIndex++)
{
//If this plugin receives all updates, just add
if(pluginArray[pIndex].registerAll)
{
newArray.push_back(PluginUpdate(pluginArray[pIndex].pluginInstance));
}
else
{
//Loop for all specific function updates
for(uint fIndex=0; fIndex<pluginArray[pIndex].registeredFunctions.size();fIndex++)
{
if(pluginArray[pIndex].registeredFunctions[fIndex] == functionName)
{
newArray.push_back(PluginUpdate(pluginArray[pIndex].pluginInstance));
break;
}
}
}
}
//Add the array to the function update listing
functionUpdates.push_back(newArray);
}
//Reset all the plugin update ids
// This is a brute force setting of all function update IDs.
// (May be slow if there are lot of registered ids)
//Loop for all plugins
for(uint pIndex = 0; pIndex<pluginArray.size(); pIndex++)
{
//Loop for all registered names in the plugin
for(uint uIndex = 0; uIndex<pluginArray[pIndex].updateIDArray.size(); uIndex++)
{
//Reset the update id
const string & updateFuncName = pluginArray[pIndex].updateIDArray[uIndex].functionName;
uint updateFuncID = pluginArray[pIndex].updateIDArray[uIndex].updateID;
//Only set if it is one of the new functions
int funcIndex = functionTable->FindFunction(updateFuncName);
if(funcIndex >= 0 && funcIndex >= (int)oldFunctionArraySize)
{
SetFunctionUpdateID(funcIndex, pluginArray[pIndex].pluginInstance, updateFuncID);
}
}
}
}
///////////////////////////////////////////////////////////////////////////////
//
void InterceptPluginManager::OnDLLUnload(InterceptPluginDLLInstance *dllInstance)
{
//Notify all plugins
for(uint i=0;i<pluginArray.size();i++)
{
pluginArray[i].pluginInstance->OnDLLUnload(dllInstance);
}
}
///////////////////////////////////////////////////////////////////////////////
//
bool InterceptPluginManager::SetFunctionUpdateID(uint funcIndex,InterceptPluginInstance *updateInstance,uint updateFuncID)
{
//Check the index
if(funcIndex >= functionUpdates.size())
{
LOGERR(("InterceptPluginManager::SetFunctionUpdateID - Invalid function index"));
return false;
}
//Get the array to update the ID for
PluginUpdateArray &updateArray = functionUpdates[funcIndex];
//Loop and check for the value to set
for(uint i=0;i<updateArray.size();i++)
{
//Update the function update id
if(updateArray[i].pluginInstance == updateInstance)
{
updateArray[i].updateID = updateFuncID;
return true;
}
}
LOGERR(("InterceptPluginManager::SetFunctionUpdateID - Plugin instance not found?"));
return false;
}
| 27.494172 | 134 | 0.6273 | [
"render"
] |
6125e46d434680350fc60670dd907b3fe259879e | 5,084 | hpp | C++ | cppcache/src/ClientProxyMembershipID.hpp | mreddington/geode-native | bfcfac5be1bb64e7b2f149202ab568f5233947ad | [
"Apache-2.0"
] | null | null | null | cppcache/src/ClientProxyMembershipID.hpp | mreddington/geode-native | bfcfac5be1bb64e7b2f149202ab568f5233947ad | [
"Apache-2.0"
] | null | null | null | cppcache/src/ClientProxyMembershipID.hpp | mreddington/geode-native | bfcfac5be1bb64e7b2f149202ab568f5233947ad | [
"Apache-2.0"
] | null | null | null | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#ifndef GEODE_CLIENTPROXYMEMBERSHIPID_H_
#define GEODE_CLIENTPROXYMEMBERSHIPID_H_
#include <sstream>
#include <string>
#include <vector>
#include <ace/INET_Addr.h>
#include <geode/DataOutput.hpp>
#include <geode/internal/functional.hpp>
#include <geode/internal/geode_globals.hpp>
#include "DSMemberForVersionStamp.hpp"
namespace apache {
namespace geode {
namespace client {
using internal::DSFid;
class ClientProxyMembershipID;
class ClientProxyMembershipID : public DSMemberForVersionStamp {
public:
const char* getDSMemberId(uint32_t& mesgLength) const;
ClientProxyMembershipID(std::string dsName, std::string randString,
const char* hostname, const ACE_INET_Addr& address,
uint32_t hostPort,
const char* durableClientId = nullptr,
const std::chrono::seconds durableClientTimeOut =
std::chrono::seconds::zero());
// This constructor is only for testing and should not be used for any
// other purpose. See testEntriesMapForVersioning.cpp for more details
ClientProxyMembershipID(const uint8_t* hostAddr, uint32_t hostAddrLen,
uint32_t hostPort, const char* dsname,
const char* uniqueTag, uint32_t vmViewId);
// ClientProxyMembershipID(const char *durableClientId = nullptr, const
// uint32_t durableClntTimeOut = 0);
ClientProxyMembershipID();
~ClientProxyMembershipID() noexcept override;
static void increaseSynchCounter();
static std::shared_ptr<Serializable> createDeserializable() {
return std::make_shared<ClientProxyMembershipID>();
}
// Do an empty check on the returned value. Only use after handshake is done.
const std::string& getDSMemberIdForThinClientUse();
// Serializable interface:
void toData(DataOutput& output) const override;
void fromData(DataInput& input) override;
DSFid getDSFID() const override { return DSFid::InternalDistributedMember; }
size_t objectSize() const override { return 0; }
void initHostAddressVector(const ACE_INET_Addr& address);
void initHostAddressVector(const uint8_t* hostAddr, uint32_t hostAddrLen);
void initObjectVars(const char* hostname, uint32_t hostPort,
const char* durableClientId,
const std::chrono::seconds durableClntTimeOut,
int32_t dcPort, int32_t vPID, int8_t vmkind,
int8_t splitBrainFlag, const char* dsname,
const char* uniqueTag, uint32_t vmViewId);
std::string getDSName() const { return m_dsname; }
std::string getUniqueTag() const { return m_uniqueTag; }
const std::vector<uint8_t>& getHostAddr() const { return m_hostAddr; }
uint32_t getHostAddrLen() const {
return static_cast<uint32_t>(m_hostAddr.size());
}
uint32_t getHostPort() const { return m_hostPort; }
std::string getHashKey() override;
int16_t compareTo(const DSMemberForVersionStamp&) const override;
int32_t hashcode() const override {
uint32_t result = 0;
std::stringstream hostAddressString;
hostAddressString << std::hex;
for (uint32_t i = 0; i < getHostAddrLen(); i++) {
hostAddressString << ":" << static_cast<int>(m_hostAddr[i]);
}
result += internal::geode_hash<std::string>{}(hostAddressString.str());
result += m_hostPort;
return result;
}
bool operator==(const CacheableKey& other) const override {
return (this->compareTo(
dynamic_cast<const DSMemberForVersionStamp&>(other)) == 0);
}
Serializable* readEssentialData(DataInput& input);
private:
std::string m_memIDStr;
std::string m_dsmemIDStr;
std::string clientID;
std::string m_dsname;
uint32_t m_hostPort;
std::vector<uint8_t> m_hostAddr;
std::string m_uniqueTag;
std::string m_hashKey;
uint32_t m_vmViewId;
static const uint8_t LONER_DM_TYPE = 13;
static const int VERSION_MASK;
static const int8_t TOKEN_ORDINAL;
void readVersion(int flags, DataInput& input);
void writeVersion(int16_t ordinal, DataOutput& output);
void readAdditionalData(DataInput& input);
};
} // namespace client
} // namespace geode
} // namespace apache
#endif // GEODE_CLIENTPROXYMEMBERSHIPID_H_
| 35.802817 | 79 | 0.712628 | [
"vector"
] |
612975fbde441a02dad7488e5efcb0c2c1bac4bd | 44,520 | c++ | C++ | faxd/ClassModem.c++ | libelle17/hylafax_copy | 15a3054bb7f2a90ebbc1b03326a7eea6dbcb907f | [
"libtiff"
] | null | null | null | faxd/ClassModem.c++ | libelle17/hylafax_copy | 15a3054bb7f2a90ebbc1b03326a7eea6dbcb907f | [
"libtiff"
] | null | null | null | faxd/ClassModem.c++ | libelle17/hylafax_copy | 15a3054bb7f2a90ebbc1b03326a7eea6dbcb907f | [
"libtiff"
] | null | null | null | /* $Id: ClassModem.c++ 1114 2012-07-02 18:27:37Z faxguy $ */
/*
* Copyright (c) 1994-1996 Sam Leffler
* Copyright (c) 1994-1996 Silicon Graphics, Inc.
* HylaFAX is a trademark of Silicon Graphics
*
* Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
* LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
#include <ctype.h>
#include <stdlib.h>
#include "ModemServer.h"
#include "FaxTrace.h"
#include "Sys.h"
/*
* Call status description strings.
*/
const char* ClassModem::callStatus[11] = {
"Call successful {E000}", // OK
"Busy signal detected {E001}", // BUSY
"No carrier detected {E002}", // NOCARRIER
"No answer from remote {E003}", // NOANSWER
"No local dialtone {E004}", // NODIALTONE
"Invalid dialing command {E005}", // ERROR
"Unknown problem {E006}", // FAILURE
"Carrier established, but Phase A failure {E007}", // NOFCON
"Data connection established (wanted fax) {E008}", // DATACONN
"Glare - RING detected {E009}", // RING
"V.34/V.8 handshake incompatibility {E013}", // V34FAIL
};
/*
* Service class descriptions. The first three
* correspond to the EIA/TIA definitions. The
* voice class is for ZyXEL modems.
*/
const char* ClassModem::serviceNames[9] = {
"\"Data\"", // SERVICE_DATA
"\"Class 1\"", // SERVICE_CLASS1
"\"Class 2\"", // SERVICE_CLASS2
"\"Class 2.0\"", // SERVICE_CLASS20 (XXX 3)
"\"Class 1.0\"", // SERVICE_CLASS10 (XXX 4)
"\"Class 2.1\"", // SERVICE_CLASS21 (XXX 5)
"", // 6
"", // 7
"\"Voice\"", // SERVICE_VOICE
};
const char* ClassModem::ATresponses[19] = {
"Nothing", // AT_NOTHING
"OK", // AT_OK
"Connection established", // AT_CONNECT
"No answer or ring back", // AT_NOANSWER
"No carrier", // AT_NOCARRIER
"No dial tone", // AT_NODIALTONE
"Busy", // AT_BUSY
"Phone off-hook", // AT_OFFHOOK
"Ring", // AT_RING
"Command error", // AT_ERROR
"Hang up", // AT_FHNG
"<Empty line>", // AT_EMPTYLINE
"<Timeout>", // AT_TIMEOUT
"<dle+etx>", // AT_DLEETX
"End of transmission", // AT_DLEEOT
"<xon>", // AT_XON
"DTMF detection", // AT_DTMF
"Voice connection", // AT_VCON
"<Unknown response>" // AT_OTHER
};
const char* ClassModem::callTypes[6] = {
"unknown",
"data",
"fax",
"voice",
"error",
"done"
};
const char* ClassModem::answerTypes[6] = {
"any",
"data",
"fax",
"voice",
"dial",
"external"
};
ClassModem::ClassModem(ModemServer& s, const ModemConfig& c)
: server(s)
, conf(c)
, mfrQueryCmd(c.mfrQueryCmd)
, modelQueryCmd(c.modelQueryCmd)
, revQueryCmd(c.revQueryCmd)
{
modemServices = 0;
rate = BR0;
flowControl = conf.flowControl;
iFlow = FLOW_NONE;
oFlow = FLOW_NONE;
setupDefault(mfrQueryCmd, conf.mfrQueryCmd, "ATI3");
setupDefault(modelQueryCmd, conf.modelQueryCmd, "ATI0");
setupDefault(revQueryCmd, conf.revQueryCmd, ""); // No "standard" way? -- dbely
}
ClassModem::~ClassModem()
{
}
/*
* Default methods for modem driver interface.
*/
bool
ClassModem::dataService()
{
return atCmd(conf.class0Cmd);
}
CallStatus
ClassModem::dial(const char* number, const char* origin, fxStr& emsg)
{
dialedNumber = fxStr(number);
protoTrace("DIAL %s", number);
fxStr dialcmd = conf.dialCmd;
u_int destpos = dialcmd.find(0, "%s");
u_int origpos = dialcmd.find(0, "%d");
if (destpos == dialcmd.length() && origpos == dialcmd.length()) {
// neither %d nor %s appear in the cmd, use dialcmd as-is
} else if (origpos == dialcmd.length()) {
// just %s appears in the cmd
dialcmd = fxStr::format((const char*) dialcmd, number);
} else if (destpos == dialcmd.length()) {
// just %d appears in the cmd
dialcmd[origpos+1] = 's'; // change %d to %s
dialcmd = fxStr::format((const char*) dialcmd, origin);
} else {
// both %d and %s appear in the cmd
dialcmd[origpos+1] = 's'; // change %d to %s
if (origpos < destpos) {
// %d appears before %s
dialcmd = fxStr::format((const char*) dialcmd, origin, number);
} else {
// %s appears before %d
dialcmd = fxStr::format((const char*) dialcmd, number, origin);
}
}
emsg = "";
CallStatus cs = (atCmd(dialcmd, AT_NOTHING) ? dialResponse(emsg) : FAILURE);
if (cs != OK && emsg == "") {
emsg = callStatus[cs];
}
return (cs);
}
/*
* Status messages to ignore when dialing.
*/
bool
ClassModem::isNoise(const char* s)
{
static const char* noiseMsgs[] = {
"CED", // RC32ACL-based modems send this before +FCON
"DIALING",
"RRING", // Telebit
"RINGING", // ZyXEL
"+FHR:", // Intel 144e
"+A8", // Class 1.0 V.8 report
"+F34:", // Class 1.0 V.34 report
"+FDB:", // DCE debugging
"MESSAGE-WAITING", // voice-mail waiting, Conexant
"\020\003", // DLE+ETX ???
};
#define NNOISE (sizeof (noiseMsgs) / sizeof (noiseMsgs[0]))
for (u_int i = 0; i < NNOISE; i++)
if (strneq(s, noiseMsgs[i], strlen(noiseMsgs[i])))
return (true);
/*
* Some modems echoes the DTMF of the dialed number, and this should be
* ignored too.
* Instead of simply checking if "dialedNumber" is equal to "s" we must
* consider the possibility of having more numbers at "conf.dialCmd".
* Eg.: conf.dialCmd = atdt0%s (zero will be echoed)
* The easiest way is to find if "dialedNumber" is a sub-string of "s".
*/
if (strstr(s, (const char *) dialedNumber) != NULL) return (true);
return (false);
}
#undef NNOISE
/*
* Set of status codes we expect to receive
* from a modem in response to an A (answer
* the phone) command.
*/
static const AnswerMsg answerMsgs[] = {
{ "CONNECT FAX",11,
ClassModem::AT_NOTHING, ClassModem::OK, ClassModem::CALLTYPE_FAX },
{ "CONNECT", 7,
ClassModem::AT_NOTHING, ClassModem::OK, ClassModem::CALLTYPE_DATA },
{ "NO ANSWER", 9,
ClassModem::AT_NOTHING, ClassModem::NOANSWER, ClassModem::CALLTYPE_ERROR },
{ "NO CARRIER", 10,
ClassModem::AT_NOTHING, ClassModem::NOCARRIER, ClassModem::CALLTYPE_ERROR },
{ "NO DIALTONE",11,
ClassModem::AT_NOTHING, ClassModem::NODIALTONE,ClassModem::CALLTYPE_ERROR },
{ "ERROR", 5,
ClassModem::AT_NOTHING, ClassModem::ERROR, ClassModem::CALLTYPE_ERROR },
{ "+FHNG:", 6,
ClassModem::AT_NOTHING, ClassModem::NOCARRIER, ClassModem::CALLTYPE_ERROR },
{ "+FHS:", 5,
ClassModem::AT_NOTHING, ClassModem::NOCARRIER, ClassModem::CALLTYPE_ERROR },
{ "OK", 2,
ClassModem::AT_NOTHING, ClassModem::NOCARRIER, ClassModem::CALLTYPE_ERROR },
{ "BUSY", 4,
ClassModem::AT_NOTHING, ClassModem::NOCARRIER, ClassModem::CALLTYPE_ERROR },
{ "FAX", 3,
ClassModem::AT_CONNECT, ClassModem::OK, ClassModem::CALLTYPE_FAX },
{ "DATA", 4,
ClassModem::AT_CONNECT, ClassModem::OK, ClassModem::CALLTYPE_DATA },
};
#define NANSWERS (sizeof (answerMsgs) / sizeof (answerMsgs[0]))
const AnswerMsg*
ClassModem::findAnswer(const char* s)
{
for (u_int i = 0; i < NANSWERS; i++)
if (strneq(s, answerMsgs[i].msg, answerMsgs[i].len))
return (&answerMsgs[i]);
return (NULL);
}
#undef NANSWERS
/*
* Deduce connection kind: fax, data, or voice.
*/
CallType
ClassModem::answerResponse(fxStr answerCmd, fxStr& emsg)
{
CallStatus cs = FAILURE;
ATResponse r;
time_t start = Sys::now();
u_short morerings = 0;
do {
r = atResponse(rbuf, conf.answerResponseTimeout);
again:
if (r == AT_TIMEOUT || r == AT_DLEEOT || r == AT_NOCARRIER)
break;
if (r == AT_RING && ++morerings > 1) {
/*
* We answered already. If we see RING once it could
* be glare. If we see it yet again, then the modem
* apparently did not see or respond to our first
* answerCmd and we've got to try it again.
*
* In some cases this may happen because our ATA comes
* too soon following the RING for the modem's liking.
* This may have to do with the presence of Caller*ID
* reporting and in such cases is probably best-resolved
* by changing the RingsBeforeAnswer setting. However,
* as a fail-safe we can try to shake up the timing by
* adding a small delay before our ATA here.
*/
atCmd(conf.answerAgainCmd, AT_NOTHING);
morerings = 0;
}
const AnswerMsg* am = findAnswer(rbuf);
if (am != NULL) {
if (am->expect != AT_NOTHING && conf.waitForConnect) {
/*
* Response string is an intermediate result that
* is only meaningful if followed by AT response
* am->next. Read the next response from the modem
* and if it's the expected one, use the message
* to intuit the call type. Otherwise, discard
* the intermediate response string and process the
* call according to the newly read response.
* This is intended to deal with modems that send
* <something>
* CONNECT
* (such as the Boca 14.4).
*/
r = atResponse(rbuf, conf.answerResponseTimeout);
if (r != am->expect)
goto again;
}
if (am->status == OK) // success
return (am->type);
cs = am->status;
break;
}
if (r == AT_EMPTYLINE) {
emsg = callStatus[cs];
return (CALLTYPE_ERROR);
}
} while ((unsigned) ((Sys::now()-start)*1000) < conf.answerResponseTimeout);
emsg = "Ring detected without successful handshake {E012}";
return (CALLTYPE_ERROR);
}
CallType
ClassModem::answerCall(AnswerType atype, fxStr& emsg, const char* number)
{
CallType ctype = CALLTYPE_ERROR;
/*
* If the request has no type-specific commands
* to use, then just use the normal commands
* intended for answering any type of call.
*/
fxStr answerCmd;
switch (atype) {
case ANSTYPE_FAX: answerCmd = conf.answerFaxCmd; break;
case ANSTYPE_DATA: answerCmd = conf.answerDataCmd; break;
case ANSTYPE_VOICE: answerCmd = conf.answerVoiceCmd; break;
case ANSTYPE_DIAL:
answerCmd = conf.answerDialCmd;
dial(number, NULL, emsg); // no error-checking
break;
}
if (answerCmd == "")
answerCmd = conf.answerAnyCmd;
if (atCmd(answerCmd, AT_NOTHING)) {
ctype = answerResponse(answerCmd, emsg);
if (atype == ANSTYPE_DIAL) ctype = CALLTYPE_FAX; // force as fax
if (ctype == CALLTYPE_UNKNOWN) {
/*
* The response does not uniquely identify the type
* of call; assume the type corresponds to the type
* of the answer request.
*/
static CallType unknownCall[] = {
CALLTYPE_FAX, // ANSTYPE_ANY (default)
CALLTYPE_DATA, // ANSTYPE_DATA
CALLTYPE_FAX, // ANSTYPE_FAX
CALLTYPE_VOICE, // ANSTYPE_VOICE
CALLTYPE_UNKNOWN, // ANSTYPE_EXTERN
};
ctype = unknownCall[atype];
}
answerCallCmd(ctype);
}
return (ctype);
}
/*
* Send any configured commands to the modem once the
* type of the call has been established. These commands
* normally configure flow control and buad rate for
* modems that, for example, require a fixed baud rate
* and flow control scheme when receiving fax.
*/
void
ClassModem::answerCallCmd(CallType ctype)
{
fxStr beginCmd;
switch (ctype) {
case CALLTYPE_FAX: beginCmd = conf.answerFaxBeginCmd; break;
case CALLTYPE_DATA: beginCmd = conf.answerDataBeginCmd; break;
case CALLTYPE_VOICE:beginCmd = conf.answerVoiceBeginCmd; break;
}
if (beginCmd != "")
(void) atCmd(beginCmd);
}
/*
* Set data transfer timeout adjusted proportionately
* according to the negotiated bit rate ("secs" as-given
* is for 14400 bps). This is set to cover the amount
* of time used in transferring a chunk of data.
*/
void
ClassModem::setDataTimeout(long secs, u_int br)
{
dataTimeout = secs*1000; // 14400 bps timeout/data write (ms)
switch (br) {
case BR_2400: dataTimeout *= 6; break;
case BR_4800: dataTimeout *= 3; break;
case BR_7200: dataTimeout *= 2; break;
case BR_9600: dataTimeout = (3*dataTimeout)/2; break;
case BR_12000: dataTimeout = (6*dataTimeout)/5; break;
}
}
/*
* Set data transfer timeout by calculating
* the timeout period from the data size.
*/
void
ClassModem::setDataTimeout(long datasize, int discount, u_int br)
{
long secs = datasize*9/10000 + 1; // ~60s per 64KB of data, rounded up
secs -= discount;
setDataTimeout(secs > 15 ? secs : 15, br); // minimum 15-second dataTimeout here
}
fxStr
ClassModem::getCapabilities() const
{
return fxStr("");
}
/*
* Tracing support.
*/
/*
* Trace a MODEM-communication-related activity.
*/
void
ClassModem::modemTrace(const char* fmt ...)
{
va_list ap;
va_start(ap, fmt);
server.vtraceStatus(FAXTRACE_MODEMCOM, fmt, ap);
va_end(ap);
}
/*
* Trace a modem capability.
*/
void
ClassModem::modemCapability(const char* fmt ...)
{
va_list ap;
va_start(ap, fmt);
static const fxStr modem("MODEM: ");
server.vtraceStatus(FAXTRACE_MODEMCAP, modem | fmt, ap);
va_end(ap);
}
/*
* Indicate a modem supports some capability.
*/
void
ClassModem::modemSupports(const char* fmt ...)
{
va_list ap;
va_start(ap, fmt);
static const fxStr supports("MODEM Supports ");
server.vtraceStatus(FAXTRACE_MODEMCAP, supports | fmt, ap);
va_end(ap);
}
/*
* Trace a protocol-related activity.
*/
void
ClassModem::protoTrace(const char* fmt ...)
{
va_list ap;
va_start(ap, fmt);
server.vtraceStatus(FAXTRACE_PROTOCOL, fmt, ap);
va_end(ap);
}
/*
* Trace a server-level activity.
*/
void
ClassModem::serverTrace(const char* fmt ...)
{
va_list ap;
va_start(ap, fmt);
server.vtraceStatus(FAXTRACE_SERVER, fmt, ap);
va_end(ap);
}
/*
* Trace a modem capability bit mask.
*/
void
ClassModem::traceBits(u_int bits, const char* bitNames[])
{
for (u_int i = 0; bits; i++)
if (BIT(i) & bits) {
modemSupports(bitNames[i]);
bits &= ~BIT(i);
}
}
/*
* Trace a modem capability true bit mask (VR, BF, JP).
*/
void
ClassModem::traceBitMask(u_int bits, const char* bitNames[])
{
u_int i = 0;
do {
if ((bits & i) == i) {
modemSupports(bitNames[i]);
bits -= i;
}
i++;
} while (bits);
}
/*
* Modem i/o support.
*/
int
ClassModem::getModemLine(char buf[], u_int bufSize, long ms)
{
int n = server.getModemLine(buf, bufSize, ms);
if (n > 0)
trimModemLine(buf, n);
return (n);
}
int ClassModem::getModemBit(long ms) { return server.getModemBit(ms); }
int ClassModem::getModemChar(long ms, bool doquery) { return server.getModemChar(ms, doquery); }
int ClassModem::getModemDataChar() { return server.getModemChar(dataTimeout); }
int ClassModem::getLastByte() { return server.getLastByte(); }
bool ClassModem::didBlockEnd() { return server.didBlockEnd(); }
void ClassModem::sawBlockEnd() { server.setBlockEnd(); }
void ClassModem::resetBlock() { server.resetBlock(); }
bool
ClassModem::putModemDLEData(const u_char* data, u_int cc, const u_char* bitrev, long ms, bool doquery)
{
u_char dlebuf[2*1024];
while (cc > 0) {
if (wasTimeout() || abortRequested())
return (false);
/*
* Copy to temp buffer, doubling DLE's.
*/
u_int i, j;
u_int n = fxmin((size_t) cc, sizeof (dlebuf)/2);
for (i = 0, j = 0; i < n; i++, j++) {
dlebuf[j] = bitrev[data[i]];
if (dlebuf[j] == DLE)
dlebuf[++j] = DLE;
}
if (!putModem(dlebuf, j, ms))
return (false);
data += n;
cc -= n;
/*
* Fax is half-duplex. Thus, we shouldn't typically need to read
* data from the modem while we are transmitting. However, Phase C
* can be long, and things can go wrong, and it will be nice to
* see the timing of any messages that will come from the modem,
* instead of letting them buffer. Furthermore, advanced Class 2
* debugging will send us messages during Phase C. So in those
* cases when it will be useful, we query the modem during transmits.
*
* In the cases where things do go wrong, we'll need to begin
* building-in the intelligence to handle that here. But we have
* to wait and see what turns up in order to do that.
*/
if (doquery) {
int c;
fxStr dbdata;
do {
c = getModemChar(0, true);
if (c != EOF && c != '\0' && c != '\r' && c != '\n')
dbdata.append(c);
else if (dbdata.length()) {
protoTrace("DCE DEBUG: %s", (const char*) dbdata);
dbdata = "";
}
} while (c != EOF);
}
}
return (true);
}
void ClassModem::flushModemInput()
{ server.modemFlushInput(); }
bool ClassModem::putModem(void* d, int n, long ms)
{ return server.putModem(d, n, ms); }
bool ClassModem::putModemData(void* d, int n, long ms)
{ return server.putModem(d, n, (ms == -1) ? dataTimeout : ms); }
bool
ClassModem::putModemLine(const char* cp, long ms)
{
u_int cc = strlen(cp);
server.traceStatus(FAXTRACE_MODEMCOM, "<-- [%u:%s\\r]", cc+1, cp);
static const char CR = '\r';
return (server.putModem1(cp, cc, ms) && server.putModem1(&CR, 1, ms));
}
void ClassModem::startTimeout(long ms) { server.startTimeout(ms); }
void ClassModem::stopTimeout(const char* w){ server.stopTimeout(w); }
const u_int MSEC_PER_SEC = 1000;
#include <sys/time.h>
#if HAS_SELECT_H
#include <sys/select.h>
#endif
void
ClassModem::pause(u_int ms)
{
if (ms == 0)
return;
protoTrace("DELAY %u ms", ms);
struct timeval tv;
tv.tv_sec = ms / MSEC_PER_SEC;
tv.tv_usec = (ms % MSEC_PER_SEC) * 1000;
(void) select(0, 0, 0, 0, &tv);
}
void
ClassModem::setupDefault(fxStr& s, const fxStr& configured, const char* def)
{
if (configured == "")
s = def;
else
s = configured;
}
/*
* Reset the modem and set the DTE-DCE rate.
*/
bool
ClassModem::selectBaudRate(BaudRate br, FlowControl i, FlowControl o)
{
rate = br;
iFlow = i;
oFlow = o;
return (reset(5*1000) || reset(5*1000)); // NB: try at most twice
}
bool ClassModem::sendBreak(bool pause)
{ return server.sendBreak(pause); }
bool
ClassModem::setBaudRate(BaudRate r)
{
if (server.setBaudRate(r)) {
if (conf.baudRateDelay)
pause(conf.baudRateDelay);
return (true);
} else
return (false);
}
bool
ClassModem::setBaudRate(BaudRate r, FlowControl i, FlowControl o)
{
iFlow = i;
oFlow = o;
rate = r;
if (server.setBaudRate(r,i,o)) {
if (conf.baudRateDelay)
pause(conf.baudRateDelay);
return (true);
} else
return (false);
}
bool
ClassModem::setXONXOFF(FlowControl i, FlowControl o, SetAction a)
{
iFlow = i;
oFlow = o;
return server.setXONXOFF(i, o, a);
}
bool ClassModem::setDTR(bool onoff)
{ return server.setDTR(onoff); }
bool ClassModem::setInputBuffering(bool onoff)
{ return server.setInputBuffering(onoff); }
bool ClassModem::modemStopOutput()
{ return server.modemStopOutput(); }
/*
* Miscellaneous server interfaces hooks.
*/
bool ClassModem::abortRequested()
{ return server.abortRequested(); }
void ClassModem::beginTimedTransfer() { server.timeout = false; }
void ClassModem::endTimedTransfer() {}
bool ClassModem::wasTimeout() { return server.timeout; }
bool ClassModem::wasModemError() { return server.modemerror; }
void ClassModem::setTimeout(bool b) { server.timeout = b; }
/*
* Parsing support routines.
*/
/*
* Cleanup a response line from the modem. This removes
* leading white space and any prefixing "+F<mumble>=" crap
* that some Class 2 modems put at the front, as well as
* any trailing white space.
*/
void
ClassModem::trimModemLine(char buf[], int& cc)
{
// trim trailing white space
if (cc > 0 && isspace(buf[cc-1])) {
do {
cc--;
} while (cc > 0 && isspace(buf[cc-1]));
buf[cc] = '\0';
}
if (cc > 0) {
int i = 0;
// leading white space
while (i < cc && isspace(buf[i]))
i++;
// check for a leading +F<mumble>=
if (i+1 < cc && buf[i] == '+' && buf[i+1] == 'F') {
u_int j = i;
for (i += 2; i < cc && buf[i] != '='; i++)
;
if (i < cc) { // trim more white space
for (i++; i < cc && isspace(buf[i]); i++)
;
} else // no '=', back out
i = j;
}
cc -= i;
memmove(buf, buf+i, cc+1);
}
}
/*
* The modem drivers and main server code require:
*
* echoOff command echo disabled
* verboseResults verbose command result strings
* resultCodes result codes enabled
* onHook modem initially on hook (hung up)
* noAutoAnswe no auto-answer (we do it manually)
*
* In addition the following configuration is included
* in the reset command set:
*
* flowControl DCE-DTE flow control method
* setupDTR DTR management technique
* setupDCD DCD management technique
* pauseTime time to pause for "," when dialing
* waitTime time to wait for carrier when dialing
*
* Any other modem-specific configuration that needs to
* be done at reset time should be implemented by overriding
* the ClassModem::reset method.
*/
bool
ClassModem::reset(long ms)
{
if (conf.dtrDropDelay) {
setDTR(false);
pause(conf.dtrDropDelay); // required DTR OFF-to-ON delay
setDTR(true);
pause(conf.resetDelay); // pause so modem can do reset
}
#ifndef CONFIG_NOREOPEN
/*
* On some systems lowering and raising DTR is not done
* properly (DTR is not raised when requested); thus we
* reopen the device to insure that DTR is reasserted.
*/
server.reopenDevice();
#endif
if (!setBaudRate(rate, iFlow, oFlow)) {
return (false);
}
flushModemInput();
/*
* Perform a soft reset as well to ensure the modem
* is in a stable state before sending the additional
* reset commands. Depending on the modem and its
* state, we may wait 30 sec for OK repsonse.
*/
if ( true != atCmd(conf.softResetCmd, AT_OK, 30*1000) ) {
return false;
}
/*
* Some modems require a pause after ATZ before they can
* accept any more commands although they have already
* replied OK to the ATZ command.
*/
pause(conf.softResetCmdDelay);
// some modems result with OK *twice* after ATZ, so flush it
flushModemInput();
if ( true != atCmd(conf.resetCmds, AT_OK, ms) ) {
return false;
}
if ( true != atCmd(conf.noAutoAnswerCmd, AT_OK, ms) ) {
return false;
}
if (conf.noAutoAnswerCmdDelay) {
/* Some modems do funny things after ATS0=0. */
pause(conf.noAutoAnswerCmdDelay);
flushModemInput();
}
if ( true != atCmd(conf.echoOffCmd, AT_OK, ms) ) {
return false;
}
if ( true != atCmd(conf.verboseResultsCmd, AT_OK, ms) ) {
return false;
}
if ( true != atCmd(conf.resultCodesCmd, AT_OK, ms) ) {
return false;
}
// some modems do not accept standard onHookCmd (ATH0) when
// they are allready on hook
// if ( true != atCmd(conf.onHookCmd, AT_OK, ms) ) {
// return false;
// }
if ( true != atCmd(conf.pauseTimeCmd, AT_OK, ms) ) {
return false;
}
if ( true != atCmd(conf.waitTimeCmd, AT_OK, ms) ) {
return false;
}
if ( true != atCmd(conf.getFlowCmd(conf.flowControl), AT_OK, ms) ) {
return false;
}
if ( true != atCmd(conf.setupDTRCmd, AT_OK, ms) ) {
return false;
}
if ( true != atCmd(conf.setupDCDCmd, AT_OK, ms) ) {
return false;
}
return true;
}
/*
* Some scenarios require a "ready" command sequence to occur
* to, for example, un-busy a line (DID) or otherwise ready
* the modem for incoming calls after the rest of the
* initialization has already occurred.
*/
bool
ClassModem::ready(long ms)
{
return atCmd(conf.readyCmds, AT_OK, ms);
}
bool
ClassModem::sync(long ms)
{
return waitFor(AT_OK, ms);
}
ATResponse
ClassModem::atResponse(char* buf, long ms)
{
bool prevTimeout = wasTimeout();
int n = getModemLine(buf, sizeof (rbuf), ms);
if (!prevTimeout && wasTimeout())
lastResponse = AT_TIMEOUT;
else if (n <= 0)
lastResponse = AT_EMPTYLINE;
else {
lastResponse = AT_OTHER;
switch (buf[0]) {
case 'B':
if (strneq(buf, "BUSY", 4))
lastResponse = AT_BUSY;
break;
case 'C':
if (strneq(buf, "CONNECT", 7))
lastResponse = AT_CONNECT;
break;
case 'D':
if (strneq(buf, "DTMF", 4))
lastResponse = AT_DTMF;
break;
case 'E':
if (strneq(buf, "ERROR", 5))
lastResponse = AT_ERROR;
break;
case 'N':
if (strneq(buf, "NO CARRIER", 10))
lastResponse = AT_NOCARRIER;
else if (strneq(buf, "NO DIAL", 7)) // NO DIALTONE or NO DIAL TONE
lastResponse = AT_NODIALTONE;
else if (strneq(buf, "NO ANSWER", 9))
lastResponse = AT_NOANSWER;
break;
case 'O':
if (strneq(buf, "OK", 2))
lastResponse = AT_OK;
break;
case 'P':
if (strneq(buf, "PHONE OFF-HOOK", 14))
lastResponse = AT_OFFHOOK;
break;
case 'R':
if (streq(buf, "RING")) // NB: avoid match of RINGING
lastResponse = AT_RING;
else if (strneq(buf, "RING/", 5)) // Match RING/CALLEDPARTYNUMBER
lastResponse = AT_RING;
break;
case 'V':
if (streq(buf, "VCON"))
lastResponse = AT_VCON;
break;
case '\020':
if (streq(buf, "\020\003")) // DLE/ETX
lastResponse = AT_DLEETX;
if (streq(buf, "\020\004"))
lastResponse = AT_DLEEOT; // DLE+EOT
break;
case '\021':
if (streq(buf, "\021")) // DC1 (XON)
lastResponse = AT_XON;
break;
}
}
return lastResponse;
}
#define isLineBreak(c) ((c) == '\n' || (c) == '\r')
#define isEscape(c) ((c) & 0x80)
/*
* Send an AT command string to the modem and, optionally
* wait for status responses. This routine breaks multi-line
* strings (demarcated by embedded \n's) and waits for each
* intermediate response. Embedded escape sequences for
* changing the DCE-DTE communication rate and/or host-modem
* flow control scheme are also recognized and handled.
*/
bool
ClassModem::atCmd(const fxStr& cmd, ATResponse r, long ms)
{
u_int cmdlen;
u_int pos;
bool respPending;
if (lastResponse == AT_RING) lastResponse = AT_NOTHING;
do {
cmdlen = cmd.length();
pos = 0;
respPending = false;
/*
* Scan string for line breaks and escape codes (byte w/ 0x80 set).
* A line break causes the current string to be sent to the modem
* and a return status string parsed (and possibly compared to an
* expected response). An escape code terminates scanning,
* with any pending string flushed to the modem before the
* associated commands are carried out. All commands are sent in
* uppercase.
*/
u_int i = 0;
while (i < cmdlen) {
if (isLineBreak(cmd[i]) && !(i+1 < cmdlen && isEscape(cmd[i+1]))) {
/*
* No escape code follows, send partial string
* to modem and await status string if necessary.
*/
if (conf.atCmdDelay)
pause(conf.atCmdDelay);
fxStr command = cmd.extract(pos, i-pos);
if (conf.raiseATCmd) command.raiseatcmd();
if (!putModemLine(command, ms))
return (false);
pos = ++i; // next segment starts after line break
if (r != AT_NOTHING) {
if (!waitFor(r, ms))
return (false);
} else {
if (!waitFor(AT_OK, ms))
return (false);
}
respPending = false;
} else if (isEscape(cmd[i])) {
/*
* Escape code; flush any partial line, process
* escape codes and carry out their actions.
*/
ATResponse resp = AT_NOTHING;
if (i > pos) {
if (conf.atCmdDelay)
pause(conf.atCmdDelay);
if (isLineBreak(cmd[i-1])) {
/*
* Send data with a line break and arrange to
* collect the expected response (possibly
* specified through a <waitfor> escape processed
* below). Note that we use putModemLine, as
* above, so that the same line break is sent
* to the modem for all segments (i.e. \n is
* translated to \r).
*/
fxStr command = cmd.extract(pos, i-1-pos);
if (conf.raiseATCmd) command.raiseatcmd();
if (!putModemLine(command, ms))
return (false);
// setup for expected response
resp = (r != AT_NOTHING ? r : AT_OK);
} else {
/*
* Flush any data as-is, w/o adding a line
* break or expecting a response. This is
* important for sending, for example, a
* command escape sequence such as "+++".
*/
u_int cc = i-pos;
const char* cp = &cmd[pos];
server.traceStatus(FAXTRACE_MODEMCOM, "<-- [%u:%s]", cc,cp);
if (!server.putModem1(cp, cc))
return (false);
}
respPending = true;
}
/*
* Process escape codes.
*/
BaudRate br = rate;
FlowControl flow = flowControl;
u_int delay = 0;
do {
switch (cmd[i] & 0xff) {
case ESC_SETBR: // set host baud rate
br = (u_char) cmd[++i];
if (br != rate) {
setBaudRate(br);
rate = br;
}
break;
case ESC_SETFLOW: // set host flow control
flow = (u_char) cmd[++i];
if (flow != flowControl) {
setBaudRate(br, flow, flow);
flowControl = flow;
}
break;
case ESC_DELAY: // host delay
delay = (u_char) cmd[++i];
if (delay != 0)
pause(delay*10); // 10 ms granularity
break;
case ESC_WAITFOR: // wait for response
resp = (u_char) cmd[++i];
if (resp != AT_NOTHING) {
// XXX check return?
// The timeout setting here (60*1000) used to be "ms" (which
// defaults to 30 s), but we find that's too short, especially
// for long-running escape sequences. It really needs to be
// escape-configurable, but for now we just make it 60 s.
(void) waitFor(resp, 60*1000);
respPending = false;
}
break;
case ESC_FLUSH: // flush input
flushModemInput();
break;
case ESC_PLAY:
{
fxStr filename = fxStr("etc/play");
filename.append(cmd[++i]);
filename.append(".raw");
protoTrace("Playing file \"%s\".", (const char*) filename);
int fd = open((const char*) filename, O_RDONLY);
if (fd > 0) {
u_char buf[1024];
int len, pos;
do {
pos = 0;
do {
len = read(fd, &buf[pos], 1);
if (buf[pos] == 0x10) buf[++pos] = 0x10;
pos++;
} while (len > 0 && (u_int) pos < sizeof(buf) - 1);
putModem(&buf[0], pos, getDataTimeout());
} while (len > 0);
close(fd);
} else {
protoTrace("Unable to open file \"%s\" for reading.", (const char*) filename);
}
u_char buf[2];
buf[0] = DLE; buf[1] = ETX;
putModem(buf, 2, getDataTimeout());
}
break;
}
} while (++i < cmdlen && isEscape(cmd[i]));
pos = i; // next segment starts here
if (respPending) {
/*
* If a segment with a line break was flushed
* but no explicit <waitfor> escape followed
* then collect the response here so that it
* does not get lost.
*/
if (resp != AT_NOTHING && !waitFor(resp, ms))
return (false);
respPending = false;
}
} else
i++;
}
/*
* Flush any pending string to modem.
*/
if (i > pos) {
if (conf.atCmdDelay)
pause(conf.atCmdDelay);
fxStr command = cmd.extract(pos, i-pos);
if (conf.raiseATCmd) command.raiseatcmd();
if (!putModemLine(command, ms))
return (false);
respPending = true;
}
/*
* Wait for any pending response.
*/
if (respPending) {
if (r != AT_NOTHING && !waitFor(r, ms)) {
if (lastResponse != AT_RING) {
return (false);
} else {
// wait for result, but some modem's don't result after glare
if (r != AT_NOTHING && !waitFor(r, ms)) {
lastResponse = AT_RING;
}
}
}
}
} while (lastResponse == AT_RING);
return (true);
}
#undef isEscape
#undef isLineBreak
/*
* Wait (carefully) for some response from the modem.
*/
bool
ClassModem::waitFor(ATResponse wanted, long ms)
{
for (;;) {
ATResponse response = atResponse(rbuf, ms);
if (response == wanted)
return (true);
// we need to translate AT responses from faxd/Class2.h
if (response == 100) response = AT_FHNG;
switch (response) {
case AT_TIMEOUT:
case AT_EMPTYLINE:
case AT_ERROR:
case AT_NOCARRIER:
case AT_NODIALTONE:
case AT_NOANSWER:
case AT_BUSY:
case AT_OFFHOOK:
case AT_RING:
case AT_FHNG:
modemTrace("MODEM %s", ATresponses[response]);
case AT_CONNECT:
case AT_OK:
/*
* If we get OK and aren't expecting it then we're back in command-mode
* and our previous command failed to acheive the desired result.
*/
return (false);
}
}
}
/*
* Process a manufacturer/model/revision query.
*/
bool
ClassModem::doQuery(const fxStr& queryCmd, fxStr& result, long ms)
{
if (queryCmd == "")
return (true);
if (queryCmd[0] == '!') {
/*
* ``!mumble'' is interpreted as "return mumble";
* this means that you can't send ! to the modem.
*/
result = queryCmd.tail(queryCmd.length()-1);
return (true);
}
return (atQuery(queryCmd, result, ms));
}
/*
* Return modem manufacturer.
*/
bool
ClassModem::setupManufacturer(fxStr& mfr)
{
return doQuery(mfrQueryCmd, mfr);
}
/*
* Return modem model identification.
*/
bool
ClassModem::setupModel(fxStr& model)
{
return doQuery(modelQueryCmd, model);
}
/*
* Return modem firmware revision.
*/
bool
ClassModem::setupRevision(fxStr& rev)
{
return doQuery(revQueryCmd, rev);
}
/*
* Send AT<what>? and get a string response.
*/
bool
ClassModem::atQuery(const char* what, fxStr& v, long ms)
{
ATResponse r = AT_ERROR;
if (atCmd(what, AT_NOTHING)) {
v.resize(0);
while ((r = atResponse(rbuf, ms)) != AT_OK) {
if (r == AT_ERROR || r == AT_TIMEOUT || r == AT_EMPTYLINE)
break;
if (v.length())
v.append('\n');
v.append(rbuf);
}
}
return (r == AT_OK);
}
/*
* Send AT<what>? and get a range response.
*/
bool
ClassModem::atQuery(const char* what, u_int& v, long ms)
{
char response[1024];
if (atCmd(what, AT_NOTHING) && atResponse(response) == AT_OTHER) {
sync(ms);
return parseRange(response, v);
}
return (false);
}
/*
* Parsing support routines.
*/
const char OPAREN = '(';
const char CPAREN = ')';
const char COMMA = ',';
const char SPACE = ' ';
/*
* Parse a Class 2 parameter range string. This is very
* forgiving because modem vendors do not exactly follow
* the syntax specified in the "standard". Try looking
* at some of the responses given by rev ~4.04 of the
* ZyXEL firmware (for example)!
*
* This can also get complicated in that the parameters may
* be in hexadecimal or decimal notation. If in the future
* a standard way to "detect" the presence of future hex values
* (i.e. the <low> value is "00" instead of "0") may be found.
* For now we just use Class2UseHex.
*
* NB: We accept alphanumeric items but don't return them
* in the parsed range so that modems like the ZyXEL 2864
* that indicate they support ``Class Z'' are handled.
*/
bool
ClassModem::vparseRange(const char* cp, int masked, int nargs ... )
{
bool b = true;
va_list ap;
va_start(ap, nargs);
while (nargs-- > 0) {
while (cp[0] == SPACE)
cp++;
char matchc;
bool acceptList;
if (cp[0] == OPAREN) { // (<items>)
matchc = CPAREN;
acceptList = true;
cp++;
} else if (isalnum(cp[0])) { // <item>
matchc = COMMA;
acceptList = (nargs == 0);
} else { // skip to comma
b = false;
break;
}
int mask = 0;
while (cp[0] && cp[0] != matchc) {
if (cp[0] == SPACE) { // ignore white space
cp++;
continue;
}
if (!isalnum(cp[0])) {
b = false;
goto done;
}
int v;
if (conf.class2UseHex) { // read as hex
if (isxdigit(cp[0])) {
char *endp;
v = (int) strtol(cp, &endp, 16);
cp = endp;
} else {
v = -1; // XXX skip item below
while (isalnum((++cp)[0]));
}
} else { // assume decimal
if (isdigit(cp[0])) {
v = 0;
do {
v = v*10 + (cp[0] - '0');
} while (isdigit((++cp)[0]));
} else {
v = -1; // XXX skip item below
while (isalnum((++cp)[0]));
}
}
int r = v;
if (cp[0] == '-') { // <low>-<high>
cp++;
if (conf.class2UseHex) { // read as hex
if (!isxdigit(cp[0])) {
b = false;
goto done;
}
char *endp;
r = (int) strtol(cp, &endp, 16);
cp = endp;
} else { // assume decimal
if (!isdigit(cp[0])) {
b = false;
goto done;
}
r = 0;
do {
r = r*10 + (cp[0] - '0');
} while (isdigit((++cp)[0]));
}
} else if (cp[0] == '.') { // <d.b>
cp++;
if (v == 2) {
if (cp[0] == '1') { // 2.1 -> 5
v = 5;
r = 5;
} else { // 2.0 -> 3
v = 3;
r = 3;
}
} else { // 1.0 -> 4
v = 4;
r = 4;
}
while (isdigit(cp[0])) // XXX
cp++;
}
if (v != -1) { // expand range or list
if ((BIT(nargs) & masked) == BIT(nargs)) {
/*
* These are pre-masked values. T.32 Table 21 gives valid
* values as: 00, 01, 02, 04, 08, 10, 20, 40 (hex).
*
* Some modems may say "(00-7F)" when what's meant is
* "(00-40)" or simply "(7F)".
*/
if (v == 00 && r == 127)
v = r = 127;
if (v == r)
mask = v;
else {
r = fxmin(r, 64); // clamp to valid range
mask = 0;
for (; v <= r; v++)
if (v == 0 || v == 1 || v == 2 || v == 4 || v == 8 || v == 16 || v == 32 || v == 64)
mask += v;
}
} else {
r = fxmin(r, 31); // clamp to valid range
for (; v <= r; v++)
mask |= 1<<v;
}
}
if (acceptList && cp[0] == COMMA) // (<item>,<item>...)
cp++;
}
*va_arg(ap, int*) = mask;
if (cp[0] == matchc)
cp++;
if (matchc == CPAREN && cp[0] == COMMA)
cp++;
}
done:
va_end(ap);
return (b);
}
/*
* Parse a single Class X range specification
* and return the resulting bit mask.
*/
bool
ClassModem::parseRange(const char* cp, u_int& a0)
{
return vparseRange(cp, 0, 1, &a0);
}
void
ClassModem::setSpeakerVolume(SpeakerVolume l)
{
atCmd(conf.setVolumeCmd[l], AT_OK, 5000);
}
void
ClassModem::hangup()
{
atCmd(conf.onHookCmd, AT_OK, 5000);
}
bool
ClassModem::poke()
{
return atCmd("AT", AT_OK, 5000);
}
bool
ClassModem::waitForRings(u_short rings, CallType& type, CallID& callid)
{
bool gotring = false;
u_int i = 0, count = 0;
int incadence[5] = { 0, 0, 0, 0, 0 };
time_t timeout = conf.ringTimeout/1000; // 6 second/ring
time_t start = Sys::now();
do {
switch (atResponse(rbuf, conf.ringTimeout)) {
case AT_DTMF:
case AT_OTHER: // check distinctive ring
if (streq(conf.ringData, rbuf))
type = CALLTYPE_DATA;
else if (streq(conf.ringFax, rbuf))
type = CALLTYPE_FAX;
else if (streq(conf.ringVoice, rbuf))
type = CALLTYPE_VOICE;
else if (conf.dringOff.length() && strneq(conf.dringOff, rbuf, conf.dringOff.length())) {
if (count++ == 0) break; //discard initial DROFF code if present
incadence[i++] = -atoi(rbuf + conf.dringOff.length());
break;
} else if (conf.dringOn.length() && strneq(conf.dringOn, rbuf, conf.dringOn.length())) {
++count;
incadence[i++] = atoi(rbuf + conf.dringOn.length());
break;
} else {
if (conf.ringExtended.length() && strneq(rbuf, conf.ringExtended, conf.ringExtended.length())) // extended RING
gotring = true;
conf.parseCallID(rbuf, callid);
fxStr callid_formatted;
for (u_int i = 0; i < callid.size(); i++) {
callid_formatted.append(callid.id(i));
callid_formatted.append(",");
}
modemTrace("MODEM CID %s", (const char *)callid_formatted);
/* DID modems may send DID data in lieu of RING */
for (u_int i = 0; i < conf.idConfig.length(); i++) {
if (conf.idConfig[i].answerlength && callid.length(i) >= conf.idConfig[i].answerlength)
gotring = true;
}
break;
}
/* fall thru... */
case AT_RING: // normal ring
if (conf.ringResponse != "" && rings+1U >= conf.ringsBeforeResponse) {
// With the MT1932ZDX we must respond ATH1>DT1 in order
// to hear DTMF tones which are DID data, and we configure
// RingExtended to be FAXCNG to then trigger ATA.
atCmd(conf.ringResponse, AT_NOTHING);
ATResponse r;
time_t ringstart = Sys::now();
bool callidwasempty = true, cmddone = false;
for (u_int i = 0; callidwasempty && i < callid.size(); i++)
if (callid.length(i) )
callidwasempty = false;
do {
r = atResponse(rbuf, 3000);
if (r == AT_OTHER && callidwasempty) {
/*
* Perhaps a modem will repeat CID/DID info for us
* with AT+VRID if we missed it before.
*/
conf.parseCallID(rbuf, callid);
fxStr callid_formatted;
for (u_int i = 0; i < callid.size(); i++) {
callid_formatted.append(callid.id(i));
callid_formatted.append(",");
}
modemTrace("MODEM CID %s", (const char *)callid_formatted);
}
if (r == AT_OK) cmddone = true;
else if (r == AT_VCON) cmddone = true; // VCON for modems that require ATA
} while (!cmddone && (Sys::now()-ringstart < 3));
for (u_int j = 0 ; j < conf.idConfig.length(); j++) {
if (conf.idConfig[j].pattern == "SHIELDED_DTMF") { // retrieve DID, e.g. via voice DTMF
ringstart = Sys::now();
bool marked = false;
int gotdigit = 0;
do {
int c = server.getModemChar(10000);
if (c == 0x10) c = server.getModemChar(10000);
if (c == 0x23 || c == 0x2A || (c >= 0x30 && c <= 0x39)) {
// a DTMF digit was received...
if (!marked || !gotdigit || (c != gotdigit)) {
protoTrace("MODEM HEARD DTMF: %c", c);
callid[j].append(fxStr::format("%c", c));
gotdigit = c;
}
} else if (c == 0x2F) {
// got IS-101 DTMF lead marker
marked = true;
gotdigit = 0;
} else if (c == 0x7E) {
// got IS-101 DTMF end marker
marked = false;
gotdigit = 0;
} else if (c == 0x73) {
// got silence, keep waiting
protoTrace("MODEM HEARD SILENCE");
} else if (c == 0x62) {
// got busy tone, fail
protoTrace("MODEM HEARD BUSY");
return (false);
} else if (c == 0x63) {
// got CNG tone, we're not going to get more DTMF, trigger answering
protoTrace("MODEM HEARD CNG");
break;
}
} while (callid.length(j) < conf.idConfig[j].answerlength && (Sys::now()-ringstart < 10));
/*
* If the sender doesn't send enough DTMF then we want to answer anyway.
*/
while (callid.length(j) < conf.idConfig[j].answerlength) callid[j].append(" ");
}
}
}
if (conf.dringOn.length()) { // Compare with all distinctive ring cadences
modemTrace("WFR: received cadence = %d, %d, %d, %d, %d", incadence[0], incadence[1], incadence[2], incadence[3], incadence[4]);
type = findCallType(incadence);
}
gotring = true;
break;
case AT_NOANSWER:
case AT_NOCARRIER:
case AT_NODIALTONE:
case AT_ERROR:
return (false);
}
} while (!gotring && Sys::now()-start < timeout);
return (gotring);
}
CallType ClassModem::findCallType(int vec[])
{
// compare x^2 than x to avoid use of math functions
double limit = 0.33*0.33;
double dif, sum;
u_int n, k;
for (n=0; n < conf.NoDRings; ++n) {
for (k=0, sum=0; k < 5; ++k) {
dif = vec[k] - conf.distinctiveRings[n].cadence[k];
sum += dif*dif;
}
if (sum/conf.distinctiveRings[n].magsqrd < limit)
return conf.distinctiveRings[n].type;
}
return CALLTYPE_UNKNOWN;
}
bool ClassModem::doCallIDDisplay(int i) const { return conf.idConfig[i].display; }
bool ClassModem::doCallIDRecord(int i) const { return conf.idConfig[i].record; }
const fxStr& ClassModem::getCallIDLabel(int i) const { return conf.idConfig[i].label; }
const fxStr& ClassModem::getCallIDType(int i) const { return conf.idConfig[i].type; }
| 27.790262 | 129 | 0.617498 | [
"model"
] |
612be19e9249ffc6b8e677ebd2b6382ba69fc9fa | 4,984 | cpp | C++ | Kickstart/KickStart19BVC/c.cpp | Shahraaz/CP_P_S5 | b068ad02d34338337e549d92a14e3b3d9e8df712 | [
"MIT"
] | null | null | null | Kickstart/KickStart19BVC/c.cpp | Shahraaz/CP_P_S5 | b068ad02d34338337e549d92a14e3b3d9e8df712 | [
"MIT"
] | null | null | null | Kickstart/KickStart19BVC/c.cpp | Shahraaz/CP_P_S5 | b068ad02d34338337e549d92a14e3b3d9e8df712 | [
"MIT"
] | null | null | null | // Optimise
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define MULTI_TEST
#ifdef LOCAL
#define db(...) ZZ(#__VA_ARGS__, __VA_ARGS__);
#define pc(...) PC(#__VA_ARGS__, __VA_ARGS__);
template <typename T, typename U>
ostream &operator<<(ostream &out, const pair<T, U> &p)
{
out << '[' << p.first << ", " << p.second << ']';
return out;
}
template <typename Arg>
void PC(const char *name, Arg &&arg)
{
while (*name == ',' || *name == ' ')
name++;
std::cerr << name << " { ";
for (const auto &v : arg)
cerr << v << ' ';
cerr << " }\n";
}
template <typename Arg1, typename... Args>
void PC(const char *names, Arg1 &&arg1, Args &&... args)
{
while (*names == ',' || *names == ' ')
names++;
const char *comma = strchr(names, ',');
std::cerr.write(names, comma - names) << " { ";
for (const auto &v : arg1)
cerr << v << ' ';
cerr << " }\n";
PC(comma, args...);
}
template <typename Arg1>
void ZZ(const char *name, Arg1 &&arg1)
{
std::cerr << name << " = " << arg1 << endl;
}
template <typename Arg1, typename... Args>
void ZZ(const char *names, Arg1 &&arg1, Args &&... args)
{
const char *comma = strchr(names + 1, ',');
std::cerr.write(names, comma - names) << " = " << arg1;
ZZ(comma, args...);
}
#else
#define db(...)
#define pc(...)
#endif
using ll = long long;
template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
#define f first
#define s second
#define pb push_back
#define all(v) v.begin(), v.end()
auto TimeStart = chrono::steady_clock::now();
auto seed = TimeStart.time_since_epoch().count();
std::mt19937 rng(seed);
template <typename T>
using Random = std::uniform_int_distribution<T>;
const int NAX = 2e5 + 5, MOD = 1000000007, s = 1 << 17;
int q, n, x, a[NAX];
vector<int> pos[NAX];
class segtree
{
public:
ll seg[s * 2], lazy[2 * s];
void init()
{
memset(seg, 0, sizeof seg);
memset(lazy, 0, sizeof lazy);
}
void lazy_evaluate(int k)
{
if ((k * 2 + 2) >= s * 2)
return;
lazy[2 * k + 2] += lazy[k];
lazy[2 * k + 1] += lazy[k];
seg[2 * k + 1] += lazy[k];
seg[2 * k + 2] += lazy[k];
lazy[k] = 0;
}
ll update(int beg, int end, int idx, int lb, int ub, ll num)
{
if (ub < beg || end < lb)
return seg[idx];
if (beg <= lb && ub <= end)
{
lazy[idx] += num;
seg[idx] += num;
return seg[idx];
}
if (lazy[idx])
lazy_evaluate(idx);
return seg[idx] = max(
update(beg, end, idx * 2 + 1, lb, (lb + ub) / 2, num),
update(beg, end, idx * 2 + 2, (lb + ub) / 2 + 1, ub, num));
}
ll query(int beg, int end, int idx, int lb, int ub)
{
// db("Query", beg, end, idx, lb, ub);
if (ub < beg || end < lb)
return -1000000000000000000LL;
if (beg <= lb && ub <= end)
return seg[idx];
if (lazy[idx])
lazy_evaluate(idx);
return max(
query(beg, end, idx * 2 + 1, lb, (lb + ub) / 2),
query(beg, end, idx * 2 + 2, (lb + ub) / 2 + 1, ub));
}
} kaede;
void solveCase(int caseNo)
{
// db("a");
kaede.init();
for (int i = 0; i < NAX; ++i)
pos[i].clear();
// db("b");
int n, x;
cin >> n >> x;
for (int i = 1; i <= n; ++i)
{
cin >> a[i];
pos[a[i]].pb(i);
}
// db("c");
ll ans = 0;
for (int i = 1; i <= n; ++i)
{
// db(i, "D");
kaede.update(i, i, 0, 0, s - 1, 1);
int t = lower_bound(pos[a[i]].begin(), pos[a[i]].end(), i) - pos[a[i]].begin();
t++;
// db(i, "E");
if (t <= x)
kaede.update(1, i - 1, 0, 0, s - 1, 1);
else
{
int p = pos[a[i]][t - x - 1];
kaede.update(p + 1, i - 1, 0, 0, s - 1, 1);
int q = 1;
if (t - x - 1 > 0)
q = pos[a[i]][t - x - 2] + 1;
kaede.update(q, p, 0, 0, s - 1, -x);
}
// db(i, "F");
ans = max(ans, kaede.query(1, i, 0, 0, s - 1));
}
cout << "Case #" << caseNo << ": ";
cout << ans << '\n';
// db("e");
}
#include<stdio.h>
int main()
{
int n;
while(1)
{
scanf("%d",&n);
if(n==42) break ;
printf("%d\n",n);
}
}
int main()
{
#ifndef LOCAL
ios_base::sync_with_stdio(0);
cin.tie(0);
#endif
int t = 1;
#ifdef MULTI_TEST
cin >> t;
#endif
for (int i = 1; i <= t; ++i)
{
solveCase(i);
#ifdef TIME
cerr << "Case #" << i << ": Time " << chrono::duration<double>(chrono::steady_clock::now() - TimeStart).count() << " s.\n";
TimeStart = chrono::steady_clock::now();
#endif
}
return 0;
}
| 25.171717 | 131 | 0.475923 | [
"vector"
] |
612c9f0903d42bfd640c39f2a712f5dce41aaafe | 2,910 | cc | C++ | components/viz/service/surfaces/surface_saved_frame_storage.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | components/viz/service/surfaces/surface_saved_frame_storage.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | components/viz/service/surfaces/surface_saved_frame_storage.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/viz/service/surfaces/surface_saved_frame_storage.h"
#include <memory>
#include <utility>
#include "base/bind.h"
#include "base/cancelable_callback.h"
#include "base/threading/thread_task_runner_handle.h"
#include "components/viz/service/surfaces/surface.h"
#include "components/viz/service/surfaces/surface_saved_frame.h"
namespace viz {
namespace {
// Expire saved frames after 5 seconds.
// TODO(vmpstr): Figure out if we need to change this for cross-origin
// animations, since the network delay can cause us to wait longer.
constexpr base::TimeDelta kExpiryTime = base::Seconds(5);
} // namespace
SurfaceSavedFrameStorage::SurfaceSavedFrameStorage(Surface* surface)
: surface_(surface) {}
SurfaceSavedFrameStorage::~SurfaceSavedFrameStorage() = default;
void SurfaceSavedFrameStorage::ProcessSaveDirective(
const CompositorFrameTransitionDirective& directive,
SurfaceSavedFrame::TransitionDirectiveCompleteCallback
directive_finished_callback) {
// Create a new saved frame, destroying the old one if it existed.
// TODO(vmpstr): This may need to change if the directive refers to a local
// subframe (RP) of the compositor frame. However, as of now, the save
// directive can only reference the root render pass.
saved_frame_ = std::make_unique<SurfaceSavedFrame>(
std::move(directive), std::move(directive_finished_callback));
// Let the saved frame append copy output requests to the render pass list.
// This is how we save the pixel output of the frame.
saved_frame_->RequestCopyOfOutput(surface_);
// Schedule an expiry callback.
// Note that since the expiry_closure_ has a shorter lifetime than `this`, we
// bind `this` as unretained.
expiry_closure_.Reset(base::BindOnce(
&SurfaceSavedFrameStorage::ExpireSavedFrame, base::Unretained(this)));
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE, expiry_closure_.callback(), kExpiryTime);
}
std::unique_ptr<SurfaceSavedFrame> SurfaceSavedFrameStorage::TakeSavedFrame() {
expiry_closure_.Cancel();
// We might not have a saved frame here if it expired.
if (saved_frame_)
saved_frame_->ReleaseSurface();
return std::move(saved_frame_);
}
bool SurfaceSavedFrameStorage::HasValidFrame() const {
return saved_frame_ && saved_frame_->IsValid();
}
void SurfaceSavedFrameStorage::ExpireSavedFrame() {
saved_frame_.reset();
}
void SurfaceSavedFrameStorage::ExpireForTesting() {
// Only do any work if we have an expiry closure.
if (!expiry_closure_.IsCancelled())
ExpireSavedFrame();
}
void SurfaceSavedFrameStorage::CompleteForTesting() {
if (saved_frame_) {
saved_frame_->CompleteSavedFrameForTesting(); // IN-TEST
}
}
} // namespace viz
| 34.235294 | 79 | 0.760825 | [
"render"
] |
9ed34f04a999c584645e45e454010559d9da340a | 7,349 | cpp | C++ | dp/multidp.cpp | zhitko/sptk-analyzer | d70de9ae4c3c20efe51864a174310ca59d31c11f | [
"MIT"
] | 7 | 2017-12-02T20:47:53.000Z | 2021-06-17T12:22:17.000Z | dp/multidp.cpp | zhitko/sptk-analyzer | d70de9ae4c3c20efe51864a174310ca59d31c11f | [
"MIT"
] | 1 | 2019-03-27T21:31:30.000Z | 2019-03-27T21:31:30.000Z | dp/multidp.cpp | zhitko/inton-trainer | d70de9ae4c3c20efe51864a174310ca59d31c11f | [
"MIT"
] | null | null | null | #include "multidp.h"
#include <QDebug>
#include "defines.h"
extern "C" {
#include "./SPTK/others/func.h"
}
MultiDP::MultiDP(int sigSize, int pttrnSize, int limit):
ContinuousDP(
new SpectrSignal(zerov(pttrnSize), 1),
new SpectrSignal(zerov(sigSize), 1),
1,
limit
)
{
qDebug() << "MultiDP::MultiDP " << sigSize << ", " << pttrnSize << ", " << limit << LOG_DATA;
this->f0Use = false;
this->df0Use = false;
this->a0Use = false;
this->da0Use = false;
this->nmpUse = false;
this->spectrumUse = false;
this->cepstrumUse = false;
this->maxF0 = 0.0;
this->maxDF0 = 0.0;
this->maxA0 = 0.0;
this->maxDA0 = 0.0;
this->maxNMP = 0.0;
this->maxSpectrum = 0.0;
this->maxCepstrum = 0.0;
}
void MultiDP::addF0(vector sig, vector pttrn, double coefficient)
{
this->f0Sig = new VectorSignal(sig);
this->f0Pttrn = new VectorSignal(pttrn);
this->f0Coefficient = coefficient;
this->f0Use = true;
}
void MultiDP::addDF0(vector sig, vector pttrn, double coefficient)
{
this->df0Sig = new VectorSignal(sig);
this->df0Pttrn = new VectorSignal(pttrn);
this->df0Coefficient = coefficient;
this->df0Use = true;
}
void MultiDP::addA0(vector sig, vector pttrn, double coefficient)
{
this->a0Sig = new VectorSignal(sig);
this->a0Pttrn = new VectorSignal(pttrn);
this->a0Coefficient = coefficient;
this->a0Use = true;
}
void MultiDP::addDA0(vector sig, vector pttrn, double coefficient)
{
this->da0Sig = new VectorSignal(sig);
this->da0Pttrn = new VectorSignal(pttrn);
this->da0Coefficient = coefficient;
this->da0Use = true;
}
void MultiDP::addNmp(vector sig, vector pttrn, double coefficient)
{
this->nmpSig = new VectorSignal(sig);
this->nmpPttrn = new VectorSignal(pttrn);
this->nmpCoefficient = coefficient;
this->nmpUse = true;
}
void MultiDP::addSpectrum(vector sig, vector pttrn, double coefficient, int size)
{
this->spectrumSig = new SpectrSignal(sig, size);
this->spectrumPttrn = new SpectrSignal(pttrn, size);
this->spectrumCoefficient = coefficient;
this->spectrumSize = size;
this->spectrumUse = true;
}
void MultiDP::addCepstrum(vector sig, vector pttrn, double coefficient, int size)
{
this->cepstrumSig = new SpectrSignal(sig, size);
this->cepstrumPttrn = new SpectrSignal(pttrn, size);
this->cepstrumCoefficient = coefficient;
this->cepstrumSize = size;
this->cepstrumUse = true;
}
double calcError(double value1, double value2)
{
double result = 0.0;
double y = 0.0;
double x = 0.0;
if (isfinite(value1))
{
x = value1;
}
if (isfinite(value2))
{
y = value2;
}
result += pow(x - y, 2.0);
if (result > 0)
{
return sqrt(result);
} else {
return result;
}
}
double calcVecError(double* value1, double* value2, int size)
{
double result = 0.0;
for(int i=0; i<size; i++)
{
double y = 0.0;
double x = 0.0;
if (isfinite(value1[i]))
{
x = value1[i];
}
if (isfinite(value2[i]))
{
y = value2[i];
}
result += pow(x - y, 2.0);
}
if (result > 0)
{
return sqrt(result/size);
} else {
return result;
}
}
double MultiDP::calculateError(int value1Pos, int value2Pos)
{
// qDebug() << "MultiDP::calculateError " << value1Pos << " - " << value2Pos << LOG_DATA;
int count = 0;
double error = 0.0;
if (this->f0Use)
{
int value1PosUpd = (1.0 * value1Pos * this->signalSize) / this->f0Sig->size();
int value2PosUpd = (1.0 * value2Pos * this->patternSize) / this->f0Pttrn->size();
double value1 = this->f0Sig->valueAt(value1PosUpd);
double value2 = this->f0Pttrn->valueAt(value2PosUpd);
double e = calcError(value1, value2) * this->f0Coefficient;
if (e > maxF0) maxF0 = e;
error += e;
count++;
}
if (this->df0Use)
{
int value1PosUpd = (1.0 * value1Pos * this->signalSize) / this->df0Sig->size();
int value2PosUpd = (1.0 * value2Pos * this->patternSize) / this->df0Pttrn->size();
double value1 = this->df0Sig->valueAt(value1PosUpd);
double value2 = this->df0Pttrn->valueAt(value2PosUpd);
double e = calcError(value1, value2) * this->df0Coefficient;
if (e > maxDF0) maxDF0 = e;
error += e;
count++;
}
if (this->a0Use)
{
int value1PosUpd = (1.0 * value1Pos * this->signalSize) / this->a0Sig->size();
int value2PosUpd = (1.0 * value2Pos * this->patternSize) / this->a0Pttrn->size();
double value1 = this->a0Sig->valueAt(value1PosUpd);
double value2 = this->a0Pttrn->valueAt(value2PosUpd);
double e = calcError(value1, value2) * this->a0Coefficient;
if (e > maxA0) maxA0 = e;
error += e;
count++;
}
if (this->da0Use)
{
int value1PosUpd = (1.0 * value1Pos * this->signalSize) / this->da0Sig->size();
int value2PosUpd = (1.0 * value2Pos * this->patternSize) / this->da0Pttrn->size();
double value1 = this->da0Sig->valueAt(value1PosUpd);
double value2 = this->da0Pttrn->valueAt(value2PosUpd);
double e = calcError(value1, value2) * this->da0Coefficient;
if (e > maxDA0) maxDA0 = e;
error += e;
count++;
}
if (this->nmpUse)
{
int value1PosUpd = (1.0 * value1Pos * this->signalSize) / this->nmpSig->size();
int value2PosUpd = (1.0 * value2Pos * this->patternSize) / this->nmpPttrn->size();
double value1 = this->nmpSig->valueAt(value1PosUpd);
double value2 = this->nmpPttrn->valueAt(value2PosUpd);
double e = calcError(value1, value2) * this->nmpCoefficient;
if (e > maxNMP) maxNMP = e;
error += e;
count++;
}
if (this->spectrumUse)
{
int value1PosUpd = (1.0 * value1Pos * this->signalSize) / this->spectrumSig->size();
int value2PosUpd = (1.0 * value2Pos * this->patternSize) / this->spectrumPttrn->size();
double* value1 = this->spectrumSig->valueAt(value1PosUpd);
double* value2 = this->spectrumPttrn->valueAt(value2PosUpd);
double e = calcVecError(value1, value2, this->spectrumSize) * this->spectrumCoefficient;
if (e > maxSpectrum) maxSpectrum = e;
error += e;
count++;
}
if (this->cepstrumUse)
{
int value1PosUpd = (1.0 * value1Pos * this->signalSize) / this->cepstrumSig->size();
int value2PosUpd = (1.0 * value2Pos * this->patternSize) / this->cepstrumPttrn->size();
double* value1 = this->cepstrumSig->valueAt(value1PosUpd);
double* value2 = this->cepstrumPttrn->valueAt(value2PosUpd);
double e = calcVecError(value1, value2, this->cepstrumSize) * this->cepstrumCoefficient;
if (e > maxCepstrum) maxCepstrum = e;
error += e;
count++;
}
//qDebug() << "MultiDP::calculateError " << (error / count) << LOG_DATA;
return error / count;
}
| 31.813853 | 98 | 0.58212 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.