text
string | size
int64 | token_count
int64 |
|---|---|---|
/*
* PROJECT: Universal C++ RunTime (UCXXRT)
* FILE: ehveccvb.cpp
* DATA: 2021/05/27
*
* PURPOSE: Universal C++ RunTime
*
* LICENSE: Relicensed under The MIT License from The CC BY 4.0 License
*
* DEVELOPER: MiroKaku (miro.kaku AT Outlook.com)
*/
/***
*ehveccvb.cpp - EH c-tor iterator helper function for class w/ virtual bases
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
*Purpose:
* EH-aware version of constructor iterator helper function for class
* with virtual bases
*
* These functions are called when constructing and destructing arrays of
* objects. Their purpose is to assure that constructed elements get
* destructed if the constructor for one of the elements throws.
*
* These functions are called when constructing and destructing arrays of
* objects. Their purpose is to assure that constructed elements get
* destructed if the constructor for one of the elements throws.
*
* Must be compiled using "-d1Binl" to be able to specify __thiscall
* at the user level
****/
#include <eh.h>
#if defined _M_CEE
#define CALLTYPE __clrcall
#define CALLEETYPE __clrcall
#define __RELIABILITY_CONTRACT \
[System::Runtime::ConstrainedExecution::ReliabilityContract( \
System::Runtime::ConstrainedExecution::Consistency::WillNotCorruptState, \
System::Runtime::ConstrainedExecution::Cer::Success \
)]
#else
#define CALLEETYPE __stdcall
#define __RELIABILITY_CONTRACT
#if defined _M_IX86
#define CALLTYPE __thiscall
#else
#define CALLTYPE __stdcall
#endif
#endif
using constructor_type = void (CALLTYPE*)(void*);
using destructor_type = void (CALLTYPE*)(void*);
__RELIABILITY_CONTRACT
void CALLEETYPE __ArrayUnwind(
void* ptr, // Pointer to array to destruct
size_t size, // Size of each element (including padding)
size_t count, // Number of elements in the array
destructor_type destructor // The destructor to call
);
__RELIABILITY_CONTRACT
void CALLEETYPE __ehvec_ctor_vb(
void* ptr, // Pointer to array to destruct
size_t size, // Size of each element (including padding)
size_t count, // Number of elements in the array
constructor_type constructor, // Constructor to call
destructor_type destructor // Destructor to call should exception be thrown
)
{
size_t i{0};
bool success{false};
__try
{
for (; i != count; ++i)
{
#pragma warning(push)
#pragma warning(disable: 4191) // unsafe conversion
reinterpret_cast<void (CALLTYPE*)(void*, int)>(constructor)(ptr, 1);
#pragma warning(pop)
ptr = static_cast<char*>(ptr) + size;
}
success = true;
}
__finally
{
if (!success)
{
__ArrayUnwind(ptr, size, i, destructor);
}
}
}
__RELIABILITY_CONTRACT
void CALLEETYPE __ehvec_ctor_vb(
void* ptr, // Pointer to array to destruct
size_t size, // Size of each element (including padding)
int count, // Number of elements in the array
constructor_type constructor, // Constructor to call
destructor_type destructor // Destructor to call should exception be thrown
)
{
__ehvec_ctor_vb(ptr, size, static_cast<size_t>(count), constructor, destructor);
}
| 3,672
| 1,073
|
#include "netlibcc/net/IOThreadPool.h"
#include <unistd.h>
#include <cstdio>
#include "netlibcc/net/EventLoop.h"
#include "netlibcc/core/Thread.h"
using namespace netlibcc;
using namespace netlibcc::net;
void showId(EventLoop* loop = nullptr) {
printf("showId: pid = %d, tid = %d, loop = %p\n", getpid(), thisthread::tid(), loop);
}
void threadFunc(EventLoop* loop) {
printf("threadFunc: pid = %d, tid = %d, loop = %p\n", getpid(), thisthread::tid(), loop);
}
int main() {
showId();
EventLoop loop;
loop.runAfter(11, std::bind(&EventLoop::quit, &loop));
// only main thread
{
printf("Single thread %p:\n", &loop);
IOThreadPool pool(&loop, "single");
pool.setThreadNum(0);
pool.start(threadFunc);
assert(pool.getNextLoop() == &loop);
assert(pool.getNextLoop() == &loop);
assert(pool.getNextLoop() == &loop);
}
// main thread + another IOThread
{
printf("Another Thread:\n");
IOThreadPool pool(&loop, "another");
pool.setThreadNum(1);
pool.start(threadFunc);
EventLoop* next_loop = pool.getNextLoop();
next_loop->runAfter(2, std::bind(showId, next_loop));
assert(next_loop != &loop);
assert(next_loop == pool.getNextLoop());
assert(next_loop == pool.getNextLoop());
::sleep(3);
}
// main thread + 3 other threads
{
printf("Three other threads:\n");
IOThreadPool pool(&loop, "three");
pool.setThreadNum(3);
pool.start(threadFunc);
EventLoop* next_loop = pool.getNextLoop();
next_loop->runInLoop(std::bind(showId, next_loop));
assert(next_loop != &loop);
assert(next_loop != pool.getNextLoop());
assert(next_loop != pool.getNextLoop());
assert(next_loop == pool.getNextLoop());
}
loop.loop();
}
| 1,877
| 612
|
//
// Created by erick on 22/03/17.
//
#include "SpriteRenderer.h"
SpriteRenderer::SpriteRenderer(Shader &shader)
{
this->shader = shader;
this->initRenderData();
}
SpriteRenderer::~SpriteRenderer()
{
glDeleteVertexArrays(1, &this->quadVAO);
}
void SpriteRenderer::DrawSprite(Texture2D &texture, glm::vec2 position, glm::vec2 size, GLfloat rotate, glm::vec3 color)
{
// Prepare transformations
this->shader.Use();
glm::mat4 model;
model = glm::translate(model, glm::vec3(position, 0.0f)); // First translate (transformations are: scale happens first, then rotation and then finall translation happens; reversed order)
model = glm::translate(model, glm::vec3(0.5f * size.x, 0.5f * size.y, 0.0f)); // Move origin of rotation to center of quad
model = glm::rotate(model, rotate, glm::vec3(0.0f, 0.0f, 1.0f)); // Then rotate
model = glm::translate(model, glm::vec3(-0.5f * size.x, -0.5f * size.y, 0.0f)); // Move origin back
model = glm::scale(model, glm::vec3(size, 1.0f)); // Last scale
this->shader.SetMatrix4("model", model);
// Render textured quad
this->shader.SetVector3f("spriteColor", color);
glActiveTexture(GL_TEXTURE0);
texture.Bind();
glBindVertexArray(this->quadVAO);
glDrawArrays(GL_TRIANGLES, 0, 6);
glBindVertexArray(0);
}
void SpriteRenderer::initRenderData()
{
// Configure VAO/VBO
GLuint VBO;
GLfloat vertices[] = {
// Pos // Tex
0.0f, 1.0f, 0.0f, 1.0f,
1.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 0.0f, 1.0f, 0.0f
};
glGenVertexArrays(1, &this->quadVAO);
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindVertexArray(this->quadVAO);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
| 1,953
| 898
|
#include "fir.h"
//------------------------------------------------------------------------
// FIR
//------------------------------------------------------------------------
//SEPARATOR_FOR_MAIN
#include <stdlib.h>
#include "fir.h"
#define AMOUNT_OF_TEST 1
int fir (in_int_t d_i[1000], in_int_t idx[1000] ) {
int i;
int tmp=0;
For_Loop: for (i=0;i<1000;i++) {
tmp += idx [i] * d_i[999-i];
}
//out [0] = tmp;
return tmp;
}
int main(void){
in_int_t d_i[AMOUNT_OF_TEST][1000];
in_int_t idx[AMOUNT_OF_TEST][1000];
inout_int_t out[AMOUNT_OF_TEST][1000];
srand(13);
for(int i = 0; i < AMOUNT_OF_TEST; ++i){
for(int j = 0; j < 1000; ++j){
d_i[0][j] = rand() % 100;
idx[0][j] = rand() % 100;
}
}
for(int i = 0; i < 1; ++i){
fir(d_i[0], idx[0] );
}
}
//SEPARATOR_FOR_MAIN
| 826
| 415
|
/*
* Copyright (c) 2014 The WebM 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 <math.h>
#include <stdlib.h>
#include <string.h>
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "test/acm_random.h"
#include "test/clear_system_state.h"
#include "test/register_state_check.h"
#include "test/util.h"
#include "vpx_scale/yv12config.h"
#include "vpx/vpx_integer.h"
#include "vp9/common/vp9_reconinter.h"
#include "vp9/encoder/vp9_context_tree.h"
#include "vp9/encoder/vp9_denoiser.h"
using libvpx_test::ACMRandom;
namespace {
const int kNumPixels = 64 * 64;
class VP9DenoiserTest : public ::testing::TestWithParam<BLOCK_SIZE> {
public:
virtual ~VP9DenoiserTest() {}
virtual void SetUp() {
bs_ = GetParam();
}
virtual void TearDown() { libvpx_test::ClearSystemState(); }
protected:
BLOCK_SIZE bs_;
};
TEST_P(VP9DenoiserTest, BitexactCheck) {
ACMRandom rnd(ACMRandom::DeterministicSeed());
const int count_test_block = 4000;
// Allocate the space for input and output,
// where sig_block is the block to be denoised,
// mc_avg_block is the denoised reference block,
// avg_block_c is the denoised result from C code,
// avg_block_sse2 is the denoised result from SSE2 code.
DECLARE_ALIGNED(16, uint8_t, sig_block[kNumPixels]);
DECLARE_ALIGNED(16, uint8_t, mc_avg_block[kNumPixels]);
DECLARE_ALIGNED(16, uint8_t, avg_block_c[kNumPixels]);
DECLARE_ALIGNED(16, uint8_t, avg_block_sse2[kNumPixels]);
for (int i = 0; i < count_test_block; ++i) {
// Generate random motion magnitude, 20% of which exceed the threshold.
const int motion_magnitude_random =
rnd.Rand8() % static_cast<int>(MOTION_MAGNITUDE_THRESHOLD * 1.2);
// Initialize a test block with random number in range [0, 255].
for (int j = 0; j < kNumPixels; ++j) {
int temp = 0;
sig_block[j] = rnd.Rand8();
// The pixels in mc_avg_block are generated by adding a random
// number in range [-19, 19] to corresponding pixels in sig_block.
temp = sig_block[j] + ((rnd.Rand8() % 2 == 0) ? -1 : 1) *
(rnd.Rand8() % 20);
// Clip.
mc_avg_block[j] = (temp < 0) ? 0 : ((temp > 255) ? 255 : temp);
}
ASM_REGISTER_STATE_CHECK(vp9_denoiser_filter_c(
sig_block, 64, mc_avg_block, 64, avg_block_c,
64, 0, bs_, motion_magnitude_random));
ASM_REGISTER_STATE_CHECK(vp9_denoiser_filter_sse2(
sig_block, 64, mc_avg_block, 64, avg_block_sse2,
64, 0, bs_, motion_magnitude_random));
// Test bitexactness.
for (int h = 0; h < (4 << b_height_log2_lookup[bs_]); ++h) {
for (int w = 0; w < (4 << b_width_log2_lookup[bs_]); ++w) {
EXPECT_EQ(avg_block_c[h * 64 + w], avg_block_sse2[h * 64 + w]);
}
}
}
}
// Test for all block size.
INSTANTIATE_TEST_CASE_P(
SSE2, VP9DenoiserTest,
::testing::Values(BLOCK_8X8, BLOCK_8X16, BLOCK_16X8, BLOCK_16X16,
BLOCK_16X32, BLOCK_32X16, BLOCK_32X32, BLOCK_32X64,
BLOCK_64X32, BLOCK_64X64));
} // namespace
| 3,388
| 1,418
|
#define INSTANCIATE_UTILS
#include "utils.h"
// System Header
#include <stdio.h>
#include <windows.h>
#include <string>
void initUtils()
{
std::string tmp;
TCHAR szModuleName[MAX_PATH];
GetCurrentDirectory(MAX_PATH, szCurPath); // rootdir/test/
GetModuleFileName(NULL, szModuleName, MAX_PATH); // rootdir/test/bin/text.exe
tmp = io::Dirname(szModuleName); // rootdir/test/bin
strcpy_s(szExePath, MAX_PATH, tmp.c_str()); // rootdir/test/bin
tmp = io::PathCombine(tmp, "tmp"); // rootdir/test/bin/tmp
strcpy_s(szTmpPath, MAX_PATH, tmp.c_str()); // rootdir/test/bin
io::DirectoryDelete(tmp);
CreateDirectory(szTmpPath, NULL);
tmp = io::Dirname(tmp); // rootdir/test/
tmp = io::Dirname(tmp); // rootdir/
tmp = io::PathCombine(tmp, "isx"); // rootdir/isx
tmp = io::PathCombine(tmp, "bin"); // rootdir/isx/bin
strcpy_s(szLibPath, MAX_PATH, tmp.c_str());
}
void DbgOutput(const char* szFormat, ...) {
char szBuff[MAX_PATH];
va_list arg;
va_start(arg, szFormat);
_vsnprintf_s(szBuff, sizeof(szBuff), szFormat, arg);
va_end(arg);
strcat_s(szBuff, MAX_PATH, "\n");
OutputDebugString("isx-test > ");
OutputDebugString(szBuff);
printf_s(szBuff, MAX_PATH);
}
void DbgPopLastError() {
char buff[MAX_PATH];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
buff, (sizeof(buff) / sizeof(wchar_t)), NULL);
MessageBox(NULL, buff, "error", MB_OK);
}
bool DirectoryExists(const std::string& path) {
DWORD ftyp = GetFileAttributes(path.c_str());
if (ftyp == INVALID_FILE_ATTRIBUTES)
return false; //something is wrong with your path!
if (ftyp & FILE_ATTRIBUTE_DIRECTORY)
return true; // this is a directory!
return false; // this is not a directory!
}
bool DirectoryDelete(const std::string& path) {
if (path.empty()) return TRUE;
if (!DirectoryExists(path)) return TRUE;
HANDLE hFind;
WIN32_FIND_DATA FindFileData;
std::string search = path + "\\*";
hFind = FindFirstFile(search.c_str(), &FindFileData);
if (hFind == INVALID_HANDLE_VALUE) return FALSE;
while (TRUE)
{
/* end */
if (!FindNextFile(hFind, &FindFileData)) {
if (GetLastError() == ERROR_NO_MORE_FILES) break;
FindClose(hFind);
return FALSE;
}
/* skip '.' and '..' */
std::string item(FindFileData.cFileName);
if (item == "." || item == "..") continue;
std::string filename = path + "\\" + item;
if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
/* item is a directory (recursive call) */
if (!DirectoryDelete(filename)) {
FindClose(hFind);
return FALSE;
}
}
else
{
/* item is a file, delete it */
if (!DeleteFile(filename.c_str())) {
FindClose(hFind);
return FALSE;
}
}
}
FindClose(hFind);
/* actual folder deletion */
if (!RemoveDirectory(path.c_str())) return FALSE;
return TRUE;
}
| 3,244
| 1,111
|
/**
* 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
*
* https://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 "Schema.hh"
namespace avro {
Schema::Schema()
{ }
Schema::~Schema()
{ }
Schema::Schema(const NodePtr &node) :
node_(node)
{ }
Schema::Schema(Node *node) :
node_(node)
{ }
RecordSchema::RecordSchema(const std::string &name) :
Schema(new NodeRecord)
{
node_->setName(name);
}
void
RecordSchema::addField(const std::string &name, const Schema &fieldSchema)
{
// add the name first. it will throw if the name is a duplicate, preventing
// the leaf from being added
node_->addName(name);
node_->addLeaf(fieldSchema.root());
}
std::string RecordSchema::getDoc() const
{
return node_->getDoc();
}
void RecordSchema::setDoc(const std::string& doc)
{
node_->setDoc(doc);
}
EnumSchema::EnumSchema(const std::string &name) :
Schema(new NodeEnum)
{
node_->setName(name);
}
void
EnumSchema::addSymbol(const std::string &symbol)
{
node_->addName(symbol);
}
ArraySchema::ArraySchema(const Schema &itemsSchema) :
Schema(new NodeArray)
{
node_->addLeaf(itemsSchema.root());
}
ArraySchema::ArraySchema(const ArraySchema &itemsSchema) :
Schema(new NodeArray)
{
node_->addLeaf(itemsSchema.root());
}
MapSchema::MapSchema(const Schema &valuesSchema) :
Schema(new NodeMap)
{
node_->addLeaf(valuesSchema.root());
}
MapSchema::MapSchema(const MapSchema &valuesSchema) :
Schema(new NodeMap)
{
node_->addLeaf(valuesSchema.root());
}
UnionSchema::UnionSchema() :
Schema(new NodeUnion)
{ }
void
UnionSchema::addType(const Schema &typeSchema)
{
if(typeSchema.type() == AVRO_UNION) {
throw Exception("Cannot add unions to unions");
}
if(typeSchema.type() == AVRO_RECORD) {
// check for duplicate records
size_t types = node_->leaves();
for(size_t i = 0; i < types; ++i) {
const NodePtr &leaf = node_->leafAt(i);
// TODO, more checks?
if(leaf->type() == AVRO_RECORD && leaf->name() == typeSchema.root()->name()) {
throw Exception("Records in unions cannot have duplicate names");
}
}
}
node_->addLeaf(typeSchema.root());
}
FixedSchema::FixedSchema(int size, const std::string &name) :
Schema(new NodeFixed)
{
node_->setFixedSize(size);
node_->setName(name);
}
SymbolicSchema::SymbolicSchema(const Name &name, const NodePtr& link) :
Schema(new NodeSymbolic(HasName(name), link))
{
}
} // namespace avro
| 3,246
| 1,042
|
// Copyright (C) 2018-2019 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <builders/ie_lstm_sequence_layer.hpp>
#include <ie_cnn_layer_builder.h>
#include <vector>
#include <string>
using namespace InferenceEngine;
Builder::LSTMSequenceLayer::LSTMSequenceLayer(const std::string& name): LayerDecorator("LSTMSequence", name) {
getLayer()->getOutputPorts().resize(3);
getLayer()->getInputPorts().resize(7);
getLayer()->getInputPorts()[1].setParameter("type", "weights");
getLayer()->getInputPorts()[2].setParameter("type", "biases");
getLayer()->getInputPorts()[3].setParameter("type", "optional");
getLayer()->getInputPorts()[6].setParameter("type", "weights");
}
Builder::LSTMSequenceLayer::LSTMSequenceLayer(const Layer::Ptr& layer): LayerDecorator(layer) {
checkType("LSTMSequence");
}
Builder::LSTMSequenceLayer::LSTMSequenceLayer(const Layer::CPtr& layer): LayerDecorator(layer) {
checkType("LSTMSequence");
}
Builder::LSTMSequenceLayer& Builder::LSTMSequenceLayer::setName(const std::string& name) {
getLayer()->setName(name);
return *this;
}
const std::vector<Port>& Builder::LSTMSequenceLayer::getInputPorts() const {
return getLayer()->getInputPorts();
}
Builder::LSTMSequenceLayer& Builder::LSTMSequenceLayer::setInputPorts(const std::vector<Port>& ports) {
getLayer()->getInputPorts() = ports;
return *this;
}
const std::vector<Port>& Builder::LSTMSequenceLayer::getOutputPorts() const {
return getLayer()->getOutputPorts();
}
Builder::LSTMSequenceLayer& Builder::LSTMSequenceLayer::setOutputPorts(const std::vector<Port>& ports) {
getLayer()->getOutputPorts() = ports;
return *this;
}
int Builder::LSTMSequenceLayer::getHiddenSize() const {
return getLayer()->getParameters().at("hidden_size");
}
Builder::LSTMSequenceLayer& Builder::LSTMSequenceLayer::setHiddenSize(int size) {
getLayer()->getParameters()["hidden_size"] = size;
return *this;
}
bool Builder::LSTMSequenceLayer::getSequenceDim() const {
return getLayer()->getParameters().at("sequence_dim");
}
Builder::LSTMSequenceLayer& Builder::LSTMSequenceLayer::setSqquenceDim(bool flag) {
getLayer()->getParameters()["sequence_dim"] = flag;
return *this;
}
const std::vector<std::string>& Builder::LSTMSequenceLayer::getActivations() const {
return getLayer()->getParameters().at("activations");
}
Builder::LSTMSequenceLayer& Builder::LSTMSequenceLayer::setActivations(const std::vector<std::string>& activations) {
getLayer()->getParameters()["activations"] = activations;
return *this;
}
const std::vector<float>& Builder::LSTMSequenceLayer::getActivationsAlpha() const {
return getLayer()->getParameters().at("activations_alpha");
}
Builder::LSTMSequenceLayer& Builder::LSTMSequenceLayer::setActivationsAlpha(const std::vector<float>& activations) {
getLayer()->getParameters()["activations_alpha"] = activations;
return *this;
}
const std::vector<float>& Builder::LSTMSequenceLayer::getActivationsBeta() const {
return getLayer()->getParameters().at("activations_beta");
}
Builder::LSTMSequenceLayer& Builder::LSTMSequenceLayer::setActivationsBeta(const std::vector<float>& activations) {
getLayer()->getParameters()["activations_beta"] = activations;
return *this;
}
float Builder::LSTMSequenceLayer::getClip() const {
return getLayer()->getParameters().at("clip");
}
Builder::LSTMSequenceLayer& Builder::LSTMSequenceLayer::setClip(float clip) {
getLayer()->getParameters()["clip"] = clip;
return *this;
}
bool Builder::LSTMSequenceLayer::getInputForget() const {
return getLayer()->getParameters().at("input_forget");
}
Builder::LSTMSequenceLayer& Builder::LSTMSequenceLayer::setInputForget(bool flag) {
getLayer()->getParameters()["input_forget"] = flag;
return *this;
}
const std::string& Builder::LSTMSequenceLayer::getDirection() const {
return getLayer()->getParameters().at("direction");
}
Builder::LSTMSequenceLayer& Builder::LSTMSequenceLayer::setDirection(const std::string& direction) {
getLayer()->getParameters()["direction"] = direction;
return *this;
}
REG_CONVERTER_FOR(LSTMSequence, [](const CNNLayerPtr& cnnLayer, Builder::Layer& layer) {
layer.getParameters()["hidden_size"] = cnnLayer->GetParamAsInt("hidden_size");
layer.getParameters()["sequence_dim"] = cnnLayer->GetParamsAsBool("sequence_dim", true);
std::vector<std::string> activations;
std::istringstream stream(cnnLayer->GetParamAsString("activations"));
std::string str;
while (getline(stream, str, ',')) {
activations.push_back(str);
}
layer.getParameters()["activations"] = activations;
layer.getParameters()["activations_alpha"] = cnnLayer->GetParamAsFloats("activations_alpha");
layer.getParameters()["activations_beta"] = cnnLayer->GetParamAsFloats("activations_beta");
layer.getParameters()["clip"] = cnnLayer->GetParamAsFloat("clip");
layer.getParameters()["input_forget"] = cnnLayer->GetParamsAsBool("input_forget", true);
layer.getParameters()["direction"] = cnnLayer->GetParamAsString("direction", "");
});
| 5,126
| 1,659
|
/*
* Copyright (c) 2018-2021 Arm Limited.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "private_data.hpp"
#include "wsi/wsi_factory.hpp"
#include <unordered_map>
namespace layer {
static std::mutex g_data_lock;
static std::unordered_map<void *, std::unique_ptr<instance_private_data>> g_instance_data;
static std::unordered_map<void *, std::unique_ptr<device_private_data>> g_device_data;
template <typename object_type, typename get_proc_type>
static PFN_vkVoidFunction get_proc_helper(object_type obj, get_proc_type get_proc,
const char *proc_name, bool required, bool &ok) {
PFN_vkVoidFunction ret = get_proc(obj, proc_name);
if (nullptr == ret && required) {
ok = false;
}
return ret;
}
VkResult instance_dispatch_table::populate(VkInstance instance,
PFN_vkGetInstanceProcAddr get_proc) {
bool ok = true;
#define REQUIRED(x) \
x = reinterpret_cast<PFN_vk##x>(get_proc_helper(instance, get_proc, "vk" #x, true, ok));
#define OPTIONAL(x) \
x = reinterpret_cast<PFN_vk##x>(get_proc_helper(instance, get_proc, "vk" #x, false, ok));
INSTANCE_ENTRYPOINTS_LIST(REQUIRED, OPTIONAL);
#undef REQUIRED
#undef OPTIONAL
return ok ? VK_SUCCESS : VK_ERROR_INITIALIZATION_FAILED;
}
VkResult device_dispatch_table::populate(VkDevice device, PFN_vkGetDeviceProcAddr get_proc) {
bool ok = true;
#define REQUIRED(x) \
x = reinterpret_cast<PFN_vk##x>(get_proc_helper(device, get_proc, "vk" #x, true, ok));
#define OPTIONAL(x) \
x = reinterpret_cast<PFN_vk##x>(get_proc_helper(device, get_proc, "vk" #x, false, ok));
DEVICE_ENTRYPOINTS_LIST(REQUIRED, OPTIONAL);
#undef REQUIRED
#undef OPTIONAL
return ok ? VK_SUCCESS : VK_ERROR_INITIALIZATION_FAILED;
}
instance_private_data::instance_private_data(const instance_dispatch_table &table,
PFN_vkSetInstanceLoaderData set_loader_data,
util::wsi_platform_set enabled_layer_platforms)
: disp(table), SetInstanceLoaderData(set_loader_data),
enabled_layer_platforms(enabled_layer_platforms) {}
template <typename dispatchable_type>
static inline void *get_key(dispatchable_type dispatchable_object) {
return *reinterpret_cast<void **>(dispatchable_object);
}
void instance_private_data::set(VkInstance inst, std::unique_ptr<instance_private_data> inst_data) {
scoped_mutex lock(g_data_lock);
g_instance_data[get_key(inst)] = std::move(inst_data);
}
template <typename dispatchable_type>
static instance_private_data &get_instance_private_data(dispatchable_type dispatchable_object) {
scoped_mutex lock(g_data_lock);
return *g_instance_data[get_key(dispatchable_object)];
}
instance_private_data &instance_private_data::get(VkInstance instance) {
return get_instance_private_data(instance);
}
instance_private_data &instance_private_data::get(VkPhysicalDevice phys_dev) {
return get_instance_private_data(phys_dev);
}
static VkIcdWsiPlatform get_platform_of_surface(VkSurfaceKHR surface) {
VkIcdSurfaceBase *surface_base = reinterpret_cast<VkIcdSurfaceBase *>(surface);
return surface_base->platform;
}
bool instance_private_data::does_layer_support_surface(VkSurfaceKHR surface) {
return enabled_layer_platforms.contains(get_platform_of_surface(surface));
}
bool instance_private_data::do_icds_support_surface(VkPhysicalDevice, VkSurfaceKHR) {
/* For now assume ICDs do not support VK_KHR_surface. This means that the layer will handle all
* the surfaces it can handle (even if the ICDs can handle the surface) and only call down for
* surfaces it cannot handle. In the future we may allow system integrators to configure which
* ICDs have precedence handling which platforms.
*/
return false;
}
bool instance_private_data::should_layer_handle_surface(VkSurfaceKHR surface) {
return surfaces.find(surface) != surfaces.end();
}
void instance_private_data::destroy(VkInstance inst) {
scoped_mutex lock(g_data_lock);
g_instance_data.erase(get_key(inst));
}
void instance_private_data::add_surface(VkSurfaceKHR surface) {
scoped_mutex lock(g_data_lock);
surfaces.insert(surface);
}
device_private_data::device_private_data(instance_private_data &inst_data,
VkPhysicalDevice phys_dev, VkDevice dev,
const device_dispatch_table &table,
PFN_vkSetDeviceLoaderData set_loader_data)
: disp{table}, instance_data{inst_data}, SetDeviceLoaderData{set_loader_data},
physical_device{phys_dev}, device{dev} {}
void device_private_data::set(VkDevice dev, std::unique_ptr<device_private_data> dev_data) {
scoped_mutex lock(g_data_lock);
g_device_data[get_key(dev)] = std::move(dev_data);
}
template <typename dispatchable_type>
static device_private_data &get_device_private_data(dispatchable_type dispatchable_object) {
scoped_mutex lock(g_data_lock);
return *g_device_data[get_key(dispatchable_object)];
}
device_private_data &device_private_data::get(VkDevice device) {
return get_device_private_data(device);
}
device_private_data &device_private_data::get(VkQueue queue) {
return get_device_private_data(queue);
}
void device_private_data::add_layer_swapchain(VkSwapchainKHR swapchain) {
scoped_mutex lock(swapchains_lock);
swapchains.insert(swapchain);
}
bool device_private_data::layer_owns_all_swapchains(const VkSwapchainKHR *swapchain,
uint32_t swapchain_count) const {
scoped_mutex lock(swapchains_lock);
for (uint32_t i = 0; i < swapchain_count; i++) {
if (swapchains.find(swapchain[i]) == swapchains.end()) {
return false;
}
}
return true;
}
bool device_private_data::should_layer_create_swapchain(VkSurfaceKHR vk_surface) {
return instance_data.should_layer_handle_surface(vk_surface);
}
bool device_private_data::can_icds_create_swapchain(VkSurfaceKHR vk_surface) {
return disp.CreateSwapchainKHR != nullptr;
}
void device_private_data::destroy(VkDevice dev) {
scoped_mutex lock(g_data_lock);
g_device_data.erase(get_key(dev));
}
} /* namespace layer */
| 7,714
| 2,512
|
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2015 Natale Patriciello <natale.patriciello@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 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 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 "tcp-general-test.h"
#include "tcp-error-model.h"
#include "ns3/node.h"
#include "ns3/log.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("TcpZeroWindowTestSuite");
/**
* \ingroup internet-test
* \ingroup tests
*
* \brief Testing the congestion avoidance increment on TCP ZeroWindow
*/
class TcpZeroWindowTest : public TcpGeneralTest
{
public:
/**
* \brief Constructor.
* \param desc Test description.
*/
TcpZeroWindowTest (const std::string &desc);
protected:
//virtual void ReceivePacket (Ptr<Socket> socket);
virtual Ptr<TcpSocketMsgBase> CreateReceiverSocket (Ptr<Node> node);
virtual void Tx (const Ptr<const Packet> p, const TcpHeader&h, SocketWho who);
virtual void Rx (const Ptr<const Packet> p, const TcpHeader&h, SocketWho who);
virtual void ProcessedAck (const Ptr<const TcpSocketState> tcb,
const TcpHeader& h, SocketWho who);
void NormalClose (SocketWho who);
void FinalChecks ();
virtual void ConfigureEnvironment ();
virtual void ConfigureProperties ();
/**
* \brief Increase the receiver buffer size.
*/
void IncreaseBufSize ();
protected:
EventId m_receivePktEvent; //!< Receive packet event.
bool m_zeroWindowProbe; //!< ZeroWindow probe.
bool m_windowUpdated; //!< Window updated.
bool m_senderFinished; //!< Send finished.
bool m_receiverFinished; //!< Receiver finished.
};
TcpZeroWindowTest::TcpZeroWindowTest (const std::string &desc)
: TcpGeneralTest (desc),
m_zeroWindowProbe (false),
m_windowUpdated (false),
m_senderFinished (false),
m_receiverFinished (false)
{
}
void
TcpZeroWindowTest::ConfigureEnvironment ()
{
TcpGeneralTest::ConfigureEnvironment ();
SetAppPktCount (20);
SetMTU (500);
SetTransmitStart (Seconds (2.0));
SetPropagationDelay (MilliSeconds (50));
}
void
TcpZeroWindowTest::ConfigureProperties ()
{
TcpGeneralTest::ConfigureProperties ();
SetInitialCwnd (SENDER, 10);
}
void
TcpZeroWindowTest::IncreaseBufSize ()
{
SetRcvBufSize (RECEIVER, 2500);
}
Ptr<TcpSocketMsgBase>
TcpZeroWindowTest::CreateReceiverSocket (Ptr<Node> node)
{
Ptr<TcpSocketMsgBase> socket = TcpGeneralTest::CreateReceiverSocket (node);
socket->SetAttribute ("RcvBufSize", UintegerValue (0));
Simulator::Schedule (Seconds (10.0),
&TcpZeroWindowTest::IncreaseBufSize, this);
return socket;
}
void
TcpZeroWindowTest::Tx (const Ptr<const Packet> p, const TcpHeader &h, SocketWho who)
{
if (who == SENDER)
{
NS_LOG_INFO ("\tSENDER TX " << h << " size " << p->GetSize ());
if (Simulator::Now ().GetSeconds () <= 6.0)
{
NS_TEST_ASSERT_MSG_EQ (p->GetSize (), 0,
"Data packet sent anyway");
}
else if (Simulator::Now ().GetSeconds () > 6.0
&& Simulator::Now ().GetSeconds () <= 7.0)
{
NS_TEST_ASSERT_MSG_EQ (m_zeroWindowProbe, false, "Sent another probe");
if (!m_zeroWindowProbe)
{
NS_TEST_ASSERT_MSG_EQ (p->GetSize (), 1,
"Data packet sent instead of window probe");
NS_TEST_ASSERT_MSG_EQ (h.GetSequenceNumber (), SequenceNumber32 (1),
"Data packet sent instead of window probe");
m_zeroWindowProbe = true;
}
}
else if (Simulator::Now ().GetSeconds () > 7.0
&& Simulator::Now ().GetSeconds () < 10.0)
{
NS_FATAL_ERROR ("No packets should be sent before the window update");
}
}
else if (who == RECEIVER)
{
NS_LOG_INFO ("\tRECEIVER TX " << h << " size " << p->GetSize ());
if (h.GetFlags () & TcpHeader::SYN)
{
NS_TEST_ASSERT_MSG_EQ (h.GetWindowSize (), 0,
"RECEIVER window size is not 0 in the SYN-ACK");
}
if (Simulator::Now ().GetSeconds () > 6.0
&& Simulator::Now ().GetSeconds () <= 7.0)
{
NS_TEST_ASSERT_MSG_EQ (h.GetSequenceNumber (), SequenceNumber32 (1),
"Data packet sent instead of window probe");
NS_TEST_ASSERT_MSG_EQ (h.GetWindowSize (), 0,
"No zero window advertised by RECEIVER");
}
else if (Simulator::Now ().GetSeconds () > 7.0
&& Simulator::Now ().GetSeconds () < 10.0)
{
NS_FATAL_ERROR ("No packets should be sent before the window update");
}
else if (Simulator::Now ().GetSeconds () >= 10.0)
{
NS_TEST_ASSERT_MSG_EQ (h.GetWindowSize (), 2500,
"Receiver window not updated");
}
}
NS_TEST_ASSERT_MSG_EQ (GetCongStateFrom (GetTcb (SENDER)), TcpSocketState::CA_OPEN,
"Sender State is not OPEN");
NS_TEST_ASSERT_MSG_EQ (GetCongStateFrom (GetTcb (RECEIVER)), TcpSocketState::CA_OPEN,
"Receiver State is not OPEN");
}
void
TcpZeroWindowTest::Rx (const Ptr<const Packet> p, const TcpHeader &h, SocketWho who)
{
if (who == SENDER)
{
NS_LOG_INFO ("\tSENDER RX " << h << " size " << p->GetSize ());
if (h.GetFlags () & TcpHeader::SYN)
{
NS_TEST_ASSERT_MSG_EQ (h.GetWindowSize (), 0,
"RECEIVER window size is not 0 in the SYN-ACK");
}
if (Simulator::Now ().GetSeconds () >= 10.0)
{
NS_TEST_ASSERT_MSG_EQ (h.GetWindowSize (), 2500,
"Receiver window not updated");
m_windowUpdated = true;
}
}
else if (who == RECEIVER)
{
NS_LOG_INFO ("\tRECEIVER RX " << h << " size " << p->GetSize ());
}
}
void
TcpZeroWindowTest::NormalClose (SocketWho who)
{
if (who == SENDER)
{
m_senderFinished = true;
}
else if (who == RECEIVER)
{
m_receiverFinished = true;
}
}
void
TcpZeroWindowTest::FinalChecks ()
{
NS_TEST_ASSERT_MSG_EQ (m_zeroWindowProbe, true,
"Zero window probe not sent");
NS_TEST_ASSERT_MSG_EQ (m_windowUpdated, true,
"Window has not updated during the connection");
NS_TEST_ASSERT_MSG_EQ (m_senderFinished, true,
"Connection not closed successfully (SENDER)");
NS_TEST_ASSERT_MSG_EQ (m_receiverFinished, true,
"Connection not closed successfully (RECEIVER)");
}
void
TcpZeroWindowTest::ProcessedAck (const Ptr<const TcpSocketState> tcb,
const TcpHeader& h, SocketWho who)
{
if (who == SENDER)
{
if (h.GetFlags () & TcpHeader::SYN)
{
EventId persistentEvent = GetPersistentEvent (SENDER);
NS_TEST_ASSERT_MSG_EQ (persistentEvent.IsRunning (), true,
"Persistent event not started");
}
}
else if (who == RECEIVER)
{
}
}
/**
* \ingroup internet-test
* \ingroup tests
*
* \brief TCP ZeroWindow TestSuite
*/
class TcpZeroWindowTestSuite : public TestSuite
{
public:
TcpZeroWindowTestSuite () : TestSuite ("tcp-zero-window-test", UNIT)
{
AddTestCase (new TcpZeroWindowTest ("zero window test"),
TestCase::QUICK);
}
};
static TcpZeroWindowTestSuite g_tcpZeroWindowTestSuite; //!< Static variable for test initialization
| 8,204
| 2,745
|
//Language: GNU C++
#include <iostream>
#include <queue>
#include <vector>
#include <set>
#include <stack>
#include <string.h>
#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#define max_nodes_size 100005
#define max_size 100005
#define ll long long int
#define mod 1000000007
#define sl(n) scanf("%lld", &n)
using namespace std;
ll grid[2005][2005];
ll vis[2005];
ll dfs(ll node, ll flag, ll n)
{
vis[node] = 1;
ll temp = 1;
for(ll i=0; i<n; i++)
{
if(i!=node && vis[i]==0)
{
if(flag)
{
if(grid[i][node]>0)
temp += dfs(i, flag, n);
}
else
{
if(grid[node][i]>0)
temp += dfs(i, flag, n);
}
}
}
//cout<<node<<" "<<temp<<endl;
return temp;
}
int main()
{
ll n, a;
cin>>n;
ll flag = 0;
for(ll i=0; i<n; i++)
{
for(ll j=0; j<n; j++)
{
sl(grid[i][j]);
}
}
for(ll i=1; i<=n; i++)
vis[i] = 0;
if(dfs(0, 0, n)==n)
flag++;
for(ll i=1; i<=n; i++)
vis[i] = 0;
if(dfs(0, 1, n)==n)
flag++;
if(flag==2)
cout<<"YES";
else
cout<<"NO";
return 0;
}
| 1,040
| 590
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "textextractordfw.h"
#include "tokenizer.h"
#include "docsumstate.h"
#include <vespa/log/log.h>
LOG_SETUP(".searchlib.docsummary.textextractordfw");
namespace search::docsummary {
TextExtractorDFW::TextExtractorDFW() :
_inputFieldEnum(-1)
{
}
bool
TextExtractorDFW::init(const vespalib::string & fieldName, const vespalib::string & inputField, const ResultConfig & config)
{
_inputFieldEnum = config.GetFieldNameEnum().Lookup(inputField.c_str());
if (_inputFieldEnum == -1) {
LOG(warning, "Did not find input field '%s' as part of the docsum fields when initializing writer for field '%s'",
inputField.c_str(), fieldName.c_str());
return false;
}
return true;
}
void
TextExtractorDFW::insertField(uint32_t, GeneralResult *gres, GetDocsumsState *, ResType,
vespalib::slime::Inserter &target)
{
vespalib::string extracted;
ResEntry * entry = gres->GetEntryFromEnumValue(_inputFieldEnum);
if (entry != nullptr) {
const char * buf = nullptr;
uint32_t buflen = 0;
entry->_resolve_field(&buf, &buflen);
// extract the text
Tokenizer tokenizer(buf, buflen);
while (tokenizer.hasMoreTokens()) {
Tokenizer::Token token = tokenizer.getNextToken();
extracted.append(token.getText());
}
} else {
LOG(warning, "Did not find input entry using field enum %d. Write an empty field", _inputFieldEnum);
}
target.insertString(vespalib::Memory(extracted.c_str(), extracted.size()));
}
}
| 1,678
| 524
|
/* Copyright (c) 2010-2019, Delft University of Technology
* All rigths reserved
*
* This file is part of the Tudat. Redistribution and use in source and
* binary forms, with or without modification, are permitted exclusively
* under the terms of the Modified BSD license. You should have received
* a copy of the license with this file. If not, please or visit:
* http://tudat.tudelft.nl/LICENSE.
*/
#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
#include <Eigen/Core>
#include <tudat/basics/testMacros.h>
#include <tudat/simulation/simulation.h>
#include <tudat/io/basicInputOutput.h>
#include <tudat/io/applicationOutput.h>
#include "tudat/astro/LowThrustTrajectories/ShapeBasedMethods/compositeFunctionHodographicShaping.h"
#include "tudat/astro/LowThrustTrajectories/ShapeBasedMethods/hodographicShaping.h"
#include "tudat/astro/LowThrustTrajectories/ShapeBasedMethods/baseFunctionsHodographicShaping.h"
#include "tudat/astro/LowThrustTrajectories/ShapeBasedMethods/createBaseFunctionHodographicShaping.h"
#include "tudat/astro/LowThrustTrajectories/ShapeBasedMethods/baseFunctionsSphericalShaping.h"
#include "tudat/astro/LowThrustTrajectories/ShapeBasedMethods/compositeFunctionSphericalShaping.h"
#include "tudat/astro/LowThrustTrajectories/ShapeBasedMethods/sphericalShaping.h"
#include "tudat/astro/ephemerides/approximatePlanetPositions.h"
#include "tudat/simulation/simulation.h"
#include "tudat/interface/spice/spiceEphemeris.h"
using namespace tudat;
using namespace tudat::input_output;
using namespace tudat::simulation_setup;
using namespace tudat::shape_based_methods;
SystemOfBodies getBetBodyMap( )
{
// Create central, departure and arrival bodies.
std::vector< std::string > bodiesToCreate;
bodiesToCreate.push_back( "Sun" );
bodiesToCreate.push_back( "Earth" );
bodiesToCreate.push_back( "Mars" );
bodiesToCreate.push_back( "Jupiter" );
std::map< std::string, std::shared_ptr< simulation_setup::BodySettings > > bodySettings =
simulation_setup::getDefaultBodySettings( bodiesToCreate );
std::string frameOrigin = "SSB";
std::string frameOrientation = "ECLIPJ2000";
// Define central body ephemeris settings.
bodySettings[ "Sun" ]->ephemerisSettings = std::make_shared< simulation_setup::ConstantEphemerisSettings >(
( Eigen::Vector6d( ) << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ).finished( ), frameOrigin, frameOrientation );
bodySettings[ "Sun" ]->ephemerisSettings->resetFrameOrientation( frameOrientation );
bodySettings[ "Sun" ]->rotationModelSettings->resetOriginalFrame( frameOrientation );
// Create system of bodies.
simulation_setup::SystemOfBodies bodies = createBodies( bodySettings );
bodies[ "Borzi" ] = std::make_shared< simulation_setup::Body >( );
bodies.at( "Borzi" )->setSuppressDependentOrientationCalculatorWarning( true );
bodies.at( "Borzi" )->setEphemeris( std::make_shared< ephemerides::TabulatedCartesianEphemeris< > >(
std::shared_ptr< interpolators::OneDimensionalInterpolator
< double, Eigen::Vector6d > >( ), frameOrigin, frameOrientation ) );
// Create radiation pressure settings
double referenceAreaRadiation = 4.0;
double radiationPressureCoefficient = 1.2;
std::vector< std::string > occultingBodies;
occultingBodies.push_back( "Earth" );
std::shared_ptr< RadiationPressureInterfaceSettings > asterixRadiationPressureSettings =
std::make_shared< CannonBallRadiationPressureInterfaceSettings >(
"Sun", referenceAreaRadiation, radiationPressureCoefficient, occultingBodies );
// Create and set radiation pressure settings
bodies[ "Borzi" ]->setRadiationPressureInterface(
"Sun", createRadiationPressureInterface(
asterixRadiationPressureSettings, "Borzi", bodies ) );
setGlobalFrameBodyEphemerides( bodies, frameOrigin, frameOrientation );
return bodies;
}
int main( )
{
std::string outputSubFolder = "ShapeBasedTrajectoriesExample/";
spice_interface::loadStandardSpiceKernels( );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////// DEFINE TRAJECTORY GLOBAL PARAMETERS ////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int numberOfRevolutions = 1;
double julianDateAtDeparture = 8174.5 * physical_constants::JULIAN_DAY;
double timeOfFlight = 580.0 * physical_constants::JULIAN_DAY;
double vehicleInitialMass = 2000.0;
double specificImpulse = 3000.0;
std::function< double( const double ) > specificImpulseFunction = [ = ]( const double ){ return specificImpulse; };
// Retrieve cartesian state at departure and arrival.
ephemerides::EphemerisPointer pointerToDepartureBodyEphemeris = std::make_shared< ephemerides::ApproximatePlanetPositions>(
ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::earthMoonBarycenter );
ephemerides::EphemerisPointer pointerToArrivalBodyEphemeris = std::make_shared< ephemerides::ApproximatePlanetPositions >(
ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::mars );
Eigen::Vector6d cartesianStateAtDeparture = pointerToDepartureBodyEphemeris->getCartesianState( julianDateAtDeparture );
Eigen::Vector6d cartesianStateAtArrival = pointerToArrivalBodyEphemeris->getCartesianState( julianDateAtDeparture + timeOfFlight );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////// DEFINE HODOGRAPHIC SHAPING LEG ////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
double frequency = 2.0 * mathematical_constants::PI / timeOfFlight;
double scaleFactor = 1.0 / timeOfFlight;
// Create base function settings for the components of the radial velocity composite function.
std::shared_ptr< BaseFunctionHodographicShapingSettings > firstRadialVelocityBaseFunctionSettings =
std::make_shared< BaseFunctionHodographicShapingSettings >( );
std::shared_ptr< BaseFunctionHodographicShapingSettings > secondRadialVelocityBaseFunctionSettings =
std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );
std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdRadialVelocityBaseFunctionSettings =
std::make_shared< PowerFunctionHodographicShapingSettings >( 2.0, scaleFactor );
// Create components of the radial velocity composite function.
std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > radialVelocityFunctionComponents;
radialVelocityFunctionComponents.push_back(
createBaseFunctionHodographicShaping( constant, firstRadialVelocityBaseFunctionSettings ) );
radialVelocityFunctionComponents.push_back(
createBaseFunctionHodographicShaping( scaledPower, secondRadialVelocityBaseFunctionSettings ) );
radialVelocityFunctionComponents.push_back(
createBaseFunctionHodographicShaping( scaledPower, thirdRadialVelocityBaseFunctionSettings ) );
// Create base function settings for the components of the normal velocity composite function.
std::shared_ptr< BaseFunctionHodographicShapingSettings > firstNormalVelocityBaseFunctionSettings =
std::make_shared< BaseFunctionHodographicShapingSettings >( );
std::shared_ptr< BaseFunctionHodographicShapingSettings > secondNormalVelocityBaseFunctionSettings =
std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );
std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdNormalVelocityBaseFunctionSettings =
std::make_shared< PowerFunctionHodographicShapingSettings >( 2.0, scaleFactor );
// Create components of the normal velocity composite function.
std::vector< std::shared_ptr< shape_based_methods::BaseFunctionHodographicShaping > > normalVelocityFunctionComponents;
normalVelocityFunctionComponents.push_back(
createBaseFunctionHodographicShaping( constant, firstNormalVelocityBaseFunctionSettings ) );
normalVelocityFunctionComponents.push_back(
createBaseFunctionHodographicShaping( scaledPower, secondNormalVelocityBaseFunctionSettings ) );
normalVelocityFunctionComponents.push_back(
createBaseFunctionHodographicShaping( scaledPower, thirdNormalVelocityBaseFunctionSettings ) );
// Create base function settings for the components of the axial velocity composite function.
std::shared_ptr< BaseFunctionHodographicShapingSettings > firstAxialVelocityBaseFunctionSettings =
std::make_shared< TrigonometricFunctionHodographicShapingSettings >( ( numberOfRevolutions + 0.5 ) * frequency );
std::shared_ptr< BaseFunctionHodographicShapingSettings > secondAxialVelocityBaseFunctionSettings =
std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >
( 3.0, ( numberOfRevolutions + 0.5 ) * frequency, scaleFactor );
std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdAxialVelocityBaseFunctionSettings =
std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >(
3.0, ( numberOfRevolutions + 0.5 ) * frequency, scaleFactor );
// Create components for the axial velocity composite function.
std::vector< std::shared_ptr< shape_based_methods::BaseFunctionHodographicShaping > > axialVelocityFunctionComponents;
axialVelocityFunctionComponents.push_back(
createBaseFunctionHodographicShaping( cosine, firstAxialVelocityBaseFunctionSettings ) );
axialVelocityFunctionComponents.push_back(
createBaseFunctionHodographicShaping( scaledPowerCosine, secondAxialVelocityBaseFunctionSettings ) );
axialVelocityFunctionComponents.push_back(
createBaseFunctionHodographicShaping( scaledPowerSine, thirdAxialVelocityBaseFunctionSettings ) );
// Initialize free coefficients vector for radial velocity function (empty here, only 3 base functions).
Eigen::VectorXd freeCoefficientsRadialVelocityFunction = Eigen::VectorXd::Zero( 0 );
// Initialize free coefficients vector for normal velocity function (empty here, only 3 base functions).
Eigen::VectorXd freeCoefficientsNormalVelocityFunction = Eigen::VectorXd::Zero( 0 );
// Initialize free coefficients vector for axial velocity function (empty here, only 3 base functions).
Eigen::VectorXd freeCoefficientsAxialVelocityFunction = Eigen::VectorXd::Zero( 0 );
// Create hodographic-shaping object with defined velocity functions and boundary conditions.
shape_based_methods::HodographicShaping hodographicShaping(
cartesianStateAtDeparture, cartesianStateAtArrival, timeOfFlight,
spice_interface::getBodyGravitationalParameter( "Sun" ), 1,
radialVelocityFunctionComponents, normalVelocityFunctionComponents, axialVelocityFunctionComponents,
freeCoefficientsRadialVelocityFunction, freeCoefficientsNormalVelocityFunction, freeCoefficientsAxialVelocityFunction,
vehicleInitialMass );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////// DEFINE SPHERICAL SHAPING LEG ////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Define root finder settings (used to update the updated value of the free coefficient, so that it matches the required time of flight).
std::shared_ptr< root_finders::RootFinderSettings > rootFinderSettings =
std::make_shared< root_finders::RootFinderSettings >( root_finders::bisection_root_finder, 1.0e-6, 30 );
// Compute shaped trajectory.
shape_based_methods::SphericalShaping sphericalShaping = shape_based_methods::SphericalShaping(
cartesianStateAtDeparture, cartesianStateAtArrival, timeOfFlight,
spice_interface::getBodyGravitationalParameter( "Sun" ),
numberOfRevolutions, 0.000703,
rootFinderSettings, 1.0e-6, 1.0e-1, vehicleInitialMass );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////// CREATE ENVIRONMENT /////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Set vehicle mass.
SystemOfBodies bodies = getBetBodyMap( );
bodies[ "Borzi" ]->setConstantBodyMass( vehicleInitialMass );
// Define body to propagate and central body.
std::vector< std::string > bodiesToPropagate;
std::vector< std::string > centralBodies;
bodiesToPropagate.push_back( "Borzi" );
centralBodies.push_back( "Sun" );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////// DEFINE PROPAGATION SETTINGS /////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Define integrator settings.
double stepSize = timeOfFlight / static_cast< double >( 8000.0 );
std::shared_ptr< numerical_integrators::IntegratorSettings< double > > integratorSettings =
std::make_shared< numerical_integrators::IntegratorSettings< double > > ( numerical_integrators::rungeKutta4, 0.0, stepSize );
// Define list of dependent variables to save.
std::vector< std::shared_ptr< propagators::SingleDependentVariableSaveSettings > > dependentVariablesList;
// Create object with list of dependent variables
std::shared_ptr< propagators::DependentVariableSaveSettings > dependentVariablesToSave =
std::make_shared< propagators::DependentVariableSaveSettings >( dependentVariablesList, false );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////// NUMERICALLY PROPAGATE THE SIMPLIFIED PROBLEM /////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::map< double, Eigen::VectorXd > hodographicShapingPropagationUnperturbedCase;
std::map< double, Eigen::Vector6d > hodographicShapingAnalyticalResults;
std::map< double, Eigen::VectorXd > hodographicShapingDependentVariablesHistory;
// Create propagator settings for hodographic shaping.
std::pair< std::shared_ptr< propagators::PropagatorSettings< double > >, std::shared_ptr< propagators::PropagatorSettings< double > > >
hodographicShapingPropagatorSettings = hodographicShaping.createLowThrustPropagatorSettings(
bodies, bodiesToPropagate.at( 0 ), centralBodies.at( 0 ), specificImpulseFunction,
basic_astrodynamics::AccelerationMap( ), integratorSettings, dependentVariablesToSave );
// Compute shaped trajectory and propagated trajectory.
hodographicShaping.computeSemiAnalyticalAndFullPropagation(
bodies, integratorSettings, hodographicShapingPropagatorSettings, hodographicShapingPropagationUnperturbedCase,
hodographicShapingAnalyticalResults, hodographicShapingDependentVariablesHistory );
std::map< double, Eigen::VectorXd > sphericalShapingPropagationUnperturbedCase;
std::map< double, Eigen::Vector6d > sphericalShapingAnalyticalResults;
std::map< double, Eigen::VectorXd > sphericalShapingDependentVariablesHistory;
// Create propagator settings for spherical shaping.
std::pair< std::shared_ptr< propagators::PropagatorSettings< double > >, std::shared_ptr< propagators::PropagatorSettings< double > > >
sphericalShapingPropagatorSettings = sphericalShaping.createLowThrustPropagatorSettings(
bodies, bodiesToPropagate.at( 0 ), centralBodies.at( 0 ), specificImpulseFunction,
basic_astrodynamics::AccelerationMap( ), integratorSettings, dependentVariablesToSave );
// Compute shaped trajectory and propagated trajectory.
sphericalShaping.computeSemiAnalyticalAndFullPropagation(
bodies, integratorSettings, sphericalShapingPropagatorSettings, sphericalShapingPropagationUnperturbedCase,
sphericalShapingAnalyticalResults, sphericalShapingDependentVariablesHistory );
input_output::writeDataMapToTextFile( hodographicShapingAnalyticalResults,
"hodographicShapingAnalyticalResults.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
input_output::writeDataMapToTextFile( sphericalShapingAnalyticalResults,
"sphericalShapingAnalyticalResults.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
input_output::writeDataMapToTextFile( hodographicShapingPropagationUnperturbedCase,
"hodographicShapingPropagationUnperturbedCase.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
input_output::writeDataMapToTextFile( sphericalShapingPropagationUnperturbedCase,
"sphericalShapingPropagationUnperturbedCase.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// RETRIEVE TRAJECTORY, MASS, THRUST AND THRUST ACCELERATION PROFILES //////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Hodographic shaping
std::vector< double > epochsVectorHodographicShaping;
for ( std::map< double, Eigen::Vector6d >::iterator itr = hodographicShapingAnalyticalResults.begin( ) ;
itr != hodographicShapingAnalyticalResults.end( ) ; itr++ )
{
epochsVectorHodographicShaping.push_back( itr->first );
}
std::map< double, Eigen::VectorXd > hodographicShapingMassProfile;
std::map< double, Eigen::VectorXd > hodographicShapingThrustProfile;
std::map< double, Eigen::VectorXd > hodographicShapingThrustAccelerationProfile;
hodographicShaping.getMassProfile(
epochsVectorHodographicShaping, hodographicShapingMassProfile, specificImpulseFunction, integratorSettings );
hodographicShaping.getThrustForceProfile(
epochsVectorHodographicShaping, hodographicShapingThrustProfile, specificImpulseFunction, integratorSettings );
hodographicShaping.getThrustAccelerationProfile(
epochsVectorHodographicShaping, hodographicShapingThrustAccelerationProfile, specificImpulseFunction, integratorSettings );
// Spherical shaping
std::vector< double > epochsVectorSphericalShaping;
for ( std::map< double, Eigen::Vector6d >::iterator itr = sphericalShapingAnalyticalResults.begin( ) ;
itr != sphericalShapingAnalyticalResults.end( ) ; itr++ )
{
epochsVectorSphericalShaping.push_back( itr->first );
}
std::map< double, Eigen::VectorXd > sphericalShapingMassProfile;
std::map< double, Eigen::VectorXd > sphericalShapingThrustProfile;
std::map< double, Eigen::VectorXd > sphericalShapingThrustAccelerationProfile;
sphericalShaping.getMassProfile(
epochsVectorSphericalShaping, sphericalShapingMassProfile, specificImpulseFunction, integratorSettings );
sphericalShaping.getThrustForceProfile(
epochsVectorSphericalShaping, sphericalShapingThrustProfile, specificImpulseFunction, integratorSettings );
sphericalShaping.getThrustAccelerationProfile(
epochsVectorSphericalShaping, sphericalShapingThrustAccelerationProfile, specificImpulseFunction, integratorSettings );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////// DEFINE PERTURBED DYNAMICAL ENVIRONMENT /////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Define propagation settings.
std::map< std::string, std::vector< std::shared_ptr< AccelerationSettings > > > accelerationSettingsPerturbedProblem;
accelerationSettingsPerturbedProblem[ "Earth" ].push_back( std::make_shared< AccelerationSettings >(
basic_astrodynamics::central_gravity ) );
accelerationSettingsPerturbedProblem[ "Mars" ].push_back( std::make_shared< AccelerationSettings >(
basic_astrodynamics::central_gravity ) );
accelerationSettingsPerturbedProblem[ "Jupiter" ].push_back( std::make_shared< AccelerationSettings >(
basic_astrodynamics::central_gravity ) );
accelerationSettingsPerturbedProblem[ "Sun" ].push_back( std::make_shared< AccelerationSettings >(
basic_astrodynamics::cannon_ball_radiation_pressure ) );
SelectedAccelerationMap accelerationMap;
accelerationMap[ "Borzi" ] = accelerationSettingsPerturbedProblem;
bodiesToPropagate.push_back( "Borzi" );
centralBodies.push_back( "Sun" );
basic_astrodynamics::AccelerationMap perturbingAccelerationsMapPertubedProblem = createAccelerationModelsMap(
bodies, accelerationMap, bodiesToPropagate, centralBodies );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////// PROPAGATE THE FULLY PERTURBED PROBLEM /////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::map< double, Eigen::VectorXd > hodographicShapingPropagationPerturbedCase;
std::map< double, Eigen::Vector6d > hodographicShapingAnalyticalResultsPerturbedCase;
std::map< double, Eigen::VectorXd > hodographicShapingDependentVariablesHistoryPerturbedCase;
std::map< double, Eigen::VectorXd > sphericalShapingPropagationPerturbedCase;
std::map< double, Eigen::Vector6d > sphericalShapingAnalyticalResultsPerturbedCase;
std::map< double, Eigen::VectorXd > sphericalShapingDependentVariablesHistoryPerturbedCase;
// Create propagator settings for hodographic shaping.
std::pair< std::shared_ptr< propagators::PropagatorSettings< double > >, std::shared_ptr< propagators::PropagatorSettings< double > > >
hodographicShapingPropagatorSettingsPerturbedCase = hodographicShaping.createLowThrustPropagatorSettings(
bodies, bodiesToPropagate.at( 0 ), centralBodies.at( 0 ), specificImpulseFunction,
perturbingAccelerationsMapPertubedProblem, integratorSettings, dependentVariablesToSave );
// Compute shaped trajectory and propagated trajectory.
hodographicShaping.computeSemiAnalyticalAndFullPropagation(
bodies, integratorSettings, hodographicShapingPropagatorSettingsPerturbedCase, hodographicShapingPropagationPerturbedCase,
hodographicShapingAnalyticalResultsPerturbedCase, hodographicShapingDependentVariablesHistoryPerturbedCase );
// Create propagator settings for spherical shaping.
std::pair< std::shared_ptr< propagators::PropagatorSettings< double > >, std::shared_ptr< propagators::PropagatorSettings< double > > >
sphericalShapingPropagatorSettingsPerturbedCase = sphericalShaping.createLowThrustPropagatorSettings(
bodies, bodiesToPropagate.at( 0 ), centralBodies.at( 0 ), specificImpulseFunction,
perturbingAccelerationsMapPertubedProblem, integratorSettings, dependentVariablesToSave );
// Compute shaped trajectory and propagated trajectory.
sphericalShaping.computeSemiAnalyticalAndFullPropagation(
bodies, integratorSettings, sphericalShapingPropagatorSettingsPerturbedCase, sphericalShapingPropagationPerturbedCase,
sphericalShapingAnalyticalResultsPerturbedCase, sphericalShapingDependentVariablesHistoryPerturbedCase );
input_output::writeDataMapToTextFile( hodographicShapingPropagationPerturbedCase,
"hodographicShapingPropagationPerturbedCase.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
input_output::writeDataMapToTextFile( sphericalShapingPropagationPerturbedCase,
"sphericalShapingPropagationPerturbedCase.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
input_output::writeDataMapToTextFile( hodographicShapingMassProfile,
"hodographicShapingMassProfile.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
input_output::writeDataMapToTextFile( hodographicShapingThrustProfile,
"hodographicShapingThrustProfile.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
input_output::writeDataMapToTextFile( hodographicShapingThrustAccelerationProfile,
"hodographicShapingThrustAccelerationProfile.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
input_output::writeDataMapToTextFile( sphericalShapingMassProfile,
"sphericalShapingMassProfile.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
input_output::writeDataMapToTextFile( sphericalShapingThrustProfile,
"sphericalShapingThrustProfile.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
input_output::writeDataMapToTextFile( sphericalShapingThrustAccelerationProfile,
"sphericalShapingThrustAccelerationProfile.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
std::cout << "deltaV hodographic shaping: " << hodographicShaping.computeDeltaV( ) << "\n\n";
std::cout << "deltaV spherical shaping: " << sphericalShaping.computeDeltaV( ) << "\n\n";
// Final statement.
// The exit code EXIT_SUCCESS indicates that the program was successfully executed.
return EXIT_SUCCESS;
}
| 31,037
| 7,883
|
#include "vega/dicom/file_meta.h"
#include "vega/dicom/writer.h"
#include "vega/dicom/data_element.h"
#include "vega/manipulator.h"
#include <cassert>
namespace vega {
namespace dicom {
const Tag FileMeta::FileMetaInformationGroupLength = Tag{0x2, 0x0};
const Tag FileMeta::TransferSyntaxUID = Tag{0x2, 0x10};
FileMeta::FileMeta()
: m_transfer_syntax(TransferSyntax::EXPLICIT_VR_LITTLE_ENDIAN)
{}
FileMeta::FileMeta(const SOPClass& sop_class)
: FileMeta(sop_class, UID::generate())
{}
FileMeta::FileMeta(const SOPClass& sop_class, const UID& media_storage_instance_uid)
: m_data_set(std::make_shared<DataSet>())
{
this->fill_defaults(sop_class, media_storage_instance_uid);
}
FileMeta::FileMeta(Reader& reader)
: m_data_set(std::make_shared<DataSet>())
{
// File meta information is written in little endian
const Endian original_endian = reader.dicom_endian();
reader.set_dicom_endianness(Endian::LITTLE);
const bool original_vr_explicit = reader.vr_explicit();
reader.set_vr_explicit(true);
this->read(reader);
reader.set_dicom_endianness(original_endian);
reader.set_vr_explicit(original_vr_explicit);
}
const TransferSyntax& FileMeta::transfer_syntax() const { return m_transfer_syntax; }
void FileMeta::set_transfer_syntax(const TransferSyntax& other) {
m_transfer_syntax = other;
}
Endian FileMeta::transfer_syntax_endian() const { return m_transfer_syntax.endianness(); }
bool FileMeta::transfer_syntax_vr_explicit() const { return m_transfer_syntax.is_explicit_vr(); }
std::shared_ptr<const DataSet> FileMeta::data_set() const { return std::const_pointer_cast<const DataSet>(m_data_set); }
const SOPClass& FileMeta::sop_class() const { return m_sop_class; }
const UID& FileMeta::media_storage_instance_uid() const { return m_media_storage_instance_uid; }
bool FileMeta::present() const { return bool(m_data_set); }
size_t FileMeta::write(std::shared_ptr<Writer> writer) {
if (!this->present()) return 0;
// File meta information is written in little endian
const Endian original_endian = writer->dicom_endian();
writer->set_dicom_endianness(Endian::LITTLE);
const bool original_vr_explicit = writer->vr_explicit();
writer->set_vr_explicit(true);
uint32_t length_of_file_meta_length_element = 0;
uint32_t file_meta_bytes = 0;
// Write each data element
bool first = true;
std::streampos file_meta_length_pos;
std::streampos end_of_file_meta_pos;
for (auto data_element : *m_data_set) {
if (first) {
first = false;
length_of_file_meta_length_element += writer->write_element(data_element);
assert(data_element->tag() == Tag(0x00020000));
file_meta_length_pos = writer->tell() - std::streampos(sizeof(file_meta_bytes));
assert(data_element->manipulator()->raw_value()->size() == sizeof(file_meta_bytes));
}
else {
file_meta_bytes += writer->write_element(data_element);
}
}
end_of_file_meta_pos = writer->tell();
writer->seek_pos(file_meta_length_pos);
writer->raw_writer().write_from(file_meta_bytes);
writer->seek_pos(end_of_file_meta_pos);
writer->set_dicom_endianness(original_endian);
writer->set_vr_explicit(original_vr_explicit);
return length_of_file_meta_length_element + file_meta_bytes;
}
void FileMeta::read(Reader& reader) {
// Expect first data_element to be File Meta Information Group Length
auto maybe_group_length = reader.read_data_element(m_data_set);
if (maybe_group_length->tag() == FileMetaInformationGroupLength) {
// Has group length
auto group_length = maybe_group_length;
auto manipulator = group_length->get_manipulator<UL_Manipulator>();
std::streampos end_of_file_meta = reader.tell() + (std::streampos)(*manipulator)[0];
m_data_set->add_data_element(group_length);
// Read in rest of file meta elements
while (reader.tell() < end_of_file_meta) {
auto data_element = reader.read_data_element(m_data_set);
if (!data_element) throw InvalidFileMeta("Unexpected error reading file meta");
if (!data_element->tag().is_file_meta()) {
throw InvalidFileMeta("Encountered non file-meta DataElement in file meta header");
}
m_data_set->add_data_element(data_element);
}
assert(reader.tell() == end_of_file_meta);
}
else {
// Group length not present, but we would like to have one anyway for compliance so create
auto actual_group_length = std::make_shared<dicom::DataElement>("FileMetaInformationGroupLength");
auto manipulator = actual_group_length->get_manipulator<UL_Manipulator>();
manipulator->push_back(0);
m_data_set->add_data_element(actual_group_length);
// Previously read in data_element still needs to be added
m_data_set->add_data_element(maybe_group_length);
// Read until no longer getting file meta elements
while (!reader.eof()) {
// Tentatively read in next tag
std::streampos cur_pos = reader.tell();
Tag temp_tag;
reader.raw_reader().read_into(&temp_tag);
reader.seek_pos(cur_pos);
if (!temp_tag.is_file_meta()) {
// Finished reading file meta
break;
}
auto data_element = reader.read_data_element(m_data_set);
if (!data_element) throw InvalidFileMeta("Unexpected error reading file meta");
m_data_set->add_data_element(data_element);
}
}
auto transfer_syntax_uid = m_data_set->data_element(TransferSyntaxUID);
if (!transfer_syntax_uid) {
throw InvalidFileMeta("Need TransferSyntaxUID element");
}
auto sop_class = m_data_set->data_element(SOPClass::TAG);
if (!sop_class) {
throw InvalidFileMeta("Need MediaStorageSOPClassUID element");
}
auto sop_class_manipulator = sop_class->get_manipulator<manipulators::UniqueIdentifierManipulator>();
m_sop_class = SOPClass(sop_class_manipulator->uid());
auto sop_instance = m_data_set->data_element("MediaStorageSOPInstanceUID");
if (!sop_instance) {
throw InvalidFileMeta("Need MediaStorageSOPInstanceUID element");
}
auto sop_instance_manipulator = sop_instance->get_manipulator<manipulators::UniqueIdentifierManipulator>();
m_media_storage_instance_uid = sop_instance_manipulator->uid();
this->set_transfer_syntax(TransferSyntax{UID{transfer_syntax_uid->str()}});
}
void FileMeta::fill_defaults(const SOPClass& sop_class, const UID& media_storage_instance_uid) {
// File meta group length
{
auto data_element = std::make_shared<dicom::DataElement>("FileMetaInformationGroupLength");
auto manipulator = data_element->get_manipulator<manipulators::UnsignedLongManipulator>();
// Store dummy value of zero here -- only need this value when writing to file
manipulator->push_back(0);
m_data_set->add_data_element(data_element);
}
// File meta information version (0x00, 0x01)
{
auto data_element = std::make_shared<dicom::DataElement>("FileMetaInformationVersion");
auto manipulator = data_element->get_manipulator<manipulators::OtherByteManipulator>();
manipulator->push_back(Byte{.u=0});
manipulator->push_back(Byte{.u=1});
m_data_set->add_data_element(data_element);
}
// SOP class uid
{
auto data_element = std::make_shared<dicom::DataElement>("MediaStorageSOPClassUID");
auto manipulator = data_element->get_manipulator<manipulators::UniqueIdentifierManipulator>();
m_sop_class = sop_class;
manipulator->uid() = m_sop_class.uid();
m_data_set->add_data_element(data_element);
}
// SOP instance uid
{
auto data_element = std::make_shared<dicom::DataElement>("MediaStorageSOPInstanceUID");
auto manipulator = data_element->get_manipulator<manipulators::UniqueIdentifierManipulator>();
m_media_storage_instance_uid = media_storage_instance_uid;
manipulator->uid() = m_media_storage_instance_uid;
m_data_set->add_data_element(data_element);
}
// Transfer syntax we default to implicit VR little endian
{
auto data_element = std::make_shared<dicom::DataElement>("TransferSyntaxUID");
auto manipulator = data_element->get_manipulator<manipulators::UniqueIdentifierManipulator>();
this->set_transfer_syntax(TransferSyntax::IMPLICIT_VR_LITTLE_ENDIAN);
manipulator->uid() = TransferSyntax::IMPLICIT_VR_LITTLE_ENDIAN.uid();
m_data_set->add_data_element(data_element);
}
// Implementation class UID
{
auto data_element = std::make_shared<dicom::DataElement>("ImplementationClassUID");
auto manipulator = data_element->get_manipulator<manipulators::UniqueIdentifierManipulator>();
manipulator->uid() = UID::IMPLEMENTATION_CLASS_UID;
m_data_set->add_data_element(data_element);
}
}
}
}
| 9,348
| 2,949
|
// Copyright 2019 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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 <fcntl.h>
#include <linux/unistd.h>
#include <sys/eventfd.h>
#include <sys/resource.h>
#include <sys/sendfile.h>
#include <sys/time.h>
#include <unistd.h>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/strings/string_view.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "test/util/file_descriptor.h"
#include "test/util/signal_util.h"
#include "test/util/temp_path.h"
#include "test/util/test_util.h"
#include "test/util/thread_util.h"
#include "test/util/timer_util.h"
namespace gvisor {
namespace testing {
namespace {
TEST(SpliceTest, TwoRegularFiles) {
// Create temp files.
const TempPath in_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
const TempPath out_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
// Open the input file as read only.
const FileDescriptor in_fd =
ASSERT_NO_ERRNO_AND_VALUE(Open(in_file.path(), O_RDONLY));
// Open the output file as write only.
const FileDescriptor out_fd =
ASSERT_NO_ERRNO_AND_VALUE(Open(out_file.path(), O_WRONLY));
// Verify that it is rejected as expected; regardless of offsets.
loff_t in_offset = 0;
loff_t out_offset = 0;
EXPECT_THAT(splice(in_fd.get(), &in_offset, out_fd.get(), &out_offset, 1, 0),
SyscallFailsWithErrno(EINVAL));
EXPECT_THAT(splice(in_fd.get(), nullptr, out_fd.get(), &out_offset, 1, 0),
SyscallFailsWithErrno(EINVAL));
EXPECT_THAT(splice(in_fd.get(), &in_offset, out_fd.get(), nullptr, 1, 0),
SyscallFailsWithErrno(EINVAL));
EXPECT_THAT(splice(in_fd.get(), nullptr, out_fd.get(), nullptr, 1, 0),
SyscallFailsWithErrno(EINVAL));
}
int memfd_create(const std::string& name, unsigned int flags) {
return syscall(__NR_memfd_create, name.c_str(), flags);
}
TEST(SpliceTest, NegativeOffset) {
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
const FileDescriptor wfd(fds[1]);
// Fill the pipe.
std::vector<char> buf(kPageSize);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(wfd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kPageSize));
// Open the output file as write only.
int fd;
EXPECT_THAT(fd = memfd_create("negative", 0), SyscallSucceeds());
const FileDescriptor out_fd(fd);
loff_t out_offset = 0xffffffffffffffffull;
constexpr int kSize = 2;
EXPECT_THAT(splice(rfd.get(), nullptr, out_fd.get(), &out_offset, kSize, 0),
SyscallFailsWithErrno(EINVAL));
}
// Write offset + size overflows int64.
//
// This is a regression test for b/148041624.
TEST(SpliceTest, WriteOverflow) {
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
const FileDescriptor wfd(fds[1]);
// Fill the pipe.
std::vector<char> buf(kPageSize);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(wfd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kPageSize));
// Open the output file.
int fd;
EXPECT_THAT(fd = memfd_create("overflow", 0), SyscallSucceeds());
const FileDescriptor out_fd(fd);
// out_offset + kSize overflows INT64_MAX.
loff_t out_offset = 0x7ffffffffffffffeull;
constexpr int kSize = 3;
EXPECT_THAT(splice(rfd.get(), nullptr, out_fd.get(), &out_offset, kSize, 0),
SyscallFailsWithErrno(EINVAL));
}
TEST(SpliceTest, SamePipe) {
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
const FileDescriptor wfd(fds[1]);
// Fill the pipe.
std::vector<char> buf(kPageSize);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(wfd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kPageSize));
// Attempt to splice to itself.
EXPECT_THAT(splice(rfd.get(), nullptr, wfd.get(), nullptr, kPageSize, 0),
SyscallFailsWithErrno(EINVAL));
}
TEST(TeeTest, SamePipe) {
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
const FileDescriptor wfd(fds[1]);
// Fill the pipe.
std::vector<char> buf(kPageSize);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(wfd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kPageSize));
// Attempt to tee to itself.
EXPECT_THAT(tee(rfd.get(), wfd.get(), kPageSize, 0),
SyscallFailsWithErrno(EINVAL));
}
TEST(TeeTest, RegularFile) {
// Open some file.
const TempPath in_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
const FileDescriptor in_fd =
ASSERT_NO_ERRNO_AND_VALUE(Open(in_file.path(), O_RDWR));
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
const FileDescriptor wfd(fds[1]);
// Attempt to tee from the file.
EXPECT_THAT(tee(in_fd.get(), wfd.get(), kPageSize, 0),
SyscallFailsWithErrno(EINVAL));
EXPECT_THAT(tee(rfd.get(), in_fd.get(), kPageSize, 0),
SyscallFailsWithErrno(EINVAL));
}
TEST(SpliceTest, PipeOffsets) {
// Create two new pipes.
int first[2], second[2];
ASSERT_THAT(pipe(first), SyscallSucceeds());
const FileDescriptor rfd1(first[0]);
const FileDescriptor wfd1(first[1]);
ASSERT_THAT(pipe(second), SyscallSucceeds());
const FileDescriptor rfd2(second[0]);
const FileDescriptor wfd2(second[1]);
// All pipe offsets should be rejected.
loff_t in_offset = 0;
loff_t out_offset = 0;
EXPECT_THAT(splice(rfd1.get(), &in_offset, wfd2.get(), &out_offset, 1, 0),
SyscallFailsWithErrno(ESPIPE));
EXPECT_THAT(splice(rfd1.get(), nullptr, wfd2.get(), &out_offset, 1, 0),
SyscallFailsWithErrno(ESPIPE));
EXPECT_THAT(splice(rfd1.get(), &in_offset, wfd2.get(), nullptr, 1, 0),
SyscallFailsWithErrno(ESPIPE));
}
// Event FDs may be used with splice without an offset.
TEST(SpliceTest, FromEventFD) {
// Open the input eventfd with an initial value so that it is readable.
constexpr uint64_t kEventFDValue = 1;
int efd;
ASSERT_THAT(efd = eventfd(kEventFDValue, 0), SyscallSucceeds());
const FileDescriptor in_fd(efd);
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
const FileDescriptor wfd(fds[1]);
// Splice 8-byte eventfd value to pipe.
constexpr int kEventFDSize = 8;
EXPECT_THAT(splice(in_fd.get(), nullptr, wfd.get(), nullptr, kEventFDSize, 0),
SyscallSucceedsWithValue(kEventFDSize));
// Contents should be equal.
std::vector<char> rbuf(kEventFDSize);
ASSERT_THAT(read(rfd.get(), rbuf.data(), rbuf.size()),
SyscallSucceedsWithValue(kEventFDSize));
EXPECT_EQ(memcmp(rbuf.data(), &kEventFDValue, rbuf.size()), 0);
}
// Event FDs may not be used with splice with an offset.
TEST(SpliceTest, FromEventFDOffset) {
int efd;
ASSERT_THAT(efd = eventfd(0, 0), SyscallSucceeds());
const FileDescriptor in_fd(efd);
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
const FileDescriptor wfd(fds[1]);
// Attempt to splice 8-byte eventfd value to pipe with offset.
//
// This is not allowed because eventfd doesn't support pread.
constexpr int kEventFDSize = 8;
loff_t in_off = 0;
EXPECT_THAT(splice(in_fd.get(), &in_off, wfd.get(), nullptr, kEventFDSize, 0),
SyscallFailsWithErrno(EINVAL));
}
// Event FDs may not be used with splice with an offset.
TEST(SpliceTest, ToEventFDOffset) {
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
const FileDescriptor wfd(fds[1]);
// Fill with a value.
constexpr int kEventFDSize = 8;
std::vector<char> buf(kEventFDSize);
buf[0] = 1;
ASSERT_THAT(write(wfd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kEventFDSize));
int efd;
ASSERT_THAT(efd = eventfd(0, 0), SyscallSucceeds());
const FileDescriptor out_fd(efd);
// Attempt to splice 8-byte eventfd value to pipe with offset.
//
// This is not allowed because eventfd doesn't support pwrite.
loff_t out_off = 0;
EXPECT_THAT(
splice(rfd.get(), nullptr, out_fd.get(), &out_off, kEventFDSize, 0),
SyscallFailsWithErrno(EINVAL));
}
TEST(SpliceTest, ToPipe) {
// Open the input file.
const TempPath in_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
const FileDescriptor in_fd =
ASSERT_NO_ERRNO_AND_VALUE(Open(in_file.path(), O_RDWR));
// Fill with some random data.
std::vector<char> buf(kPageSize);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(in_fd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kPageSize));
ASSERT_THAT(lseek(in_fd.get(), 0, SEEK_SET), SyscallSucceedsWithValue(0));
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
const FileDescriptor wfd(fds[1]);
// Splice to the pipe.
EXPECT_THAT(splice(in_fd.get(), nullptr, wfd.get(), nullptr, kPageSize, 0),
SyscallSucceedsWithValue(kPageSize));
// Contents should be equal.
std::vector<char> rbuf(kPageSize);
ASSERT_THAT(read(rfd.get(), rbuf.data(), rbuf.size()),
SyscallSucceedsWithValue(kPageSize));
EXPECT_EQ(memcmp(rbuf.data(), buf.data(), buf.size()), 0);
}
TEST(SpliceTest, ToPipeEOF) {
// Create and open an empty input file.
const TempPath in_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
const FileDescriptor in_fd =
ASSERT_NO_ERRNO_AND_VALUE(Open(in_file.path(), O_RDONLY));
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
const FileDescriptor wfd(fds[1]);
// Splice from the empty file to the pipe.
EXPECT_THAT(splice(in_fd.get(), nullptr, wfd.get(), nullptr, 123, 0),
SyscallSucceedsWithValue(0));
}
TEST(SpliceTest, ToPipeOffset) {
// Open the input file.
const TempPath in_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
const FileDescriptor in_fd =
ASSERT_NO_ERRNO_AND_VALUE(Open(in_file.path(), O_RDWR));
// Fill with some random data.
std::vector<char> buf(kPageSize);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(in_fd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kPageSize));
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
const FileDescriptor wfd(fds[1]);
// Splice to the pipe.
loff_t in_offset = kPageSize / 2;
EXPECT_THAT(
splice(in_fd.get(), &in_offset, wfd.get(), nullptr, kPageSize / 2, 0),
SyscallSucceedsWithValue(kPageSize / 2));
// Contents should be equal to only the second part.
std::vector<char> rbuf(kPageSize / 2);
ASSERT_THAT(read(rfd.get(), rbuf.data(), rbuf.size()),
SyscallSucceedsWithValue(kPageSize / 2));
EXPECT_EQ(memcmp(rbuf.data(), buf.data() + (kPageSize / 2), rbuf.size()), 0);
}
TEST(SpliceTest, FromPipe) {
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
const FileDescriptor wfd(fds[1]);
// Fill with some random data.
std::vector<char> buf(kPageSize);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(wfd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kPageSize));
// Open the output file.
const TempPath out_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
const FileDescriptor out_fd =
ASSERT_NO_ERRNO_AND_VALUE(Open(out_file.path(), O_RDWR));
// Splice to the output file.
EXPECT_THAT(splice(rfd.get(), nullptr, out_fd.get(), nullptr, kPageSize, 0),
SyscallSucceedsWithValue(kPageSize));
// The offset of the output should be equal to kPageSize. We assert that and
// reset to zero so that we can read the contents and ensure they match.
EXPECT_THAT(lseek(out_fd.get(), 0, SEEK_CUR),
SyscallSucceedsWithValue(kPageSize));
ASSERT_THAT(lseek(out_fd.get(), 0, SEEK_SET), SyscallSucceedsWithValue(0));
// Contents should be equal.
std::vector<char> rbuf(kPageSize);
ASSERT_THAT(read(out_fd.get(), rbuf.data(), rbuf.size()),
SyscallSucceedsWithValue(kPageSize));
EXPECT_EQ(memcmp(rbuf.data(), buf.data(), buf.size()), 0);
}
TEST(SpliceTest, FromPipeMultiple) {
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
const FileDescriptor wfd(fds[1]);
std::string buf = "abcABC123";
ASSERT_THAT(write(wfd.get(), buf.c_str(), buf.size()),
SyscallSucceedsWithValue(buf.size()));
// Open the output file.
const TempPath out_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
const FileDescriptor out_fd =
ASSERT_NO_ERRNO_AND_VALUE(Open(out_file.path(), O_RDWR));
// Splice from the pipe to the output file over several calls.
EXPECT_THAT(splice(rfd.get(), nullptr, out_fd.get(), nullptr, 3, 0),
SyscallSucceedsWithValue(3));
EXPECT_THAT(splice(rfd.get(), nullptr, out_fd.get(), nullptr, 3, 0),
SyscallSucceedsWithValue(3));
EXPECT_THAT(splice(rfd.get(), nullptr, out_fd.get(), nullptr, 3, 0),
SyscallSucceedsWithValue(3));
// Reset cursor to zero so that we can check the contents.
ASSERT_THAT(lseek(out_fd.get(), 0, SEEK_SET), SyscallSucceedsWithValue(0));
// Contents should be equal.
std::vector<char> rbuf(buf.size());
ASSERT_THAT(read(out_fd.get(), rbuf.data(), rbuf.size()),
SyscallSucceedsWithValue(rbuf.size()));
EXPECT_EQ(memcmp(rbuf.data(), buf.c_str(), buf.size()), 0);
}
TEST(SpliceTest, FromPipeOffset) {
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
const FileDescriptor wfd(fds[1]);
// Fill with some random data.
std::vector<char> buf(kPageSize);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(wfd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kPageSize));
// Open the input file.
const TempPath out_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
const FileDescriptor out_fd =
ASSERT_NO_ERRNO_AND_VALUE(Open(out_file.path(), O_RDWR));
// Splice to the output file.
loff_t out_offset = kPageSize / 2;
EXPECT_THAT(
splice(rfd.get(), nullptr, out_fd.get(), &out_offset, kPageSize, 0),
SyscallSucceedsWithValue(kPageSize));
// Content should reflect the splice. We write to a specific offset in the
// file, so the internals should now be allocated sparsely.
std::vector<char> rbuf(kPageSize);
ASSERT_THAT(read(out_fd.get(), rbuf.data(), rbuf.size()),
SyscallSucceedsWithValue(kPageSize));
std::vector<char> zbuf(kPageSize / 2);
memset(zbuf.data(), 0, zbuf.size());
EXPECT_EQ(memcmp(rbuf.data(), zbuf.data(), zbuf.size()), 0);
EXPECT_EQ(memcmp(rbuf.data() + kPageSize / 2, buf.data(), kPageSize / 2), 0);
}
TEST(SpliceTest, TwoPipes) {
// Create two new pipes.
int first[2], second[2];
ASSERT_THAT(pipe(first), SyscallSucceeds());
const FileDescriptor rfd1(first[0]);
const FileDescriptor wfd1(first[1]);
ASSERT_THAT(pipe(second), SyscallSucceeds());
const FileDescriptor rfd2(second[0]);
const FileDescriptor wfd2(second[1]);
// Fill with some random data.
std::vector<char> buf(kPageSize);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(wfd1.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kPageSize));
// Splice to the second pipe, using two operations.
EXPECT_THAT(
splice(rfd1.get(), nullptr, wfd2.get(), nullptr, kPageSize / 2, 0),
SyscallSucceedsWithValue(kPageSize / 2));
EXPECT_THAT(
splice(rfd1.get(), nullptr, wfd2.get(), nullptr, kPageSize / 2, 0),
SyscallSucceedsWithValue(kPageSize / 2));
// Content should reflect the splice.
std::vector<char> rbuf(kPageSize);
ASSERT_THAT(read(rfd2.get(), rbuf.data(), rbuf.size()),
SyscallSucceedsWithValue(kPageSize));
EXPECT_EQ(memcmp(rbuf.data(), buf.data(), kPageSize), 0);
}
TEST(SpliceTest, TwoPipesPartialRead) {
// Create two pipes.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor first_rfd(fds[0]);
const FileDescriptor first_wfd(fds[1]);
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor second_rfd(fds[0]);
const FileDescriptor second_wfd(fds[1]);
// Write half a page of data to the first pipe.
std::vector<char> buf(kPageSize / 2);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(first_wfd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kPageSize / 2));
// Attempt to splice one page from the first pipe to the second; it should
// immediately return after splicing the half-page previously written to the
// first pipe.
EXPECT_THAT(
splice(first_rfd.get(), nullptr, second_wfd.get(), nullptr, kPageSize, 0),
SyscallSucceedsWithValue(kPageSize / 2));
}
TEST(SpliceTest, TwoPipesPartialWrite) {
// Create two pipes.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor first_rfd(fds[0]);
const FileDescriptor first_wfd(fds[1]);
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor second_rfd(fds[0]);
const FileDescriptor second_wfd(fds[1]);
// Write two pages of data to the first pipe.
std::vector<char> buf(2 * kPageSize);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(first_wfd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(2 * kPageSize));
// Limit the second pipe to two pages, then write one page of data to it.
ASSERT_THAT(fcntl(second_wfd.get(), F_SETPIPE_SZ, 2 * kPageSize),
SyscallSucceeds());
ASSERT_THAT(write(second_wfd.get(), buf.data(), buf.size() / 2),
SyscallSucceedsWithValue(kPageSize));
// Attempt to splice two pages from the first pipe to the second; it should
// immediately return after splicing the first page previously written to the
// first pipe.
EXPECT_THAT(splice(first_rfd.get(), nullptr, second_wfd.get(), nullptr,
2 * kPageSize, 0),
SyscallSucceedsWithValue(kPageSize));
}
TEST(TeeTest, TwoPipesPartialRead) {
// Create two pipes.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor first_rfd(fds[0]);
const FileDescriptor first_wfd(fds[1]);
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor second_rfd(fds[0]);
const FileDescriptor second_wfd(fds[1]);
// Write half a page of data to the first pipe.
std::vector<char> buf(kPageSize / 2);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(first_wfd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kPageSize / 2));
// Attempt to tee one page from the first pipe to the second; it should
// immediately return after copying the half-page previously written to the
// first pipe.
EXPECT_THAT(tee(first_rfd.get(), second_wfd.get(), kPageSize, 0),
SyscallSucceedsWithValue(kPageSize / 2));
}
TEST(TeeTest, TwoPipesPartialWrite) {
// Create two pipes.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor first_rfd(fds[0]);
const FileDescriptor first_wfd(fds[1]);
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor second_rfd(fds[0]);
const FileDescriptor second_wfd(fds[1]);
// Write two pages of data to the first pipe.
std::vector<char> buf(2 * kPageSize);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(first_wfd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(2 * kPageSize));
// Limit the second pipe to two pages, then write one page of data to it.
ASSERT_THAT(fcntl(second_wfd.get(), F_SETPIPE_SZ, 2 * kPageSize),
SyscallSucceeds());
ASSERT_THAT(write(second_wfd.get(), buf.data(), buf.size() / 2),
SyscallSucceedsWithValue(kPageSize));
// Attempt to tee two pages from the first pipe to the second; it should
// immediately return after copying the first page previously written to the
// first pipe.
EXPECT_THAT(tee(first_rfd.get(), second_wfd.get(), 2 * kPageSize, 0),
SyscallSucceedsWithValue(kPageSize));
}
TEST(SpliceTest, TwoPipesCircular) {
// This test deadlocks the sentry on VFS1 because VFS1 splice ordering is
// based on fs.File.UniqueID, which does not prevent circular ordering between
// e.g. inode-level locks taken by fs.FileOperations.
SKIP_IF(IsRunningWithVFS1());
// Create two pipes.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor first_rfd(fds[0]);
const FileDescriptor first_wfd(fds[1]);
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor second_rfd(fds[0]);
const FileDescriptor second_wfd(fds[1]);
// On Linux, each pipe is normally limited to
// include/linux/pipe_fs_i.h:PIPE_DEF_BUFFERS buffers worth of data.
constexpr size_t PIPE_DEF_BUFFERS = 16;
// Write some data to each pipe. Below we splice 1 byte at a time between
// pipes, which very quickly causes each byte to be stored in a separate
// buffer, so we must ensure that the total amount of data in the system is <=
// PIPE_DEF_BUFFERS bytes.
std::vector<char> buf(PIPE_DEF_BUFFERS / 2);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(first_wfd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(buf.size()));
ASSERT_THAT(write(second_wfd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(buf.size()));
// Have another thread splice from the second pipe to the first, while we
// splice from the first to the second. The test passes if this does not
// deadlock.
const int kIterations = 1000;
DisableSave ds;
ScopedThread t([&]() {
for (int i = 0; i < kIterations; i++) {
ASSERT_THAT(
splice(second_rfd.get(), nullptr, first_wfd.get(), nullptr, 1, 0),
SyscallSucceedsWithValue(1));
}
});
for (int i = 0; i < kIterations; i++) {
ASSERT_THAT(
splice(first_rfd.get(), nullptr, second_wfd.get(), nullptr, 1, 0),
SyscallSucceedsWithValue(1));
}
}
TEST(SpliceTest, Blocking) {
// Create two new pipes.
int first[2], second[2];
ASSERT_THAT(pipe(first), SyscallSucceeds());
const FileDescriptor rfd1(first[0]);
const FileDescriptor wfd1(first[1]);
ASSERT_THAT(pipe(second), SyscallSucceeds());
const FileDescriptor rfd2(second[0]);
const FileDescriptor wfd2(second[1]);
// This thread writes to the main pipe.
std::vector<char> buf(kPageSize);
RandomizeBuffer(buf.data(), buf.size());
ScopedThread t([&]() {
ASSERT_THAT(write(wfd1.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kPageSize));
});
// Attempt a splice immediately; it should block.
EXPECT_THAT(splice(rfd1.get(), nullptr, wfd2.get(), nullptr, kPageSize, 0),
SyscallSucceedsWithValue(kPageSize));
// Thread should be joinable.
t.Join();
// Content should reflect the splice.
std::vector<char> rbuf(kPageSize);
ASSERT_THAT(read(rfd2.get(), rbuf.data(), rbuf.size()),
SyscallSucceedsWithValue(kPageSize));
EXPECT_EQ(memcmp(rbuf.data(), buf.data(), kPageSize), 0);
}
TEST(TeeTest, Blocking) {
// Create two new pipes.
int first[2], second[2];
ASSERT_THAT(pipe(first), SyscallSucceeds());
const FileDescriptor rfd1(first[0]);
const FileDescriptor wfd1(first[1]);
ASSERT_THAT(pipe(second), SyscallSucceeds());
const FileDescriptor rfd2(second[0]);
const FileDescriptor wfd2(second[1]);
// This thread writes to the main pipe.
std::vector<char> buf(kPageSize);
RandomizeBuffer(buf.data(), buf.size());
ScopedThread t([&]() {
ASSERT_THAT(write(wfd1.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kPageSize));
});
// Attempt a tee immediately; it should block.
EXPECT_THAT(tee(rfd1.get(), wfd2.get(), kPageSize, 0),
SyscallSucceedsWithValue(kPageSize));
// Thread should be joinable.
t.Join();
// Content should reflect the splice, in both pipes.
std::vector<char> rbuf(kPageSize);
ASSERT_THAT(read(rfd2.get(), rbuf.data(), rbuf.size()),
SyscallSucceedsWithValue(kPageSize));
EXPECT_EQ(memcmp(rbuf.data(), buf.data(), kPageSize), 0);
ASSERT_THAT(read(rfd1.get(), rbuf.data(), rbuf.size()),
SyscallSucceedsWithValue(kPageSize));
EXPECT_EQ(memcmp(rbuf.data(), buf.data(), kPageSize), 0);
}
TEST(TeeTest, BlockingWrite) {
// Create two new pipes.
int first[2], second[2];
ASSERT_THAT(pipe(first), SyscallSucceeds());
const FileDescriptor rfd1(first[0]);
const FileDescriptor wfd1(first[1]);
ASSERT_THAT(pipe(second), SyscallSucceeds());
const FileDescriptor rfd2(second[0]);
const FileDescriptor wfd2(second[1]);
// Make some data available to be read.
std::vector<char> buf1(kPageSize);
RandomizeBuffer(buf1.data(), buf1.size());
ASSERT_THAT(write(wfd1.get(), buf1.data(), buf1.size()),
SyscallSucceedsWithValue(kPageSize));
// Fill up the write pipe's buffer.
int pipe_size = -1;
ASSERT_THAT(pipe_size = fcntl(wfd2.get(), F_GETPIPE_SZ), SyscallSucceeds());
std::vector<char> buf2(pipe_size);
ASSERT_THAT(write(wfd2.get(), buf2.data(), buf2.size()),
SyscallSucceedsWithValue(pipe_size));
ScopedThread t([&]() {
absl::SleepFor(absl::Milliseconds(100));
ASSERT_THAT(read(rfd2.get(), buf2.data(), buf2.size()),
SyscallSucceedsWithValue(pipe_size));
});
// Attempt a tee immediately; it should block.
EXPECT_THAT(tee(rfd1.get(), wfd2.get(), kPageSize, 0),
SyscallSucceedsWithValue(kPageSize));
// Thread should be joinable.
t.Join();
// Content should reflect the tee.
std::vector<char> rbuf(kPageSize);
ASSERT_THAT(read(rfd2.get(), rbuf.data(), rbuf.size()),
SyscallSucceedsWithValue(kPageSize));
EXPECT_EQ(memcmp(rbuf.data(), buf1.data(), kPageSize), 0);
}
TEST(SpliceTest, NonBlocking) {
// Create two new pipes.
int first[2], second[2];
ASSERT_THAT(pipe(first), SyscallSucceeds());
const FileDescriptor rfd1(first[0]);
const FileDescriptor wfd1(first[1]);
ASSERT_THAT(pipe(second), SyscallSucceeds());
const FileDescriptor rfd2(second[0]);
const FileDescriptor wfd2(second[1]);
// Splice with no data to back it.
EXPECT_THAT(splice(rfd1.get(), nullptr, wfd2.get(), nullptr, kPageSize,
SPLICE_F_NONBLOCK),
SyscallFailsWithErrno(EAGAIN));
}
TEST(TeeTest, NonBlocking) {
// Create two new pipes.
int first[2], second[2];
ASSERT_THAT(pipe(first), SyscallSucceeds());
const FileDescriptor rfd1(first[0]);
const FileDescriptor wfd1(first[1]);
ASSERT_THAT(pipe(second), SyscallSucceeds());
const FileDescriptor rfd2(second[0]);
const FileDescriptor wfd2(second[1]);
// Splice with no data to back it.
EXPECT_THAT(tee(rfd1.get(), wfd2.get(), kPageSize, SPLICE_F_NONBLOCK),
SyscallFailsWithErrno(EAGAIN));
}
TEST(TeeTest, MultiPage) {
// Create two new pipes.
int first[2], second[2];
ASSERT_THAT(pipe(first), SyscallSucceeds());
const FileDescriptor rfd1(first[0]);
const FileDescriptor wfd1(first[1]);
ASSERT_THAT(pipe(second), SyscallSucceeds());
const FileDescriptor rfd2(second[0]);
const FileDescriptor wfd2(second[1]);
// Make some data available to be read.
std::vector<char> wbuf(8 * kPageSize);
RandomizeBuffer(wbuf.data(), wbuf.size());
ASSERT_THAT(write(wfd1.get(), wbuf.data(), wbuf.size()),
SyscallSucceedsWithValue(wbuf.size()));
// Attempt a tee immediately; it should complete.
EXPECT_THAT(tee(rfd1.get(), wfd2.get(), wbuf.size(), 0),
SyscallSucceedsWithValue(wbuf.size()));
// Content should reflect the tee.
std::vector<char> rbuf(wbuf.size());
ASSERT_THAT(read(rfd2.get(), rbuf.data(), rbuf.size()),
SyscallSucceedsWithValue(rbuf.size()));
EXPECT_EQ(memcmp(rbuf.data(), wbuf.data(), rbuf.size()), 0);
ASSERT_THAT(read(rfd1.get(), rbuf.data(), rbuf.size()),
SyscallSucceedsWithValue(rbuf.size()));
EXPECT_EQ(memcmp(rbuf.data(), wbuf.data(), rbuf.size()), 0);
}
TEST(SpliceTest, FromPipeMaxFileSize) {
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
const FileDescriptor wfd(fds[1]);
// Fill with some random data.
std::vector<char> buf(kPageSize);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(wfd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kPageSize));
// Open the input file.
const TempPath out_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
const FileDescriptor out_fd =
ASSERT_NO_ERRNO_AND_VALUE(Open(out_file.path(), O_RDWR));
EXPECT_THAT(ftruncate(out_fd.get(), 13 << 20), SyscallSucceeds());
EXPECT_THAT(lseek(out_fd.get(), 0, SEEK_END),
SyscallSucceedsWithValue(13 << 20));
// Set our file size limit.
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGXFSZ);
TEST_PCHECK(sigprocmask(SIG_BLOCK, &set, nullptr) == 0);
rlimit rlim = {};
rlim.rlim_cur = rlim.rlim_max = (13 << 20);
EXPECT_THAT(setrlimit(RLIMIT_FSIZE, &rlim), SyscallSucceeds());
// Splice to the output file.
EXPECT_THAT(
splice(rfd.get(), nullptr, out_fd.get(), nullptr, 3 * kPageSize, 0),
SyscallFailsWithErrno(EFBIG));
// Contents should be equal.
std::vector<char> rbuf(kPageSize);
ASSERT_THAT(read(rfd.get(), rbuf.data(), rbuf.size()),
SyscallSucceedsWithValue(kPageSize));
EXPECT_EQ(memcmp(rbuf.data(), buf.data(), buf.size()), 0);
}
TEST(SpliceTest, FromPipeToDevZero) {
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
FileDescriptor wfd(fds[1]);
// Fill with some random data.
std::vector<char> buf(kPageSize);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(wfd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kPageSize));
const FileDescriptor zero =
ASSERT_NO_ERRNO_AND_VALUE(Open("/dev/zero", O_WRONLY));
// Close the write end to prevent blocking below.
wfd.reset();
// Splice to /dev/zero. The first call should empty the pipe, and the return
// value should not exceed the number of bytes available for reading.
EXPECT_THAT(
splice(rfd.get(), nullptr, zero.get(), nullptr, kPageSize + 123, 0),
SyscallSucceedsWithValue(kPageSize));
EXPECT_THAT(splice(rfd.get(), nullptr, zero.get(), nullptr, 1, 0),
SyscallSucceedsWithValue(0));
}
static volatile int signaled = 0;
void SigUsr1Handler(int sig, siginfo_t* info, void* context) { signaled = 1; }
TEST(SpliceTest, ToPipeWithSmallCapacityDoesNotSpin) {
// Writes to a pipe that are less than PIPE_BUF must be atomic. This test
// creates a pipe with only 128 bytes of capacity (< PIPE_BUF) and checks that
// splicing to the pipe does not spin. See b/170743336.
// Create a file with one page of data.
std::vector<char> buf(kPageSize);
RandomizeBuffer(buf.data(), buf.size());
auto file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(
GetAbsoluteTestTmpdir(), absl::string_view(buf.data(), buf.size()),
TempPath::kDefaultFileMode));
auto fd = ASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDONLY));
// Create a pipe with size 4096, and fill all but 128 bytes of it.
int p[2];
ASSERT_THAT(pipe(p), SyscallSucceeds());
ASSERT_THAT(fcntl(p[1], F_SETPIPE_SZ, kPageSize), SyscallSucceeds());
const int kWriteSize = kPageSize - 128;
std::vector<char> writeBuf(kWriteSize);
RandomizeBuffer(writeBuf.data(), writeBuf.size());
ASSERT_THAT(write(p[1], writeBuf.data(), writeBuf.size()),
SyscallSucceedsWithValue(kWriteSize));
// Set up signal handler.
struct sigaction sa = {};
sa.sa_sigaction = SigUsr1Handler;
sa.sa_flags = SA_SIGINFO;
const auto cleanup_sigact =
ASSERT_NO_ERRNO_AND_VALUE(ScopedSigaction(SIGUSR1, sa));
// Send SIGUSR1 to this thread in 1 second.
struct sigevent sev = {};
sev.sigev_notify = SIGEV_THREAD_ID;
sev.sigev_signo = SIGUSR1;
sev.sigev_notify_thread_id = gettid();
auto timer = ASSERT_NO_ERRNO_AND_VALUE(TimerCreate(CLOCK_MONOTONIC, sev));
struct itimerspec its = {};
its.it_value = absl::ToTimespec(absl::Seconds(1));
DisableSave ds; // Asserting an EINTR.
ASSERT_NO_ERRNO(timer.Set(0, its));
// Now splice the file to the pipe. This should block, but not spin, and
// should return EINTR because it is interrupted by the signal.
EXPECT_THAT(splice(fd.get(), nullptr, p[1], nullptr, kPageSize, 0),
SyscallFailsWithErrno(EINTR));
// Alarm should have been handled.
EXPECT_EQ(signaled, 1);
}
} // namespace
} // namespace testing
} // namespace gvisor
| 33,753
| 13,012
|
//===-- MipsMCExpr.cpp - Mips specific MC expression classes --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "MipsMCExpr.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCAssembler.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCObjectStreamer.h"
using namespace llvm;
#define DEBUG_TYPE "mipsmcexpr"
bool MipsMCExpr::isSupportedBinaryExpr(MCSymbolRefExpr::VariantKind VK,
const MCBinaryExpr *BE) {
switch (VK) {
case MCSymbolRefExpr::VK_Mips_ABS_LO:
case MCSymbolRefExpr::VK_Mips_ABS_HI:
case MCSymbolRefExpr::VK_Mips_HIGHER:
case MCSymbolRefExpr::VK_Mips_HIGHEST:
break;
default:
return false;
}
// We support expressions of the form "(sym1 binop1 sym2) binop2 const",
// where "binop2 const" is optional.
if (isa<MCBinaryExpr>(BE->getLHS())) {
if (!isa<MCConstantExpr>(BE->getRHS()))
return false;
BE = cast<MCBinaryExpr>(BE->getLHS());
}
return (isa<MCSymbolRefExpr>(BE->getLHS())
&& isa<MCSymbolRefExpr>(BE->getRHS()));
}
const MipsMCExpr*
MipsMCExpr::create(MCSymbolRefExpr::VariantKind VK, const MCExpr *Expr,
MCContext &Ctx) {
VariantKind Kind;
switch (VK) {
case MCSymbolRefExpr::VK_Mips_ABS_LO:
Kind = VK_Mips_LO;
break;
case MCSymbolRefExpr::VK_Mips_ABS_HI:
Kind = VK_Mips_HI;
break;
case MCSymbolRefExpr::VK_Mips_HIGHER:
Kind = VK_Mips_HIGHER;
break;
case MCSymbolRefExpr::VK_Mips_HIGHEST:
Kind = VK_Mips_HIGHEST;
break;
default:
llvm_unreachable("Invalid kind!");
}
return new (Ctx) MipsMCExpr(Kind, Expr);
}
void MipsMCExpr::printImpl(raw_ostream &OS, const MCAsmInfo *MAI) const {
switch (Kind) {
default: llvm_unreachable("Invalid kind!");
case VK_Mips_LO: OS << "%lo"; break;
case VK_Mips_HI: OS << "%hi"; break;
case VK_Mips_HIGHER: OS << "%higher"; break;
case VK_Mips_HIGHEST: OS << "%highest"; break;
}
OS << '(';
Expr->print(OS, MAI);
OS << ')';
}
bool
MipsMCExpr::evaluateAsRelocatableImpl(MCValue &Res,
const MCAsmLayout *Layout,
const MCFixup *Fixup) const {
return getSubExpr()->evaluateAsRelocatable(Res, Layout, Fixup);
}
void MipsMCExpr::visitUsedExpr(MCStreamer &Streamer) const {
Streamer.visitUsedExpr(*getSubExpr());
}
| 2,582
| 971
|
/*
University of Bologna
First cicle degree in Computer Science
00819 - Programmazione
Luca Tagliavini #971133
04/27/2021
screen.cpp: implements engine's utility functions mainly to manipulate
integers and strings, for the choice ui element and the results menu
*/
#include "utils.hpp"
int Engine::Utils::digits(int n) {
int k = 0;
while (n > 0) {
k++;
n /= 10;
}
return k;
}
char Engine::Utils::digitize(int n) {
if (n > 9)
return u'-'; // undefined behaviour
return u'0' + n;
}
void Engine::Utils::stringify(int n, Nostd::String &str) {
if (n == 0)
str.insert(str.length(), u'0');
else {
if (n < 0) {
str.insert(0, u'-');
n = -n; // make it positive
}
int last = str.length();
while (n > 0) {
str.insert(last, digitize(n % 10));
n /= 10;
}
}
}
void Engine::Utils::leftpad(size_t n, Nostd::String &str) {
size_t len = str.length();
if (len > n) {
str = str.substr(0, n - 1);
} else if (len != n) {
size_t amount = n - len;
char space[amount + 1];
// fill the space string with the right amount of spaces
for (size_t i = 0; i < amount; i++)
space[i] = u' ';
space[amount] = '\0';
str.insert(0, space, amount);
}
}
| 1,258
| 496
|
/*
* Copyright (C) 2010 DiamondCore <http://diamondcore.eu/>
*
* 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 "Common.h"
#include "Database/DatabaseEnv.h"
#include "RealmList.h"
#include "Config/Config.h"
#include "Log.h"
#include "AuthSocket.h"
#include "SystemConfig.h"
#include "revision_nr.h"
#include "Util.h"
#include <openssl/opensslv.h>
#include <openssl/crypto.h>
#include <ace/Get_Opt.h>
#include <ace/Dev_Poll_Reactor.h>
#include <ace/ACE.h>
#include <ace/Acceptor.h>
#include <ace/SOCK_Acceptor.h>
#ifdef WIN32
#include "ServiceWin32.h"
char serviceName[] = "LogonServer";
char serviceLongName[] = "DiamondCore Realm service";
char serviceDescription[] = "Massive Network Game Object Server";
/*
* -1 - not in service mode
* 0 - stopped
* 1 - running
* 2 - paused
*/
int m_ServiceStatus = -1;
#endif
bool StartDB();
void UnhookSignals();
void HookSignals();
bool stopEvent = false; ///< Setting it to true stops the server
DatabaseType loginDatabase; ///< Accessor to the realm server database
/// Print out the usage string for this program on the console.
void usage(const char *prog)
{
sLog.outString("Usage: \n %s [<options>]\n"
" -v, --version print version and exist\n\r"
" -c config_file use config_file as configuration file\n\r"
#ifdef WIN32
" Running as service functions:\n\r"
" -s run run as service\n\r"
" -s install install service\n\r"
" -s uninstall uninstall service\n\r"
#endif
,prog);
}
/// Launch the realm server
extern int main(int argc, char **argv)
{
///- Command line parsing
char const* cfg_file = _LOGON_CONFIG;
#ifdef WIN32
char const *options = ":c:s:";
#else
char const *options = ":c:";
#endif
ACE_Get_Opt cmd_opts(argc, argv, options);
cmd_opts.long_option("version", 'v');
int option;
while ((option = cmd_opts()) != EOF)
{
switch (option)
{
case 'c':
cfg_file = cmd_opts.opt_arg();
break;
case 'v':
printf("%s\n", _FULLVERSION);
return 0;
#ifdef WIN32
case 's':
{
const char *mode = cmd_opts.opt_arg();
if (!strcmp(mode, "install"))
{
if (WinServiceInstall())
sLog.outString("Installing service");
return 1;
}
else if (!strcmp(mode, "uninstall"))
{
if (WinServiceUninstall())
sLog.outString("Uninstalling service");
return 1;
}
else if (!strcmp(mode, "run"))
WinServiceRun();
else
{
sLog.outError("Runtime-Error: -%c unsupported argument %s", cmd_opts.opt_opt(), mode);
usage(argv[0]);
Log::WaitBeforeContinueIfNeed();
return 1;
}
break;
}
#endif
case ':':
sLog.outError("Runtime-Error: -%c option requires an input argument", cmd_opts.opt_opt());
usage(argv[0]);
return 1;
default:
sLog.outError("Runtime-Error: bad format of commandline arguments");
usage(argv[0]);
return 1;
}
}
if (!sConfig.SetSource(cfg_file))
{
sLog.outError("Could not find configuration file %s.", cfg_file);
return 1;
}
sLog.Initialize();
sLog.outString( "%s [realm-daemon]", _FULLVERSION);
sLog.outString( "<Ctrl-C> to stop.\n" );
sLog.outString("Using configuration file %s.", cfg_file);
///- Check the version of the configuration file
uint32 confVersion = sConfig.GetIntDefault("ConfVersion", 0);
if (confVersion < _LOGONCONFVERSION)
{
sLog.outError("*****************************************************************************");
sLog.outError(" WARNING: Your LogonServer.conf version indicates your conf file is out of date!");
sLog.outError(" Please check for updates, as your current default values may cause");
sLog.outError(" strange behavior.");
sLog.outError("*****************************************************************************");
clock_t pause = 3000 + clock();
while (pause > clock())
{
}
}
sLog.outDetail("%s (Library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION));
if (SSLeay() < 0x009080bfL)
{
sLog.outDetail("WARNING: Outdated version of OpenSSL lib. Logins to server may not work!");
sLog.outDetail("WARNING: Minimal required version [OpenSSL 0.9.8k]");
}
#if defined (ACE_HAS_EVENT_POLL) || defined (ACE_HAS_DEV_POLL)
ACE_Reactor::instance(new ACE_Reactor(new ACE_Dev_Poll_Reactor(ACE::max_handles(), 1), 1), true);
#endif
sLog.outBasic("Max allowed open files is %d", ACE::max_handles());
/// LogonServer PID file creation
std::string pidfile = sConfig.GetStringDefault("PidFile", "");
if (!pidfile.empty())
{
uint32 pid = CreatePIDFile(pidfile);
if (!pid )
{
sLog.outError( "Cannot create PID file %s.\n", pidfile.c_str());
return 1;
}
sLog.outString("Daemon PID: %u\n", pid );
}
///- Initialize the database connection
if (!StartDB())
return 1;
///- Get the list of realms for the server
sRealmList.Initialize(sConfig.GetIntDefault("RealmsStateUpdateDelay", 20));
if (sRealmList.size() == 0)
{
sLog.outError("No valid realms specified.");
return 1;
}
// cleanup query
// set expired bans to inactive
loginDatabase.Execute("UPDATE account_banned SET active = 0 WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
///- Launch the listening network socket
ACE_Acceptor<AuthSocket, ACE_SOCK_Acceptor> acceptor;
uint16 rmport = sConfig.GetIntDefault("RealmServerPort", DEFAULT_REALMSERVER_PORT);
std::string bind_ip = sConfig.GetStringDefault("BindIP", "0.0.0.0");
ACE_INET_Addr bind_addr(rmport, bind_ip.c_str());
if(acceptor.open(bind_addr, ACE_Reactor::instance(), ACE_NONBLOCK) == -1)
{
sLog.outError("LogonServer can not bind to %s:%d", bind_ip.c_str(), rmport);
return 1;
}
///- Catch termination signals
HookSignals();
///- Handle affinity for multiple processors and process priority on Windows
#ifdef WIN32
{
HANDLE hProcess = GetCurrentProcess();
uint32 Aff = sConfig.GetIntDefault("UseProcessors", 0);
if (Aff > 0)
{
ULONG_PTR appAff;
ULONG_PTR sysAff;
if (GetProcessAffinityMask(hProcess, &appAff, &sysAff))
{
ULONG_PTR curAff = Aff & appAff; // remove non accessible processors
if (!curAff)
{
sLog.outError("Processors marked in UseProcessors bitmask (hex) %x not accessible for realmd. Accessible processors bitmask (hex): %x", Aff,appAff);
}
else
{
if (SetProcessAffinityMask(hProcess, curAff))
sLog.outString("Using processors (bitmask, hex): %x", curAff);
else
sLog.outError("Can't set used processors (hex): %x", curAff);
}
}
sLog.outString();
}
bool Prio = sConfig.GetBoolDefault("ProcessPriority", false);
if (Prio)
{
if (SetPriorityClass(hProcess,HIGH_PRIORITY_CLASS))
sLog.outString("LogonServer process priority class set to HIGH");
else
sLog.outError("ERROR: Can't set LogonServer process priority class.");
}
}
#endif
// maximum counter for next ping
uint32 numLoops = (sConfig.GetIntDefault("MaxPingTime", 30) * (MINUTE * 1000000 / 100000));
uint32 loopCounter = 0;
///- Wait for termination signal
while (!stopEvent)
{
// dont move this outside the loop, the reactor will modify it
ACE_Time_Value interval(0, 100000);
if (ACE_Reactor::instance()->run_reactor_event_loop(interval) == -1)
break;
if ((++loopCounter) == numLoops)
{
loopCounter = 0;
sLog.outDetail("Ping MySQL to keep connection alive");
delete loginDatabase.Query("SELECT 1 FROM realmlist LIMIT 1");
}
#ifdef WIN32
if (m_ServiceStatus == 0)
stopEvent = true;
while (m_ServiceStatus == 2)
Sleep(1000);
#endif
}
///- Wait for the delay thread to exit
loginDatabase.HaltDelayThread();
///- Remove signal handling before leaving
UnhookSignals();
sLog.outString("Halting process...");
return 0;
}
/// Handle termination signals
/** Put the global variable stopEvent to 'true' if a termination signal is caught **/
void OnSignal(int s)
{
switch (s)
{
case SIGINT:
case SIGTERM:
stopEvent = true;
break;
#ifdef _WIN32
case SIGBREAK:
stopEvent = true;
break;
#endif
}
signal(s, OnSignal);
}
/// Initialize connection to the database
bool StartDB()
{
std::string dbstring = sConfig.GetStringDefault("LoginDatabaseInfo", "");
if (dbstring.empty())
{
sLog.outError("Database not specified");
return false;
}
sLog.outString("Database: %s", dbstring.c_str() );
if (!loginDatabase.Initialize(dbstring.c_str()))
{
sLog.outError("Cannot connect to database");
return false;
}
return true;
}
/// Define hook 'OnSignal' for all termination signals
void HookSignals()
{
signal(SIGINT, OnSignal);
signal(SIGTERM, OnSignal);
#ifdef _WIN32
signal(SIGBREAK, OnSignal);
#endif
}
/// Unhook the signals before leaving
void UnhookSignals()
{
signal(SIGINT, 0);
signal(SIGTERM, 0);
#ifdef _WIN32
signal(SIGBREAK, 0);
#endif
}
/// @}
| 11,186
| 3,481
|
/* -----------------------------------------------------------------------------
Software License for The Fraunhofer FDK AAC Codec Library for Android
© Copyright 1995 - 2019 Fraunhofer-Gesellschaft zur Förderung der angewandten
Forschung e.V. All rights reserved.
1. INTRODUCTION
The Fraunhofer FDK AAC Codec Library for Android ("FDK AAC Codec") is software
that implements the MPEG Advanced Audio Coding ("AAC") encoding and decoding
scheme for digital audio. This FDK AAC Codec software is intended to be used on
a wide variety of Android devices.
AAC's HE-AAC and HE-AAC v2 versions are regarded as today's most efficient
general perceptual audio codecs. AAC-ELD is considered the best-performing
full-bandwidth communications codec by independent studies and is widely
deployed. AAC has been standardized by ISO and IEC as part of the MPEG
specifications.
Patent licenses for necessary patent claims for the FDK AAC Codec (including
those of Fraunhofer) may be obtained through Via Licensing
(www.vialicensing.com) or through the respective patent owners individually for
the purpose of encoding or decoding bit streams in products that are compliant
with the ISO/IEC MPEG audio standards. Please note that most manufacturers of
Android devices already license these patent claims through Via Licensing or
directly from the patent owners, and therefore FDK AAC Codec software may
already be covered under those patent licenses when it is used for those
licensed purposes only.
Commercially-licensed AAC software libraries, including floating-point versions
with enhanced sound quality, are also available from Fraunhofer. Users are
encouraged to check the Fraunhofer website for additional applications
information and documentation.
2. COPYRIGHT LICENSE
Redistribution and use in source and binary forms, with or without modification,
are permitted without payment of copyright license fees provided that you
satisfy the following conditions:
You must retain the complete text of this software license in redistributions of
the FDK AAC Codec or your modifications thereto in source code form.
You must retain the complete text of this software license in the documentation
and/or other materials provided with redistributions of the FDK AAC Codec or
your modifications thereto in binary form. You must make available free of
charge copies of the complete source code of the FDK AAC Codec and your
modifications thereto to recipients of copies in binary form.
The name of Fraunhofer may not be used to endorse or promote products derived
from this library without prior written permission.
You may not charge copyright license fees for anyone to use, copy or distribute
the FDK AAC Codec software or your modifications thereto.
Your modified versions of the FDK AAC Codec must carry prominent notices stating
that you changed the software and the date of any change. For modified versions
of the FDK AAC Codec, the term "Fraunhofer FDK AAC Codec Library for Android"
must be replaced by the term "Third-Party Modified Version of the Fraunhofer FDK
AAC Codec Library for Android."
3. NO PATENT LICENSE
NO EXPRESS OR IMPLIED LICENSES TO ANY PATENT CLAIMS, including without
limitation the patents of Fraunhofer, ARE GRANTED BY THIS SOFTWARE LICENSE.
Fraunhofer provides no warranty of patent non-infringement with respect to this
software.
You may use this FDK AAC Codec software or modifications thereto only for
purposes that are authorized by appropriate patent licenses.
4. DISCLAIMER
This FDK AAC Codec software is provided by Fraunhofer on behalf of the copyright
holders and contributors "AS IS" and WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES,
including but not limited to the implied warranties of merchantability and
fitness for a particular purpose. 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), arising in any way out of the use of
this software, even if advised of the possibility of such damage.
5. CONTACT INFORMATION
Fraunhofer Institute for Integrated Circuits IIS
Attention: Audio and Multimedia Departments - FDK AAC LL
Am Wolfsmantel 33
91058 Erlangen, Germany
www.iis.fraunhofer.de/amm
amm-info@iis.fraunhofer.de
----------------------------------------------------------------------------- */
/******************* Library for basic calculation routines ********************
Author(s): Josef Hoepfl, Manuel Jander, Youliy Ninov, Daniel Hagel
Description: MDCT/MDST routines
*******************************************************************************/
#include "mdct.h"
#include "FDK_tools_rom.h"
#include "dct.h"
#include "fixpoint_math.h"
void mdct_init(H_MDCT hMdct, FIXP_DBL *overlap, INT overlapBufferSize) {
hMdct->overlap.freq = overlap;
// FDKmemclear(overlap, overlapBufferSize*sizeof(FIXP_DBL));
hMdct->prev_fr = 0;
hMdct->prev_nr = 0;
hMdct->prev_tl = 0;
hMdct->ov_size = overlapBufferSize;
hMdct->prevAliasSymmetry = 0;
hMdct->prevPrevAliasSymmetry = 0;
hMdct->pFacZir = NULL;
hMdct->pAsymOvlp = NULL;
}
/*
This program implements the forward MDCT transform on an input block of data.
The input block is in a form (A,B,C,D) where A,B,C and D are the respective
1/4th segments of the block. The program takes the input block and folds it in
the form:
(-D-Cr,A-Br). This block is twice shorter and here the 'r' suffix denotes
flipping of the sequence (reversing the order of the samples). While folding the
input block in the above mentioned shorter block the program windows the data.
Because the two operations (windowing and folding) are not implemented
sequentially, but together the program's structure is not easy to understand.
Once the output (already windowed) block (-D-Cr,A-Br) is ready it is passed to
the DCT IV for processing.
*/
INT mdct_block(H_MDCT hMdct, const INT_PCM *RESTRICT timeData,
const INT noInSamples, FIXP_DBL *RESTRICT mdctData,
const INT nSpec, const INT tl, const FIXP_WTP *pRightWindowPart,
const INT fr, SHORT *pMdctData_e) {
int i, n;
/* tl: transform length
fl: left window slope length
nl: left window slope offset
fr: right window slope length
nr: right window slope offset
See FDK_tools/doc/intern/mdct.tex for more detail. */
int fl, nl, nr;
const FIXP_WTP *wls, *wrs;
wrs = pRightWindowPart;
/* Detect FRprevious / FL mismatches and override parameters accordingly */
if (hMdct->prev_fr ==
0) { /* At start just initialize and pass parameters as they are */
hMdct->prev_fr = fr;
hMdct->prev_wrs = wrs;
hMdct->prev_tl = tl;
}
/* Derive NR */
nr = (tl - fr) >> 1;
/* Skip input samples if tl is smaller than block size */
timeData += (noInSamples - tl) >> 1;
/* windowing */
for (n = 0; n < nSpec; n++) {
/*
* MDCT scale:
* + 1: fMultDiv2() in windowing.
* + 1: Because of factor 1/2 in Princen-Bradley compliant windowed TDAC.
*/
INT mdctData_e = 1 + 1;
/* Derive left parameters */
wls = hMdct->prev_wrs;
fl = hMdct->prev_fr;
nl = (tl - fl) >> 1;
/* Here we implement a simplified version of what happens after the this
piece of code (see the comments below). We implement the folding of A and B
segments to (A-Br) but A is zero, because in this part of the MDCT sequence
the window coefficients with which A must be multiplied are zero. */
for (i = 0; i < nl; i++) {
#if SAMPLE_BITS == DFRACT_BITS /* SPC_BITS and DFRACT_BITS should be equal. */
mdctData[(tl / 2) + i] = -((FIXP_DBL)timeData[tl - i - 1] >> (1));
#else
mdctData[(tl / 2) + i] = -(FIXP_DBL)timeData[tl - i - 1]
<< (DFRACT_BITS - SAMPLE_BITS - 1); /* 0(A)-Br */
#endif
}
/* Implements the folding and windowing of the left part of the sequence,
that is segments A and B. The A segment is multiplied by the respective left
window coefficient and placed in a temporary variable.
tmp0 = fMultDiv2((FIXP_PCM)timeData[i+nl], pLeftWindowPart[i].v.im);
After this the B segment taken in reverse order is multiplied by the left
window and subtracted from the previously derived temporary variable, so
that finally we implement the A-Br operation. This output is written to the
right part of the MDCT output : (-D-Cr,A-Br).
mdctData[(tl/2)+i+nl] = fMultSubDiv2(tmp0, (FIXP_PCM)timeData[tl-nl-i-1],
pLeftWindowPart[i].v.re);//A*window-Br*window
The (A-Br) data is written to the output buffer (mdctData) without being
flipped. */
for (i = 0; i < fl / 2; i++) {
FIXP_DBL tmp0;
tmp0 = fMultDiv2((FIXP_PCM)timeData[i + nl], wls[i].v.im); /* a*window */
mdctData[(tl / 2) + i + nl] =
fMultSubDiv2(tmp0, (FIXP_PCM)timeData[tl - nl - i - 1],
wls[i].v.re); /* A*window-Br*window */
}
/* Right window slope offset */
/* Here we implement a simplified version of what happens after the this
piece of code (see the comments below). We implement the folding of C and D
segments to (-D-Cr) but D is zero, because in this part of the MDCT sequence
the window coefficients with which D must be multiplied are zero. */
for (i = 0; i < nr; i++) {
#if SAMPLE_BITS == \
DFRACT_BITS /* This should be SPC_BITS instead of DFRACT_BITS. */
mdctData[(tl / 2) - 1 - i] = -((FIXP_DBL)timeData[tl + i] >> (1));
#else
mdctData[(tl / 2) - 1 - i] =
-(FIXP_DBL)timeData[tl + i]
<< (DFRACT_BITS - SAMPLE_BITS - 1); /* -C flipped at placing */
#endif
}
/* Implements the folding and windowing of the right part of the sequence,
that is, segments C and D. The C segment is multiplied by the respective
right window coefficient and placed in a temporary variable.
tmp1 = fMultDiv2((FIXP_PCM)timeData[tl+nr+i], pRightWindowPart[i].v.re);
After this the D segment taken in reverse order is multiplied by the right
window and added from the previously derived temporary variable, so that we
get (C+Dr) operation. This output is negated to get (-C-Dr) and written to
the left part of the MDCT output while being reversed (flipped) at the same
time, so that from (-C-Dr) we get (-D-Cr)=> (-D-Cr,A-Br).
mdctData[(tl/2)-nr-i-1] = -fMultAddDiv2(tmp1,
(FIXP_PCM)timeData[(tl*2)-nr-i-1], pRightWindowPart[i].v.im);*/
for (i = 0; i < fr / 2; i++) {
FIXP_DBL tmp1;
tmp1 = fMultDiv2((FIXP_PCM)timeData[tl + nr + i],
wrs[i].v.re); /* C*window */
mdctData[(tl / 2) - nr - i - 1] =
-fMultAddDiv2(tmp1, (FIXP_PCM)timeData[(tl * 2) - nr - i - 1],
wrs[i].v.im); /* -(C*window+Dr*window) and flip before
placing -> -Cr - D */
}
/* We pass the shortened folded data (-D-Cr,A-Br) to the MDCT function */
dct_IV(mdctData, tl, &mdctData_e);
pMdctData_e[n] = (SHORT)mdctData_e;
timeData += tl;
mdctData += tl;
hMdct->prev_wrs = wrs;
hMdct->prev_fr = fr;
hMdct->prev_tl = tl;
}
return nSpec * tl;
}
void imdct_gain(FIXP_DBL *pGain_m, int *pGain_e, int tl) {
FIXP_DBL gain_m = *pGain_m;
int gain_e = *pGain_e;
int log2_tl;
gain_e += -MDCT_OUTPUT_GAIN - MDCT_OUT_HEADROOM + 1;
if (tl == 0) {
/* Dont regard the 2/N factor from the IDCT. It is compensated for somewhere
* else. */
*pGain_e = gain_e;
return;
}
log2_tl = DFRACT_BITS - 1 - fNormz((FIXP_DBL)tl);
gain_e += -log2_tl;
FDK_ASSERT(log2_tl - 2 >= 0);
FDK_ASSERT(log2_tl - 2 < 8*sizeof(int));
/* Detect non-radix 2 transform length and add amplitude compensation factor
which cannot be included into the exponent above */
switch ((tl) >> (log2_tl - 2)) {
case 0x7: /* 10 ms, 1/tl = 1.0/(FDKpow(2.0, -log2_tl) *
0.53333333333333333333) */
if (gain_m == (FIXP_DBL)0) {
gain_m = FL2FXCONST_DBL(0.53333333333333333333f);
} else {
gain_m = fMult(gain_m, FL2FXCONST_DBL(0.53333333333333333333f));
}
break;
case 0x6: /* 3/4 of radix 2, 1/tl = 1.0/(FDKpow(2.0, -log2_tl) * 2.0/3.0) */
if (gain_m == (FIXP_DBL)0) {
gain_m = FL2FXCONST_DBL(2.0 / 3.0f);
} else {
gain_m = fMult(gain_m, FL2FXCONST_DBL(2.0 / 3.0f));
}
break;
case 0x5: /* 0.8 of radix 2 (e.g. tl 160), 1/tl = 1.0/(FDKpow(2.0, -log2_tl)
* 0.8/1.5) */
if (gain_m == (FIXP_DBL)0) {
gain_m = FL2FXCONST_DBL(0.53333333333333333333f);
} else {
gain_m = fMult(gain_m, FL2FXCONST_DBL(0.53333333333333333333f));
}
break;
case 0x4:
/* radix 2, nothing to do. */
break;
default:
/* unsupported */
FDK_ASSERT(0);
break;
}
*pGain_m = gain_m;
*pGain_e = gain_e;
}
INT imdct_drain(H_MDCT hMdct, FIXP_DBL *output, INT nrSamplesRoom) {
int buffered_samples = 0;
if (nrSamplesRoom > 0) {
buffered_samples = hMdct->ov_offset;
FDK_ASSERT(buffered_samples <= nrSamplesRoom);
if (buffered_samples > 0) {
FDKmemcpy(output, hMdct->overlap.time,
buffered_samples * sizeof(FIXP_DBL));
hMdct->ov_offset = 0;
}
}
return buffered_samples;
}
INT imdct_copy_ov_and_nr(H_MDCT hMdct, FIXP_DBL *pTimeData, INT nrSamples) {
FIXP_DBL *pOvl;
int nt, nf, i;
nt = fMin(hMdct->ov_offset, nrSamples);
nrSamples -= nt;
nf = fMin(hMdct->prev_nr, nrSamples);
FDKmemcpy(pTimeData, hMdct->overlap.time, nt * sizeof(FIXP_DBL));
pTimeData += nt;
pOvl = hMdct->overlap.freq + hMdct->ov_size - 1;
if (hMdct->prevPrevAliasSymmetry == 0) {
for (i = 0; i < nf; i++) {
FIXP_DBL x = -(*pOvl--);
*pTimeData = IMDCT_SCALE_DBL(x);
pTimeData++;
}
} else {
for (i = 0; i < nf; i++) {
FIXP_DBL x = (*pOvl--);
*pTimeData = IMDCT_SCALE_DBL(x);
pTimeData++;
}
}
return (nt + nf);
}
void imdct_adapt_parameters(H_MDCT hMdct, int *pfl, int *pnl, int tl,
const FIXP_WTP *wls, int noOutSamples) {
int fl = *pfl, nl = *pnl;
int window_diff, use_current = 0, use_previous = 0;
if (hMdct->prev_tl == 0) {
hMdct->prev_wrs = wls;
hMdct->prev_fr = fl;
hMdct->prev_nr = (noOutSamples - fl) >> 1;
hMdct->prev_tl = noOutSamples;
hMdct->ov_offset = 0;
use_current = 1;
}
window_diff = (hMdct->prev_fr - fl) >> 1;
/* check if the previous window slope can be adjusted to match the current
* window slope */
if (hMdct->prev_nr + window_diff > 0) {
use_current = 1;
}
/* check if the current window slope can be adjusted to match the previous
* window slope */
if (nl - window_diff > 0) {
use_previous = 1;
}
/* if both is possible choose the larger of both window slope lengths */
if (use_current && use_previous) {
if (fl < hMdct->prev_fr) {
use_current = 0;
}
}
/*
* If the previous transform block is big enough, enlarge previous window
* overlap, if not, then shrink current window overlap.
*/
if (use_current) {
hMdct->prev_nr += window_diff;
hMdct->prev_fr = fl;
hMdct->prev_wrs = wls;
} else {
nl -= window_diff;
fl = hMdct->prev_fr;
}
*pfl = fl;
*pnl = nl;
}
/*
This program implements the inverse modulated lapped transform, a generalized
version of the inverse MDCT transform. Setting none of the MLT_*_ALIAS_FLAG
flags computes the IMDCT, setting all of them computes the IMDST. Other
combinations of these flags compute type III transforms used by the RSVD60
multichannel tool for transitions between MDCT/MDST. The following description
relates to the IMDCT only.
If we pass the data block (A,B,C,D,E,F) to the FORWARD MDCT it will produce two
outputs. The first one will be over the (A,B,C,D) part =>(-D-Cr,A-Br) and the
second one will be over the (C,D,E,F) part => (-F-Er,C-Dr), since there is a
overlap between consequtive passes of the algorithm. This overlap is over the
(C,D) segments. The two outputs will be given sequentially to the DCT IV
algorithm. At the INVERSE MDCT side we get two consecutive outputs from the IDCT
IV algorithm, namely the same blocks: (-D-Cr,A-Br) and (-F-Er,C-Dr). The first
of them lands in the Overlap buffer and the second is in the working one, which,
one algorithm pass later will substitute the one residing in the overlap
register. The IMDCT algorithm has to produce the C and D segments from the two
buffers. In order to do this we take the left part of the overlap
buffer(-D-Cr,A-Br), namely (-D-Cr) and add it appropriately to the right part of
the working buffer (-F-Er,C-Dr), namely (C-Dr), so that we get first the C
segment and later the D segment. We do this in the following way: From the right
part of the working buffer(C-Dr) we subtract the flipped left part of the
overlap buffer(-D-Cr):
Result = (C-Dr) - flipped(-D-Cr) = C -Dr + Dr + C = 2C
We divide by two and get the C segment. What we did is adding the right part of
the first frame to the left part of the second one. While applying these
operation we multiply the respective segments with the appropriate window
functions.
In order to get the D segment we do the following:
From the negated second part of the working buffer(C-Dr) we subtract the flipped
first part of the overlap buffer (-D-Cr):
Result= - (C -Dr) - flipped(-D-Cr)= -C +Dr +Dr +C = 2Dr.
After dividing by two and flipping we get the D segment.What we did is adding
the right part of the first frame to the left part of the second one. While
applying these operation we multiply the respective segments with the
appropriate window functions.
Once we have obtained the C and D segments the overlap buffer is emptied and the
current buffer is sent in it, so that the E and F segments are available for
decoding in the next algorithm pass.*/
INT imlt_block(H_MDCT hMdct, FIXP_DBL *output, FIXP_DBL *spectrum,
const SHORT scalefactor[], const INT nSpec,
const INT noOutSamples, const INT tl, const FIXP_WTP *wls,
INT fl, const FIXP_WTP *wrs, const INT fr, FIXP_DBL gain,
int flags) {
FIXP_DBL *pOvl;
FIXP_DBL *pOut0 = output, *pOut1;
INT nl, nr;
int w, i, nrSamples = 0, specShiftScale, transform_gain_e = 0;
int currAliasSymmetry = (flags & MLT_FLAG_CURR_ALIAS_SYMMETRY);
/* Derive NR and NL */
nr = (tl - fr) >> 1;
nl = (tl - fl) >> 1;
/* Include 2/N IMDCT gain into gain factor and exponent. */
imdct_gain(&gain, &transform_gain_e, tl);
/* Detect FRprevious / FL mismatches and override parameters accordingly */
if (hMdct->prev_fr != fl) {
imdct_adapt_parameters(hMdct, &fl, &nl, tl, wls, noOutSamples);
}
pOvl = hMdct->overlap.freq + hMdct->ov_size - 1;
if (noOutSamples > nrSamples) {
/* Purge buffered output. */
for (i = 0; i < hMdct->ov_offset; i++) {
*pOut0 = hMdct->overlap.time[i];
pOut0++;
}
nrSamples = hMdct->ov_offset;
hMdct->ov_offset = 0;
}
for (w = 0; w < nSpec; w++) {
FIXP_DBL *pSpec, *pCurr;
const FIXP_WTP *pWindow;
/* Detect FRprevious / FL mismatches and override parameters accordingly */
if (hMdct->prev_fr != fl) {
imdct_adapt_parameters(hMdct, &fl, &nl, tl, wls, noOutSamples);
}
specShiftScale = transform_gain_e;
/* Setup window pointers */
pWindow = hMdct->prev_wrs;
/* Current spectrum */
pSpec = spectrum + w * tl;
/* DCT IV of current spectrum. */
if (currAliasSymmetry == 0) {
if (hMdct->prevAliasSymmetry == 0) {
dct_IV(pSpec, tl, &specShiftScale);
} else {
FIXP_DBL _tmp[1024 + ALIGNMENT_DEFAULT / sizeof(FIXP_DBL)];
FIXP_DBL *tmp = (FIXP_DBL *)ALIGN_PTR(_tmp);
C_ALLOC_ALIGNED_REGISTER(tmp, sizeof(_tmp));
dct_III(pSpec, tmp, tl, &specShiftScale);
C_ALLOC_ALIGNED_UNREGISTER(tmp);
}
} else {
if (hMdct->prevAliasSymmetry == 0) {
FIXP_DBL _tmp[1024 + ALIGNMENT_DEFAULT / sizeof(FIXP_DBL)];
FIXP_DBL *tmp = (FIXP_DBL *)ALIGN_PTR(_tmp);
C_ALLOC_ALIGNED_REGISTER(tmp, sizeof(_tmp));
dst_III(pSpec, tmp, tl, &specShiftScale);
C_ALLOC_ALIGNED_UNREGISTER(tmp);
} else {
dst_IV(pSpec, tl, &specShiftScale);
}
}
/* Optional scaling of time domain - no yet windowed - of current spectrum
*/
/* and de-scale current spectrum signal (time domain, no yet windowed) */
if (gain != (FIXP_DBL)0) {
for (i = 0; i < tl; i++) {
pSpec[i] = fMult(pSpec[i], gain);
}
}
{
int loc_scale =
fixmin_I(scalefactor[w] + specShiftScale, (INT)DFRACT_BITS - 1);
DWORD_ALIGNED(pSpec);
scaleValuesSaturate(pSpec, tl, loc_scale);
}
if (noOutSamples <= nrSamples) {
/* Divert output first half to overlap buffer if we already got enough
* output samples. */
pOut0 = hMdct->overlap.time + hMdct->ov_offset;
hMdct->ov_offset += hMdct->prev_nr + fl / 2;
} else {
/* Account output samples */
nrSamples += hMdct->prev_nr + fl / 2;
}
/* NR output samples 0 .. NR. -overlap[TL/2..TL/2-NR] */
if ((hMdct->pFacZir != 0) && (hMdct->prev_nr == fl / 2)) {
/* In the case of ACELP -> TCX20 -> FD short add FAC ZIR on nr signal part
*/
for (i = 0; i < hMdct->prev_nr; i++) {
FIXP_DBL x = -(*pOvl--);
*pOut0 = fAddSaturate(x, IMDCT_SCALE_DBL(hMdct->pFacZir[i]));
pOut0++;
}
hMdct->pFacZir = NULL;
} else {
/* Here we implement a simplified version of what happens after the this
piece of code (see the comments below). We implement the folding of C and
D segments from (-D-Cr) but D is zero, because in this part of the MDCT
sequence the window coefficients with which D must be multiplied are zero.
"pOut0" writes sequentially the C block from left to right. */
if (hMdct->prevPrevAliasSymmetry == 0) {
for (i = 0; i < hMdct->prev_nr; i++) {
FIXP_DBL x = -(*pOvl--);
*pOut0 = IMDCT_SCALE_DBL(x);
pOut0++;
}
} else {
for (i = 0; i < hMdct->prev_nr; i++) {
FIXP_DBL x = *pOvl--;
*pOut0 = IMDCT_SCALE_DBL(x);
pOut0++;
}
}
}
if (noOutSamples <= nrSamples) {
/* Divert output second half to overlap buffer if we already got enough
* output samples. */
pOut1 = hMdct->overlap.time + hMdct->ov_offset + fl / 2 - 1;
hMdct->ov_offset += fl / 2 + nl;
} else {
pOut1 = pOut0 + (fl - 1);
nrSamples += fl / 2 + nl;
}
/* output samples before window crossing point NR .. TL/2.
* -overlap[TL/2-NR..TL/2-NR-FL/2] + current[NR..TL/2] */
/* output samples after window crossing point TL/2 .. TL/2+FL/2.
* -overlap[0..FL/2] - current[TL/2..FL/2] */
pCurr = pSpec + tl - fl / 2;
DWORD_ALIGNED(pCurr);
C_ALLOC_ALIGNED_REGISTER(pWindow, fl);
DWORD_ALIGNED(pWindow);
C_ALLOC_ALIGNED_UNREGISTER(pWindow);
if (hMdct->prevPrevAliasSymmetry == 0) {
if (hMdct->prevAliasSymmetry == 0) {
if (!hMdct->pAsymOvlp) {
for (i = 0; i < fl / 2; i++) {
FIXP_DBL x0, x1;
cplxMultDiv2(&x1, &x0, *pCurr++, -*pOvl--, pWindow[i]);
*pOut0 = IMDCT_SCALE_DBL_LSH1(x0);
*pOut1 = IMDCT_SCALE_DBL_LSH1(-x1);
pOut0++;
pOut1--;
}
} else {
FIXP_DBL *pAsymOvl = hMdct->pAsymOvlp + fl / 2 - 1;
for (i = 0; i < fl / 2; i++) {
FIXP_DBL x0, x1;
x1 = -fMultDiv2(*pCurr, pWindow[i].v.re) +
fMultDiv2(*pAsymOvl, pWindow[i].v.im);
x0 = fMultDiv2(*pCurr, pWindow[i].v.im) -
fMultDiv2(*pOvl, pWindow[i].v.re);
pCurr++;
pOvl--;
pAsymOvl--;
*pOut0++ = IMDCT_SCALE_DBL_LSH1(x0);
*pOut1-- = IMDCT_SCALE_DBL_LSH1(x1);
}
hMdct->pAsymOvlp = NULL;
}
} else { /* prevAliasingSymmetry == 1 */
for (i = 0; i < fl / 2; i++) {
FIXP_DBL x0, x1;
cplxMultDiv2(&x1, &x0, *pCurr++, -*pOvl--, pWindow[i]);
*pOut0 = IMDCT_SCALE_DBL_LSH1(x0);
*pOut1 = IMDCT_SCALE_DBL_LSH1(x1);
pOut0++;
pOut1--;
}
}
} else { /* prevPrevAliasingSymmetry == 1 */
if (hMdct->prevAliasSymmetry == 0) {
for (i = 0; i < fl / 2; i++) {
FIXP_DBL x0, x1;
cplxMultDiv2(&x1, &x0, *pCurr++, *pOvl--, pWindow[i]);
*pOut0 = IMDCT_SCALE_DBL_LSH1(x0);
*pOut1 = IMDCT_SCALE_DBL_LSH1(-x1);
pOut0++;
pOut1--;
}
} else { /* prevAliasingSymmetry == 1 */
for (i = 0; i < fl / 2; i++) {
FIXP_DBL x0, x1;
cplxMultDiv2(&x1, &x0, *pCurr++, *pOvl--, pWindow[i]);
*pOut0 = IMDCT_SCALE_DBL_LSH1(x0);
*pOut1 = IMDCT_SCALE_DBL_LSH1(x1);
pOut0++;
pOut1--;
}
}
}
if (hMdct->pFacZir != 0) {
/* add FAC ZIR of previous ACELP -> mdct transition */
FIXP_DBL *pOut = pOut0 - fl / 2;
FDK_ASSERT(fl / 2 <= 128);
for (i = 0; i < fl / 2; i++) {
pOut[i] = fAddSaturate(pOut[i], IMDCT_SCALE_DBL(hMdct->pFacZir[i]));
}
hMdct->pFacZir = NULL;
}
pOut0 += (fl / 2) + nl;
/* NL output samples TL/2+FL/2..TL. - current[FL/2..0] */
pOut1 += (fl / 2) + 1;
pCurr = pSpec + tl - fl / 2 - 1;
/* Here we implement a simplified version of what happens above the this
piece of code (see the comments above). We implement the folding of C and D
segments from (C-Dr) but C is zero, because in this part of the MDCT
sequence the window coefficients with which C must be multiplied are zero.
"pOut1" writes sequentially the D block from left to right. */
if (hMdct->prevAliasSymmetry == 0) {
for (i = 0; i < nl; i++) {
FIXP_DBL x = -(*pCurr--);
*pOut1++ = IMDCT_SCALE_DBL(x);
}
} else {
for (i = 0; i < nl; i++) {
FIXP_DBL x = *pCurr--;
*pOut1++ = IMDCT_SCALE_DBL(x);
}
}
/* Set overlap source pointer for next window pOvl = pSpec + tl/2 - 1; */
pOvl = pSpec + tl / 2 - 1;
/* Previous window values. */
hMdct->prev_nr = nr;
hMdct->prev_fr = fr;
hMdct->prev_tl = tl;
hMdct->prev_wrs = wrs;
/* Previous aliasing symmetry */
hMdct->prevPrevAliasSymmetry = hMdct->prevAliasSymmetry;
hMdct->prevAliasSymmetry = currAliasSymmetry;
}
/* Save overlap */
pOvl = hMdct->overlap.freq + hMdct->ov_size - tl / 2;
FDKmemcpy(pOvl, &spectrum[(nSpec - 1) * tl], (tl / 2) * sizeof(FIXP_DBL));
return nrSamples;
}
| 27,077
| 10,152
|
#pragma once
#include "cgp/base/base.hpp"
#include "cgp/containers/buffer_stack/buffer_stack.hpp"
#include "cgp/containers/offset_grid/offset_grid.hpp"
#include <sstream>
#include <iomanip>
/* ************************************************** */
/* Header */
/* ************************************************** */
namespace cgp
{
/** Container for 2D-matrix structure storing elements on stack (fixed size known at compile time)
*
* Elements of matrix_stack are stored contiguously in stack memory as array of array and remain fully compatible with std::array and pointers.
* Elements are stored along rows
* matrix[0] ( 0:[0,0] 1:[0,1] 2:[0,2] ... N2-1:[0,N2-1] )
* matrix[1] ( N2:[1,0] N2+1:[1,1] ... 2*N2-1:[1,N2-1] )
* ...
* matrix[k1] k1*N2+k2:[k1,k2]
* ...
* matrix[N1-1] ( (N1-1)*N2:[N1-1,0] ... N1*N2-1:[N1-1,N2-1] )
**/
template <typename T, int N1, int N2>
struct matrix_stack
{
/** Internal storage as a 1D buffer */
buffer_stack< buffer_stack<T, N2>, N1> data;
/** Constructors */
matrix_stack();
matrix_stack(buffer_stack< buffer_stack<T, N2>, N1> const& elements);
matrix_stack(buffer_stack<T, N1* N2> const& elements);
// Construct from a matrix with different size.
// Consider the min between (N1,N1_arg) and (N2,N2_arg)
template <int N1_arg, int N2_arg>
explicit matrix_stack(matrix_stack<T, N1_arg, N2_arg> const& M);
matrix_stack(std::initializer_list<T> const& arg);
matrix_stack(std::initializer_list<buffer_stack<T,N1> > const& arg);
static matrix_stack<T, N1, N2> build_identity();
static matrix_stack<T, N1, N2> diagonal(buffer_stack<T, std::min(N1,N2)> const& arg);
/** Total number of elements size = dimension[0] * dimension[1] */
int size() const;
/** Return {N1,N2} */
int2 dimension() const;
/** Fill all elements of the grid_2D with the same element*/
matrix_stack<T, N1, N2>& fill(T const& value);
/** Element access
* Bound checking is performed unless cgp_NO_DEBUG is defined. */
buffer_stack<T, N2> const& operator[](int k1) const;
buffer_stack<T, N2>& operator[](int k1);
buffer_stack<T, N2> const& operator()(int k1) const;
buffer_stack<T, N2>& operator()(int k1);
T const& operator()(int k1, int k2) const;
T& operator()(int k1, int k2);
T const& at_offset(int offset) const;
T& at_offset(int offset);
matrix_stack<T, N1 - 1, N2 - 1> remove_row_column(int k1, int k2) const;
/** Set a block within the matrix from a specific offset
* @block: the matrix to be copied in the current one
* @offset: the offsets where the block has to be writter. Default value are (0,0). The block is written on the top-left corner.
* Conditions:
* offset_1 + N1_arg < N1
* offset_2 + N2_arg < N2
*/
template <int N1_arg, int N2_arg>
matrix_stack<T, N1, N2>& set_block(matrix_stack<T, N1_arg, N2_arg> const& block, int offset_1 = 0, int offset_2 = 0);
/** Iterators
* Iterators compatible with STL syntax and std::array */
T* begin();
T* end();
T const* begin() const;
T const* end() const;
T const* cbegin() const;
T const* cend() const;
inline T const& at(int k1, int k2) const;
inline T& at(int k1, int k2);
T const& at_unsafe(int k1, int k2) const;
T& at_unsafe(int k1, int k2);
buffer_stack<T, N2> const& at_unsafe(int k1) const;
buffer_stack<T, N2>& at_unsafe(int k1);
T const& at_offset_unsafe(int offset) const;
T& at_offset_unsafe(int offset);
};
template <typename T, int N1, int N2> std::string type_str(matrix_stack<T, N1, N2> const&);
/** Display all elements of the buffer.*/
template <typename T, int N1, int N2> std::ostream& operator<<(std::ostream& s, matrix_stack<T, N1, N2> const& v);
/** Convert all elements of the matrix to a string.
* Default behavior: display all elements separated by a space as a 1D buffer
*
* [begin]
* [begin_line] v(0,0) [separator] v(0,1) [separator] ... v(0,N2-1) [end_line]
* [begin_line] v(1,0) [separator] v(1,1) [separator] ... v(1,N2-1) [end_line]
* ...
* [begin_line] v(N1-1,0) [separator] v(N1-1,1) [separator] ... v(N1-1,N2-1) [end_line]
* ...
* [end]
*/
template <typename T, int N1, int N2> std::string str(matrix_stack<T, N1, N2> const& v, std::string const& separator = " ", std::string const& begin = "", std::string const& end = "", std::string const& begin_line="", std::string const& end_line=" ");
/** Convert element of the matrix to a string. Default set for pretty 2D display. */
template <typename T, int N1, int N2> std::string str_pretty(matrix_stack<T, N1, N2> const& M, std::string const& separator=" ", std::string const& begin="", std::string const& end="", std::string const& begin_line="(", std::string const& end_line=")\n");
template <typename T, int N1, int N2> T const* ptr(matrix_stack<T,N1,N2> const& M);
template <typename T, int N1, int N2> int size_in_memory(matrix_stack<T,N1,N2> const& M);
/** Direct compiled-checked access to data */
template <int idx1, int idx2, typename T, int N1, int N2> T const& get(matrix_stack<T, N1, N2> const& data);
template <int idx1, int idx2, typename T, int N1, int N2> T& get(matrix_stack<T, N1, N2>& data);
template <int idx1, typename T, int N1, int N2> buffer_stack<T, N2> const& get(matrix_stack<T, N1, N2> const& data);
template <int idx1, typename T, int N1, int N2> buffer_stack<T, N2>& get(matrix_stack<T, N1, N2>& data);
template <int offset, typename T, int N1, int N2> T const& get_offset(matrix_stack<T, N1, N2> const& data);
template <int offset, typename T, int N1, int N2> T& get_offset(matrix_stack<T, N1, N2>& data);
/** Equality test between grid_2D */
template <typename Ta, typename Tb, int Na1, int Na2, int Nb1, int Nb2> bool is_equal(matrix_stack<Ta, Na1, Na2> const& a, matrix_stack<Tb, Nb1, Nb2> const& b);
/** Math operators
* Common mathematical operations between buffers, and scalar or element values. */
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator+=(matrix_stack<T, N1, N2>& a, matrix_stack<T, N1, N2> const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator+=(matrix_stack<T, N1, N2>& a, T const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator+(matrix_stack<T, N1, N2> const& a, matrix_stack<T, N1, N2> const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator+(matrix_stack<T, N1, N2> const& a, T const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator+(T const& a, matrix_stack<T, N1, N2> const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator-=(matrix_stack<T, N1, N2>& a, matrix_stack<T, N1, N2> const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator-=(matrix_stack<T, N1, N2>& a, T const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator-(matrix_stack<T, N1, N2> const& a, matrix_stack<T, N1, N2> const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator-(matrix_stack<T, N1, N2> const& a, T const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator-(T const& a, matrix_stack<T, N1, N2> const& b);
template <typename T, int N> matrix_stack<T, N, N>& operator*=(matrix_stack<T, N, N>& a, matrix_stack<T, N, N> const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator*=(matrix_stack<T, N1, N2>& a, float b);
template <typename T, int N1, int N2, int N3> matrix_stack<T, N1, N3> operator*(matrix_stack<T, N1, N2> const& a, matrix_stack<T, N2, N3> const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator*(matrix_stack<T, N1, N2> const& a, float b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator*(float a, matrix_stack<T, N1, N2> const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator/=(matrix_stack<T, N1, N2>& a, float b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator/(matrix_stack<T, N1, N2> const& a, float b);
// Unary negation
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator-(matrix_stack<T, N1, N2> const& m);
// Componentwise multiplication between two matrices with the same size
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> multiply_componentwise(matrix_stack<T, N1, N2> const& a, matrix_stack<T, N1, N2> const& b);
// Matrix vector product
template <typename T, int N1, int N2> buffer_stack<T, N1> operator*(matrix_stack<T, N1, N2> const& a, buffer_stack<T, N2> const& b);
/** Transposition of matrix */
template <typename T, int N1, int N2> matrix_stack<T, N2, N1> transpose(matrix_stack<T, N1, N2> const& m);
/** Trace of a square matrix*/
template <typename T, int N> T trace(matrix_stack<T, N, N> const& m);
/** Componentwise norm : sqrt(sum_(i,j) a_ij^2) */
template <typename T, int N1, int N2> T norm(matrix_stack<T,N1,N2> const& m);
}
/* ************************************************** */
/* IMPLEMENTATION */
/* ************************************************** */
namespace cgp
{
template <typename T, int N1, int N2>
T const& matrix_stack<T, N1, N2>::at(int k1, int k2) const
{
return *(begin() + k2 + N2 * k1);
}
template <typename T, int N1, int N2>
T& matrix_stack<T, N1, N2>::at(int k1, int k2)
{
return *(begin() + k2 + N2 * k1);
}
template <typename T, int N1, int N2> T* matrix_stack<T, N1, N2>::begin() { return &at_unsafe(0, 0); }
template <typename T, int N1, int N2> T* matrix_stack<T, N1, N2>::end() { return &at_unsafe(N1-1, N2-1)+1; }
template <typename T, int N1, int N2> T const* matrix_stack<T, N1, N2>::begin() const { return &at_unsafe(0, 0); }
template <typename T, int N1, int N2> T const* matrix_stack<T, N1, N2>::end() const { return &at_unsafe(N1 - 1, N2 - 1) + 1; }
template <typename T, int N1, int N2> T const* matrix_stack<T, N1, N2>::cbegin() const { return &at_unsafe(0, 0); }
template <typename T, int N1, int N2> T const* matrix_stack<T, N1, N2>::cend() const { return &at_unsafe(N1 - 1, N2 - 1) + 1; }
template <typename T, int N1, int N2> T const& matrix_stack<T, N1, N2>::at_unsafe(int k1, int k2) const { return data.at_unsafe(k1).at_unsafe(k2); }
template <typename T, int N1, int N2> T& matrix_stack<T, N1, N2>::at_unsafe(int k1, int k2) { return data.at_unsafe(k1).at_unsafe(k2); }
template <typename T, int N1, int N2> buffer_stack<T, N2> const& matrix_stack<T, N1, N2>::at_unsafe(int k1) const { return data.at_unsafe(k1); }
template <typename T, int N1, int N2> buffer_stack<T, N2>& matrix_stack<T, N1, N2>::at_unsafe(int k1) { return data.at_unsafe(k1); }
template <typename T, int N1, int N2> T const& matrix_stack<T, N1, N2>::at_offset_unsafe(int offset) const { return begin()[offset];}
template <typename T, int N1, int N2> T& matrix_stack<T, N1, N2>::at_offset_unsafe(int offset) { return begin()[offset]; }
template <typename T, int N1, int N2>
matrix_stack<T, N1, N2>::matrix_stack()
: data()
{}
template <typename T, int N1, int N2>
matrix_stack<T, N1, N2>::matrix_stack(buffer_stack< buffer_stack<T, N2>, N1> const& elements)
:data(elements)
{}
template <typename T, int N1, int N2>
matrix_stack<T, N1, N2>::matrix_stack(buffer_stack<T, N1* N2> const& elements)
: data()
{
int counter = 0;
for (int k1 = 0; k1 < N1; ++k1)
for (int k2 = 0; k2 < N2; ++k2) {
at_unsafe(k1, k2) = elements.at_unsafe(counter);
counter++;
}
}
template <typename T, int N1, int N2>
matrix_stack<T, N1, N2>::matrix_stack(std::initializer_list<T> const& arg)
: data()
{
assert_cgp(arg.size() >= N1 * N2, "Insufficient size to initialize matrix_stack");
auto it_arg = arg.begin();
for (int k1 = 0; k1 < N1; ++k1) {
for (int k2 = 0; k2 < N2; ++k2) {
at_unsafe(k1, k2) = *it_arg;
++it_arg;
}
}
}
template <typename T, int N1, int N2>
matrix_stack<T, N1, N2>::matrix_stack(std::initializer_list<buffer_stack<T, N1> > const& arg)
:data()
{
assert_cgp(arg.size() >= N1, "Insufficient size to initialize matrix_stack");
auto it_arg = arg.begin();
for (int k1 = 0; k1 < N1; ++k1) {
data.at_unsafe(k1) = *it_arg;
++it_arg;
}
}
template <typename T, int N1, int N2>
template <int N1_arg, int N2_arg>
matrix_stack<T, N1, N2>::matrix_stack(matrix_stack<T, N1_arg, N2_arg> const& M)
:data()
{
int const N1m = std::min(N1, N1_arg);
int const N2m = std::min(N2, N2_arg);
for (int k1 = 0; k1 < N1m; ++k1)
for (int k2 = 0; k2 < N2m; ++k2)
at_unsafe(k1, k2) = M.at_unsafe(k1, k2);
}
template <typename T, int N1, int N2> int matrix_stack<T, N1, N2>::size() const { return N1 * N2; }
template <typename T, int N1, int N2> int2 matrix_stack<T, N1, N2>::dimension() const { return { N1,N2 }; }
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& matrix_stack<T, N1, N2>::fill(T const& value)
{
auto it = begin();
auto const it_end = end();
for (; it != it_end; ++it)
*it = value;
return *this;
}
template <typename T, int N1, int N2>
void check_index_bounds(int index1, int index2, matrix_stack<T, N1, N2> const& data)
{
#ifndef cgp_NO_DEBUG
if (index1 < 0 || index2 < 0 || index1 >= N1 || index2 >= N2)
{
std::string msg = "\n";
msg += "\t> Try to access matrix_stack(" + str(index1) + "," + str(index2) + ")\n";
msg += "\t> - matrix_stack has dimension = (" + str(N1) + "," + str(N2) + ")\n";
msg += "\t> - Type of matrix_stack: " + type_str(data) + "\n";
if (index1 < 0 || index2 < 0)
{
msg += "\t> Buffer cannot be access with negative index.\n";
}
else if (N1 == 0 || N2 == 0)
{
msg += "\t> The buffer is empty, its elements cannot be accessed.\n";
}
else if (index1 == N1 || index2 == N2)
{
msg += "\t> Index reached the maximal size of the buffer \n";
msg += "\t> The maximal possible indexes should be (" + str(N1 - 1) + "," + str(N2 - 1) + ") \n";
}
else if (index1 >= N1 || index2 >= N2)
{
msg += "\t> Exceeded buffer dimension \n";
}
msg += "\n\t The function and variable that generated this error can be found in analysis the Call Stack.\n";
error_cgp(msg);
}
#endif
}
template <typename T, int N1, int N2>
void check_index_bounds(int index2, matrix_stack<T, N1, N2> const& data)
{
#ifndef cgp_NO_DEBUG
if (index2 < 0 || index2 >= N2)
{
std::string msg = "\n";
msg += "\t> Try to access matrix_stack(" + str(index2) + ")\n";
msg += "\t> - matrix_stack has dimension = (" + str(N1) + "," + str(N2) + ")\n";
msg += "\t> - maximal first index is = (" + str(N2-1) + ")\n";
msg += "\t> - Type of matrix_stack: " + type_str(data) + "\n";
if (index2 < 0)
{
msg += "\t> Buffer cannot be access with negative index.\n";
}
else if (N2 == 0)
{
msg += "\t> The buffer is empty, its elements cannot be accessed.\n";
}
else if (index2 == N2)
{
msg += "\t> Index reached the maximal size of the buffer \n";
msg += "\t> The maximal possible indexes should be (" + str(N1 - 1) + "," + str(N2 - 1) + ") \n";
}
else if (index2 >= N2)
{
msg += "\t> Exceeded buffer dimension \n";
}
msg += "\n\t The function and variable that generated this error can be found in analysis the Call Stack.\n";
error_cgp(msg);
}
#endif
}
template <typename T, int N1, int N2>
void check_offset_bounds(int offset, matrix_stack<T, N1, N2> const& data)
{
#ifndef cgp_NO_DEBUG
if (offset < 0 || offset >= N1*N2 )
{
std::string msg = "\n";
msg += "\t> Try to access matrix_stack.at_offset(" + str(offset) + ")\n";
msg += "\t> - matrix_stack has dimension = (" + str(N1) + "," + str(N2) + ")\n";
msg += "\t> - the maximal offset is = (" + str(N1*N2) + ")\n";
msg += "\t> - Type of matrix_stack: " + type_str(data) + "\n";
if (offset < 0)
{
msg += "\t> Buffer cannot be access with negative index.\n";
}
else if (offset == 0)
{
msg += "\t> The buffer is empty, its elements cannot be accessed.\n";
}
else if (offset == N1*N2)
{
msg += "\t> Offset reached the maximal size of the buffer \n";
msg += "\t> The maximal possible offset should be (" + str( N1*N2 - 1) + ") \n";
}
else if (offset >= N1*N2 )
{
msg += "\t> Exceeded buffer dimension \n";
}
msg += "\n\t The function and variable that generated this error can be found in analysis the Call Stack.\n";
error_cgp(msg);
}
#endif
}
template <typename T, int N1, int N2>
buffer_stack<T, N2> const& matrix_stack<T, N1, N2>::operator[](int k1) const {
check_index_bounds(k1, *this);
return at_unsafe(k1);
}
template <typename T, int N1, int N2>
buffer_stack<T, N2>& matrix_stack<T, N1, N2>::operator[](int k1) {
check_index_bounds(k1, *this);
return at_unsafe(k1);
}
template <typename T, int N1, int N2>
buffer_stack<T, N2> const& matrix_stack<T, N1, N2>::operator()(int k1) const {
check_index_bounds(k1, *this);
return at_unsafe(k1);
}
template <typename T, int N1, int N2>
buffer_stack<T, N2>& matrix_stack<T, N1, N2>::operator()(int k1) {
check_index_bounds(k1, *this);
return at_unsafe(k1);
}
template <typename T, int N1, int N2>
T const& matrix_stack<T, N1, N2>::operator()(int k1, int k2) const {
check_index_bounds(k1, k2, *this);
return at_unsafe(k1,k2);
}
template <typename T, int N1, int N2>
T& matrix_stack<T, N1, N2>::operator()(int k1, int k2) {
check_index_bounds(k1, k2, *this);
return at_unsafe(k1, k2);
}
template <typename T, int N1, int N2>
T const& matrix_stack<T, N1, N2>::at_offset(int offset) const {
check_offset_bounds(offset, *this);
return at_offset_unsafe(offset);
}
template <typename T, int N1, int N2>
T& matrix_stack<T, N1, N2>::at_offset(int offset) {
check_offset_bounds(offset, *this);
return at_offset_unsafe(offset);
}
template <typename T, int N1, int N2>
template <int N1_arg, int N2_arg>
matrix_stack<T, N1, N2>& matrix_stack<T, N1, N2>::set_block(matrix_stack<T, N1_arg, N2_arg> const& block, int offset_1, int offset_2)
{
static_assert(N1_arg < N1, "Block size is too large for the current matrix");
static_assert(N2_arg < N2, "Block size is too large for the current matrix");
assert_cgp(N1_arg + offset_1 < N1, "Block size exceed current matrix size");
assert_cgp(N2_arg + offset_2 < N2, "Block size exceed current matrix size");
for (int k1 = 0; k1 < N1_arg; ++k1) {
int const idx_1 = k1 + offset_1;
for (int k2 = 0; k2 < N2_arg; ++k2) {
int const idx_2 = k2 + offset_2;
at_unsafe(idx_1, idx_2) = block.at_unsafe(k1, k2);
}
}
return *this;
}
}
namespace cgp
{
template <typename T, int N1, int N2> std::string type_str(matrix_stack<T, N1, N2> const&)
{
return "matrix_stack<" + type_str(T()) + "," + str(N1) + "," + str(N2) + ">";
}
template <typename Ta, typename Tb, int Na1, int Na2, int Nb1, int Nb2> bool is_equal(matrix_stack<Ta, Na1, Na2> const& a, matrix_stack<Tb, Nb1, Nb2> const& b)
{
if (Na1 != Nb1 || Na2 != Nb2)
return false;
return is_equal(a.data, b.data);
}
template <typename T, int N1, int N2> T const* ptr(matrix_stack<T, N1, N2> const& M)
{
return &get<0,0>(M);
}
template <typename T, int N1, int N2> int size_in_memory(matrix_stack<T, N1, N2> const& )
{
return size_in_memory(T{})*N1*N2;
}
template <int idx1, int idx2, typename T, int N1, int N2> T const& get(matrix_stack<T, N1, N2> const& data)
{
static_assert( (idx1 < N1) && (idx2 < N2), "Index too large for matrix_stack access");
return data.at(idx1, idx2);
}
template <int idx1, int idx2, typename T, int N1, int N2> T& get(matrix_stack<T, N1, N2>& data)
{
static_assert((idx1 < N1) && (idx2 < N2), "Index too large for matrix_stack access");
return data.at(idx1, idx2);
}
template <int idx1, typename T, int N1, int N2> buffer_stack<T, N2> const& get(matrix_stack<T, N1, N2> const& data)
{
static_assert(idx1<N1, "Index too large for matrix_stack access");
return get<idx1>(data.data);
}
template <int idx1, typename T, int N1, int N2> buffer_stack<T, N2>& get(matrix_stack<T, N1, N2>& data)
{
static_assert(idx1 < N1, "Index too large for matrix_stack access");
return get<idx1>(data.data);
}
template <int offset, typename T, int N1, int N2> T const& get_offset(matrix_stack<T, N1, N2> const& data)
{
static_assert(offset<N1*N2, "Index too large for matrix_stack access");
return data.at_offset_unsafe(offset);
}
template <int offset, typename T, int N1, int N2> T& get_offset(matrix_stack<T, N1, N2>& data)
{
static_assert(offset < N1* N2, "Index too large for matrix_stack access");
return data.at_offset_unsafe(offset);
}
template <typename T, int N1, int N2> std::ostream& operator<<(std::ostream& s, matrix_stack<T, N1, N2> const& v)
{
return s << v.data;
}
template <typename T, int N1, int N2> std::string str(matrix_stack<T, N1, N2> const& v, std::string const& separator, std::string const& begin, std::string const& end, std::string const& begin_line, std::string const& end_line)
{
std::string s;
s += begin;
for (int k1 = 0; k1 < N1; ++k1) {
s += begin_line;
for (int k2 = 0; k2 < N2; ++k2) {
s += str(v.at_unsafe(k1, k2));
if ( k2 != N2 - 1)
s += separator;
}
s += end_line;
}
s += end;
return s;
}
template <typename T,int N1, int N2> std::string str_pretty(matrix_stack<T, N1, N2> const& M, std::string const& separator, std::string const& begin, std::string const& end, std::string const& begin_line, std::string const& end_line)
{
std::string s;
std::stringstream ss;
ss << begin;
for (int k1 = 0; k1 < N1; ++k1) {
ss << begin_line;
for (int k2 = 0; k2 < N2; ++k2) {
ss <<std::fixed<<std::setprecision(2) << std::setw(7) << M.at(k1,k2);
if ( k2 != N2 - 1 )
ss << separator;
}
ss << end_line;
}
ss << end;
return ss.str();
}
template <typename T, int N1, int N2> std::string str_2D(matrix_stack<T, N1, N2> const& v, std::string const& separator, std::string const& begin, std::string const& end, std::string const& begin_line, std::string const& end_line)
{
return str(v, separator, begin, end, begin_line, end_line);
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator+=(matrix_stack<T, N1, N2>& a, matrix_stack<T, N1, N2> const& b)
{
a.data += b.data;
return a;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator+=(matrix_stack<T, N1, N2>& a, T const& b)
{
a.data += b;
return a;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator+(matrix_stack<T, N1, N2> const& a, matrix_stack<T, N1, N2> const& b)
{
matrix_stack<T, N1, N2> res;
res.data = a.data + b.data;
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator+(matrix_stack<T, N1, N2> const& a, T const& b)
{
matrix_stack<T, N1, N2> res;
res.data = a.data + b;
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator+(T const& a, matrix_stack<T, N1, N2> const& b)
{
matrix_stack<T, N1, N2> res;
res.data = a + b.data;
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator-=(matrix_stack<T, N1, N2>& a, matrix_stack<T, N1, N2> const& b)
{
a.data += b.data;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator-=(matrix_stack<T, N1, N2>& a, T const& b)
{
a.data -= b;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator-(matrix_stack<T, N1, N2> const& a, matrix_stack<T, N1, N2> const& b)
{
matrix_stack<T, N1, N2> res;
res.data = a.data - b.data;
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator-(matrix_stack<T, N1, N2> const& a, T const& b)
{
matrix_stack<T, N1, N2> res;
res.data = a.data - b;
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator-(T const& a, matrix_stack<T, N1, N2> const& b)
{
matrix_stack<T, N1, N2> res;
res.data = a - b.data;
return res;
}
template <typename T, int N> matrix_stack<T, N, N>& operator*=(matrix_stack<T, N, N>& a, matrix_stack<T, N, N> const& b)
{
matrix_stack<T, N, N> res = a * b;
a = res;
return a;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator*=(matrix_stack<T, N1, N2>& a, float b)
{
a.data *= b;
return a;
}
template <typename T, int N1, int N2, int N3> matrix_stack<T, N1, N3> operator*(matrix_stack<T, N1, N2> const& a, matrix_stack<T, N2, N3> const& b)
{
matrix_stack<T, N1, N3> res;
for (int k1 = 0; k1 < N1; ++k1)
{
for (int k3 = 0; k3 < N3; ++k3)
{
T s {};
for (int k2 = 0; k2 < N2; ++k2)
s += a.at(k1, k2) * b.at(k2, k3);
res(k1, k3) = s;
}
}
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator*(matrix_stack<T, N1, N2> const& a, float b)
{
matrix_stack<T, N1, N2> res;
res.data = a.data * b;
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator*(float a, matrix_stack<T, N1, N2> const& b)
{
matrix_stack<T, N1, N2> res;
res.data = a * b.data;
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator/=(matrix_stack<T, N1, N2>& a, float b)
{
a.data /= b;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator/(matrix_stack<T, N1, N2> const& a, float b)
{
matrix_stack<T, N1, N2> res;
res.data = a.data / b;
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator-(matrix_stack<T, N1, N2> const& m)
{
matrix_stack<T, N1, N2> res = m;
res *= -1.0f;
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> multiply_componentwise(matrix_stack<T, N1, N2> const& a, matrix_stack<T, N1, N2> const& b)
{
matrix_stack<T, N1, N2> res;
res.data = a.data * b.data;
return res;
}
template <typename T, int N1, int N2> buffer_stack<T, N1> operator*(matrix_stack<T, N1, N2> const& a, buffer_stack<T, N2> const& b)
{
buffer_stack<T, N1> res = {};
for (int k1 = 0; k1 < N1; ++k1) {
auto& current = res.at_unsafe(k1);
for (int k2 = 0; k2 < N2; ++k2)
current += a.at(k1,k2) * b.at(k2);
res.at_unsafe(k1) = current;
}
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N2, N1> transpose(matrix_stack<T, N1, N2> const& m)
{
matrix_stack<T, N2, N1> res;
for (int k1 = 0; k1 < N1; ++k1)
for (int k2 = 0; k2 < N2; ++k2)
res(k2, k1) = m(k1, k2);
return res;
}
template <typename T, int N1, int N2>
matrix_stack<T, N1 - 1, N2 - 1> matrix_stack<T, N1, N2>::remove_row_column(int idx1, int idx2) const
{
assert_cgp( (idx1 < N1) && (idx2 < N2), "Incorrect index for removing row and column to matrix");
matrix_stack<T, N1 - 1, N2 - 1> res;
int k1_res = 0;
for (int k1 = 0; k1 < N1; ++k1) {
if (k1 != idx1) {
int k2_res = 0;
for (int k2 = 0; k2 < N2; ++k2) {
if (k2 != idx2){
res.at_unsafe(k1_res, k2_res) = at_unsafe(k1, k2);
++k2_res;
}
}
++k1_res;
}
}
return res;
}
template <typename T, int N1, int N2>
matrix_stack<T, N1, N2> matrix_stack<T, N1, N2>::build_identity()
{
int const N = std::min(N1, N2);
matrix_stack<T, N1, N2> id = {};
for (int k = 0; k < N; ++k)
id.at_unsafe(k, k) = cgp_trait<T>::one();
return id;
}
template <typename T, int N1, int N2>
matrix_stack<T, N1, N2> matrix_stack<T, N1, N2>::diagonal(buffer_stack<T, std::min(N1, N2)> const& arg)
{
int const N = std::min(N1, N2);
matrix_stack<T, N1, N2> m = {};
for (int k = 0; k < N; ++k)
m.at_unsafe(k, k) = arg[k];
return m;
}
template <typename T, int N1, int N2> T norm(matrix_stack<T, N1, N2> const& m)
{
using std::sqrt;
T s{};
for(int k1=0; k1<N1; ++k1)
for(int k2=0; k2<N2; ++k2)
s += m.at_unsafe(k1,k2);
return sqrt(s);
}
template <typename T, int N> T trace(matrix_stack<T, N, N> const& m)
{
T s = {};
for (int k = 0; k < N; ++k)
s += m(k, k);
return s;
}
}
#include "special_types/special_types.hpp"
| 31,827
| 11,907
|
/*
*
* Copyright (C) 1994-2019, OFFIS e.V.
* All rights reserved. See COPYRIGHT file for details.
*
* This software and supporting documentation were developed by
*
* OFFIS e.V.
* R&D Division Health
* Escherweg 2
* D-26121 Oldenburg, Germany
*
*
* Module: dcmdata
*
* Author: Gerd Ehlers, Andreas Barth
*
* Purpose: Implementation of class DcmFloatingPointSingle
*
*/
#include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */
#include "dcmtk/ofstd/ofstream.h"
#include "dcmtk/ofstd/ofstd.h"
#include "dcmtk/dcmdata/dcvrfl.h"
#define INCLUDE_CSTDIO
#define INCLUDE_CSTRING
#include "dcmtk/ofstd/ofstdinc.h"
// ********************************
DcmFloatingPointSingle::DcmFloatingPointSingle(const DcmTag &tag)
: DcmElement(tag, 0)
{
}
DcmFloatingPointSingle::DcmFloatingPointSingle(const DcmTag &tag,
const Uint32 len)
: DcmElement(tag, len)
{
}
DcmFloatingPointSingle::DcmFloatingPointSingle(const DcmFloatingPointSingle &old)
: DcmElement(old)
{
}
DcmFloatingPointSingle::~DcmFloatingPointSingle()
{
}
DcmFloatingPointSingle &DcmFloatingPointSingle::operator=(const DcmFloatingPointSingle &obj)
{
DcmElement::operator=(obj);
return *this;
}
int DcmFloatingPointSingle::compare(const DcmElement& rhs) const
{
int result = DcmElement::compare(rhs);
if (result != 0)
{
return result;
}
/* cast away constness (dcmdata is not const correct...) */
DcmFloatingPointSingle* myThis = NULL;
DcmFloatingPointSingle* myRhs = NULL;
myThis = OFconst_cast(DcmFloatingPointSingle*, this);
myRhs = OFstatic_cast(DcmFloatingPointSingle*, OFconst_cast(DcmElement*, &rhs));
/* compare number of values */
unsigned long thisNumValues = myThis->getNumberOfValues();
unsigned long rhsNumValues = myRhs->getNumberOfValues();
if (thisNumValues < rhsNumValues)
{
return -1;
}
else if (thisNumValues > rhsNumValues)
{
return 1;
}
// iterate over all components and test equality */
for (unsigned long count = 0; count < thisNumValues; count++)
{
Float32 val = 0;
if (myThis->getFloat32(val, count).good())
{
Float32 rhsVal = 0;
if (myRhs->getFloat32(rhsVal, count).good())
{
if (val > rhsVal)
{
return 1;
}
else if (val < rhsVal)
{
return -1;
}
}
}
}
/* all values as well as VM equal: objects are equal */
return 0;
}
OFCondition DcmFloatingPointSingle::copyFrom(const DcmObject& rhs)
{
if (this != &rhs)
{
if (rhs.ident() != ident()) return EC_IllegalCall;
*this = OFstatic_cast(const DcmFloatingPointSingle &, rhs);
}
return EC_Normal;
}
// ********************************
DcmEVR DcmFloatingPointSingle::ident() const
{
return EVR_FL;
}
OFCondition DcmFloatingPointSingle::checkValue(const OFString &vm,
const OFBool /*oldFormat*/)
{
/* check VM only, further checks on the floating point values could be added later */
return DcmElement::checkVM(getVM(), vm);
}
unsigned long DcmFloatingPointSingle::getVM()
{
return getNumberOfValues();
}
unsigned long DcmFloatingPointSingle::getNumberOfValues()
{
return OFstatic_cast(unsigned long, getLengthField() / sizeof(Float32));
}
// ********************************
void DcmFloatingPointSingle::print(STD_NAMESPACE ostream &out,
const size_t flags,
const int level,
const char * /*pixelFileName*/,
size_t * /*pixelCounter*/)
{
if (valueLoaded())
{
/* get float data */
Float32 *floatVals;
errorFlag = getFloat32Array(floatVals);
if (floatVals != NULL)
{
/* do not use getVM() because derived classes might always return 1 */
const unsigned long count = getNumberOfValues();
/* double-check length field for valid value */
if (count > 0)
{
const unsigned long maxLength = (flags & DCMTypes::PF_shortenLongTagValues) ?
DCM_OptPrintLineLength : OFstatic_cast(unsigned long, -1) /*unlimited*/;
unsigned long printedLength = 0;
unsigned long newLength = 0;
char buffer[64];
/* print line start with tag and VR */
printInfoLineStart(out, flags, level);
/* print multiple values */
for (unsigned int i = 0; i < count; i++, floatVals++)
{
/* check whether first value is printed (omit delimiter) */
if (i == 0)
OFStandard::ftoa(buffer, sizeof(buffer), *floatVals, 0, 0, 8 /* FLT_DIG + 2 for DICOM FL */);
else
{
buffer[0] = '\\';
OFStandard::ftoa(buffer + 1, sizeof(buffer) - 1, *floatVals, 0, 0, 8 /* FLT_DIG + 2 for DICOM FL */);
}
/* check whether current value sticks to the length limit */
newLength = printedLength + OFstatic_cast(unsigned long, strlen(buffer));
if ((newLength <= maxLength) && ((i + 1 == count) || (newLength + 3 <= maxLength)))
{
out << buffer;
printedLength = newLength;
} else {
/* check whether output has been truncated */
if (i + 1 < count)
{
out << "...";
printedLength += 3;
}
break;
}
}
/* print line end with length, VM and tag name */
printInfoLineEnd(out, flags, printedLength);
} else {
/* count can be zero if we have an invalid element with less than four bytes length */
printInfoLine(out, flags, level, "(invalid value)");
}
} else
printInfoLine(out, flags, level, "(no value available)" );
} else
printInfoLine(out, flags, level, "(not loaded)" );
}
// ********************************
OFCondition DcmFloatingPointSingle::getFloat32(Float32 &floatVal,
const unsigned long pos)
{
/* get float data */
Float32 *floatValues = NULL;
errorFlag = getFloat32Array(floatValues);
/* check data before returning */
if (errorFlag.good())
{
if (floatValues == NULL)
errorFlag = EC_IllegalCall;
/* do not use getVM() because derived classes might always return 1 */
else if (pos >= getNumberOfValues())
errorFlag = EC_IllegalParameter;
else
floatVal = floatValues[pos];
}
/* clear value in case of error */
if (errorFlag.bad())
floatVal = 0;
return errorFlag;
}
OFCondition DcmFloatingPointSingle::getFloat32Array(Float32 *&floatVals)
{
floatVals = OFstatic_cast(Float32 *, getValue());
return errorFlag;
}
// ********************************
OFCondition DcmFloatingPointSingle::getOFString(OFString &value,
const unsigned long pos,
OFBool /*normalize*/)
{
Float32 floatVal;
/* get the specified numeric value */
errorFlag = getFloat32(floatVal, pos);
if (errorFlag.good())
{
/* ... and convert it to a character string */
char buffer[64];
OFStandard::ftoa(buffer, sizeof(buffer), floatVal, 0, 0, 8 /* FLT_DIG + 2 for DICOM FL */);
/* assign result */
value = buffer;
}
return errorFlag;
}
// ********************************
OFCondition DcmFloatingPointSingle::putFloat32(const Float32 floatVal,
const unsigned long pos)
{
Float32 val = floatVal;
errorFlag = changeValue(&val, OFstatic_cast(Uint32, sizeof(Float32) * pos), OFstatic_cast(Uint32, sizeof(Float32)));
return errorFlag;
}
OFCondition DcmFloatingPointSingle::putFloat32Array(const Float32 *floatVals,
const unsigned long numFloats)
{
errorFlag = EC_Normal;
if (numFloats > 0)
{
/* check for valid float data */
if (floatVals != NULL)
errorFlag = putValue(floatVals, OFstatic_cast(Uint32, sizeof(Float32) * OFstatic_cast(size_t, numFloats)));
else
errorFlag = EC_CorruptedData;
} else
putValue(NULL, 0);
return errorFlag;
}
// ********************************
OFCondition DcmFloatingPointSingle::putString(const char *stringVal)
{
/* determine length of the string value */
const size_t stringLen = (stringVal != NULL) ? strlen(stringVal) : 0;
/* call the real function */
return putString(stringVal, OFstatic_cast(Uint32, stringLen));
}
OFCondition DcmFloatingPointSingle::putString(const char *stringVal,
const Uint32 stringLen)
{
errorFlag = EC_Normal;
/* determine VM of the string */
const unsigned long vm = DcmElement::determineVM(stringVal, stringLen);
if (vm > 0)
{
Float32 *field = new Float32[vm];
OFBool success = OFFalse;
OFString value;
size_t pos = 0;
/* retrieve float data from character string */
for (unsigned long i = 0; (i < vm) && errorFlag.good(); i++)
{
/* get specified value from multi-valued string */
pos = DcmElement::getValueFromString(stringVal, pos, stringLen, value);
if (!value.empty())
{
field[i] = OFstatic_cast(Float32, OFStandard::atof(value.c_str(), &success));
if (!success)
errorFlag = EC_CorruptedData;
} else
errorFlag = EC_CorruptedData;
}
/* set binary data as the element value */
if (errorFlag.good())
errorFlag = putFloat32Array(field, vm);
/* delete temporary buffer */
delete[] field;
} else
errorFlag = putValue(NULL, 0);
return errorFlag;
}
// ********************************
OFCondition DcmFloatingPointSingle::verify(const OFBool autocorrect)
{
/* check for valid value length */
if (getLengthField() % (sizeof(Float32)) != 0)
{
errorFlag = EC_CorruptedData;
if (autocorrect)
{
/* strip to valid length */
setLengthField(getLengthField() - (getLengthField() % OFstatic_cast(Uint32, sizeof(Float32))));
}
} else
errorFlag = EC_Normal;
return errorFlag;
}
OFBool DcmFloatingPointSingle::matches(const DcmElement& candidate,
const OFBool enableWildCardMatching) const
{
OFstatic_cast(void,enableWildCardMatching);
if (ident() == candidate.ident())
{
// some const casts to call the getter functions, I do not modify the values, I promise!
DcmFloatingPointSingle& key = OFconst_cast(DcmFloatingPointSingle&,*this);
DcmElement& can = OFconst_cast(DcmElement&,candidate);
Float32 a, b;
for( unsigned long ui = 0; ui < key.getVM(); ++ui )
for( unsigned long uj = 0; uj < can.getVM(); ++uj )
if( key.getFloat32( a, ui ).good() && can.getFloat32( b, uj ).good() && a == b )
return OFTrue;
return key.getVM() == 0;
}
return OFFalse;
}
| 11,923
| 3,562
|
#include "GpDateTimeOps.hpp"
#if defined(GP_USE_DATE_TIME)
#include <date/date.h> //TODO: remove with c++20
namespace GPlatform {
const microseconds_t GpDateTimeOps::sStartSteadyTS = GpDateTimeOps::SSteadyTS_us();
const GpArray<std::string, GpDateTimeFormat::SCount().As<size_t>()> GpDateTimeOps::sFormats =
{
"%FT%X+00:00", //ISO_8601: 2021-01-11T20:15:31+00:00
"%a, %d %b %Y %X +0000", //RFC_2822: Mon, 11 Jan 2021 20:15:31 +0000
"%F %X", //STD_DATE_TIME: 2021-01-11 20:15:31
"%FT%X", //STD_DATE_TIME_T,//2021-01-11T20:15:31
"%F", //STD_DATE: 2021-01-11
"%X" //STD_TIME: 20:15:31
};
unix_ts_ms_t GpDateTimeOps::SUnixTS_ms (void) noexcept
{
const auto val = std::chrono::system_clock::now().time_since_epoch();
const auto cnt = std::chrono::duration_cast<std::chrono::milliseconds>(val).count();
return unix_ts_ms_t::SMake(cnt);
}
unix_ts_s_t GpDateTimeOps::SUnixTS_s (void) noexcept
{
return SUnixTS_ms();
}
unix_ts_ms_t GpDateTimeOps::SUnixTsFromStr_ms
(
GpRawPtrCharR aStr,
std::string_view aFormat
)
{
std::istringstream in{std::string(aStr.AsStringView())};
date::sys_time<std::chrono::milliseconds> tp;
in >> date::parse(std::string(aFormat), tp);
const auto val = tp.time_since_epoch();
const auto cnt = std::chrono::duration_cast<std::chrono::milliseconds>(val).count();
return unix_ts_ms_t::SMake(cnt);
}
unix_ts_s_t GpDateTimeOps::SUnixTsFromStr_s
(
GpRawPtrCharR aStr,
std::string_view aFormat
)
{
return SUnixTsFromStr_ms(aStr, aFormat);
}
unix_ts_ms_t GpDateTimeOps::SUnixTsFromStr_ms
(
GpRawPtrCharR aStr,
FormatTE aFormat
)
{
return SUnixTsFromStr_ms(aStr, sFormats.at(aFormat));
}
unix_ts_s_t GpDateTimeOps::SUnixTsFromStr_s
(
GpRawPtrCharR aStr,
FormatTE aFormat
)
{
return SUnixTsFromStr_ms(aStr, sFormats.at(aFormat));
}
/*std::chrono::hh_mm_ss GpDateTimeOps::SUnixTsToHH_MM_SS (const unix_ts_ms_t aTs) noexcept
{
?
}*/
/*hours_t GpDateTimeOps::SUnixTsToHH (const unix_ts_ms_t aTs) noexcept
{
date::sys_time<std::chrono::milliseconds> tp(std::chrono::milliseconds(aTs.Value()));
date::hh_mm_ss h(tp.time_since_epoch());
return hours_t::SMake(h.hours().count());
}*/
microseconds_t GpDateTimeOps::SSteadyTS_us (void) noexcept
{
const auto val = std::chrono::steady_clock::now().time_since_epoch();
const auto cnt = std::chrono::duration_cast<std::chrono::microseconds>(val).count();
return microseconds_t::SMake(microseconds_t::value_type(cnt));
}
milliseconds_t GpDateTimeOps::SSteadyTS_ms (void) noexcept
{
const auto val = std::chrono::steady_clock::now().time_since_epoch();
const auto cnt = std::chrono::duration_cast<std::chrono::milliseconds>(val).count();
return milliseconds_t::SMake(milliseconds_t::value_type(cnt));
}
seconds_t GpDateTimeOps::SSteadyTS_s (void) noexcept
{
return SSteadyTS_ms();
}
microseconds_t GpDateTimeOps::SHighResTS_us (void) noexcept
{
const auto val = std::chrono::high_resolution_clock::now().time_since_epoch();
const auto cnt = std::chrono::duration_cast<std::chrono::microseconds>(val).count();
return microseconds_t::SMake(microseconds_t::value_type(cnt));
}
std::string GpDateTimeOps::SUnixTsToStr
(
const unix_ts_ms_t aTs,
std::string_view aFormat
)
{
std::ostringstream out;
//https://howardhinnant.github.io/date/date.html
//https://gitter.im/HowardHinnant/date?at=5e404b1fb612cc7bb1588132
date::sys_time<std::chrono::milliseconds> tp(std::chrono::milliseconds(aTs.Value()));
out << date::format(std::string(aFormat), tp);
return out.str();
}
std::string GpDateTimeOps::SUnixTsToStr
(
const unix_ts_s_t aTs,
std::string_view aFormat
)
{
return SUnixTsToStr(aTs.As<unix_ts_ms_t>(), aFormat);
}
std::string GpDateTimeOps::SUnixTsToStr
(
const unix_ts_ms_t aTs,
const FormatTE aFormat
)
{
return SUnixTsToStr(aTs, sFormats.at(aFormat));
}
std::string GpDateTimeOps::SUnixTsToStr
(
const unix_ts_s_t aTs,
const FormatTE aFormat
)
{
return SUnixTsToStr(aTs.As<unix_ts_ms_t>(), sFormats.at(aFormat));
}
}//GPlatform
#endif//#if defined(GP_USE_DATE_TIME)
| 4,561
| 1,955
|
#include "../World.h"
#include "../../Engine/Math.h"
#include "../Components/CBrain.h"
#include "../Entities/HeadersEntities.h"
#include "../Components/CWeapon.h"
#include "../UI/WLifebar.h"
#include "../Components/CAnimation.h"
#include "../../Engine/Audio/Audiosource.h"
#include "../Scene.h"
#include "Behaviors.h"
/* BEHAVIORS */
// ATTACK
Ptr<Attack> Attack::Create(Ptr<CBrain> BrainComponent)
{
return new Attack(BrainComponent);
}
Attack::Attack(Ptr<CBrain> BrainComponent)
{
mOwnerBrain = BrainComponent;
mStatus = eInvalid;
}
Attack::~Attack()
{
mOwnerBrain = nullptr;
}
Status Attack::Update(float Step)
{
// Try to attack with the secondary weapon (more powerful)
// If not, then try to attack with the primary weapon
if (mOwnerBrain != nullptr && World::IsEntityValid(mOwnerBrain->GetMyEntity()) && mOwnerBrain->GetMyEntity().DownCast<EShip>() != nullptr)
{
if (mOwnerBrain->GetMyEntity().DownCast<EShip>()->GetSecondaryWeaponComp() != nullptr && !mOwnerBrain->GetMyEntity().DownCast<EShip>()->GetSecondaryWeaponComp()->IsWeaponInCooldown())
{
mOwnerBrain->GetMyEntity().DownCast<EShip>()->GetSecondaryWeaponComp()->Fire(mOwnerBrain->GetMyEntity().DownCast<EShip>()->GetProjectileSpawnPos(), mOwnerBrain->GetMyEntity()->GetRotation());
return eSuccess;
}
else if(mOwnerBrain->GetMyEntity().DownCast<EShip>()->GetPrimaryWeaponComp() != nullptr && !mOwnerBrain->GetMyEntity().DownCast<EShip>()->GetPrimaryWeaponComp()->IsWeaponInCooldown())
{
mOwnerBrain->GetMyEntity().DownCast<EShip>()->GetPrimaryWeaponComp()->Fire(mOwnerBrain->GetMyEntity().DownCast<EShip>()->GetProjectileSpawnPos(), mOwnerBrain->GetMyEntity()->GetRotation());
return eSuccess;
}
else
return eFail;
}
else
{
// Weapon in Cooldown
return eFail;
}
return eInvalid;
}
// MOVEMENT
Ptr<WantToMove> WantToMove::Create(Ptr<CBrain> BrainComponent, float TargetReachedRadius)
{
return new WantToMove(BrainComponent, TargetReachedRadius);
}
WantToMove::WantToMove(Ptr<CBrain> BrainComponent, float TargetReachedRadius)
{
mOwnerBrain = BrainComponent;
mTargetReachedRadius = TargetReachedRadius;
mStatus = eInvalid;
}
WantToMove::~WantToMove()
{
mOwnerBrain = nullptr;
}
Status WantToMove::Update(float Step)
{
// Only move if not inside the acceptance radius
if (mOwnerBrain != nullptr && World::IsEntityValid(mOwnerBrain->GetMyEntity()) && mOwnerBrain->GetMyEntity().DownCast<EShip>() != nullptr && mOwnerBrain->GetMyEntity().DownCast<EShip>()->IsMovementControllerActivated())
{
if (SqrDistance(mOwnerBrain->GetMyEntity()->GetPosition(), mOwnerBrain->GetTargetPosition(false)) <= powf(mTargetReachedRadius, 2))
return eFail;
else
return eSuccess;
}
return eInvalid;
}
Ptr<MoveToTarget> MoveToTarget::Create(Ptr<CBrain> BrainComponent, float TargetReachedRadius)
{
return new MoveToTarget(BrainComponent, TargetReachedRadius);
}
MoveToTarget::MoveToTarget(Ptr<CBrain> BrainComponent, float TargetReachedRadius)
{
mOwnerBrain = BrainComponent;
mTargetReachedRadius = TargetReachedRadius;
mStatus = eInvalid;
mAbortBehaviorTimer = 10.0f;
}
MoveToTarget::~MoveToTarget()
{
mOwnerBrain = nullptr;
}
Status MoveToTarget::Update(float Step)
{
if (mOwnerBrain != nullptr)
{
// In case the MoveTo behavior went wrong, abort it
if (mContAbortBehaviorTimer >= mAbortBehaviorTimer)
{
mOwnerBrain->SelectNewTargetPosition();
return eInvalid;
}
else if (World::IsEntityValid(mOwnerBrain->GetMyEntity()) && mOwnerBrain->GetMyEntity().DownCast<EShip>() != nullptr && mOwnerBrain->GetMyEntity().DownCast<EShip>()->IsMovementControllerActivated())
{
// Check if entity is inside the acceptance radius
if (SqrDistance(mOwnerBrain->GetMyEntity()->GetPosition(), mOwnerBrain->GetTargetPosition(false)) <= powf(mTargetReachedRadius, 2))
{
// If inside acceptance radius, activate the linear inertia to decelerate
if (!mOwnerBrain->GetAILinearInertiaActivated())
{
mOwnerBrain->SetAILinearInertiaActivated(true);
mOwnerBrain->GetMyEntity()->ActivateLinearInertia();
}
return eSuccess;
}
else
{
// Set a linear steering on forward vector
mOwnerBrain->SetAILinearInertiaActivated(false);
mOwnerBrain->GetMyEntity()->DeactivateLinearInertia();
mOwnerBrain->GetMyEntity()->SetLinearSteering(vec2(mOwnerBrain->GetMyEntity()->GetForwardVector().x * mOwnerBrain->GetMyEntity()->GetMaxLinearAcc(), mOwnerBrain->GetMyEntity()->GetForwardVector().y * mOwnerBrain->GetMyEntity()->GetMaxLinearAcc()));
return eRunning;
}
}
}
return eInvalid;
}
// TARGETING
Ptr<RotateToTarget> RotateToTarget::Create(Ptr<CBrain> BrainComponent, bool TargetingOpponent, float TargetReachedValue)
{
return new RotateToTarget(BrainComponent, TargetingOpponent, TargetReachedValue);
}
RotateToTarget::RotateToTarget(Ptr<CBrain> BrainComponent, bool TargetingOpponent, float TargetReachedValue)
{
mOwnerBrain = BrainComponent;
mTargetReachedValue = TargetReachedValue;
mStatus = eInvalid;
mTargetingOpponent = TargetingOpponent;
}
RotateToTarget::~RotateToTarget()
{
mOwnerBrain = nullptr;
}
Status RotateToTarget::Update(float Step)
{
if (mTargetingOpponent && !World::IsEntityValid(mOwnerBrain->GetMyOpponent().UpCast<Entity>()))
{
return eInvalid;
}
if (mOwnerBrain != nullptr && World::IsEntityValid(mOwnerBrain->GetMyEntity()))
{
if (mOwnerBrain->GetMyEntity().DownCast<EShip>() != nullptr && mOwnerBrain->GetMyEntity().DownCast<EShip>()->IsMovementControllerActivated())
{
if (mOwnerBrain->GetNormDirectionToTarget(mTargetingOpponent) > 0)
{
// Calculate the angle from entity to target
float NewAngle = DegACos(mOwnerBrain->GetMyEntity()->GetForwardVector().x * mOwnerBrain->GetDirectionToTarget(mTargetingOpponent).x + mOwnerBrain->GetMyEntity()->GetForwardVector().y * mOwnerBrain->GetDirectionToTarget(mTargetingOpponent).y);
if (NewAngle < mTargetReachedValue)
{
// If angle is minor acceptance value, activate angular inertia
mOwnerBrain->GetMyEntity()->SetAngularSteering(0.0f);
if (!mOwnerBrain->GetAIAngularInertiaActivated())
{
mOwnerBrain->SetAIAngularInertiaActivated(true);
mOwnerBrain->GetMyEntity()->ActivateAngularInertia();
}
return eSuccess;
}
else
{
// In case the entity has to turn, first get the turn direction (left/right) and then set an angular steering
float CrossProd = mOwnerBrain->GetMyEntity()->GetForwardVector().x * mOwnerBrain->GetDirectionToTarget(mTargetingOpponent).y - mOwnerBrain->GetMyEntity()->GetForwardVector().y * mOwnerBrain->GetDirectionToTarget(mTargetingOpponent).x;
int8 TurnDirection = 1;
if (CrossProd > 0)
TurnDirection = -1;
mOwnerBrain->GetMyEntity()->SetTurnDirection(TurnDirection);
mOwnerBrain->GetMyEntity()->DeactivateAngularInertia();
mOwnerBrain->SetAIAngularInertiaActivated(false);
mOwnerBrain->GetMyEntity()->SetAngularSteering(TurnDirection * mOwnerBrain->GetMyEntity()->GetMaxAngularAcc());
return eRunning;
}
}
}
}
return eInvalid;
}
// IDLE
Ptr<Idle> Idle::Create(Ptr<CBrain> BrainComponent)
{
return new Idle(BrainComponent);
}
Idle::Idle(Ptr<CBrain> BrainComponent)
{
mOwnerBrain = BrainComponent;
mStatus = eInvalid;
}
Idle::~Idle()
{
mOwnerBrain = nullptr;
}
Status Idle::Update(float Step)
{
return eSuccess;
}
| 8,337
| 2,516
|
//****************************************
//effectpal.cpp
//****************************************
/*
Copyright 1999, Be Incorporated. All Rights Reserved.
This file may be used under the terms of the Be Sample Code License.
*/
#include <image.h>
#include "effectpal.h"
#include "effect.h"
#include <Application.h>
#include <Roster.h>
#include <Path.h>
#include <Directory.h>
#include <stdio.h>
//****************************************
//EffectPal class functions
//constructor
EffectPal::EffectPal( BRect frame, const char *title, window_type type, uint32 flags,
uint32 workspaces )
: BWindow( frame, title, type, flags, workspaces )
{
}
//destructor
EffectPal::~EffectPal()
{
}
//Init
void EffectPal::Init( void )
{
image_id addonId;
status_t err = B_NO_ERROR;
Effect* peffect = NULL;
BPoint point(0,0), apoint;
Effect* (*NewEffect)( image_id ); //addon function prototype
app_info info;
BPath path;
//look in app directory for effects
be_app->GetAppInfo(&info);
BEntry entry(&info.ref);
entry.GetPath(&path);
path.GetParent(&path);
path.Append("Effects");
BDirectory dir( path.Path() );
//load all effects
while( err == B_NO_ERROR ){
err = dir.GetNextEntry( (BEntry*)&entry, TRUE );
if( entry.InitCheck() != B_NO_ERROR ){
break;
}
if( entry.GetPath(&path) != B_NO_ERROR ){
printf( "entry.GetPath failed\n" );
}else{
addonId = load_add_on( path.Path() );
if( addonId < 0 ){
printf( "load_add_on( %s ) failed\n", path.Path() );
}else{
printf( "load_add_on( %s ) successful!\n", path.Path() );
if( get_image_symbol( addonId,
"NewEffect",
B_SYMBOL_TYPE_TEXT,
(void **)&NewEffect) ){
printf( "get_image_symbol( NewEffect ) failed\n" );
unload_add_on( addonId );
}else{
peffect = (*NewEffect)( addonId );
if( !peffect ){
printf( "failed to create new effect\n" );
}else{
peffect->Init( this, point );
peffect->GetButtonSize( (BPoint*) &apoint );
point.y += apoint.y;
}
}
}
}
}
}
bool EffectPal::QuitRequested()
{
be_app->PostMessage(B_QUIT_REQUESTED);
return(true);
}
//****************************************
| 2,242
| 904
|
////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
// Authors: Kern Handa
////////////////////////////////////////////////////////////////////////////////////////////////////
#include "AcceraPasses.h"
#include <ir/include/IRUtil.h>
#include <ir/include/value/ValueDialect.h>
#include <mlir/IR/Location.h>
#include <value/include/MLIREmitterContext.h>
#include <mlir/Analysis/LoopAnalysis.h>
#include <mlir/Dialect/Affine/IR/AffineOps.h>
#include <mlir/Dialect/GPU/GPUDialect.h>
#include <mlir/Dialect/Linalg/IR/LinalgOps.h>
#include <mlir/Dialect/SPIRV/IR/SPIRVDialect.h>
#include <mlir/Dialect/SPIRV/IR/SPIRVOps.h>
#include <mlir/Dialect/SPIRV/IR/TargetAndABI.h>
#include <mlir/Dialect/StandardOps/IR/Ops.h>
#include <mlir/Pass/Pass.h>
#include <mlir/Pass/PassManager.h>
#include <mlir/Transforms/GreedyPatternRewriteDriver.h>
#include <mlir/Transforms/LoopUtils.h>
#include <mlir/Transforms/RegionUtils.h>
#include <llvm/ADT/STLExtras.h>
#include <llvm/ADT/SetVector.h>
#include <llvm/ADT/TypeSwitch.h>
#include <llvm/Support/FormatVariadic.h>
#include <cassert>
#include <memory>
using namespace mlir;
namespace ir = accera::ir;
namespace utilir = accera::ir::util;
namespace vir = accera::ir::value;
namespace tr = accera::transforms;
namespace vtr = accera::transforms::value;
namespace
{
void HoistOpToParentAffineScope(Operation* op)
{
Operation* parentOp = op->getParentOp();
assert(parentOp != nullptr && "Can only hoist an op that has a parent op");
if (!parentOp->hasTrait<OpTrait::AffineScope>())
{
auto affineScopeParent = op->getParentWithTrait<OpTrait::AffineScope>();
auto& firstRegion = affineScopeParent->getRegion(0);
auto& firstBlock = firstRegion.front();
op->moveBefore(&firstBlock, firstBlock.begin());
}
}
void HoistGPUBlockThreadIds(vir::ValueModuleOp vModule)
{
// Hoist GPU block and thread ID ops to the top of the parent AffineScope (e.g. a mlir::FuncOp or a value::LambdaOp)
// this enables the block and thread ID's to be used with Affine ops, as they
// are index types that are defined in the top level of an AffineScope.
// This is safe because the value of the block and thread IDs don't change based
// on their position in the graph within an AffineScope
vModule.walk([](mlir::gpu::ThreadIdOp op) {
HoistOpToParentAffineScope(op.getOperation());
});
vModule.walk([](mlir::gpu::BlockIdOp op) {
HoistOpToParentAffineScope(op.getOperation());
});
}
constexpr auto kDefaultExecutionTarget = vir::ExecutionTarget::CPU;
constexpr size_t kLaunchConfigNumDims = 6;
struct ValueFuncToTargetPass : public tr::ValueFuncToTargetBase<ValueFuncToTargetPass>
{
void runOnOperation() final
{
auto module = getOperation();
auto context = module.getContext();
for (auto vModule : make_early_inc_range(module.getOps<vir::ValueModuleOp>()))
{
{
OwningRewritePatternList patterns(context);
vtr::populateValueLambdaToFuncPatterns(context, patterns);
(void)applyPatternsAndFoldGreedily(vModule, std::move(patterns));
}
{
OwningRewritePatternList patterns(context);
vtr::populateValueLaunchFuncInlinerPatterns(context, patterns);
(void)applyPatternsAndFoldGreedily(vModule, std::move(patterns));
}
{
OwningRewritePatternList patterns(context);
vtr::populateValueFuncToTargetPatterns(context, patterns);
(void)applyPatternsAndFoldGreedily(vModule, std::move(patterns));
}
HoistGPUBlockThreadIds(vModule);
}
module.walk([&](AffineForOp op) {
if (op->getAttrOfType<UnitAttr>("accv_unrolled"))
{
auto tripCount = mlir::getConstantTripCount(op);
if (tripCount && *tripCount >= 1)
(void)mlir::loopUnrollFull(op);
}
else if (auto jammed = op->getAttrOfType<IntegerAttr>("accv_unroll_jam"))
{
(void)mlir::loopUnrollJamByFactor(op, (uint64_t)jammed.getInt());
}
else
{
(void)mlir::promoteIfSingleIteration(op);
}
});
}
};
struct ValueReturnOpConversion : OpRewritePattern<vir::ReturnOp>
{
using OpRewritePattern::OpRewritePattern;
LogicalResult matchAndRewrite(
vir::ReturnOp returnOp,
PatternRewriter& rewriter) const override
{
auto operands = returnOp.operands();
rewriter.replaceOpWithNewOp<mlir::ReturnOp>(returnOp, operands);
return success();
}
};
struct ValueFuncToTargetPattern : OpRewritePattern<vir::ValueFuncOp>
{
using OpRewritePattern::OpRewritePattern;
LogicalResult matchAndRewrite(
vir::ValueFuncOp funcOp,
PatternRewriter& rewriter) const override
{
auto loc = rewriter.getFusedLoc({ funcOp.getLoc(), accera::ir::util::GetLocation(rewriter, __FILE__, __LINE__) });
OpBuilder::InsertionGuard guard(rewriter);
rewriter.setInsertionPoint(funcOp);
[[maybe_unused]] auto target = funcOp.exec_target();
auto newFuncName = funcOp.sym_name().str();
auto newFuncOp = rewriter.create<mlir::FuncOp>(
loc, newFuncName, funcOp.getType());
newFuncOp.setVisibility(funcOp.getVisibility());
if (!funcOp->getAttr("external"))
{
Region& newBody = newFuncOp.getBody();
rewriter.inlineRegionBefore(funcOp.getBody(), newBody, newBody.begin());
}
// Carry forward attributes
newFuncOp->setAttrs(funcOp->getAttrs());
if (funcOp->getAttr(accera::ir::NoInlineAttrName))
{
newFuncOp->setAttr("passthrough", rewriter.getArrayAttr({ rewriter.getStringAttr("noinline") }));
}
rewriter.eraseOp(funcOp);
return success();
}
};
struct ValueLambdaRewritePattern : mlir::OpRewritePattern<vir::ValueLambdaOp>
{
using OpRewritePattern::OpRewritePattern;
LogicalResult match(vir::ValueLambdaOp op) const final
{
auto lambdaFound = false;
op.body().walk([&](vir::ValueLambdaOp) { lambdaFound = true; return WalkResult::interrupt(); });
return success(!lambdaFound);
}
void rewrite(vir::ValueLambdaOp op, PatternRewriter& rewriter) const final
{
// get a list of all values used in the lambda that come from above
llvm::SetVector<Value> valuesDefinedAbove;
getUsedValuesDefinedAbove(op.body(), valuesDefinedAbove);
llvm::SmallVector<Operation*, 8> constants;
llvm::SmallVector<Value, 4> capturedValues;
// This could be a std::partition, but mlir::Value doesn't have swap defined and idk how to work with their
// non-owning lists yet
for (const Value& v : valuesDefinedAbove)
{
if (auto constantOp = v.getDefiningOp(); constantOp && constantOp->hasTrait<mlir::OpTrait::ConstantLike>())
{
constants.push_back(constantOp);
}
else
{
capturedValues.push_back(v);
}
}
// the new function will take all the args that the lambda took, plus all the implicitly captured values
auto argTypes = llvm::to_vector<4>(op.getArgumentTypes());
auto capturedValueTypes = mlir::ValueRange{ capturedValues }.getTypes();
argTypes.append(capturedValueTypes.begin(), capturedValueTypes.end());
// TODO: maybe support return types with lambdas
auto fnType = rewriter.getFunctionType(argTypes, llvm::None);
auto vFuncOp = [&] {
auto vModuleOp = utilir::CastOrGetParentOfType<vir::ValueModuleOp>(op);
assert(vModuleOp);
OpBuilder::InsertionGuard guard(rewriter);
rewriter.restoreInsertionPoint(utilir::GetTerminalInsertPoint<vir::ValueModuleOp, vir::ModuleTerminatorOp>(vModuleOp));
auto loc = accera::ir::util::GetLocation(rewriter, __FILE__, __LINE__);
vir::ValueFuncOp vFuncOp = rewriter.create<vir::ValueFuncOp>(loc, op.sym_name(), fnType, op.exec_target());
vFuncOp.setPrivate();
return vFuncOp;
}();
auto& bodyBlock = vFuncOp.front();
auto funcArgs = ValueRange{ vFuncOp.getArguments() };
{
OpBuilder::InsertionGuard guard(rewriter);
rewriter.setInsertionPoint(&bodyBlock, bodyBlock.end());
BlockAndValueMapping valueMapper;
for (auto [fromValue, toValue] : llvm::zip(op.args(), funcArgs.take_front(op.args().size())))
{
if (!valueMapper.contains(fromValue))
valueMapper.map(fromValue, toValue);
}
for (auto [fromValue, toValue] : llvm::zip(capturedValues, funcArgs.drop_front(op.args().size())))
{
if (!valueMapper.contains(fromValue))
valueMapper.map(fromValue, toValue);
}
for (Operation* constant : constants)
{
rewriter.clone(*constant, valueMapper);
}
rewriter.cloneRegionBefore(op.body(), vFuncOp.body(), vFuncOp.body().end(), valueMapper);
rewriter.mergeBlocks(&vFuncOp.back(), &vFuncOp.front(), vFuncOp.front().getArguments().take_front(vFuncOp.back().getNumArguments()));
}
vFuncOp.setType(rewriter.getFunctionType(vFuncOp.front().getArgumentTypes(), llvm::None));
auto args = llvm::to_vector<4>(op.args());
args.append(capturedValues.begin(), capturedValues.end());
[[maybe_unused]] auto launchFuncOp = rewriter.create<vir::LaunchFuncOp>(accera::ir::util::GetLocation(rewriter, __FILE__, __LINE__), vFuncOp, args);
if (auto launchAttr = op->getAttr(vir::ValueFuncOp::getGPULaunchAttrName()))
{
launchFuncOp->setAttr(vir::ValueFuncOp::getGPULaunchAttrName(), launchAttr);
vFuncOp->setAttr(vir::ValueFuncOp::getGPULaunchAttrName(), launchAttr);
}
rewriter.eraseOp(op);
}
};
struct ValueLaunchFuncOpInlinerPattern : OpRewritePattern<vir::LaunchFuncOp>
{
using OpRewritePattern::OpRewritePattern;
LogicalResult matchAndRewrite(vir::LaunchFuncOp op, PatternRewriter& rewriter) const final
{
auto target = op.exec_targetAttr();
auto callee = op.callee().getLeafReference();
auto parentFnOp = op->getParentWithTrait<mlir::OpTrait::FunctionLike>();
if (parentFnOp->getAttr(ir::RawPointerAPIAttrName))
{
// Don't inline calls from RawPointerAPI functions
return failure();
}
if (auto attr = parentFnOp->getAttrOfType<vir::ExecutionTargetAttr>(vir::ValueFuncOp::getExecTargetAttrName());
attr && target == attr)
{
auto callInterface = mlir::dyn_cast<mlir::CallOpInterface>(op.getOperation());
auto callable = callInterface.resolveCallable();
if (!callable)
{
callable = mlir::SymbolTable::lookupNearestSymbolFrom(parentFnOp->getParentOp(), callee);
}
assert(llvm::isa<vir::ValueFuncOp>(callable) || llvm::isa<vir::ValueLambdaOp>(callable));
if (callable->getAttr("external"))
{
return failure();
}
if (callable->getAttr(ir::NoInlineAttrName))
{
return failure();
}
auto& body = callable->getRegion(0);
mlir::BlockAndValueMapping mapping;
for (auto [src, dst] : llvm::zip(body.front().getArguments(), op.getOperands()))
{
mapping.map(src, dst);
}
for (auto& bodyOp : body.front().without_terminator())
{
rewriter.clone(bodyOp, mapping);
}
rewriter.eraseOp(op);
return success();
}
return failure();
}
};
} // namespace
namespace accera::transforms::value
{
void populateValueFuncToTargetPatterns(mlir::MLIRContext* context, mlir::OwningRewritePatternList& patterns)
{
uint16_t benefit = 1;
patterns.insert<ValueReturnOpConversion>(context, benefit++);
patterns.insert<ValueFuncToTargetPattern>(context, benefit++);
}
void populateValueLambdaToFuncPatterns(mlir::MLIRContext* context, mlir::OwningRewritePatternList& patterns)
{
uint16_t benefit = 1;
patterns.insert<ValueLambdaRewritePattern>(context, benefit++);
}
void populateValueLaunchFuncInlinerPatterns(mlir::MLIRContext* context, mlir::OwningRewritePatternList& patterns)
{
uint16_t benefit = 1;
patterns.insert<ValueLaunchFuncOpInlinerPattern>(context, benefit++);
}
std::unique_ptr<mlir::OperationPass<mlir::ModuleOp>> createValueFuncToTargetPass()
{
return std::make_unique<ValueFuncToTargetPass>();
}
} // namespace accera::transforms::value
| 13,270
| 3,952
|
#include <stdio.h>
#include <opencv2/opencv.hpp>
#include "headerfile.h"
using namespace cv;
bool readImage(char *img,Mat &image){
image = imread(img, CV_LOAD_IMAGE_COLOR);
if(! image.data )
{
printf( "Could not open or find the image\n" );
return false;
}
return true;
}
| 302
| 115
|
#include "AI01320xDecoder.h"
namespace zxing {
namespace oned {
namespace rss {
AI01320xDecoder::AI01320xDecoder(Ref<BitArray> information)
: AI013x0xDecoder(information)
{
}
void AI01320xDecoder::addWeightCode(String &buf, int weight)
{
if (weight < 10000) {
buf.append("(3202)");
} else {
buf.append("(3203)");
}
}
int AI01320xDecoder::checkWeight(int weight)
{
if (weight < 10000) {
return weight;
}
return weight - 10000;
}
}
}
}
| 492
| 226
|
#include <iostream>
#include <vector>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
int a, b;
cin >> a >> b;
vector<int> sequence(1, 1);
int sumRange = 0;
while (sequence.size() < 1000) {
int lastNumber = sequence.back();
for (int i = 0; i <= lastNumber; i++) {
sequence.push_back(lastNumber + 1);
}
}
for (int i = a - 1; i < b; i++) {
sumRange += sequence[i];
}
cout << sumRange << "\n";
return 0;
}
| 532
| 202
|
// { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
vector <int> countDistinct(int[], int, int);
int main()
{
int t;
cin >> t;
while (t--)
{
int n, k;
cin >> n >> k;
int a[n];
for (int i = 0; i < n; i++)
cin >> a[i];
vector <int> result = countDistinct(a, n, k);
for (int i : result)
cout << i << " ";
cout << endl;
}
return 0;
}// } Driver Code Ends
vector <int> countDistinct (int A[], int n, int k)
{
//code here.
unordered_map<int, int> m;
for(int i = 0; i < k; i++)
{
m[A[i]]++;
}
vector<int> v;
v.push_back(m.size());
for(int i = k; i < n; i++)
{
m[A[i - k]]--;
if(m[A[i - k]] == 0)
{
m.erase(A[i - k]);
}
m[A[i]]++;
v.push_back(m.size());
}
return v;
}
| 945
| 382
|
#include <bits/stdc++.h>
using namespace std;
//function to calculate range for given set of numeric data
template <typename T>
double range(T arr[], int start, int end)
{
double max = arr[start], min = arr[start];
for (int i = start; i < end; i++)
{
if (arr[i] > max)
max = arr[i];
if (arr[i] < min)
min = arr[i];
}
return max - min;
}
//function to calculate variance with respect to given mean for given range of numeric data types
template <typename T>
double variance(T arr[], int start, int end, double mean)
{
double temp, sum = 0;
for (int i = start; i < end; i++)
{
temp = mean - arr[i];
sum += (temp * temp);
}
return sum / (end - start);
}
//function to calculate standard deviation with respect to given mean for given range of numeric data types
template <typename T>
double standard_deviation(T arr[], int start, int end, double mean)
{
return sqrt(variance(arr, start, end, mean));
}
int main()
{
int i, n = 10;
int arr[] = {1, 2, 3, 4, 4, 6, 7, 8, 8, 10};
cout << "Range = " << range(arr, 0, n) << "\n";
cout << "Variance with respect to 5 = " << variance(arr, 0, n, 5) << "\n";
cout << "Standard Deviation with respect to 5 = " << standard_deviation(arr, 0, n, 5);
}
| 1,303
| 445
|
#include "Isis.h"
#include <map>
#include "Application.h"
#include "ControlMeasure.h"
#include "ControlNet.h"
#include "ControlPoint.h"
#include "FileList.h"
#include "IException.h"
#include "IString.h"
#include "Latitude.h"
#include "Longitude.h"
#include "Preference.h"
#include "Progress.h"
#include "Pvl.h"
#include "PvlGroup.h"
#include "PvlObject.h"
#include "SerialNumberList.h"
#include "SpecialPixel.h"
#include "SurfacePoint.h"
#include "TextFile.h"
#include "UserInterface.h"
using namespace std;
using namespace Isis;
std::map <int, QString> snMap;
//std::map <string,int> fscMap;
void IsisMain() {
// The following steps can take a significant amount of time, so
// set up a progress object, incrementing at 1%, to keep the user informed
PvlGroup &uip = Preference::Preferences().findGroup("UserInterface");
uip["ProgressBarPercent"] = "1";
UserInterface &ui = Application::GetUserInterface();
Progress progress;
// Prepare the ISIS2 list of file names
FileList list2(ui.GetFileName("LIST2"));
// Prepare the ISIS3 SNs, pass the progress object to SerialNumberList
SerialNumberList snl(ui.GetFileName("LIST3"), true, &progress);
progress.CheckStatus();
if (list2.size() != snl.size()) {
QString msg = "Invalid input file number of lines. The ISIS2 file list [";
msg += ui.GetAsString("LIST2") + "] must contain the same number of lines ";
msg += "as the ISIS3 file list [" + ui.GetAsString("LIST3") + "]";
throw IException(IException::User, msg, _FILEINFO_);
}
progress.SetText("Mapping ISIS2 fsc numbers to ISIS3 serial numbers.");
progress.SetMaximumSteps(list2.size());
// Setup a map between ISIS2 image number (fsc) and ISIS3 sn
// **NOTE:
// The order of the ISIS2 and ISIS3 lists MUST correspond so that we can map
// each ISIS2 FSC to the proper ISIS3 Serial Number.
// Otherwise, we would be required to write a separate routine for each
// mission to determine the corresponding serial number for a given FSC.
// Jeannie Backer 2011-06-30
for (int f = 0; f < list2.size(); f++) {
progress.CheckStatus();
QString currFile(list2[f].toString());
Pvl lab(currFile);
PvlObject qube(lab.findObject("QUBE"));
IString fsc;
if (qube.hasKeyword("IMAGE_NUMBER")) {
fsc = qube.findKeyword("IMAGE_NUMBER")[0];
}
else if (qube.hasKeyword("IMAGE_ID")) {
fsc = qube.findKeyword("IMAGE_ID")[0];
}
else {
throw IException(IException::Unknown,
"Can not find required keyword IMAGE_NUMBER or IMAGE_ID "
"in [" + currFile + "]",
_FILEINFO_);
}
QString sn(snl.serialNumber(f));
snMap.insert(std::pair<int, QString>((int)fsc, sn));
}
progress.CheckStatus();
// Create a new control network
ControlNet cnet;
cnet.SetNetworkId(ui.GetString("NETWORKID"));
// first try to set target from user entered TargetName
cnet.SetTarget(ui.GetString("TARGET"));
// if that fails, look in a cube label for the info
if ( !cnet.GetTargetRadii()[0].isValid() ) {
Pvl isis3Lab(snl.fileName(0));
cnet.SetTarget(isis3Lab);
}
cnet.SetUserName(Application::UserName());
cnet.SetCreatedDate(Application::DateTime());
cnet.SetDescription(ui.GetString("DESCRIPTION"));
// Open the match point file
TextFile mpFile(ui.GetFileName("MATCH"));
QString currLine;
int inTotalMeas = 0;
// Read the first line with the number of measurments
mpFile.GetLine(currLine);
currLine = currLine.simplified();
currLine.remove(0, currLine.indexOf("="));
currLine.remove(0, currLine.indexOf(" "));
try {
inTotalMeas = toInt(currLine);
}
catch (IException &e) {
throw IException(e,
IException::User, "Invalid match point file "
"header for [" + ui.GetAsString("MATCH")
+ "]. First line does not contain number of "
"measurements.",
_FILEINFO_);
}
// Read line 2, the column header line
mpFile.GetLine(currLine);
currLine = currLine.simplified();
QStringList tokens = currLine.split(" ", QString::SkipEmptyParts);
while (!tokens.isEmpty()) {
QString label = tokens.takeFirst();
// this line should contain only text labels,
double error = 0;
try {
error = toDouble(label);
// if we are able to convert label to a double, we have an error
throw IException(IException::User, "Invalid match point file "
"header for [" + ui.GetAsString("MATCH")
+ "]. Second line does not contain proper "
"non-numerical column labels.",
_FILEINFO_);
}
catch (IException &e) {
// if this line does not contain a double, continue
if (error == 0) {
continue;
}
// if this line contains numeric data, throw an error
else {
throw;
}
}
}
// Reset the progress object for feedback about conversion processing
progress.SetText("Converting match point file");
progress.SetMaximumSteps(inTotalMeas);
int line = 2;
while (mpFile.GetLine(currLine)) {
line ++;
// Update the Progress object
try {
progress.CheckStatus();
}
catch (IException &e) {
QString msg = "\"Matchpoint total\" keyword at the top of the match point "
"file [";
msg += ui.GetAsString("MATCH") + "] equals [" + toString(inTotalMeas);
msg += "] and is likely incorrect. Number of measures in match point file"
" exceeds this value at line [";
msg += toString(line) + "].";
throw IException(e, IException::User, msg, _FILEINFO_);
}
// Declare the Point and Measure
ControlPoint *cpoint = NULL;
ControlMeasure *cmeasure = new ControlMeasure;
// Section the match point line into the important pieces
currLine = currLine.simplified();
QString pid = "";
QString fsc = "";
double lineNum, sampNum, diam;
QString matClass = "";
try {
QStringList tokens = currLine.split(" ");
if (tokens.count() < 6)
throw IException();
pid = tokens.takeFirst(); // ID of the point
fsc = tokens.takeFirst(); // FSC of the ISIS2 cube
lineNum = toDouble(tokens.takeFirst()); // line number
sampNum = toDouble(tokens.takeFirst()); // sample number
matClass = tokens.takeFirst(); // Match Point Class
diam = toDouble(tokens.takeFirst()); // Diameter, in case of a crater
}
catch (IException &e) {
QString msg = "Invalid value(s) in match point file [";
msg += ui.GetAsString("MATCH") + "] at line [" + toString(line);
msg += "]. Verify line, sample, diameter values are doubles.";
throw IException(e, IException::User, msg, _FILEINFO_);
}
// Set the coordinate and serial number for this measure
cmeasure->SetCoordinate(sampNum, lineNum);
cmeasure->SetCubeSerialNumber(snMap[toInt(fsc)]);
if (snMap[toInt(fsc)].isEmpty()) {
QString msg = "None of the images specified in the ISIS2 file list [";
msg += ui.GetAsString("LIST2");
msg += "] have an IMAGE_NUMBER or IMAGE_ID that matches the FSC [" + fsc;
msg += "], from the match point file [" + ui.GetAsString("MATCH");
msg += "] at line [" + toString(line) + "]";
throw IException(IException::User, msg, _FILEINFO_);
}
bool isReferenceMeasure = false;
//Set the Measure Type
if (matClass.toUpper() == "U") {//Unmeasured -these are ignored in isis2
cmeasure->SetType(ControlMeasure::Candidate);
cmeasure->SetIgnored(true);
}
else if (matClass.toUpper() == "T") {
// Truth type, aka reference measure, is no longer a measure type
// what this means is it has to be handled by the control point.
// So, further down the boolean set here will be used.
isReferenceMeasure = true;
}
else if (matClass.toUpper() == "S") { //SubPixel
cmeasure->SetType(ControlMeasure::RegisteredSubPixel);
}
else if (matClass.toUpper() == "M") { //Measured
cmeasure->SetType(ControlMeasure::RegisteredPixel);
}
else if (matClass.toUpper() == "A") { //Approximate
cmeasure->SetType(ControlMeasure::Candidate);
}
else {
QString msg = "Unknown measurment type [" + matClass + "] ";
msg += "in match point file [" + ui.GetAsString("MATCH") + "] ";
msg += "at line [" + toString(line) + "]";
throw IException(IException::User, msg, _FILEINFO_);
}
//Set Diameter
try {
//Check to see if the column was, in fact, a double
if ((double)IString(diam) != 0.0)
cmeasure->SetDiameter(diam);
}
catch (IException &) {
//If we get here, diam was not a double,
// but the error is not important otherwise
}
// Check whether we should lock all measures
cmeasure->SetEditLock(ui.GetBoolean("MEASURELOCK"));
//Find the point that matches the PointID, create point if it does not exist
if (cnet.ContainsPoint(pid)) {
cpoint = cnet.GetPoint((QString) pid);
}
else {
cpoint = new ControlPoint(pid);
cnet.AddPoint(cpoint);
}
//Add the measure
try {
cpoint->Add(cmeasure);
// Equivalent to (IString::Equal(matClass, "T")), as seen above
if (isReferenceMeasure) {
cpoint->SetRefMeasure(cmeasure);
}
}
catch (IException &e) {
QString msg = "Invalid match point file [" + ui.GetAsString("MATCH") +"]";
msg += ". Repeated PointID/FSC combination [" + pid + ", " + fsc;
msg += "] in match point file at line [" + toString(line) + "].";
throw IException(e, IException::User, msg, _FILEINFO_);
}
}
// Update the Progress object
try {
progress.CheckStatus();
}
catch (IException &e) {
QString msg = "\"Matchpoint total\" keyword at the top of the match point "
"file [";
msg += ui.GetAsString("MATCH") + "] equals [" + toString(inTotalMeas);
msg += "] and is likely incorrect. Number of measures in match point file "
"exceeds this value at line [";
msg += toString(line) + "].";
throw IException(e, IException::User, msg, _FILEINFO_);
}
// 10/5/2009 Jeannie Walldren - Added RAND PPP file as input
// 7/12/2011 Jeannie Backer - Added option to lock all points in RAND PPP file
// Open the RAND PPP file
if (ui.GetBoolean("INPUTPPP")) {
int numRandOnly = 0;
vector<QString> randOnlyIDs;
TextFile randFile(ui.GetFileName("PPP"));
progress.SetText("Converting RAND PPP file");
randFile.GetLine(currLine);
int inTotalLine = (int)(randFile.Size() / (currLine.size()));
progress.SetMaximumSteps(inTotalLine);
randFile.Rewind();
line = 0;
while (randFile.GetLine(currLine)) {
line ++;
// Update the Progress object
try {
progress.CheckStatus();
}
catch (IException &e) {
QString msg = "RAND PPP file may not be valid. Line count calculated [";
msg += toString(inTotalLine) + "] for RAND PPP file [";
msg += ui.GetAsString("PPP") + "] appears invalid at line [";
msg += toString(line) + "].";
throw IException(e, IException::Programmer, msg, _FILEINFO_);
}
// Declare the Point
ControlPoint *cpoint = NULL;
// if end of valid data, break, stop processing
if (currLine.contains("JULIAN")) {
// Since Progress MaximumSteps was approximated using the number of
// lines in the RAND PPP file, we need to subtract the number of lines
// left from the Progress steps since the following lines are not going
// to be processed
progress.AddSteps(line - inTotalLine); // line < inTotalLine,
//so this is negative
break;
}
// break columns into substrings since some files have colunms that can't
// be tokenized easily. This is because some files have columns running
// into each other without spaces separating them
// column 1 = latitude, begins the line and is 24 characters
double lat;
QString col1 = currLine.mid(0, 24);
// remove any white space from beginning of string
//col1.ConvertWhiteSpace();
//col1.TrimHead(" ");
try {
// convert to double
lat = toDouble(col1);
}
catch (IException &e) {
QString msg = "Invalid value(s) in RAND PPP file [";
msg += ui.GetAsString("PPP") + "] at line [" + toString(line);
msg += "]. Verify latitude value is a double.";
throw IException(e, IException::User, msg, _FILEINFO_);
}
// column 2 = longitude, begins at 25th char and is 24 characters
double lon;
QString col2 = currLine.mid(24, 24);
// remove any white space from beginning of string
//col2.TrimHead(" ");
try {
// convert to double
lon = toDouble(col2);
}
catch (IException &e) {
QString msg = "Invalid value(s) in RAND PPP file [";
msg += ui.GetAsString("PPP") + "] at line [" + toString(line);
msg += "]. Verify longitude value is a double.";
throw IException(e, IException::User, msg, _FILEINFO_);
}
// column 3 = radius, begins at 49th char and is 24 characters
double rad;
QString col3 = currLine.mid(48, 24);
// remove any white space from beginning of string
//col3.TrimHead(" ");
try {
// convert to double and convert km to meters
rad = toDouble(col3);
rad = rad * 1000;
}
catch (IException &e) {
QString msg = "Invalid value(s) in RAND PPP file [";
msg += ui.GetAsString("PPP") + "] at line [" + toString(line);
msg += "]. Verify radius value is a double.";
throw IException(e, IException::User, msg, _FILEINFO_);
}
// column 4 = point id, begins at 73rd char and is 7 characters
QString pid = currLine.mid(72);
// remove any white space from beginning of string
pid = pid.remove(QRegExp("^ *"));
if (pid.length() > 7) {
QString msg = "Invalid value(s) in RAND PPP file [";
msg += ui.GetAsString("PPP") + "] at line [" + toString(line);
msg += "]. Point ID [" + pid + "] has more than 7 characters.";
throw IException(IException::User, msg, _FILEINFO_);
}
//Find the point that matches the PointID, if it does not exist alert the
//user
if (!cnet.ContainsPoint(pid)) {
numRandOnly++;
randOnlyIDs.push_back(currLine);
}
else {
cpoint = cnet.GetPoint((QString) pid);
// if the point is already added to the control net, it was found in
// the match point file also.
if (ui.GetString("POINTTYPE") == "FIXED") {
// If the POINTTYPE parameter is set to fixed, change point type
// of points in rand file
cpoint->SetType(ControlPoint::Fixed);
}
cpoint->SetAprioriSurfacePointSource(
ControlPoint::SurfacePointSource::BundleSolution);
cpoint->SetAprioriSurfacePointSourceFile(ui.GetAsString("PPP"));
cpoint->SetAprioriRadiusSource(
ControlPoint::RadiusSource::BundleSolution);
cpoint->SetAprioriRadiusSourceFile(ui.GetAsString("PPP"));
}
if (cpoint != NULL) {
//Add the lat,lon,rad to point
try {
SurfacePoint surfacePt(Latitude(lat, Angle::Degrees),
Longitude(lon, Angle::Degrees),
Distance(rad, Distance::Meters));
cpoint->SetAprioriSurfacePoint(surfacePt);
cpoint->SetEditLock(ui.GetBoolean("POINTLOCK"));
}
catch (IException &e) {
QString msg = "Unable to set universal ground point to control "
"network from line [";
msg += toString(line) + "] of RAND PPP file [";
msg += ui.GetAsString("PPP") + "]";
throw IException(e, IException::User, msg, _FILEINFO_);
}
}
}
// Update the Progress object
try {
progress.CheckStatus();
}
catch (IException &e) {
QString msg = "RAND PPP file may not be valid. Line count calculated [";
msg += toString(inTotalLine) + "] for RAND PPP file [";
msg += ui.GetAsString("PPP");
msg += "] appears invalid at line [" + toString(line) + "].";
throw IException(e, IException::Programmer, msg, _FILEINFO_);
}
// Write results to Logs
// Summary group is created with the counts of RAND PPP only points
PvlGroup summaryGroup = PvlGroup("Summary");
summaryGroup.addKeyword(PvlKeyword("RandOnlyPoints", toString(numRandOnly)));
bool log;
FileName logFile;
// if a filename was entered, use it to create the log
if (ui.WasEntered("LOG")) {
log = true;
logFile = ui.GetFileName("LOG");
}
// if no filename was entered, but there were some RAND PPP only points,
// create an log named "pppOnlyPoints" in the current directory
else if (numRandOnly > 0) {
log = true;
logFile = "pppOnlyPoints.log";
}
// if all RAND PPP points are found in the MATCH file and no log file is
// named, only output summary to application log
else {
log = false;
}
if (log) {
// Write details in error log
Pvl results;
results.setName("Results");
results.addGroup(summaryGroup);
if (numRandOnly > 0) {
// if there are any RAND PPP only points,
// add comment to the summary log to alert user
summaryGroup.addComment("Some Point IDs in the RAND PPP file have no "
"measures in the MATCH file.");
summaryGroup.addComment("These Point IDs are contained "
"in [" + logFile.name() + "].");
TextFile outlog(logFile.expanded(), "overwrite", randOnlyIDs);
}
else {
// if there are no RAND PPP only points and user wanted to create a log,
// add comment to the summary log to alert user
summaryGroup.addComment("All Point IDs in the RAND PPP file have "
"measures in the MATCH file.");
summaryGroup.addComment("No RAND PPP log was created.");
}
}
// Write summary to application log
Application::Log(summaryGroup);
}
// Write the control network out
cnet.Write(ui.GetFileName("ONET"));
}
| 18,565
| 5,734
|
#pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/Handle.hpp>
#include <RED4ext/Scripting/Natives/Generated/quest/ETimeDilationOverride.hpp>
#include <RED4ext/Scripting/Natives/Generated/quest/TimeDilation_NodeTypeParam.hpp>
namespace RED4ext
{
namespace quest { struct TimeDilation_Operation; }
namespace quest {
struct TimeDilation_Player : quest::TimeDilation_NodeTypeParam
{
static constexpr const char* NAME = "questTimeDilation_Player";
static constexpr const char* ALIAS = NAME;
Handle<quest::TimeDilation_Operation> operation; // 30
quest::ETimeDilationOverride globalTimeDilationOverride; // 40
uint8_t unk44[0x48 - 0x44]; // 44
};
RED4EXT_ASSERT_SIZE(TimeDilation_Player, 0x48);
} // namespace quest
} // namespace RED4ext
| 847
| 286
|
#include "token_type.hpp"
#include <string>
#include <unordered_map>
#include <cassert>
#include <cstring>
namespace mt {
TokenType from_symbol(std::string_view s) {
static std::unordered_map<std::string, TokenType> symbol_map{
{"(", TokenType::left_parens},
{")", TokenType::right_parens},
{"[", TokenType::left_bracket},
{"]", TokenType::right_bracket},
{"{", TokenType::left_brace},
{"}", TokenType::right_brace},
{"=", TokenType::equal},
{"==", TokenType::equal_equal},
{"~=", TokenType::not_equal},
{"<", TokenType::less},
{">", TokenType::greater},
{"<=", TokenType::less_equal},
{">=", TokenType::greater_equal},
{"~", TokenType::tilde},
{":", TokenType::colon},
{";", TokenType::semicolon},
{".", TokenType::period},
{",", TokenType::comma},
{"+", TokenType::plus},
{"-", TokenType::minus},
{"*", TokenType::asterisk},
{"/", TokenType::forward_slash},
{"\\", TokenType::back_slash},
{"^", TokenType::carat},
{".*", TokenType::dot_asterisk},
{"./", TokenType::dot_forward_slash},
{".\\", TokenType::dot_back_slash},
{".^", TokenType::dot_carat},
{"@", TokenType::at},
{"\n", TokenType::new_line},
{"?", TokenType::question},
{"'", TokenType::apostrophe},
{"\"", TokenType::quote},
{"|", TokenType::vertical_bar},
{"&", TokenType::ampersand},
{"||", TokenType::double_vertical_bar},
{"&&", TokenType::double_ampersand},
{"break", TokenType::keyword_break},
{"case", TokenType::keyword_case},
{"catch", TokenType::keyword_catch},
{"classdef", TokenType::keyword_classdef},
{"continue", TokenType::keyword_continue},
{"else", TokenType::keyword_else},
{"elseif", TokenType::keyword_elseif},
{"end", TokenType::keyword_end},
{"for", TokenType::keyword_for},
{"function", TokenType::keyword_function},
{"fun", TokenType::keyword_fun_type},
{"global", TokenType::keyword_global},
{"if", TokenType::keyword_if},
{"otherwise", TokenType::keyword_otherwise},
{"parfor", TokenType::keyword_parfor},
{"persistent", TokenType::keyword_persistent},
{"return", TokenType::keyword_return},
{"spmd", TokenType::keyword_spmd},
{"switch", TokenType::keyword_switch},
{"try", TokenType::keyword_try},
{"while", TokenType::keyword_while},
{"enumeration", TokenType::keyword_enumeration},
{"events", TokenType::keyword_events},
{"methods", TokenType::keyword_methods},
{"properties", TokenType::keyword_properties},
{"import", TokenType::keyword_import},
{"begin", TokenType::keyword_begin},
{"export", TokenType::keyword_export},
{"given", TokenType::keyword_given},
{"let", TokenType::keyword_let},
{"namespace", TokenType::keyword_namespace},
{"struct", TokenType::keyword_struct},
{"record", TokenType::keyword_record},
{"@T", TokenType::type_annotation_macro},
{"::", TokenType::double_colon},
{"declare", TokenType::keyword_declare},
{"constructor", TokenType::keyword_constructor},
{"list", TokenType::keyword_list},
{"cast", TokenType::keyword_cast},
{"presume", TokenType::keyword_presume}
};
const auto it = symbol_map.find(std::string(s));
if (it == symbol_map.end()) {
return TokenType::null;
} else {
return it->second;
}
}
const char* to_symbol(TokenType type) {
switch (type) {
case TokenType::left_parens:
return "(";
case TokenType::right_parens:
return ")";
case TokenType::left_brace:
return "{";
case TokenType::right_brace:
return "}";
case TokenType::left_bracket:
return "[";
case TokenType::right_bracket:
return "]";
// Punct
case TokenType::ellipsis:
return "...";
case TokenType::equal:
return "=";
case TokenType::equal_equal:
return "==";
case TokenType::not_equal:
return "~=";
case TokenType::less:
return "<";
case TokenType::greater:
return ">";
case TokenType::less_equal:
return "<=";
case TokenType::greater_equal:
return ">=";
case TokenType::tilde:
return "~";
case TokenType::colon:
return ":";
case TokenType::double_colon:
return "::";
case TokenType::semicolon:
return ";";
case TokenType::period:
return ".";
case TokenType::comma:
return ",";
case TokenType::plus:
return "+";
case TokenType::minus:
return "-";
case TokenType::asterisk:
return "*";
case TokenType::forward_slash:
return "/";
case TokenType::back_slash:
return "\\";
case TokenType::carat:
return "^";
case TokenType::dot_asterisk:
return ".*";
case TokenType::dot_forward_slash:
return "./";
case TokenType::dot_back_slash:
return ".\\";
case TokenType::dot_carat:
return ".^";
case TokenType::dot_apostrophe:
return ".'";
case TokenType::at:
return "@";
case TokenType::new_line:
return "\n";
case TokenType::question:
return "?";
case TokenType::apostrophe:
return "'";
case TokenType::quote:
return "\"";
case TokenType::vertical_bar:
return "|";
case TokenType::ampersand:
return "&";
case TokenType::double_vertical_bar:
return "||";
case TokenType::double_ampersand:
return "&&";
case TokenType::op_end:
return "end";
// Ident + literals
case TokenType::identifier:
return "<identifier>";
case TokenType::char_literal:
return "<char_literal>";
case TokenType::string_literal:
return "<string_literal>";
case TokenType::number_literal:
return "<number_literal>";
// Keywords
case TokenType::keyword_break:
return "break";
case TokenType::keyword_case:
return "case";
case TokenType::keyword_catch:
return "catch";
case TokenType::keyword_classdef:
return "classdef";
case TokenType::keyword_continue:
return "continue";
case TokenType::keyword_else:
return "else";
case TokenType::keyword_elseif:
return "elseif";
case TokenType::keyword_end:
return "end";
case TokenType::keyword_for:
return "for";
case TokenType::keyword_function:
return "function";
case TokenType::keyword_global:
return "global";
case TokenType::keyword_if:
return "if";
case TokenType::keyword_otherwise:
return "otherwise";
case TokenType::keyword_parfor:
return "parfor";
case TokenType::keyword_persistent:
return "persistent";
case TokenType::keyword_return:
return "return";
case TokenType::keyword_spmd:
return "spmd";
case TokenType::keyword_switch:
return "switch";
case TokenType::keyword_try:
return "try";
case TokenType::keyword_while:
return "while";
// Class keywords
case TokenType::keyword_enumeration:
return "enumeration";
case TokenType::keyword_events:
return "events";
case TokenType::keyword_methods:
return "methods";
case TokenType::keyword_properties:
return "properties";
case TokenType::keyword_import:
return "import";
// Typing keywords
case TokenType::keyword_begin:
return "begin";
case TokenType::keyword_export:
return "export";
case TokenType::keyword_given:
return "given";
case TokenType::keyword_let:
return "let";
case TokenType::keyword_namespace:
return "namespace";
case TokenType::keyword_struct:
return "struct";
case TokenType::keyword_record:
return "record";
case TokenType::keyword_function_type:
return "function";
case TokenType::keyword_fun_type:
return "fun";
case TokenType::keyword_end_type:
return "end";
case TokenType::type_annotation_macro:
return "@T";
case TokenType::keyword_declare:
return "declare";
case TokenType::keyword_constructor:
return "constructor";
case TokenType::keyword_list:
return "list";
case TokenType::keyword_cast:
return "cast";
case TokenType::keyword_presume:
return "presume";
case TokenType::null:
return "<null>";
}
assert(false);
return "<null>";
}
const char* to_string(TokenType type) {
switch (type) {
case TokenType::left_parens:
return "left_parens";
case TokenType::right_parens:
return "right_parens";
case TokenType::left_brace:
return "left_brace";
case TokenType::right_brace:
return "right_brace";
case TokenType::left_bracket:
return "left_bracket";
case TokenType::right_bracket:
return "right_bracket";
// Punct
case TokenType::ellipsis:
return "ellipsis";
case TokenType::equal:
return "equal";
case TokenType::equal_equal:
return "equal_equal";
case TokenType::not_equal:
return "not_equal";
case TokenType::less:
return "less";
case TokenType::greater:
return "greater";
case TokenType::less_equal:
return "less_equal";
case TokenType::greater_equal:
return "greater_equal";
case TokenType::tilde:
return "tilde";
case TokenType::colon:
return "colon";
case TokenType::double_colon:
return "double_colon";
case TokenType::semicolon:
return "semicolon";
case TokenType::period:
return "period";
case TokenType::comma:
return "comma";
case TokenType::plus:
return "plus";
case TokenType::minus:
return "minus";
case TokenType::asterisk:
return "asterisk";
case TokenType::forward_slash:
return "forward_slash";
case TokenType::back_slash:
return "back_slash";
case TokenType::carat:
return "carat";
case TokenType::dot_apostrophe:
return "dot_apostrophe";
case TokenType::dot_asterisk:
return "dot_asterisk";
case TokenType::dot_forward_slash:
return "dot_forward_slash";
case TokenType::dot_back_slash:
return "dot_backslash";
case TokenType::dot_carat:
return "dot_carat";
case TokenType::at:
return "at";
case TokenType::new_line:
return "new_line";
case TokenType::question:
return "question";
case TokenType::apostrophe:
return "apostrophe";
case TokenType::quote:
return "quote";
case TokenType::vertical_bar:
return "vertical_bar";
case TokenType::ampersand:
return "ampersand";
case TokenType::double_vertical_bar:
return "double_vertical_bar";
case TokenType::double_ampersand:
return "double_ampersand";
case TokenType::op_end:
return "op_end";
// Ident + literals
case TokenType::identifier:
return "identifier";
case TokenType::char_literal:
return "char_literal";
case TokenType::string_literal:
return "string_literal";
case TokenType::number_literal:
return "number_literal";
// Keywords
case TokenType::keyword_break:
return "keyword_break";
case TokenType::keyword_case:
return "keyword_case";
case TokenType::keyword_catch:
return "keyword_catch";
case TokenType::keyword_classdef:
return "keyword_classdef";
case TokenType::keyword_continue:
return "keyword_continue";
case TokenType::keyword_else:
return "keyword_else";
case TokenType::keyword_elseif:
return "keyword_elseif";
case TokenType::keyword_end:
return "keyword_end";
case TokenType::keyword_for:
return "keyword_for";
case TokenType::keyword_function:
return "keyword_function";
case TokenType::keyword_global:
return "keyword_global";
case TokenType::keyword_if:
return "keyword_if";
case TokenType::keyword_otherwise:
return "keyword_otherwise";
case TokenType::keyword_parfor:
return "keyword_parfor";
case TokenType::keyword_persistent:
return "keyword_persistent";
case TokenType::keyword_return:
return "keyword_return";
case TokenType::keyword_spmd:
return "keyword_spmd";
case TokenType::keyword_switch:
return "keyword_switch";
case TokenType::keyword_try:
return "keyword_try";
case TokenType::keyword_while:
return "keyword_while";
// Class keywords
case TokenType::keyword_enumeration:
return "keyword_enumeration";
case TokenType::keyword_events:
return "keyword_events";
case TokenType::keyword_methods:
return "keyword_methods";
case TokenType::keyword_properties:
return "keyword_properties";
case TokenType::keyword_import:
return "keyword_import";
// Typing keywords
case TokenType::keyword_begin:
return "keyword_begin";
case TokenType::keyword_export:
return "keyword_export";
case TokenType::keyword_given:
return "keyword_given";
case TokenType::keyword_let:
return "keyword_let";
case TokenType::keyword_namespace:
return "keyword_namespace";
case TokenType::keyword_struct:
return "keyword_struct";
case TokenType::keyword_record:
return "keyword_record";
case TokenType::keyword_function_type:
return "keyword_function_type";
case TokenType::keyword_fun_type:
return "keyword_fun_type";
case TokenType::keyword_end_type:
return "keyword_end_type";
case TokenType::keyword_declare:
return "keyword_declare";
case TokenType::keyword_constructor:
return "keyword_constructor";
case TokenType::keyword_list:
return "keyword_list";
case TokenType::keyword_cast:
return "keyword_cast";
case TokenType::keyword_presume:
return "keyword_presume";
case TokenType::type_annotation_macro:
return "type_annotation_macro";
case TokenType::null:
return "null";
}
assert(false);
return "null";
}
bool unsafe_represents_keyword(TokenType type) {
// @TODO: Implement this more carefully.
// std::strlen("keyword")
return std::strncmp("keyword", to_string(type), 7) == 0;
}
bool represents_literal(TokenType type) {
return type == TokenType::string_literal || type == TokenType::char_literal ||
type == TokenType::number_literal;
}
bool represents_expr_terminator(TokenType type) {
return represents_stmt_terminator(type) || represents_grouping_terminator(type) || type == TokenType::equal;
}
bool represents_stmt_terminator(TokenType type) {
return type == TokenType::semicolon || type == TokenType::comma || type == TokenType::new_line ||
type == TokenType::null;
}
bool represents_grouping_component(TokenType type) {
const auto min = static_cast<unsigned int>(TokenType::left_parens);
const auto max = static_cast<unsigned int>(TokenType::right_bracket);
const auto t = static_cast<unsigned int>(type);
return t >= min && t <= max;
}
bool represents_grouping_initiator(TokenType type) {
return type == TokenType::left_parens || type == TokenType::left_brace ||
type == TokenType::left_bracket;
}
bool represents_grouping_terminator(TokenType type) {
return type == TokenType::right_parens || type == TokenType::right_brace ||
type == TokenType::right_bracket;
}
bool represents_binary_operator(TokenType type) {
// @Hack, first 21 token types are binary operators.
return static_cast<unsigned int>(type) < 21;
}
bool represents_unary_operator(TokenType type) {
return represents_postfix_unary_operator(type) || represents_prefix_unary_operator(type);
}
bool represents_prefix_unary_operator(TokenType type) {
return type == TokenType::plus || type == TokenType::minus || type == TokenType::tilde;
}
bool can_precede_prefix_unary_operator(TokenType type) {
switch (type) {
case TokenType::identifier:
case TokenType::string_literal:
case TokenType::char_literal:
case TokenType::number_literal:
case TokenType::keyword_end:
case TokenType::op_end:
return false;
default:
return !represents_grouping_terminator(type) && !represents_postfix_unary_operator(type);
}
}
bool can_be_skipped_in_classdef_block(TokenType type) {
switch (type) {
case TokenType::comma:
case TokenType::semicolon:
case TokenType::new_line:
return true;
default:
return false;
}
}
bool can_precede_postfix_unary_operator(TokenType type) {
return represents_literal(type) || represents_grouping_terminator(type) ||
type == TokenType::identifier || type == TokenType::apostrophe || type == TokenType::dot_apostrophe;
}
bool represents_postfix_unary_operator(TokenType type) {
return type == TokenType::apostrophe || type == TokenType::dot_apostrophe;
}
std::array<TokenType, 3> grouping_terminators() {
return {{TokenType::right_parens, TokenType::right_bracket, TokenType::right_bracket}};
}
TokenType grouping_terminator_for(TokenType initiator) {
switch (initiator) {
case TokenType::left_brace:
return TokenType::right_brace;
case TokenType::left_bracket:
return TokenType::right_bracket;
case TokenType::left_parens:
return TokenType::right_parens;
default:
assert(false && "No grouping terminator for type.");
return TokenType::null;
}
}
}
| 17,342
| 5,292
|
// ArduinoJson - arduinojson.org
// Copyright Benoit Blanchon 2014-2020
// MIT License
#pragma once
#include <ArduinoJson/Namespace.hpp>
namespace ARDUINOJSON_NAMESPACE {
struct NestingLimit {
NestingLimit() : value(ARDUINOJSON_DEFAULT_NESTING_LIMIT) {}
explicit NestingLimit(uint8_t n) : value(n) {}
uint8_t value;
};
} // namespace ARDUINOJSON_NAMESPACE
| 385
| 159
|
/******************************************************************************/
/* Mednafen - Multi-system Emulator */
/******************************************************************************/
/* scsicd.cpp:
** Copyright (C) 2006-2018 Mednafen Team
**
** DoNEC_*() functions additionally:
** Copyright (C) 2004 Ki
**
** 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.,
** 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/*
When changing CD read timing(throughput, and startup/seek delay), be sure to test:
4 in 1 Super CD (check for stuck note when starting "Gate of Thunder")
Downtown Nekketsu Monogatari (with text speed set to fast, quickly enter and exit store and listen to ADPCM playback for glitches)
Galaxy Fraulein Yuna HuVideo CD
It Came from the Desert
John Madden Duo Football
Kuusou Kagaku Sekai Gulliver Boy
Magical Fantasy Adventure: Popful Mail (third cutscene, check for glitches and hang)
Mirai Shonen Conan (check for hang after boat sinking cutscene)
Sherlock Holmes Consulting Detective
*/
#include <mednafen/mednafen.h>
#include <mednafen/cdrom/CDInterface.h>
#include <trio/trio.h>
#include "scsicd.h"
#include "SimpleFIFO.h"
#if defined(__SSE2__)
#include <xmmintrin.h>
#include <emmintrin.h>
#endif
namespace Mednafen
{
//#define SCSIDBG(format, ...) { printf("[SCSICD] " format "\n", ## __VA_ARGS__); }
//#define SCSIDBG(format, ...) { }
using namespace CDUtility;
static uint32 CD_DATA_TRANSFER_RATE;
static uint32 System_Clock;
static void (*CDIRQCallback)(int);
static void (*CDStuffSubchannels)(uint8, int);
static int32* HRBufs[2];
static int WhichSystem;
static CDInterface *Cur_CDIF;
static bool TrayOpen;
// Internal operation to the SCSI CD unit. Only pass 1 or 0 to these macros!
#define SetIOP(mask, set) { cd_bus.signals &= ~mask; if(set) cd_bus.signals |= mask; }
#define SetBSY(set) SetIOP(SCSICD_BSY_mask, set)
#define SetIO(set) SetIOP(SCSICD_IO_mask, set)
#define SetCD(set) SetIOP(SCSICD_CD_mask, set)
#define SetMSG(set) SetIOP(SCSICD_MSG_mask, set)
static INLINE void SetREQ(bool set)
{
if(set && !REQ_signal)
CDIRQCallback(SCSICD_IRQ_MAGICAL_REQ);
SetIOP(SCSICD_REQ_mask, set);
}
#define SetkingACK(set) SetIOP(SCSICD_kingACK_mask, set)
#define SetkingRST(set) SetIOP(SCSICD_kingRST_mask, set)
#define SetkingSEL(set) SetIOP(SCSICD_kingSEL_mask, set)
#define SetkingATN(set) SetIOP(SCSICD_kingATN_mask, set)
enum
{
QMode_Zero = 0,
QMode_Time = 1,
QMode_MCN = 2, // Media Catalog Number
QMode_ISRC = 3 // International Standard Recording Code
};
typedef struct
{
bool last_RST_signal;
// The pending message to send(in the message phase)
uint8 message_pending;
bool status_sent, message_sent;
// Pending error codes
uint8 key_pending, asc_pending, ascq_pending, fru_pending;
uint8 command_buffer[256];
uint8 command_buffer_pos;
uint8 command_size_left;
// false if not all pending data is in the FIFO, true if it is.
// Used for multiple sector CD reads.
bool data_transfer_done;
// To target(the cd unit); for "MODE SELECT".
uint8 data_out[256]; // Technically it only needs to be 255, but powers of 2 are better than those degenerate powers of 2 minus one goons.
uint8 data_out_pos; // Current index for writing into data_out.
uint8 data_out_want; // Total number of bytes to buffer into data_out.
bool DiscChanged;
uint8 SubQBuf[4][0xC]; // One for each of the 4 most recent q-Modes.
uint8 SubQBuf_Last[0xC]; // The most recent q subchannel data, regardless of q-mode.
uint8 SubPWBuf[96];
} scsicd_t;
enum
{
CDDASTATUS_PAUSED = -1,
CDDASTATUS_STOPPED = 0,
CDDASTATUS_PLAYING = 1,
CDDASTATUS_SCANNING = 2,
};
enum
{
PLAYMODE_SILENT = 0x00,
PLAYMODE_NORMAL,
PLAYMODE_INTERRUPT,
PLAYMODE_LOOP,
};
typedef struct
{
uint32 CDDADivAcc;
uint8 CDDADivAccVolFudge; // For PC-FX CD-DA rate control RE impulses and resampling; 100 = 1.0.
uint32 scan_sec_end;
uint8 PlayMode;
int32 CDDAVolume[2]; // 65536 = 1.0, the maximum.
int16 CDDASectorBuffer[1176];
uint32 CDDAReadPos;
int8 CDDAStatus;
uint8 ScanMode;
int64 CDDADiv;
int CDDATimeDiv;
int16 OversampleBuffer[2][0x10 * 2]; // *2 so our MAC loop can blast through without masking the index.
unsigned OversamplePos;
int16 sr[2];
uint8 OutPortChSelect[2];
uint32 OutPortChSelectCache[2];
int32 OutPortVolumeCache[2];
float DeemphState[2][2];
} cdda_t;
void MakeSense(uint8 * target, uint8 key, uint8 asc, uint8 ascq, uint8 fru)
{
memset(target, 0, 18);
target[0] = 0x70; // Current errors and sense data is not SCSI compliant
target[2] = key;
target[7] = 0x0A;
target[12] = asc; // Additional Sense Code
target[13] = ascq; // Additional Sense Code Qualifier
target[14] = fru; // Field Replaceable Unit code
}
static void (*SCSILog)(const char *, const char *format, ...);
static void InitModePages(void);
static scsicd_timestamp_t lastts;
static int64 monotonic_timestamp;
static int64 pce_lastsapsp_timestamp;
scsicd_t cd;
scsicd_bus_t cd_bus;
static cdda_t cdda;
static SimpleFIFO<uint8> *din = NULL;
static CDUtility::TOC toc;
static uint32 read_sec_start;
static uint32 read_sec;
static uint32 read_sec_end;
static int32 CDReadTimer;
static uint32 SectorAddr;
static uint32 SectorCount;
enum
{
PHASE_BUS_FREE = 0,
PHASE_COMMAND,
PHASE_DATA_IN,
PHASE_DATA_OUT,
PHASE_STATUS,
PHASE_MESSAGE_IN,
PHASE_MESSAGE_OUT
};
static unsigned int CurrentPhase;
static void ChangePhase(const unsigned int new_phase);
static void FixOPV(void)
{
for(int port = 0; port < 2; port++)
{
int32 tmpvol = cdda.CDDAVolume[port] * 100 / (2 * cdda.CDDADivAccVolFudge);
//printf("TV: %d\n", tmpvol);
cdda.OutPortVolumeCache[port] = tmpvol;
if(cdda.OutPortChSelect[port] & 0x01)
cdda.OutPortChSelectCache[port] = 0;
else if(cdda.OutPortChSelect[port] & 0x02)
cdda.OutPortChSelectCache[port] = 1;
else
{
cdda.OutPortChSelectCache[port] = 0;
cdda.OutPortVolumeCache[port] = 0;
}
}
}
static void VirtualReset(void)
{
InitModePages();
din->Flush();
CDReadTimer = 0;
pce_lastsapsp_timestamp = monotonic_timestamp;
SectorAddr = SectorCount = 0;
read_sec_start = read_sec = 0;
read_sec_end = ~0;
cdda.PlayMode = PLAYMODE_SILENT;
cdda.CDDAReadPos = 0;
cdda.CDDAStatus = CDDASTATUS_STOPPED;
cdda.CDDADiv = 1;
cdda.ScanMode = 0;
cdda.scan_sec_end = 0;
cdda.OversamplePos = 0;
memset(cdda.sr, 0, sizeof(cdda.sr));
memset(cdda.OversampleBuffer, 0, sizeof(cdda.OversampleBuffer));
memset(cdda.DeemphState, 0, sizeof(cdda.DeemphState));
memset(cd.data_out, 0, sizeof(cd.data_out));
cd.data_out_pos = 0;
cd.data_out_want = 0;
FixOPV();
ChangePhase(PHASE_BUS_FREE);
}
void SCSICD_Power(scsicd_timestamp_t system_timestamp)
{
memset(&cd, 0, sizeof(scsicd_t));
memset(&cd_bus, 0, sizeof(scsicd_bus_t));
monotonic_timestamp = system_timestamp;
cd.DiscChanged = false;
if(Cur_CDIF && !TrayOpen)
Cur_CDIF->ReadTOC(&toc);
CurrentPhase = PHASE_BUS_FREE;
VirtualReset();
}
void SCSICD_SetDB(uint8 data)
{
cd_bus.DB = data;
//printf("Set DB: %02x\n", data);
}
void SCSICD_SetACK(bool set)
{
SetkingACK(set);
//printf("Set ACK: %d\n", set);
}
void SCSICD_SetSEL(bool set)
{
SetkingSEL(set);
//printf("Set SEL: %d\n", set);
}
void SCSICD_SetRST(bool set)
{
SetkingRST(set);
//printf("Set RST: %d\n", set);
}
void SCSICD_SetATN(bool set)
{
SetkingATN(set);
//printf("Set ATN: %d\n", set);
}
static void GenSubQFromSubPW(void)
{
uint8 SubQBuf[0xC];
memset(SubQBuf, 0, 0xC);
for(int i = 0; i < 96; i++)
SubQBuf[i >> 3] |= ((cd.SubPWBuf[i] & 0x40) >> 6) << (7 - (i & 7));
//printf("Real %d/ SubQ %d - ", read_sec, BCD_to_U8(SubQBuf[7]) * 75 * 60 + BCD_to_U8(SubQBuf[8]) * 75 + BCD_to_U8(SubQBuf[9]) - 150);
// Debug code, remove me.
//for(int i = 0; i < 0xC; i++)
// printf("%02x ", SubQBuf[i]);
//printf("\n");
if(!subq_check_checksum(SubQBuf))
{
//SCSIDBG("SubQ checksum error!");
}
else
{
memcpy(cd.SubQBuf_Last, SubQBuf, 0xC);
uint8 adr = SubQBuf[0] & 0xF;
if(adr <= 0x3)
memcpy(cd.SubQBuf[adr], SubQBuf, 0xC);
//if(adr == 0x02)
//for(int i = 0; i < 12; i++)
// printf("%02x\n", cd.SubQBuf[0x2][i]);
}
}
#define STATUS_GOOD 0
#define STATUS_CHECK_CONDITION 1
#define STATUS_CONDITION_MET 2
#define STATUS_BUSY 4
#define STATUS_INTERMEDIATE 8
#define SENSEKEY_NO_SENSE 0x0
#define SENSEKEY_NOT_READY 0x2
#define SENSEKEY_MEDIUM_ERROR 0x3
#define SENSEKEY_HARDWARE_ERROR 0x4
#define SENSEKEY_ILLEGAL_REQUEST 0x5
#define SENSEKEY_UNIT_ATTENTION 0x6
#define SENSEKEY_ABORTED_COMMAND 0xB
#define ASC_MEDIUM_NOT_PRESENT 0x3A
// NEC sub-errors(ASC), no ASCQ.
#define NSE_NO_DISC 0x0B // Used with SENSEKEY_NOT_READY - This condition occurs when tray is closed with no disc present.
#define NSE_TRAY_OPEN 0x0D // Used with SENSEKEY_NOT_READY
#define NSE_SEEK_ERROR 0x15
#define NSE_HEADER_READ_ERROR 0x16 // Used with SENSEKEY_MEDIUM_ERROR
#define NSE_NOT_AUDIO_TRACK 0x1C // Used with SENSEKEY_MEDIUM_ERROR
#define NSE_NOT_DATA_TRACK 0x1D // Used with SENSEKEY_MEDIUM_ERROR
#define NSE_INVALID_COMMAND 0x20
#define NSE_INVALID_ADDRESS 0x21
#define NSE_INVALID_PARAMETER 0x22
#define NSE_END_OF_VOLUME 0x25
#define NSE_INVALID_REQUEST_IN_CDB 0x27
#define NSE_DISC_CHANGED 0x28 // Used with SENSEKEY_UNIT_ATTENTION
#define NSE_AUDIO_NOT_PLAYING 0x2C
// ASC, ASCQ pair
#define AP_UNRECOVERED_READ_ERROR 0x11, 0x00
#define AP_LEC_UNCORRECTABLE_ERROR 0x11, 0x05
#define AP_CIRC_UNRECOVERED_ERROR 0x11, 0x06
#define AP_UNKNOWN_MEDIUM_FORMAT 0x30, 0x01
#define AP_INCOMPAT_MEDIUM_FORMAT 0x30, 0x02
static void ChangePhase(const unsigned int new_phase)
{
//printf("New phase: %d %lld\n", new_phase, monotonic_timestamp);
switch(new_phase)
{
case PHASE_BUS_FREE:
SetBSY(false);
SetMSG(false);
SetCD(false);
SetIO(false);
SetREQ(false);
CDIRQCallback(0x8000 | SCSICD_IRQ_DATA_TRANSFER_DONE);
break;
case PHASE_DATA_IN: // Us to them
SetBSY(true);
SetMSG(false);
SetCD(false);
SetIO(true);
//SetREQ(true);
SetREQ(false);
break;
case PHASE_STATUS: // Us to them
SetBSY(true);
SetMSG(false);
SetCD(true);
SetIO(true);
SetREQ(true);
break;
case PHASE_MESSAGE_IN: // Us to them
SetBSY(true);
SetMSG(true);
SetCD(true);
SetIO(true);
SetREQ(true);
break;
case PHASE_DATA_OUT: // Them to us
SetBSY(true);
SetMSG(false);
SetCD(false);
SetIO(false);
SetREQ(true);
break;
case PHASE_COMMAND: // Them to us
SetBSY(true);
SetMSG(false);
SetCD(true);
SetIO(false);
SetREQ(true);
break;
case PHASE_MESSAGE_OUT: // Them to us
SetBSY(true);
SetMSG(true);
SetCD(true);
SetIO(false);
SetREQ(true);
break;
}
CurrentPhase = new_phase;
}
static void SendStatusAndMessage(uint8 status, uint8 message)
{
// This should never ever happen, but that doesn't mean it won't. ;)
if(din->CanRead())
{
//printf("[SCSICD] BUG: %d bytes still in SCSI CD FIFO\n", din->CanRead());
din->Flush();
}
cd.message_pending = message;
cd.status_sent = false;
cd.message_sent = false;
if(WhichSystem == SCSICD_PCE)
{
if(status == STATUS_GOOD || status == STATUS_CONDITION_MET)
cd_bus.DB = 0x00;
else
cd_bus.DB = 0x01;
}
else
cd_bus.DB = status << 1;
ChangePhase(PHASE_STATUS);
}
static void DoSimpleDataIn(const uint8 *data_in, uint32 len)
{
din->Write(data_in, len);
cd.data_transfer_done = true;
ChangePhase(PHASE_DATA_IN);
}
void SCSICD_SetDisc(bool new_tray_open, CDInterface *cdif, bool no_emu_side_effects)
{
Cur_CDIF = cdif;
// Closing the tray.
if(TrayOpen && !new_tray_open)
{
TrayOpen = false;
if(cdif)
{
cdif->ReadTOC(&toc);
if(!no_emu_side_effects)
{
memset(cd.SubQBuf, 0, sizeof(cd.SubQBuf));
memset(cd.SubQBuf_Last, 0, sizeof(cd.SubQBuf_Last));
cd.DiscChanged = true;
}
}
}
else if(!TrayOpen && new_tray_open) // Opening the tray
{
TrayOpen = true;
}
}
static void CommandCCError(int key, int asc = 0, int ascq = 0)
{
//printf("[SCSICD] CC Error: %02x %02x %02x\n", key, asc, ascq);
cd.key_pending = key;
cd.asc_pending = asc;
cd.ascq_pending = ascq;
cd.fru_pending = 0x00;
SendStatusAndMessage(STATUS_CHECK_CONDITION, 0x00);
}
static bool ValidateRawDataSector(uint8 *data, const uint32 lba)
{
bool ok = true;
const uint8 mode = data[12 + 3];
// TODO: Don't accept mode 2 on PC Engine
if(mode != 0x1 && mode != 0x2)
ok = false;
else if(mode == 0x2 && (data[12 + 6] & 0x20)) // Error if mode 2 form 2.
ok = false;
else if(!edc_lec_check_and_correct(data, mode == 2))
ok = false;
if(!ok)
{
MDFN_Notify(MDFN_NOTICE_WARNING, _("Uncorrectable error(s) in sector %d."), lba);
din->Flush();
cd.data_transfer_done = false;
CommandCCError(SENSEKEY_MEDIUM_ERROR, AP_LEC_UNCORRECTABLE_ERROR);
return(false);
}
return(true);
}
static void DoMODESELECT6(const uint8 *cdb)
{
if(cdb[4])
{
cd.data_out_pos = 0;
cd.data_out_want = cdb[4];
//printf("Switch to DATA OUT phase, len: %d\n", cd.data_out_want);
ChangePhase(PHASE_DATA_OUT);
}
else
SendStatusAndMessage(STATUS_GOOD, 0x00);
}
/*
All Japan Female Pro Wrestle:
Datumama: 10, 00 00 00 00 00 00 00 00 00 0a
Kokuu Hyouryuu Nirgends:
Datumama: 10, 00 00 00 00 00 00 00 00 00 0f
Datumama: 10, 00 00 00 00 00 00 00 00 00 0f
Last Imperial Prince:
Datumama: 10, 00 00 00 00 00 00 00 00 00 0f
Datumama: 10, 00 00 00 00 00 00 00 00 00 0f
Megami Paradise II:
Datumama: 10, 00 00 00 00 00 00 00 00 00 0a
Miraculum:
Datumama: 7, 00 00 00 00 29 01 00
Datumama: 10, 00 00 00 00 00 00 00 00 00 0f
Datumama: 7, 00 00 00 00 29 01 00
Datumama: 10, 00 00 00 00 00 00 00 00 00 00
Datumama: 7, 00 00 00 00 29 01 00
Pachio Kun FX:
Datumama: 10, 00 00 00 00 00 00 00 00 00 14
Return to Zork:
Datumama: 10, 00 00 00 00 00 00 00 00 00 00
Sotsugyou II:
Datumama: 10, 00 00 00 00 01 00 00 00 00 01
Tokimeki Card Paradise:
Datumama: 10, 00 00 00 00 00 00 00 00 00 14
Datumama: 10, 00 00 00 00 00 00 00 00 00 07
Tonari no Princess Rolfee:
Datumama: 10, 00 00 00 00 00 00 00 00 00 00
Zoku Hakutoi Monogatari:
Datumama: 10, 00 00 00 00 00 00 00 00 00 14
*/
// Page 151: MODE SENSE(6)
// PC = 0 current
// PC = 1 Changeable
// PC = 2 Default
// PC = 3 Saved
// Page 183: Mode parameter header.
// Page 363: CD-ROM density codes.
// Page 364: CD-ROM mode page codes.
// Page 469: ASC and ASCQ table
struct ModePageParam
{
uint8 default_value;
uint8 alterable_mask; // Alterable mask reported when PC == 1
uint8 real_mask; // Real alterable mask.
};
struct ModePage
{
const uint8 code;
const uint8 param_length;
const ModePageParam params[64]; // 64 should be more than enough
uint8 current_value[64];
};
/*
Mode pages present:
0x00:
0x0E:
0x28:
0x29:
0x2A:
0x2B:
0x3F(Yes, not really a mode page but a fetch method)
*/
// Remember to update the code in StateAction() if we change the number or layout of modepages here.
static const int NumModePages = 5;
static ModePage ModePages[NumModePages] =
{
// Unknown
{ 0x28,
0x04,
{
{ 0x00, 0x00, 0xFF },
{ 0x00, 0x00, 0xFF },
{ 0x00, 0x00, 0xFF },
{ 0x00, 0x00, 0xFF },
}
},
// Unknown
{ 0x29,
0x01,
{
{ 0x00, 0x00, 0xFF },
}
},
// Unknown
{ 0x2a,
0x02,
{
{ 0x00, 0x00, 0xFF },
{ 0x11, 0x00, 0xFF },
}
},
// CD-DA playback speed modifier
{ 0x2B,
0x01,
{
{ 0x00, 0x00, 0xFF },
}
},
// 0x0E goes last, for correct order of return data when page code == 0x3F
// Real mask values are probably not right; some functionality not emulated yet.
// CD-ROM audio control parameters
{ 0x0E,
0x0E,
{
{ 0x04, 0x04, 0x04 }, // Immed
{ 0x00, 0x00, 0x00 }, // Reserved
{ 0x00, 0x00, 0x00 }, // Reserved
{ 0x00, 0x01, 0x01 }, // Reserved?
{ 0x00, 0x00, 0x00 }, // MSB of LBA per second.
{ 0x00, 0x00, 0x00 }, // LSB of LBA per second.
{ 0x01, 0x01, 0x03 }, // Outport port 0 channel selection.
{ 0xFF, 0x00, 0x00 }, // Outport port 0 volume.
{ 0x02, 0x02, 0x03 }, // Outport port 1 channel selection.
{ 0xFF, 0x00, 0x00 }, // Outport port 1 volume.
{ 0x00, 0x00, 0x00 }, // Outport port 2 channel selection.
{ 0x00, 0x00, 0x00 }, // Outport port 2 volume.
{ 0x00, 0x00, 0x00 }, // Outport port 3 channel selection.
{ 0x00, 0x00, 0x00 }, // Outport port 3 volume.
}
},
};
static void UpdateMPCacheP(const ModePage* mp)
{
switch(mp->code)
{
case 0x0E:
{
const uint8 *pd = &mp->current_value[0];
for(int i = 0; i < 2; i++)
cdda.OutPortChSelect[i] = pd[6 + i * 2];
FixOPV();
}
break;
case 0x28:
break;
case 0x29:
break;
case 0x2A:
break;
case 0x2B:
{
int speed;
int rate;
//
// Not sure what the actual limits are, or what happens when exceeding them, but these will at least keep the
// CD-DA playback system from imploding in on itself.
//
// The range of speed values accessible via the BIOS CD-DA player is apparently -10 to 10.
//
// No game is known to use the CD-DA playback speed control. It may be useful in homebrew to lower the rate for fitting more CD-DA onto the disc,
// is implemented on the PC-FX in such a way that it degrades audio quality, so it wouldn't really make sense to increase the rate in homebrew.
//
// Due to performance considerations, we only partially emulate the CD-DA oversampling filters used on the PC Engine and PC-FX, and instead
// blast impulses into the 1.78MHz buffer, relying on the final sound resampler to kill spectrum mirrors. This is less than ideal, but generally
// works well in practice, except when lowering CD-DA playback rate...which causes the spectrum mirrors to enter the non-murder zone, causing
// the sound output amplitude to approach overflow levels.
// But, until there's a killer PC-FX homebrew game that necessitates more computationally-expensive CD-DA handling,
// I don't see a good reason to change how CD-DA resampling is currently implemented.
//
speed = std::max<int>(-32, std::min<int>(32, (int8)mp->current_value[0]));
rate = 44100 + 441 * speed;
//printf("[SCSICD] Speed: %d(pre-clamped=%d) %d\n", speed, (int8)mp->current_value[0], rate);
cdda.CDDADivAcc = ((int64)System_Clock * (1024 * 1024) / (2 * rate));
cdda.CDDADivAccVolFudge = 100 + speed;
FixOPV(); // Resampler impulse amplitude volume adjustment(call after setting cdda.CDDADivAccVolFudge)
}
break;
}
}
static void UpdateMPCache(uint8 code)
{
for(int pi = 0; pi < NumModePages; pi++)
{
const ModePage* mp = &ModePages[pi];
if(mp->code == code)
{
UpdateMPCacheP(mp);
break;
}
}
}
static void InitModePages(void)
{
for(int pi = 0; pi < NumModePages; pi++)
{
ModePage *mp = &ModePages[pi];
const ModePageParam *params = &ModePages[pi].params[0];
for(int parami = 0; parami < mp->param_length; parami++)
mp->current_value[parami] = params[parami].default_value;
UpdateMPCacheP(mp);
}
}
static void FinishMODESELECT6(const uint8 *data, const uint8 data_len)
{
uint8 mode_data_length, medium_type, device_specific, block_descriptor_length;
uint32 offset = 0;
//printf("[SCSICD] Mode Select (6) Data: Length=0x%02x, ", data_len);
//for(uint32 i = 0; i < data_len; i++)
// printf("0x%02x ", data[i]);
//printf("\n");
if(data_len < 4)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_PARAMETER);
return;
}
mode_data_length = data[offset++];
medium_type = data[offset++];
device_specific = data[offset++];
block_descriptor_length = data[offset++];
// For now, shut up gcc.
(void)mode_data_length;
(void)medium_type;
(void)device_specific;
if(block_descriptor_length & 0x7)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_PARAMETER);
return;
}
if((offset + block_descriptor_length) > data_len)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_PARAMETER);
return;
}
// TODO: block descriptors.
offset += block_descriptor_length;
// Now handle mode pages
while(offset < data_len)
{
const uint8 code = data[offset++];
uint8 param_len = 0;
bool page_found = false;
if(code == 0x00)
{
if((offset + 0x5) > data_len)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_PARAMETER);
return;
}
UpdateMPCache(0x00);
offset += 0x5;
continue;
}
if(offset >= data_len)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_PARAMETER);
return;
}
param_len = data[offset++];
for(int pi = 0; pi < NumModePages; pi++)
{
ModePage *mp = &ModePages[pi];
if(code == mp->code)
{
page_found = true;
if(param_len != mp->param_length)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_PARAMETER);
return;
}
if((param_len + offset) > data_len)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_PARAMETER);
return;
}
for(int parami = 0; parami < mp->param_length; parami++)
{
mp->current_value[parami] &= ~mp->params[parami].real_mask;
mp->current_value[parami] |= (data[offset++]) & mp->params[parami].real_mask;
}
UpdateMPCacheP(mp);
break;
}
}
if(!page_found)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_PARAMETER);
return;
}
}
SendStatusAndMessage(STATUS_GOOD, 0x00);
}
static void DoMODESENSE6(const uint8 *cdb)
{
unsigned int PC = (cdb[2] >> 6) & 0x3;
unsigned int PageCode = cdb[2] & 0x3F;
bool DBD = cdb[1] & 0x08;
int AllocSize = cdb[4];
int index = 0;
uint8 data_in[8192];
uint8 PageMatchOR = 0x00;
bool AnyPageMatch = false;
//SCSIDBG("Mode sense 6: %02x %d %d %d", PageCode, PC, DBD, AllocSize);
if(!AllocSize)
{
SendStatusAndMessage(STATUS_GOOD, 0x00);
return;
}
if(PC == 3)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_PARAMETER);
return;
}
if(PageCode == 0x00) // Special weird case.
{
if(DBD || PC)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_PARAMETER);
return;
}
memset(data_in, 0, 0xA);
data_in[0] = 0x09;
data_in[2] = 0x80;
data_in[9] = 0x0F;
if(AllocSize > 0xA)
AllocSize = 0xA;
DoSimpleDataIn(data_in, AllocSize);
return;
}
data_in[0] = 0x00; // Fill this in later.
data_in[1] = 0x00; // Medium type
data_in[2] = 0x00; // Device-specific parameter.
data_in[3] = DBD ? 0x00 : 0x08; // Block descriptor length.
index += 4;
if(!DBD)
{
data_in[index++] = 0x00; // Density code.
MDFN_en24msb(&data_in[index], 0x6E); // FIXME: Number of blocks?
index += 3;
data_in[index++] = 0x00; // Reserved
MDFN_en24msb(&data_in[index], 0x800); // Block length;
index += 3;
}
PageMatchOR = 0x00;
if(PageCode == 0x3F)
PageMatchOR = 0x3F;
for(int pi = 0; pi < NumModePages; pi++)
{
const ModePage *mp = &ModePages[pi];
const ModePageParam *params = &ModePages[pi].params[0];
if((mp->code | PageMatchOR) != PageCode)
continue;
AnyPageMatch = true;
data_in[index++] = mp->code;
data_in[index++] = mp->param_length;
for(int parami = 0; parami < mp->param_length; parami++)
{
uint8 data;
if(PC == 0x02)
data = params[parami].default_value;
else if(PC == 0x01)
data = params[parami].alterable_mask;
else
data = mp->current_value[parami];
data_in[index++] = data;
}
}
if(!AnyPageMatch)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_PARAMETER);
return;
}
if(AllocSize > index)
AllocSize = index;
data_in[0] = AllocSize - 1;
DoSimpleDataIn(data_in, AllocSize);
}
static void DoSTARTSTOPUNIT6(const uint8 *cdb)
{
//bool Immed = cdb[1] & 0x01;
//bool LoEj = cdb[4] & 0x02;
//bool Start = cdb[4] & 0x01;
//SCSIDBG("Do start stop unit 6: %d %d %d\n", Immed, LoEj, Start);
SendStatusAndMessage(STATUS_GOOD, 0x00);
}
static void DoREZEROUNIT(const uint8 *cdb)
{
//SCSIDBG("Rezero Unit: %02x\n", cdb[5]);
SendStatusAndMessage(STATUS_GOOD, 0x00);
}
// This data was originally taken from a PC-FXGA software loader, but
// while it was mostly correct(maybe it is correct for the FXGA, but not for the PC-FX?),
// it was 3 bytes too long, and the last real byte was 0x45 instead of 0x20.
// TODO: Investigate this discrepancy by testing an FXGA with the official loader software.
#if 0
static const uint8 InqData[0x24] =
{
// Standard
0x05, 0x80, 0x02, 0x00,
// Additional Length
0x1F,
// Vendor Specific
0x00, 0x00, 0x00, 0x4E, 0x45, 0x43, 0x20, 0x20,
0x20, 0x20, 0x20, 0x43, 0x44, 0x2D, 0x52, 0x4F,
0x4D, 0x20, 0x44, 0x52, 0x49, 0x56, 0x45, 0x3A,
0x46, 0x58, 0x20, 0x31, 0x2E, 0x30, 0x20
};
#endif
// Miraculum behaves differently if the last byte(offset 0x23) of the inquiry data is 0x45(ASCII character 'E'). Relavent code is at PC=0x3E382
// If it's = 0x45, it will run MODE SELECT, and transfer this data to the CD unit: 00 00 00 00 29 01 00
static const uint8 InqData[0x24] =
{
// Peripheral device-type: CD-ROM/read-only direct access device
0x05,
// Removable media: yes
// Device-type qualifier: 0
0x80,
// ISO version: 0
// ECMA version: 0
// ANSI version: 2 (SCSI-2? ORLY?)
0x02,
// Supports asynchronous event notification: no
// Supports the terminate I/O process message: no
// Response data format: 0 (not exactly correct, not exactly incorrect, meh. :b)
0x00,
// Additional Length
0x1F,
// Reserved
0x00, 0x00,
// Yay, no special funky features.
0x00,
// 8-15, vendor ID
// NEC
0x4E, 0x45, 0x43, 0x20, 0x20, 0x20, 0x20, 0x20,
// 16-31, product ID
// CD-ROM DRIVE:FX
0x43, 0x44, 0x2D, 0x52, 0x4F, 0x4D, 0x20, 0x44, 0x52, 0x49, 0x56, 0x45, 0x3A, 0x46, 0x58, 0x20,
// 32-35, product revision level
// 1.0
0x31, 0x2E, 0x30, 0x20
};
static void DoINQUIRY(const uint8 *cdb)
{
unsigned int AllocSize = (cdb[4] < sizeof(InqData)) ? cdb[4] : sizeof(InqData);
if(AllocSize)
DoSimpleDataIn(InqData, AllocSize);
else
SendStatusAndMessage(STATUS_GOOD, 0x00);
}
static void DoNEC_NOP(const uint8 *cdb)
{
SendStatusAndMessage(STATUS_GOOD, 0x00);
}
/********************************************************
* *
* PC-FX CD Command 0xDC - EJECT *
* *
********************************************************/
static void DoNEC_EJECT(const uint8 *cdb)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_REQUEST_IN_CDB);
}
static void DoREQUESTSENSE(const uint8 *cdb)
{
uint8 data_in[8192];
MakeSense(data_in, cd.key_pending, cd.asc_pending, cd.ascq_pending, cd.fru_pending);
DoSimpleDataIn(data_in, 18);
cd.key_pending = 0;
cd.asc_pending = 0;
cd.ascq_pending = 0;
cd.fru_pending = 0;
}
static void EncodeM3TOC(uint8 *buf, uint8 POINTER_RAW, int32 LBA, uint32 PLBA, uint8 control)
{
uint8 MIN, SEC, FRAC;
uint8 PMIN, PSEC, PFRAC;
LBA_to_AMSF(LBA, &MIN, &SEC, &FRAC);
LBA_to_AMSF(PLBA, &PMIN, &PSEC, &PFRAC);
buf[0x0] = control << 4;
buf[0x1] = 0x00; // TNO
buf[0x2] = POINTER_RAW;
buf[0x3] = U8_to_BCD(MIN);
buf[0x4] = U8_to_BCD(SEC);
buf[0x5] = U8_to_BCD(FRAC);
buf[0x6] = 0x00; // Zero
buf[0x7] = U8_to_BCD(PMIN);
buf[0x8] = U8_to_BCD(PSEC);
buf[0x9] = U8_to_BCD(PFRAC);
}
/********************************************************
* *
* PC-FX CD Command 0xDE - Get Directory Info *
* *
********************************************************/
static void DoNEC_GETDIRINFO(const uint8 *cdb)
{
// Problems:
// Mode 0x03 has a few semi-indeterminate(but within a range, and they only change when the disc is reloaded) fields on a real PC-FX, that correspond to where in the lead-in area the data
// was read, that we don't bother to handle here.
// Mode 0x03 returns weird/wrong control field data for the "last track" and "leadout" entries in the "Blue Breaker" TOC.
// A bug in the PC-FX CD firmware, or an oddity of the disc(maybe other PC-FX discs are similar)? Or maybe it's an undefined field in that context?
// "Match" value of 0xB0 is probably not handled properly. Is it to return the catalog number, or something else?
uint8 data_in[2048];
uint32 data_in_size = 0;
memset(data_in, 0, sizeof(data_in));
switch(cdb[1] & 0x03)
{
// This commands returns relevant raw TOC data as encoded in the Q subchannel(sans the CRC bytes).
case 0x3:
{
int offset = 0;
int32 lilba = -150;
uint8 match = cdb[2];
if(match != 0x00 && match != 0xA0 && match != 0xA1 && match != 0xA2 && match != 0xB0)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_ADDRESS);
return;
}
memset(data_in, 0, sizeof(data_in));
data_in[0] = 0x00; // Size MSB???
data_in[1] = 0x00; // Total Size - 2(we'll fill it in later).
offset = 2;
if(!match || match == 0xA0)
{
EncodeM3TOC(&data_in[offset], 0xA0, lilba, toc.first_track * 75 * 60 - 150, toc.tracks[toc.first_track].control);
lilba++;
offset += 0xA;
}
if(!match || match == 0xA1)
{
EncodeM3TOC(&data_in[offset], 0xA1, lilba, toc.last_track * 75 * 60 - 150, toc.tracks[toc.last_track].control);
lilba++;
offset += 0xA;
}
if(!match || match == 0xA2)
{
EncodeM3TOC(&data_in[offset], 0xA2, lilba, toc.tracks[100].lba, toc.tracks[100].control);
lilba++;
offset += 0xA;
}
if(!match)
for(int track = toc.first_track; track <= toc.last_track; track++)
{
EncodeM3TOC(&data_in[offset], U8_to_BCD(track), lilba, toc.tracks[track].lba, toc.tracks[track].control);
lilba++;
offset += 0xA;
}
if(match == 0xB0)
{
memset(&data_in[offset], 0, 0x14);
offset += 0x14;
}
assert((unsigned int)offset <= sizeof(data_in));
data_in_size = offset;
MDFN_en16msb(&data_in[0], offset - 2);
}
break;
case 0x0:
data_in[0] = U8_to_BCD(toc.first_track);
data_in[1] = U8_to_BCD(toc.last_track);
data_in_size = 4;
break;
case 0x1:
{
uint8 m, s, f;
LBA_to_AMSF(toc.tracks[100].lba, &m, &s, &f);
data_in[0] = U8_to_BCD(m);
data_in[1] = U8_to_BCD(s);
data_in[2] = U8_to_BCD(f);
data_in_size = 4;
}
break;
case 0x2:
{
uint8 m, s, f;
int track = BCD_to_U8(cdb[2]);
if(track < toc.first_track || track > toc.last_track)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_ADDRESS);
return;
}
LBA_to_AMSF(toc.tracks[track].lba, &m, &s, &f);
data_in[0] = U8_to_BCD(m);
data_in[1] = U8_to_BCD(s);
data_in[2] = U8_to_BCD(f);
data_in[3] = toc.tracks[track].control;
data_in_size = 4;
}
break;
}
DoSimpleDataIn(data_in, data_in_size);
}
static void DoREADTOC(const uint8 *cdb)
{
uint8 data_in[8192];
int FirstTrack = toc.first_track;
int LastTrack = toc.last_track;
int StartingTrack = cdb[6];
unsigned int AllocSize = (cdb[7] << 8) | cdb[8];
unsigned int RealSize = 0;
const bool WantInMSF = cdb[1] & 0x2;
if(!AllocSize)
{
SendStatusAndMessage(STATUS_GOOD, 0x00);
return;
}
if((cdb[1] & ~0x2) || cdb[2] || cdb[3] || cdb[4] || cdb[5] || cdb[9])
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_PARAMETER);
return;
}
if(!StartingTrack)
StartingTrack = 1;
else if(StartingTrack == 0xAA)
{
StartingTrack = LastTrack + 1;
}
else if(StartingTrack > toc.last_track)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_PARAMETER);
return;
}
data_in[2] = FirstTrack;
data_in[3] = LastTrack;
RealSize += 4;
// Read leadout track too LastTrack + 1 ???
for(int track = StartingTrack; track <= (LastTrack + 1); track++)
{
uint8 *subptr = &data_in[RealSize];
uint32 lba;
uint8 m, s, f;
uint32 eff_track;
if(track == (LastTrack + 1))
eff_track = 100;
else
eff_track = track;
lba = toc.tracks[eff_track].lba;
LBA_to_AMSF(lba, &m, &s, &f);
subptr[0] = 0;
subptr[1] = toc.tracks[eff_track].control | (toc.tracks[eff_track].adr << 4);
if(eff_track == 100)
subptr[2] = 0xAA;
else
subptr[2] = track;
subptr[3] = 0;
if(WantInMSF)
{
subptr[4] = 0;
subptr[5] = m; // Min
subptr[6] = s; // Sec
subptr[7] = f; // Frames
}
else
{
subptr[4] = lba >> 24;
subptr[5] = lba >> 16;
subptr[6] = lba >> 8;
subptr[7] = lba >> 0;
}
RealSize += 8;
}
// PC-FX: AllocSize too small doesn't reflect in this.
data_in[0] = (RealSize - 2) >> 8;
data_in[1] = (RealSize - 2) >> 0;
DoSimpleDataIn(data_in, (AllocSize < RealSize) ? AllocSize : RealSize);
}
/********************************************************
* *
* SCSI-2 CD Command 0x25 - READ CD-ROM CAPACITY *
* *
********************************************************/
static void DoREADCDCAP10(const uint8 *cdb)
{
bool pmi = cdb[8] & 0x1;
uint32 lba = MDFN_de32msb(cdb + 0x2);
uint32 ret_lba;
uint32 ret_bl;
uint8 data_in[8];
memset(data_in, 0, sizeof(data_in));
if(lba > 0x05FF69)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_END_OF_VOLUME);
return;
}
ret_lba = toc.tracks[100].lba - 1;
if(pmi)
{
// Look for the track containing the LBA specified, then search for the first track afterwards that has a different track type(audio, data),
// and set the returned LBA to the sector preceding that track.
//
// If the specified LBA is >= leadout track, return the LBA of the sector immediately before the leadout track.
//
// If the specified LBA is < than the LBA of the first track, then return the LBA of sector preceding the first track. (I don't know if PC-FX can even handle discs like this, though)
if(lba >= toc.tracks[100].lba)
ret_lba = toc.tracks[100].lba - 1;
else if(lba < toc.tracks[toc.first_track].lba)
ret_lba = toc.tracks[toc.first_track].lba - 1;
else
{
const int track = toc.FindTrackByLBA(lba);
for(int st = track + 1; st <= toc.last_track; st++)
{
if((toc.tracks[st].control ^ toc.tracks[track].control) & 0x4)
{
ret_lba = toc.tracks[st].lba - 1;
break;
}
}
}
}
ret_bl = 2048;
MDFN_en32msb(&data_in[0], ret_lba);
MDFN_en32msb(&data_in[4], ret_bl);
cdda.CDDAStatus = CDDASTATUS_STOPPED;
DoSimpleDataIn(data_in, 8);
}
static void DoREADHEADER10(const uint8 *cdb)
{
uint8 data_in[8192];
bool WantInMSF = cdb[1] & 0x2;
uint32 HeaderLBA = MDFN_de32msb(cdb + 0x2);
int AllocSize = MDFN_de16msb(cdb + 0x7);
uint8 raw_buf[2352 + 96];
uint8 mode;
int m, s, f;
uint32 lba;
// Don't run command at all if AllocSize == 0(FIXME: On a real PC-FX, this command will return success
// if there's no CD when AllocSize == 0, implement this here, might require refactoring).
if(!AllocSize)
{
SendStatusAndMessage(STATUS_GOOD, 0x00);
return;
}
if(HeaderLBA >= toc.tracks[100].lba)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_PARAMETER);
return;
}
if(HeaderLBA < toc.tracks[toc.first_track].lba)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_PARAMETER);
return;
}
Cur_CDIF->ReadRawSector(raw_buf, HeaderLBA); //, HeaderLBA + 1);
if(!ValidateRawDataSector(raw_buf, HeaderLBA))
return;
m = BCD_to_U8(raw_buf[12 + 0]);
s = BCD_to_U8(raw_buf[12 + 1]);
f = BCD_to_U8(raw_buf[12 + 2]);
mode = raw_buf[12 + 3];
lba = AMSF_to_LBA(m, s, f);
//printf("%d:%d:%d(LBA=%08x) %02x\n", m, s, f, lba, mode);
data_in[0] = mode;
data_in[1] = 0;
data_in[2] = 0;
data_in[3] = 0;
if(WantInMSF)
{
data_in[4] = 0;
data_in[5] = m; // Min
data_in[6] = s; // Sec
data_in[7] = f; // Frames
}
else
{
data_in[4] = lba >> 24;
data_in[5] = lba >> 16;
data_in[6] = lba >> 8;
data_in[7] = lba >> 0;
}
cdda.CDDAStatus = CDDASTATUS_STOPPED;
DoSimpleDataIn(data_in, 8);
}
static void DoNEC_SST(const uint8 *cdb) // Command 0xDB, Set Stop Time
{
SendStatusAndMessage(STATUS_GOOD, 0x00);
}
static void DoPABase(const uint32 lba, const uint32 length, unsigned int status = CDDASTATUS_PLAYING, unsigned int mode = PLAYMODE_NORMAL)
{
if(lba > toc.tracks[100].lba) // > is not a typo, it's a PC-FX bug apparently.
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_PARAMETER);
return;
}
if(lba < toc.tracks[toc.first_track].lba)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_PARAMETER);
return;
}
if(!length) // FIXME to return good status in this case even if no CD is present
{
SendStatusAndMessage(STATUS_GOOD, 0x00);
return;
}
else
{
if(toc.tracks[toc.FindTrackByLBA(lba)].control & 0x04)
{
CommandCCError(SENSEKEY_MEDIUM_ERROR, NSE_NOT_AUDIO_TRACK);
return;
}
cdda.CDDAReadPos = 588;
read_sec = read_sec_start = lba;
read_sec_end = read_sec_start + length;
cdda.CDDAStatus = status;
cdda.PlayMode = mode;
if(read_sec < toc.tracks[100].lba)
{
Cur_CDIF->HintReadSector(read_sec); //, read_sec_end, read_sec_start);
}
}
SendStatusAndMessage(STATUS_GOOD, 0x00);
}
/********************************************************
* *
* PC-FX CD Command 0xD8 - SAPSP *
* *
********************************************************/
static void DoNEC_SAPSP(const uint8 *cdb)
{
uint32 lba;
switch (cdb[9] & 0xc0)
{
default:
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_PARAMETER);
return;
break;
case 0x00:
lba = MDFN_de24msb(&cdb[3]);
break;
case 0x40:
{
uint8 m, s, f;
if(!BCD_to_U8_check(cdb[2], &m) || !BCD_to_U8_check(cdb[3], &s) || !BCD_to_U8_check(cdb[4], &f))
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_PARAMETER);
return;
}
lba = AMSF_to_LBA(m, s, f);
}
break;
case 0x80:
{
uint8 track;
if(!cdb[2] || !BCD_to_U8_check(cdb[2], &track))
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_PARAMETER);
return;
}
if(track == toc.last_track + 1)
track = 100;
else if(track > toc.last_track)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_END_OF_VOLUME);
return;
}
lba = toc.tracks[track].lba;
}
break;
}
if(cdb[1] & 0x01)
DoPABase(lba, toc.tracks[100].lba - lba, CDDASTATUS_PLAYING, PLAYMODE_NORMAL);
else
DoPABase(lba, toc.tracks[100].lba - lba, CDDASTATUS_PAUSED, PLAYMODE_SILENT);
}
/********************************************************
* *
* PC-FX CD Command 0xD9 - SAPEP *
* *
********************************************************/
static void DoNEC_SAPEP(const uint8 *cdb)
{
uint32 lba;
if(cdda.CDDAStatus == CDDASTATUS_STOPPED)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_AUDIO_NOT_PLAYING);
return;
}
switch (cdb[9] & 0xc0)
{
default:
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_PARAMETER);
return;
break;
case 0x00:
lba = MDFN_de24msb(&cdb[3]);
break;
case 0x40:
{
uint8 m, s, f;
if(!BCD_to_U8_check(cdb[2], &m) || !BCD_to_U8_check(cdb[3], &s) || !BCD_to_U8_check(cdb[4], &f))
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_PARAMETER);
return;
}
lba = AMSF_to_LBA(m, s, f);
}
break;
case 0x80:
{
uint8 track;
if(!cdb[2] || !BCD_to_U8_check(cdb[2], &track))
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_PARAMETER);
return;
}
if(track == toc.last_track + 1)
track = 100;
else if(track > toc.last_track)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_END_OF_VOLUME);
return;
}
lba = toc.tracks[track].lba;
}
break;
}
switch(cdb[1] & 0x7)
{
case 0x00: cdda.PlayMode = PLAYMODE_SILENT;
break;
case 0x04: cdda.PlayMode = PLAYMODE_LOOP;
break;
default: cdda.PlayMode = PLAYMODE_NORMAL;
break;
}
cdda.CDDAStatus = CDDASTATUS_PLAYING;
read_sec_end = lba;
SendStatusAndMessage(STATUS_GOOD, 0x00);
}
/********************************************************
* *
* SCSI-2 CD Command 0x45 - PLAY AUDIO(10) *
* *
********************************************************/
static void DoPA10(const uint8 *cdb)
{
// Real PC-FX Bug: Error out on LBA >(not >=) leadout sector number
const uint32 lba = MDFN_de32msb(cdb + 0x2);
const uint16 length = MDFN_de16msb(cdb + 0x7);
DoPABase(lba, length);
}
/********************************************************
* *
* SCSI-2 CD Command 0xA5 - PLAY AUDIO(12) *
* *
********************************************************/
static void DoPA12(const uint8 *cdb)
{
// Real PC-FX Bug: Error out on LBA >(not >=) leadout sector number
const uint32 lba = MDFN_de32msb(cdb + 0x2);
const uint32 length = MDFN_de32msb(cdb + 0x6);
DoPABase(lba, length);
}
/********************************************************
* *
* SCSI-2 CD Command 0x47 - PLAY AUDIO MSF *
* *
********************************************************/
static void DoPAMSF(const uint8 *cdb)
{
int32 lba_start, lba_end;
lba_start = AMSF_to_LBA(cdb[3], cdb[4], cdb[5]);
lba_end = AMSF_to_LBA(cdb[6], cdb[7], cdb[8]);
if(lba_start < 0 || lba_end < 0 || lba_start >= (int32)toc.tracks[100].lba)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_END_OF_VOLUME);
return;
}
if(lba_start == lba_end)
{
SendStatusAndMessage(STATUS_GOOD, 0x00);
return;
}
else if(lba_start > lba_end)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_ADDRESS);
return;
}
cdda.CDDAReadPos = 588;
read_sec = read_sec_start = lba_start;
read_sec_end = lba_end;
cdda.CDDAStatus = CDDASTATUS_PLAYING;
cdda.PlayMode = PLAYMODE_NORMAL;
SendStatusAndMessage(STATUS_GOOD, 0x00);
}
static void DoPATI(const uint8 *cdb)
{
// "Boundary Gate" uses this command.
// Problems:
// The index fields aren't handled. The ending index wouldn't be too bad, but the starting index would require a bit of work and code uglyfying(to scan for the index), and may be highly
// problematic when Mednafen is used with a physical CD.
int StartTrack = cdb[4];
int EndTrack = cdb[7];
//int StartIndex = cdb[5];
//int EndIndex = cdb[8];
if(!StartTrack || StartTrack < toc.first_track || StartTrack > toc.last_track)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_PARAMETER);
return;
}
//printf("PATI: %d %d %d SI: %d, EI: %d\n", StartTrack, EndTrack, Cur_CDIF->GetTrackStartPositionLBA(StartTrack), StartIndex, EndIndex);
DoPABase(toc.tracks[StartTrack].lba, toc.tracks[EndTrack].lba - toc.tracks[StartTrack].lba);
}
static void DoPATRBase(const uint32 lba, const uint32 length)
{
if(lba >= toc.tracks[100].lba)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_PARAMETER);
return;
}
if(lba < toc.tracks[toc.first_track].lba)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_PARAMETER);
return;
}
if(!length) // FIXME to return good status in this case even if no CD is present
{
SendStatusAndMessage(STATUS_GOOD, 0x00);
return;
}
else
{
if(toc.tracks[toc.FindTrackByLBA(lba)].control & 0x04)
{
CommandCCError(SENSEKEY_MEDIUM_ERROR, NSE_NOT_AUDIO_TRACK);
return;
}
cdda.CDDAReadPos = 588;
read_sec = read_sec_start = lba;
read_sec_end = read_sec_start + length;
cdda.CDDAStatus = CDDASTATUS_PLAYING;
cdda.PlayMode = PLAYMODE_NORMAL;
}
SendStatusAndMessage(STATUS_GOOD, 0x00);
}
/********************************************************
* *
* SCSI-2 CD Command 0x49 - PLAY AUDIO TRACK *
* RELATIVE(10) *
********************************************************/
static void DoPATR10(const uint8 *cdb)
{
const int32 rel_lba = MDFN_de32msb(cdb + 0x2);
const int StartTrack = cdb[6];
const uint16 length = MDFN_de16msb(cdb + 0x7);
if(!StartTrack || StartTrack < toc.first_track || StartTrack > toc.last_track)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_PARAMETER);
return;
}
DoPATRBase(toc.tracks[StartTrack].lba + rel_lba, length);
}
/********************************************************
* *
* SCSI-2 CD Command 0xA9 - PLAY AUDIO TRACK *
* RELATIVE(12) *
********************************************************/
static void DoPATR12(const uint8 *cdb)
{
const int32 rel_lba = MDFN_de32msb(cdb + 0x2);
const int StartTrack = cdb[10];
const uint32 length = MDFN_de32msb(cdb + 0x6);
if(!StartTrack || StartTrack < toc.first_track || StartTrack > toc.last_track)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_PARAMETER);
return;
}
DoPATRBase(toc.tracks[StartTrack].lba + rel_lba, length);
}
static void DoPAUSERESUME(const uint8 *cdb)
{
// Pause/resume
// "It shall not be considered an error to request a pause when a pause is already in effect,
// or to request a resume when a play operation is in progress."
if(cdda.CDDAStatus == CDDASTATUS_STOPPED)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_AUDIO_NOT_PLAYING);
return;
}
if(cdb[8] & 1) // Resume
cdda.CDDAStatus = CDDASTATUS_PLAYING;
else
cdda.CDDAStatus = CDDASTATUS_PAUSED;
SendStatusAndMessage(STATUS_GOOD, 0x00);
}
static void DoREADBase(uint32 sa, uint32 sc)
{
int track;
if(sa > toc.tracks[100].lba) // Another one of those off-by-one PC-FX CD bugs.
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_END_OF_VOLUME);
return;
}
if((track = toc.FindTrackByLBA(sa)) == 0)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_END_OF_VOLUME);
return;
}
if(!(toc.tracks[track].control) & 0x4)
{
CommandCCError(SENSEKEY_MEDIUM_ERROR, NSE_NOT_DATA_TRACK);
return;
}
// Case for READ(10) and READ(12) where sc == 0, and sa == toc.tracks[100].lba
if(!sc && sa == toc.tracks[100].lba)
{
CommandCCError(SENSEKEY_MEDIUM_ERROR, NSE_HEADER_READ_ERROR);
return;
}
if(SCSILog)
{
int Track = toc.FindTrackByLBA(sa);
uint32 Offset = sa - toc.tracks[Track].lba; //Cur_CDIF->GetTrackStartPositionLBA(Track);
SCSILog("SCSI", "Read: start=0x%08x(track=%d, offs=0x%08x), cnt=0x%08x", sa, Track, Offset, sc);
}
//const uint32 PrevSectorAddr = SectorAddr;
SectorAddr = sa;
SectorCount = sc;
if(SectorCount)
{
Cur_CDIF->HintReadSector(sa); //, sa + sc);
CDReadTimer = (uint64)((WhichSystem == SCSICD_PCE) ? 8 : 1) * 2048 * System_Clock / CD_DATA_TRANSFER_RATE;
//printf("%d\n", SectorAddr - PrevSectorAddr);
//TODO?: CDReadTimer = (double)((WhichSystem == SCSICD_PCE) ? ((PrevSectorAddr == SectorAddr) ? 0.5 : 8) : 1) * 2048 * System_Clock / CD_DATA_TRANSFER_RATE;
}
else
{
CDReadTimer = 0;
SendStatusAndMessage(STATUS_GOOD, 0x00);
}
cdda.CDDAStatus = CDDASTATUS_STOPPED;
}
/********************************************************
* *
* SCSI-2 CD Command 0x08 - READ(6) *
* *
********************************************************/
static void DoREAD6(const uint8 *cdb)
{
uint32 sa = ((cdb[1] & 0x1F) << 16) | (cdb[2] << 8) | (cdb[3] << 0);
uint32 sc = cdb[4];
// TODO: confirm real PCE does this(PC-FX does at least).
if(!sc)
{
//SCSIDBG("READ(6) with count == 0.\n");
sc = 256;
}
DoREADBase(sa, sc);
}
/********************************************************
* *
* SCSI-2 CD Command 0x28 - READ(10) *
* *
********************************************************/
static void DoREAD10(const uint8 *cdb)
{
uint32 sa = MDFN_de32msb(cdb + 0x2);
uint32 sc = MDFN_de16msb(cdb + 0x7);
DoREADBase(sa, sc);
}
/********************************************************
* *
* SCSI-2 CD Command 0xA8 - READ(12) *
* *
********************************************************/
static void DoREAD12(const uint8 *cdb)
{
uint32 sa = MDFN_de32msb(cdb + 0x2);
uint32 sc = MDFN_de32msb(cdb + 0x6);
DoREADBase(sa, sc);
}
/********************************************************
* *
* SCSI-2 CD Command 0x34 - PREFETCH(10) *
* *
********************************************************/
static void DoPREFETCH(const uint8 *cdb)
{
uint32 lba = MDFN_de32msb(cdb + 0x2);
//uint32 len = MDFN_de16msb(cdb + 0x7);
//bool reladdr = cdb[1] & 0x1;
//bool immed = cdb[1] & 0x2;
// Note: This command appears to lock up the CD unit to some degree on a real PC-FX if the (lba + len) >= leadout_track_lba,
// more testing is needed if we ever try to fully emulate this command.
if(lba >= toc.tracks[100].lba)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_END_OF_VOLUME);
return;
}
//printf("Prefetch: %08x %08x %d %d %d %d\n", lba, len, link, flag, reladdr, immed);
//SendStatusAndMessage(STATUS_GOOD, 0x00);
SendStatusAndMessage(STATUS_CONDITION_MET, 0x00);
}
// SEEK functions are mostly just stubs for now, until(if) we emulate seek delays.
static void DoSEEKBase(uint32 lba)
{
if(lba >= toc.tracks[100].lba)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_END_OF_VOLUME);
return;
}
cdda.CDDAStatus = CDDASTATUS_STOPPED;
SendStatusAndMessage(STATUS_GOOD, 0x00);
}
/********************************************************
* *
* SCSI-2 CD Command 0x0B - SEEK(6) *
* *
********************************************************/
static void DoSEEK6(const uint8 *cdb)
{
uint32 lba = ((cdb[1] & 0x1F) << 16) | (cdb[2] << 8) | cdb[3];
DoSEEKBase(lba);
}
/********************************************************
* *
* SCSI-2 CD Command 0x2B - SEEK(10) *
* *
********************************************************/
static void DoSEEK10(const uint8 *cdb)
{
uint32 lba = MDFN_de32msb(cdb + 0x2);
DoSEEKBase(lba);
}
// 353
/********************************************************
* *
* SCSI-2 CD Command 0x42 - READ SUB-CHANNEL(10) *
* *
********************************************************/
static void DoREADSUBCHANNEL(const uint8 *cdb)
{
uint8 data_in[8192];
int DataFormat = cdb[3];
int TrackNum = cdb[6];
unsigned AllocSize = (cdb[7] << 8) | cdb[8];
bool WantQ = cdb[2] & 0x40;
bool WantMSF = cdb[1] & 0x02;
uint32 offset = 0;
if(!AllocSize)
{
SendStatusAndMessage(STATUS_GOOD, 0x00);
return;
}
if(DataFormat > 0x3)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_PARAMETER);
return;
}
if(DataFormat == 0x3 && (TrackNum < toc.first_track || TrackNum > toc.last_track))
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_PARAMETER);
return;
}
data_in[offset++] = 0;
// FIXME: Is this audio status code correct for scanning playback??
if(cdda.CDDAStatus == CDDASTATUS_PLAYING || cdda.CDDAStatus == CDDASTATUS_SCANNING)
data_in[offset++] = 0x11; // Audio play operation in progress
else if(cdda.CDDAStatus == CDDASTATUS_PAUSED)
data_in[offset++] = 0x12; // Audio play operation paused
else
data_in[offset++] = 0x13; // 0x13(audio play operation completed successfully) or 0x15(no current audio status to return)? :(
// Subchannel data length(at data_in[0x2], filled out at the end of the function)
data_in[offset++] = 0x00;
data_in[offset++] = 0x00;
//printf("42Read SubChannel: %02x %02x %d %d %d\n", DataFormat, TrackNum, AllocSize, WantQ, WantMSF);
if(WantQ)
{
// Sub-channel format code
data_in[offset++] = DataFormat;
if(!DataFormat || DataFormat == 0x01)
{
uint8 *SubQBuf = cd.SubQBuf[QMode_Time];
data_in[offset++] = ((SubQBuf[0] & 0x0F) << 4) | ((SubQBuf[0] & 0xF0) >> 4); // Control/adr
data_in[offset++] = SubQBuf[1]; // Track
data_in[offset++] = SubQBuf[2]; // Index
// Absolute CD-ROM address
if(WantMSF)
{
data_in[offset++] = 0;
data_in[offset++] = BCD_to_U8(SubQBuf[7]); // M
data_in[offset++] = BCD_to_U8(SubQBuf[8]); // S
data_in[offset++] = BCD_to_U8(SubQBuf[9]); // F
}
else
{
uint32 tmp_lba = BCD_to_U8(SubQBuf[7]) * 60 * 75 + BCD_to_U8(SubQBuf[8]) * 75 + BCD_to_U8(SubQBuf[9]) - 150;
data_in[offset++] = tmp_lba >> 24;
data_in[offset++] = tmp_lba >> 16;
data_in[offset++] = tmp_lba >> 8;
data_in[offset++] = tmp_lba >> 0;
}
// Relative CD-ROM address
if(WantMSF)
{
data_in[offset++] = 0;
data_in[offset++] = BCD_to_U8(SubQBuf[3]); // M
data_in[offset++] = BCD_to_U8(SubQBuf[4]); // S
data_in[offset++] = BCD_to_U8(SubQBuf[5]); // F
}
else
{
uint32 tmp_lba = BCD_to_U8(SubQBuf[3]) * 60 * 75 + BCD_to_U8(SubQBuf[4]) * 75 + BCD_to_U8(SubQBuf[5]); // Don't subtract 150 in the conversion!
data_in[offset++] = tmp_lba >> 24;
data_in[offset++] = tmp_lba >> 16;
data_in[offset++] = tmp_lba >> 8;
data_in[offset++] = tmp_lba >> 0;
}
}
if(!DataFormat || DataFormat == 0x02)
{
if(DataFormat == 0x02)
{
data_in[offset++] = 0x00;
data_in[offset++] = 0x00;
data_in[offset++] = 0x00;
}
data_in[offset++] = 0x00; // MCVal and reserved.
for(int i = 0; i < 15; i++)
data_in[offset++] = 0x00;
}
// Track ISRC
if(!DataFormat || DataFormat == 0x03)
{
if(DataFormat == 0x03)
{
uint8 *SubQBuf = cd.SubQBuf[QMode_Time]; // FIXME
data_in[offset++] = ((SubQBuf[0] & 0x0F) << 4) | ((SubQBuf[0] & 0xF0) >> 4); // Control/adr
data_in[offset++] = TrackNum; // From sub Q or from parameter?
data_in[offset++] = 0x00; // Reserved.
}
data_in[offset++] = 0x00; // TCVal and reserved
for(int i = 0; i < 15; i++)
data_in[offset++] = 0x00;
}
}
MDFN_en16msb(&data_in[0x2], offset - 0x4);
DoSimpleDataIn(data_in, (AllocSize > offset) ? offset : AllocSize);
}
/********************************************************
* *
* PC-FX CD Command 0xDD - READ SUB Q *
* *
********************************************************/
static void DoNEC_READSUBQ(const uint8 *cdb)
{
uint8 *SubQBuf = cd.SubQBuf[QMode_Time];
uint8 data_in[10];
const uint8 alloc_size = (cdb[1] < 10) ? cdb[1] : 10;
memset(data_in, 0x00, 10);
if(cdda.CDDAStatus == CDDASTATUS_PAUSED)
data_in[0] = 2; // Pause
else if(cdda.CDDAStatus == CDDASTATUS_PLAYING || cdda.CDDAStatus == CDDASTATUS_SCANNING) // FIXME: Is this the correct status code for scanning playback?
data_in[0] = 0; // Playing
else
data_in[0] = 3; // Stopped
data_in[1] = SubQBuf[0]; // Control/adr
data_in[2] = SubQBuf[1]; // Track
data_in[3] = SubQBuf[2]; // Index
data_in[4] = SubQBuf[3]; // M(rel)
data_in[5] = SubQBuf[4]; // S(rel)
data_in[6] = SubQBuf[5]; // F(rel)
data_in[7] = SubQBuf[7]; // M(abs)
data_in[8] = SubQBuf[8]; // S(abs)
data_in[9] = SubQBuf[9]; // F(abs)
DoSimpleDataIn(data_in, alloc_size);
}
static void DoTESTUNITREADY(const uint8 *cdb)
{
SendStatusAndMessage(STATUS_GOOD, 0x00);
}
static void DoNEC_PAUSE(const uint8 *cdb)
{
if(cdda.CDDAStatus != CDDASTATUS_STOPPED) // Hmm, should we give an error if it tries to pause and it's already paused?
{
cdda.CDDAStatus = CDDASTATUS_PAUSED;
SendStatusAndMessage(STATUS_GOOD, 0x00);
}
else // Definitely give an error if it tries to pause when no track is playing!
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_AUDIO_NOT_PLAYING);
}
}
static void DoNEC_SCAN(const uint8 *cdb)
{
uint32 sector_tmp = 0;
// 0: 0xD2
// 1: 0x03 = reverse scan, 0x02 = forward scan
// 2: End M
// 3: End S
// 4: End F
switch (cdb[9] & 0xc0)
{
default:
//SCSIDBG("Unknown NECSCAN format");
break;
case 0x00:
sector_tmp = (cdb[3] << 16) | (cdb[4] << 8) | cdb[5];
break;
case 0x40:
sector_tmp = AMSF_to_LBA(BCD_to_U8(cdb[2]), BCD_to_U8(cdb[3]), BCD_to_U8(cdb[4]));
break;
case 0x80: // FIXME: error on invalid track number???
sector_tmp = toc.tracks[BCD_to_U8(cdb[2])].lba;
break;
}
cdda.ScanMode = cdb[1] & 0x3;
cdda.scan_sec_end = sector_tmp;
if(cdda.CDDAStatus != CDDASTATUS_STOPPED)
{
if(cdda.ScanMode)
{
cdda.CDDAStatus = CDDASTATUS_SCANNING;
}
}
SendStatusAndMessage(STATUS_GOOD, 0x00);
}
/********************************************************
* *
* SCSI-2 CD Command 0x1E - PREVENT/ALLOW MEDIUM *
* REMOVAL *
********************************************************/
static void DoPREVENTALLOWREMOVAL(const uint8 *cdb)
{
//bool prevent = cdb[4] & 0x01;
//const int logical_unit = cdb[1] >> 5;
//SCSIDBG("PREVENT ALLOW MEDIUM REMOVAL: %d for %d\n", cdb[4] & 0x1, logical_unit);
//SendStatusAndMessage(STATUS_GOOD, 0x00);
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_REQUEST_IN_CDB);
}
//
//
//
#include "scsicd-pce-commands.inc"
#define SCF_REQUIRES_MEDIUM 0x0001
#define SCF_INCOMPLETE 0x4000
#define SCF_UNTESTED 0x8000
typedef struct
{
uint8 cmd;
uint32 flags;
void (*func)(const uint8 *cdb);
const char *pretty_name;
const char *format_string;
} SCSICH;
static const int32 RequiredCDBLen[16] =
{
6, // 0x0n
6, // 0x1n
10, // 0x2n
10, // 0x3n
10, // 0x4n
10, // 0x5n
10, // 0x6n
10, // 0x7n
10, // 0x8n
10, // 0x9n
12, // 0xAn
12, // 0xBn
10, // 0xCn
10, // 0xDn
10, // 0xEn
10, // 0xFn
};
static SCSICH PCFXCommandDefs[] =
{
{ 0x00, SCF_REQUIRES_MEDIUM, DoTESTUNITREADY, "Test Unit Ready" },
{ 0x01, 0/* ? */, DoREZEROUNIT, "Rezero Unit" },
{ 0x03, 0, DoREQUESTSENSE, "Request Sense" },
{ 0x08, SCF_REQUIRES_MEDIUM, DoREAD6, "Read(6)" },
{ 0x0B, SCF_REQUIRES_MEDIUM, DoSEEK6, "Seek(6)" },
{ 0x0D, 0, DoNEC_NOP, "No Operation" },
{ 0x12, 0, DoINQUIRY, "Inquiry" },
{ 0x15, 0, DoMODESELECT6, "Mode Select(6)" },
// TODO: { 0x16, 0 /* ? */, DoRESERVE, "Reserve" }, // 9.2.12
// TODO: { 0x17, 0 /* ? */, DoRELEASE, "Release" }, // 9.2.11
{ 0x1A, 0, DoMODESENSE6, "Mode Sense(6)" },
{ 0x1B, SCF_REQUIRES_MEDIUM, DoSTARTSTOPUNIT6, "Start/Stop Unit" }, // 9.2.17
// TODO: { 0x1D, , DoSENDDIAG, "Send Diagnostic" }, // 8.2.15
{ 0x1E, 0, DoPREVENTALLOWREMOVAL, "Prevent/Allow Media Removal" },
{ 0x25, SCF_REQUIRES_MEDIUM, DoREADCDCAP10, "Read CD-ROM Capacity" }, // 14.2.8
{ 0x28, SCF_REQUIRES_MEDIUM, DoREAD10, "Read(10)" },
{ 0x2B, SCF_REQUIRES_MEDIUM, DoSEEK10, "Seek(10)" },
// TODO: { 0x2F, SCF_REQUIRES_MEDIUM, DoVERIFY10, "Verify(10)" }, // 16.2.11
{ 0x34, SCF_REQUIRES_MEDIUM, DoPREFETCH, "Prefetch" },
// TODO: { 0x3B, 0, 10, DoWRITEBUFFER, "Write Buffer" }, // 8.2.17
// TODO: { 0x3C, 0, 10, DoREADBUFFER, "Read Buffer" }, // 8.2.12
{ 0x42, SCF_REQUIRES_MEDIUM, DoREADSUBCHANNEL, "Read Subchannel" },
{ 0x43, SCF_REQUIRES_MEDIUM, DoREADTOC, "Read TOC" },
{ 0x44, SCF_REQUIRES_MEDIUM, DoREADHEADER10, "Read Header" },
{ 0x45, SCF_REQUIRES_MEDIUM, DoPA10, "Play Audio(10)" },
{ 0x47, SCF_REQUIRES_MEDIUM, DoPAMSF, "Play Audio MSF" },
{ 0x48, SCF_REQUIRES_MEDIUM, DoPATI, "Play Audio Track Index" },
{ 0x49, SCF_REQUIRES_MEDIUM, DoPATR10, "Play Audio Track Relative(10)" },
{ 0x4B, SCF_REQUIRES_MEDIUM, DoPAUSERESUME, "Pause/Resume" },
{ 0xA5, SCF_REQUIRES_MEDIUM, DoPA12, "Play Audio(12)" },
{ 0xA8, SCF_REQUIRES_MEDIUM, DoREAD12, "Read(12)" },
{ 0xA9, SCF_REQUIRES_MEDIUM, DoPATR12, "Play Audio Track Relative(12)" },
// TODO: { 0xAF, SCF_REQUIRES_MEDIUM, DoVERIFY12, "Verify(12)" }, // 16.2.12
{ 0xD2, SCF_REQUIRES_MEDIUM, DoNEC_SCAN, "Scan" },
{ 0xD8, SCF_REQUIRES_MEDIUM, DoNEC_SAPSP, "Set Audio Playback Start Position" }, // "Audio track search"
{ 0xD9, SCF_REQUIRES_MEDIUM, DoNEC_SAPEP, "Set Audio Playback End Position" }, // "Play"
{ 0xDA, SCF_REQUIRES_MEDIUM, DoNEC_PAUSE, "Pause" }, // "Still"
{ 0xDB, SCF_REQUIRES_MEDIUM | SCF_UNTESTED, DoNEC_SST, "Set Stop Time" },
{ 0xDC, SCF_REQUIRES_MEDIUM, DoNEC_EJECT, "Eject" },
{ 0xDD, SCF_REQUIRES_MEDIUM, DoNEC_READSUBQ, "Read Subchannel Q" },
{ 0xDE, SCF_REQUIRES_MEDIUM, DoNEC_GETDIRINFO, "Get Dir Info" },
{ 0xFF, 0, 0, NULL, NULL },
};
static SCSICH PCECommandDefs[] =
{
{ 0x00, SCF_REQUIRES_MEDIUM, DoTESTUNITREADY, "Test Unit Ready" },
{ 0x03, 0, DoREQUESTSENSE, "Request Sense" },
{ 0x08, SCF_REQUIRES_MEDIUM, DoREAD6, "Read(6)" },
//{ 0x15, DoMODESELECT6, "Mode Select(6)" },
{ 0xD8, SCF_REQUIRES_MEDIUM, DoNEC_PCE_SAPSP, "Set Audio Playback Start Position" },
{ 0xD9, SCF_REQUIRES_MEDIUM, DoNEC_PCE_SAPEP, "Set Audio Playback End Position" },
{ 0xDA, SCF_REQUIRES_MEDIUM, DoNEC_PCE_PAUSE, "Pause" },
{ 0xDD, SCF_REQUIRES_MEDIUM, DoNEC_PCE_READSUBQ, "Read Subchannel Q" },
{ 0xDE, SCF_REQUIRES_MEDIUM, DoNEC_PCE_GETDIRINFO, "Get Dir Info" },
{ 0xFF, 0, 0, NULL, NULL },
};
void SCSICD_ResetTS(uint32 ts_base)
{
lastts = ts_base;
}
void SCSICD_GetCDDAValues(int16 &left, int16 &right)
{
if(cdda.CDDAStatus)
{
left = cdda.sr[0];
right = cdda.sr[1];
}
else
left = right = 0;
}
#define CDDA_FILTER_NUMCONVOLUTIONS 7
#define CDDA_FILTER_NUMCONVOLUTIONS_PADDED 8
#define CDDA_FILTER_NUMPHASES_SHIFT 6
#define CDDA_FILTER_NUMPHASES (1 << CDDA_FILTER_NUMPHASES_SHIFT)
alignas(16) static const int16 CDDA_Filter[1 + CDDA_FILTER_NUMPHASES + 1][CDDA_FILTER_NUMCONVOLUTIONS_PADDED] =
{
#include "scsicd_cdda_filter.inc"
};
alignas(16) static const int16 OversampleFilter[2][0x10] =
{
{ -82, 217, -463, 877, -1562, 2783, -5661, 29464, 9724, -3844, 2074, -1176, 645, -323, 138, -43, }, /* sum=32768, sum_abs=59076 */
{ -43, 138, -323, 645, -1176, 2074, -3844, 9724, 29464, -5661, 2783, -1562, 877, -463, 217, -82, }, /* sum=32768, sum_abs=59076 */
};
static INLINE void RunCDDA(uint32 system_timestamp, int32 run_time)
{
if(cdda.CDDAStatus == CDDASTATUS_PLAYING || cdda.CDDAStatus == CDDASTATUS_SCANNING)
{
cdda.CDDADiv -= (int64)run_time << 20;
while(cdda.CDDADiv <= 0)
{
const uint32 synthtime_ex = (((uint64)system_timestamp << 20) + (int64)cdda.CDDADiv) / cdda.CDDATimeDiv;
const int synthtime = (synthtime_ex >> 16) & 0xFFFF; // & 0xFFFF(or equivalent) to prevent overflowing HRBufs[]
const int synthtime_phase = (int)(synthtime_ex & 0xFFFF) - 0x80;
const int synthtime_phase_int = synthtime_phase >> (16 - CDDA_FILTER_NUMPHASES_SHIFT);
const int synthtime_phase_fract = synthtime_phase & ((1 << (16 - CDDA_FILTER_NUMPHASES_SHIFT)) - 1);
int32 sample_va[2];
cdda.CDDADiv += cdda.CDDADivAcc;
if(!(cdda.OversamplePos & 1))
{
if(cdda.CDDAReadPos == 588)
{
if(read_sec >= read_sec_end || (cdda.CDDAStatus == CDDASTATUS_SCANNING && read_sec == cdda.scan_sec_end))
{
switch(cdda.PlayMode)
{
case PLAYMODE_SILENT:
case PLAYMODE_NORMAL:
cdda.CDDAStatus = CDDASTATUS_STOPPED;
break;
case PLAYMODE_INTERRUPT:
cdda.CDDAStatus = CDDASTATUS_STOPPED;
CDIRQCallback(SCSICD_IRQ_DATA_TRANSFER_DONE);
break;
case PLAYMODE_LOOP:
read_sec = read_sec_start;
break;
}
// If CDDA playback is stopped, break out of our while(CDDADiv ...) loop and don't play any more sound!
if(cdda.CDDAStatus == CDDASTATUS_STOPPED)
break;
}
// Don't play past the user area of the disc.
if(read_sec >= toc.tracks[100].lba)
{
cdda.CDDAStatus = CDDASTATUS_STOPPED;
break;
}
if(TrayOpen || !Cur_CDIF)
{
cdda.CDDAStatus = CDDASTATUS_STOPPED;
#if 0
cd.data_transfer_done = false;
cd.key_pending = SENSEKEY_NOT_READY;
cd.asc_pending = ASC_MEDIUM_NOT_PRESENT;
cd.ascq_pending = 0x00;
cd.fru_pending = 0x00;
SendStatusAndMessage(STATUS_CHECK_CONDITION, 0x00);
#endif
break;
}
cdda.CDDAReadPos = 0;
{
uint8 tmpbuf[2352 + 96];
Cur_CDIF->ReadRawSector(tmpbuf, read_sec); //, read_sec_end, read_sec_start);
for(int i = 0; i < 588 * 2; i++)
cdda.CDDASectorBuffer[i] = MDFN_de16lsb(&tmpbuf[i * 2]);
memcpy(cd.SubPWBuf, tmpbuf + 2352, 96);
}
GenSubQFromSubPW();
if(!(cd.SubQBuf_Last[0] & 0x10))
{
// Not using de-emphasis, so clear the de-emphasis filter state.
memset(cdda.DeemphState, 0, sizeof(cdda.DeemphState));
}
if(cdda.CDDAStatus == CDDASTATUS_SCANNING)
{
int64 tmp_read_sec = read_sec;
if(cdda.ScanMode & 1)
{
tmp_read_sec -= 24;
if(tmp_read_sec < cdda.scan_sec_end)
tmp_read_sec = cdda.scan_sec_end;
}
else
{
tmp_read_sec += 24;
if(tmp_read_sec > cdda.scan_sec_end)
tmp_read_sec = cdda.scan_sec_end;
}
read_sec = tmp_read_sec;
}
else
read_sec++;
} // End if(CDDAReadPos == 588)
if(!(cdda.CDDAReadPos % 6))
{
int subindex = cdda.CDDAReadPos / 6 - 2;
if(subindex >= 0)
CDStuffSubchannels(cd.SubPWBuf[subindex], subindex);
else // The system-specific emulation code should handle what value the sync bytes are.
CDStuffSubchannels(0x00, subindex);
}
// If the last valid sub-Q data decoded indicate that the corresponding sector is a data sector, don't output the
// current sector as audio.
if(!(cd.SubQBuf_Last[0] & 0x40) && cdda.PlayMode != PLAYMODE_SILENT)
{
cdda.sr[0] = cdda.CDDASectorBuffer[cdda.CDDAReadPos * 2 + cdda.OutPortChSelectCache[0]];
cdda.sr[1] = cdda.CDDASectorBuffer[cdda.CDDAReadPos * 2 + cdda.OutPortChSelectCache[1]];
}
#if 0
{
static int16 wv = 0x7FFF; //0x5000;
static unsigned counter = 0;
static double phase = 0;
static double phase_inc = 0;
static const double phase_inc_inc = 0.000003 / 2;
cdda.sr[0] = 32767 * sin(phase);
cdda.sr[1] = 32767 * sin(phase);
//cdda.sr[0] = wv;
//cdda.sr[1] = wv;
if(counter == 0)
wv = -wv;
counter = (counter + 1) & 1;
phase += phase_inc;
phase_inc += phase_inc_inc;
}
#endif
{
const unsigned obwp = cdda.OversamplePos >> 1;
cdda.OversampleBuffer[0][obwp] = cdda.OversampleBuffer[0][0x10 + obwp] = cdda.sr[0];
cdda.OversampleBuffer[1][obwp] = cdda.OversampleBuffer[1][0x10 + obwp] = cdda.sr[1];
}
cdda.CDDAReadPos++;
} // End if(!(cdda.OversamplePos & 1))
{
const int16* f = OversampleFilter[cdda.OversamplePos & 1];
#if defined(__SSE2__)
__m128i f0 = _mm_load_si128((__m128i *)&f[0]);
__m128i f1 = _mm_load_si128((__m128i *)&f[8]);
#endif
for(unsigned lr = 0; lr < 2; lr++)
{
const int16* b = &cdda.OversampleBuffer[lr][((cdda.OversamplePos >> 1) + 1) & 0xF];
#if defined(__SSE2__)
union
{
int32 accum;
float accum_f;
//__m128i accum_m128;
};
{
__m128i b0;
__m128i b1;
__m128i sum;
b0 = _mm_loadu_si128((__m128i *)&b[0]);
b1 = _mm_loadu_si128((__m128i *)&b[8]);
sum = _mm_add_epi32(_mm_madd_epi16(f0, b0), _mm_madd_epi16(f1, b1));
sum = _mm_add_epi32(sum, _mm_shuffle_epi32(sum, (3 << 0) | (2 << 2) | (1 << 4) | (0 << 6)));
sum = _mm_add_epi32(sum, _mm_shuffle_epi32(sum, (1 << 0) | (0 << 2) | (3 << 4) | (2 << 6)));
_mm_store_ss(&accum_f, (__m128)sum);
//_mm_store_si128(&accum_m128, sum);
}
#else
int32 accum = 0;
for(unsigned i = 0; i < 0x10; i++)
accum += f[i] * b[i];
#endif
// sum_abs * cdda_min =
// 59076 * -32768 = -1935802368
// OPVC can have a maximum value of 65536.
// -1935802368 * 65536 = -126864743989248
//
// -126864743989248 / 65536 = -1935802368
sample_va[lr] = ((int64)accum * cdda.OutPortVolumeCache[lr]) >> 16;
// Output of this stage will be (approximate max ranges) -2147450880 through 2147385345.
}
}
//
// This de-emphasis filter's frequency response isn't totally correct, but it's much better than nothing(and it's not like any known PCE CD/TG16 CD/PC-FX games
// utilize pre-emphasis anyway).
//
if(MDFN_UNLIKELY(cd.SubQBuf_Last[0] & 0x10))
{
//puts("Deemph");
for(unsigned lr = 0; lr < 2; lr++)
{
float inv = sample_va[lr] * 0.35971507338824012f;
cdda.DeemphState[lr][1] = (cdda.DeemphState[lr][0] - 0.4316395666f * inv) + (0.7955522347f * cdda.DeemphState[lr][1]);
cdda.DeemphState[lr][0] = inv;
sample_va[lr] = std::max<float>(-2147483648.0, std::min<float>(2147483647.0, cdda.DeemphState[lr][1]));
//printf("%u: %f, %d\n", lr, cdda.DeemphState[lr][1], sample_va[lr]);
}
}
if(HRBufs[0] && HRBufs[1])
{
//
// FINAL_OUT_SHIFT should be 32 so we can take advantage of 32x32->64 multipliers on 32-bit CPUs.
//
#define FINAL_OUT_SHIFT 32
#define MULT_SHIFT_ADJ (32 - (26 + (8 - CDDA_FILTER_NUMPHASES_SHIFT)))
#if (((1 << (16 - CDDA_FILTER_NUMPHASES_SHIFT)) - 0) << MULT_SHIFT_ADJ) > 32767
#error "COEFF MULT OVERFLOW"
#endif
const int16 mult_a = ((1 << (16 - CDDA_FILTER_NUMPHASES_SHIFT)) - synthtime_phase_fract) << MULT_SHIFT_ADJ;
const int16 mult_b = synthtime_phase_fract << MULT_SHIFT_ADJ;
int32 coeff[CDDA_FILTER_NUMCONVOLUTIONS];
//if(synthtime_phase_fract == 0)
// printf("%5d: %d %d\n", synthtime_phase_fract, mult_a, mult_b);
for(unsigned c = 0; c < CDDA_FILTER_NUMCONVOLUTIONS; c++)
{
coeff[c] = (CDDA_Filter[1 + synthtime_phase_int + 0][c] * mult_a +
CDDA_Filter[1 + synthtime_phase_int + 1][c] * mult_b);
}
int32* tb0 = &HRBufs[0][synthtime];
int32* tb1 = &HRBufs[1][synthtime];
for(unsigned c = 0; c < CDDA_FILTER_NUMCONVOLUTIONS; c++)
{
tb0[c] += ((int64)coeff[c] * sample_va[0]) >> FINAL_OUT_SHIFT;
tb1[c] += ((int64)coeff[c] * sample_va[1]) >> FINAL_OUT_SHIFT;
}
#undef FINAL_OUT_SHIFT
#undef MULT_SHIFT_ADJ
}
cdda.OversamplePos = (cdda.OversamplePos + 1) & 0x1F;
} // end while(cdda.CDDADiv <= 0)
}
}
static INLINE void RunCDRead(uint32 system_timestamp, int32 run_time)
{
if(CDReadTimer > 0)
{
CDReadTimer -= run_time;
if(CDReadTimer <= 0)
{
if(din->CanWrite() < ((WhichSystem == SCSICD_PCFX) ? 2352 : 2048)) // +96 if we find out the PC-FX can read subchannel data along with raw data too. ;)
{
//printf("Carp: %d %d %d\n", din->CanWrite(), SectorCount, CDReadTimer);
//CDReadTimer = (cd.data_in_size - cd.data_in_pos) * 10;
CDReadTimer += (uint64) 1 * 2048 * System_Clock / CD_DATA_TRANSFER_RATE;
//CDReadTimer += (uint64) 1 * 128 * System_Clock / CD_DATA_TRANSFER_RATE;
}
else
{
uint8 tmp_read_buf[2352 + 96];
if(TrayOpen)
{
din->Flush();
cd.data_transfer_done = false;
CommandCCError(SENSEKEY_NOT_READY, NSE_TRAY_OPEN);
}
else if(!Cur_CDIF)
{
CommandCCError(SENSEKEY_NOT_READY, NSE_NO_DISC);
}
else if(SectorAddr >= toc.tracks[100].lba)
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_END_OF_VOLUME);
}
else if(!Cur_CDIF->ReadRawSector(tmp_read_buf, SectorAddr)) //, SectorAddr + SectorCount))
{
cd.data_transfer_done = false;
CommandCCError(SENSEKEY_ILLEGAL_REQUEST);
}
else if(ValidateRawDataSector(tmp_read_buf, SectorAddr))
{
memcpy(cd.SubPWBuf, tmp_read_buf + 2352, 96);
if(tmp_read_buf[12 + 3] == 0x2)
din->Write(tmp_read_buf + 24, 2048);
else
din->Write(tmp_read_buf + 16, 2048);
GenSubQFromSubPW();
CDIRQCallback(SCSICD_IRQ_DATA_TRANSFER_READY);
SectorAddr++;
SectorCount--;
if(CurrentPhase != PHASE_DATA_IN)
ChangePhase(PHASE_DATA_IN);
if(SectorCount)
{
cd.data_transfer_done = false;
CDReadTimer += (uint64) 1 * 2048 * System_Clock / CD_DATA_TRANSFER_RATE;
}
else
{
cd.data_transfer_done = true;
}
}
} // end else to if(!Cur_CDIF->ReadSector
}
}
}
uint32 SCSICD_Run(scsicd_timestamp_t system_timestamp)
{
int32 run_time = system_timestamp - lastts;
if(system_timestamp < lastts)
{
fprintf(stderr, "Meow: %d %d\n", system_timestamp, lastts);
assert(system_timestamp >= lastts);
}
monotonic_timestamp += run_time;
lastts = system_timestamp;
RunCDRead(system_timestamp, run_time);
RunCDDA(system_timestamp, run_time);
bool ResetNeeded = false;
if(RST_signal && !cd.last_RST_signal)
ResetNeeded = true;
cd.last_RST_signal = RST_signal;
if(ResetNeeded)
{
//puts("RST");
VirtualReset();
}
else if(CurrentPhase == PHASE_BUS_FREE)
{
if(SEL_signal)
{
if(WhichSystem == SCSICD_PCFX)
{
//if(cd_bus.DB == 0x84)
{
ChangePhase(PHASE_COMMAND);
}
}
else // PCE
{
ChangePhase(PHASE_COMMAND);
}
}
}
else if(ATN_signal && !REQ_signal && !ACK_signal)
{
//printf("Yay: %d %d\n", REQ_signal, ACK_signal);
ChangePhase(PHASE_MESSAGE_OUT);
}
else switch(CurrentPhase)
{
case PHASE_COMMAND:
if(REQ_signal && ACK_signal) // Data bus is valid nowww
{
//printf("Command Phase Byte I->T: %02x, %d\n", cd_bus.DB, cd.command_buffer_pos);
cd.command_buffer[cd.command_buffer_pos++] = cd_bus.DB;
SetREQ(false);
}
if(!REQ_signal && !ACK_signal && cd.command_buffer_pos) // Received at least one byte, what should we do?
{
if(cd.command_buffer_pos == RequiredCDBLen[cd.command_buffer[0] >> 4])
{
const SCSICH *cmd_info_ptr;
if(WhichSystem == SCSICD_PCFX)
cmd_info_ptr = PCFXCommandDefs;
else
cmd_info_ptr = PCECommandDefs;
while(cmd_info_ptr->pretty_name && cmd_info_ptr->cmd != cd.command_buffer[0])
cmd_info_ptr++;
if(SCSILog)
{
char log_buffer[1024];
int lb_pos;
log_buffer[0] = 0;
lb_pos = trio_snprintf(log_buffer, 1024, "Command: %02x, %s%s ", cd.command_buffer[0], cmd_info_ptr->pretty_name ? cmd_info_ptr->pretty_name : "!!BAD COMMAND!!",
(cmd_info_ptr->flags & SCF_UNTESTED) ? "(UNTESTED)" : "");
for(int i = 0; i < RequiredCDBLen[cd.command_buffer[0] >> 4]; i++)
lb_pos += trio_snprintf(log_buffer + lb_pos, 1024 - lb_pos, "%02x ", cd.command_buffer[i]);
SCSILog("SCSI", "%s", log_buffer);
//puts(log_buffer);
}
if(cmd_info_ptr->pretty_name == NULL) // Command not found!
{
CommandCCError(SENSEKEY_ILLEGAL_REQUEST, NSE_INVALID_COMMAND);
//SCSIDBG("Bad Command: %02x\n", cd.command_buffer[0]);
if(SCSILog)
SCSILog("SCSI", "Bad Command: %02x", cd.command_buffer[0]);
cd.command_buffer_pos = 0;
}
else
{
if(cmd_info_ptr->flags & SCF_UNTESTED)
{
//SCSIDBG("Untested SCSI command: %02x, %s", cd.command_buffer[0], cmd_info_ptr->pretty_name);
}
if(TrayOpen && (cmd_info_ptr->flags & SCF_REQUIRES_MEDIUM))
{
CommandCCError(SENSEKEY_NOT_READY, NSE_TRAY_OPEN);
}
else if(!Cur_CDIF && (cmd_info_ptr->flags & SCF_REQUIRES_MEDIUM))
{
CommandCCError(SENSEKEY_NOT_READY, NSE_NO_DISC);
}
else if(cd.DiscChanged && (cmd_info_ptr->flags & SCF_REQUIRES_MEDIUM))
{
CommandCCError(SENSEKEY_UNIT_ATTENTION, NSE_DISC_CHANGED);
cd.DiscChanged = false;
}
else
{
bool prev_ps = (cdda.CDDAStatus == CDDASTATUS_PLAYING || cdda.CDDAStatus == CDDASTATUS_SCANNING);
cmd_info_ptr->func(cd.command_buffer);
bool new_ps = (cdda.CDDAStatus == CDDASTATUS_PLAYING || cdda.CDDAStatus == CDDASTATUS_SCANNING);
// A bit kludgey, but ehhhh.
if(!prev_ps && new_ps)
{
memset(cdda.sr, 0, sizeof(cdda.sr));
memset(cdda.OversampleBuffer, 0, sizeof(cdda.OversampleBuffer));
memset(cdda.DeemphState, 0, sizeof(cdda.DeemphState));
//printf("CLEAR BUFFERS LALALA\n");
}
}
cd.command_buffer_pos = 0;
}
} // end if(cd.command_buffer_pos == RequiredCDBLen[cd.command_buffer[0] >> 4])
else // Otherwise, get more data for the command!
SetREQ(true);
}
break;
case PHASE_DATA_OUT:
if(REQ_signal && ACK_signal) // Data bus is valid nowww
{
//printf("DATAOUT-SCSIIN: %d %02x\n", cd.data_out_pos, cd_bus.DB);
cd.data_out[cd.data_out_pos++] = cd_bus.DB;
SetREQ(false);
}
else if(!REQ_signal && !ACK_signal && cd.data_out_pos)
{
if(cd.data_out_pos == cd.data_out_want)
{
cd.data_out_pos = 0;
if(cd.command_buffer[0] == 0x15)
FinishMODESELECT6(cd.data_out, cd.data_out_want);
else // Error out here? It shouldn't be reached:
SendStatusAndMessage(STATUS_GOOD, 0x00);
}
else
SetREQ(true);
}
break;
case PHASE_MESSAGE_OUT:
//printf("%d %d, %02x\n", REQ_signal, ACK_signal, cd_bus.DB);
if(REQ_signal && ACK_signal)
{
SetREQ(false);
// ABORT message is 0x06, but the code isn't set up to be able to recover from a MESSAGE OUT phase back to the previous phase, so we treat any message as an ABORT.
// Real tests are needed on the PC-FX to determine its behavior.
// (Previously, ATN emulation was a bit broken, which resulted in the wrong data on the data bus in this code path in at least "Battle Heat", but it's fixed now and 0x06 is on the data bus).
//if(cd_bus.DB == 0x6) // ABORT message!
if(1)
{
//printf("[SCSICD] Abort Received(DB=0x%02x)\n", cd_bus.DB);
din->Flush();
cd.data_out_pos = cd.data_out_want = 0;
CDReadTimer = 0;
cdda.CDDAStatus = CDDASTATUS_STOPPED;
ChangePhase(PHASE_BUS_FREE);
}
//else
// printf("[SCSICD] Message to target: 0x%02x\n", cd_bus.DB);
}
break;
case PHASE_STATUS:
if(REQ_signal && ACK_signal)
{
SetREQ(false);
cd.status_sent = true;
}
if(!REQ_signal && !ACK_signal && cd.status_sent)
{
// Status sent, so get ready to send the message!
cd.status_sent = false;
cd_bus.DB = cd.message_pending;
ChangePhase(PHASE_MESSAGE_IN);
}
break;
case PHASE_DATA_IN:
if(!REQ_signal && !ACK_signal)
{
//puts("REQ and ACK false");
if(din->CanRead() == 0) // aaand we're done!
{
CDIRQCallback(0x8000 | SCSICD_IRQ_DATA_TRANSFER_READY);
if(cd.data_transfer_done)
{
SendStatusAndMessage(STATUS_GOOD, 0x00);
cd.data_transfer_done = false;
CDIRQCallback(SCSICD_IRQ_DATA_TRANSFER_DONE);
}
}
else
{
cd_bus.DB = din->ReadByte();
SetREQ(true);
}
}
if(REQ_signal && ACK_signal)
{
//puts("REQ and ACK true");
SetREQ(false);
}
break;
case PHASE_MESSAGE_IN:
if(REQ_signal && ACK_signal)
{
SetREQ(false);
cd.message_sent = true;
}
if(!REQ_signal && !ACK_signal && cd.message_sent)
{
cd.message_sent = false;
ChangePhase(PHASE_BUS_FREE);
}
break;
}
int32 next_time = 0x7fffffff;
if(CDReadTimer > 0 && CDReadTimer < next_time)
next_time = CDReadTimer;
if(cdda.CDDAStatus == CDDASTATUS_PLAYING || cdda.CDDAStatus == CDDASTATUS_SCANNING)
{
int32 cdda_div_sexytime = (cdda.CDDADiv + (cdda.CDDADivAcc * (cdda.OversamplePos & 1)) + ((1 << 20) - 1)) >> 20;
if(cdda_div_sexytime > 0 && cdda_div_sexytime < next_time)
next_time = cdda_div_sexytime;
}
assert(next_time >= 0);
return(next_time);
}
void SCSICD_SetLog(void (*logfunc)(const char *, const char *, ...))
{
SCSILog = logfunc;
}
void SCSICD_SetTransferRate(uint32 TransferRate)
{
CD_DATA_TRANSFER_RATE = TransferRate;
}
void SCSICD_Close(void)
{
if(din)
{
delete din;
din = NULL;
}
}
void SCSICD_Init(int type, int cdda_time_div, int32* left_hrbuf, int32* right_hrbuf, uint32 TransferRate, uint32 SystemClock, void (*IRQFunc)(int), void (*SSCFunc)(uint8, int))
{
Cur_CDIF = NULL;
TrayOpen = true;
assert(SystemClock < 30000000); // 30 million, sanity check.
monotonic_timestamp = 0;
lastts = 0;
SCSILog = NULL;
if(type == SCSICD_PCFX)
din = new SimpleFIFO<uint8>(65536); //4096);
else
din = new SimpleFIFO<uint8>(2048); //8192); //1024); /2048);
WhichSystem = type;
cdda.CDDADivAcc = (int64)System_Clock * (1024 * 1024) / 88200;
cdda.CDDADivAccVolFudge = 100;
cdda.CDDATimeDiv = cdda_time_div * (1 << (4 + 2));
cdda.CDDAVolume[0] = 65536;
cdda.CDDAVolume[1] = 65536;
FixOPV();
HRBufs[0] = left_hrbuf;
HRBufs[1] = right_hrbuf;
CD_DATA_TRANSFER_RATE = TransferRate;
System_Clock = SystemClock;
CDIRQCallback = IRQFunc;
CDStuffSubchannels = SSCFunc;
}
void SCSICD_SetCDDAVolume(double left, double right)
{
cdda.CDDAVolume[0] = 65536 * left;
cdda.CDDAVolume[1] = 65536 * right;
for(int i = 0; i < 2; i++)
{
if(cdda.CDDAVolume[i] > 65536)
{
printf("[SCSICD] Debug Warning: CD-DA volume %d too large: %d\n", i, cdda.CDDAVolume[i]);
cdda.CDDAVolume[i] = 65536;
}
}
FixOPV();
}
void SCSICD_StateAction(StateMem* sm, const unsigned load, const bool data_only, const char *sname)
{
SFORMAT StateRegs[] =
{
SFVARN(cd_bus.DB, "DB"),
SFVARN(cd_bus.signals, "Signals"),
SFVAR(CurrentPhase),
SFVARN(cd.last_RST_signal, "last_RST"),
SFVARN(cd.message_pending, "message_pending"),
SFVARN(cd.status_sent, "status_sent"),
SFVARN(cd.message_sent, "message_sent"),
SFVARN(cd.key_pending, "key_pending"),
SFVARN(cd.asc_pending, "asc_pending"),
SFVARN(cd.ascq_pending, "ascq_pending"),
SFVARN(cd.fru_pending, "fru_pending"),
SFPTR8N(cd.command_buffer, 256, "command_buffer"),
SFVARN(cd.command_buffer_pos, "command_buffer_pos"),
SFVARN(cd.command_size_left, "command_size_left"),
// Don't save the FIFO's write position, it will be reconstructed from read_pos and in_count
SFPTR8N(&din->data[0], din->data.size(), "din_fifo"),
SFVARN(din->read_pos, "din_read_pos"),
SFVARN(din->in_count, "din_in_count"),
SFVARN(cd.data_transfer_done, "data_transfer_done"),
SFPTR8N(cd.data_out, sizeof(cd.data_out), "data_out"),
SFVARN(cd.data_out_pos, "data_out_pos"),
SFVARN(cd.data_out_want, "data_out_want"),
SFVARN(cd.DiscChanged, "DiscChanged"),
SFVAR(cdda.PlayMode),
SFPTR16(cdda.CDDASectorBuffer, 1176),
SFVAR(cdda.CDDAReadPos),
SFVAR(cdda.CDDAStatus),
SFVAR(cdda.CDDADiv),
SFVAR(read_sec_start),
SFVAR(read_sec),
SFVAR(read_sec_end),
SFVAR(CDReadTimer),
SFVAR(SectorAddr),
SFVAR(SectorCount),
SFVAR(cdda.ScanMode),
SFVAR(cdda.scan_sec_end),
SFVAR(cdda.OversamplePos),
SFPTR16(&cdda.sr[0], sizeof(cdda.sr) / sizeof(cdda.sr[0])),
SFVARN(cdda.OversampleBuffer, "&cdda.OversampleBuffer[0][0]"),
SFVAR(cdda.DeemphState[0][0]),
SFVAR(cdda.DeemphState[0][1]),
SFVAR(cdda.DeemphState[1][0]),
SFVAR(cdda.DeemphState[1][1]),
SFVARN(cd.SubQBuf, "SubQBufs"),
SFVARN(cd.SubQBuf_Last, "SubQBufLast"),
SFVARN(cd.SubPWBuf, "SubPWBuf"),
SFVAR(monotonic_timestamp),
SFVAR(pce_lastsapsp_timestamp),
//
//
//
SFPTR8(ModePages[0].current_value, ModePages[0].param_length),
SFPTR8(ModePages[1].current_value, ModePages[1].param_length),
SFPTR8(ModePages[2].current_value, ModePages[2].param_length),
SFPTR8(ModePages[3].current_value, ModePages[3].param_length),
SFPTR8(ModePages[4].current_value, ModePages[4].param_length),
SFEND
};
MDFNSS_StateAction(sm, load, data_only, StateRegs, sname);
if(load)
{
din->in_count %= din->size + 1;
din->read_pos &= din->size - 1;
din->write_pos = (din->read_pos + din->in_count) & (din->size - 1);
//printf("%d %d %d\n", din->in_count, din->read_pos, din->write_pos);
if(load < 0x0935)
cdda.CDDADiv /= 2;
if(cdda.CDDADiv < 1)
cdda.CDDADiv = 1;
cdda.CDDAReadPos %= 588 + 1;
cdda.OversamplePos &= 0x1F;
for(int i = 0; i < NumModePages; i++)
UpdateMPCacheP(&ModePages[i]);
}
}
}
| 83,372
| 37,967
|
#include <iostream>
#include <string>
#include <d3dcompiler.h>
#include <shellapi.h>
#include <windows.h>
#include <windowsx.h>
#include "../../src/util/com/com_pointer.h"
using namespace dxvk;
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow) {
int argc = 0;
LPWSTR* argv = CommandLineToArgvW(
GetCommandLineW(), &argc);
if (argc < 2 || argc > 3) {
std::cerr << "Usage: dxbc-disasm input.dxbc [output]" << std::endl;
return 1;
}
Com<ID3DBlob> assembly;
Com<ID3DBlob> binary;
// input file
if (FAILED(D3DReadFileToBlob(argv[1], &binary))) {
std::cerr << "Failed to read shader" << std::endl;
return 1;
}
HRESULT hr = D3DDisassemble(
binary->GetBufferPointer(),
binary->GetBufferSize(),
D3D_DISASM_ENABLE_INSTRUCTION_NUMBERING, nullptr,
&assembly);
if (FAILED(hr)) {
std::cerr << "Failed to disassemble shader" << std::endl;
return 1;
}
// output file variant
if (argc == 3 && FAILED(D3DWriteBlobToFile(assembly.ptr(), argv[2], 1))) {
std::cerr << "Failed to write shader" << std::endl;
return 1;
}
// stdout variant
if (argc == 2) {
std::string data((const char *)assembly->GetBufferPointer(), assembly->GetBufferSize());
std::cout << data;
}
return 0;
}
| 1,373
| 529
|
/****************************************************************************
Copyright (c) 2014 cocos2d-x.org
Copyright (c) 2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCController.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include <functional>
#include "ccMacros.h"
#include "CCDirector.h"
#include "jni/JniHelper.h"
#include "base/CCEventController.h"
NS_CC_BEGIN
class ControllerImpl
{
public:
ControllerImpl(Controller* controller)
: _controller(controller)
{
}
static std::vector<Controller*>::iterator findController(const std::string& deviceName, int deviceId)
{
auto iter = std::find_if(Controller::s_allController.begin(), Controller::s_allController.end(), [&](Controller* controller){
return (deviceName == controller->_deviceName) && (deviceId == controller->_deviceId);
});
return iter;
}
static void onConnected(const std::string& deviceName, int deviceId)
{
// Check whether the controller is already connected.
CCLOG("onConnected %s,%d", deviceName.c_str(),deviceId);
auto iter = findController(deviceName, deviceId);
if (iter != Controller::s_allController.end())
return;
// It's a new controller being connected.
auto controller = new cocos2d::Controller();
controller->_deviceId = deviceId;
controller->_deviceName = deviceName;
Controller::s_allController.push_back(controller);
controller->onConnected();
}
static void onDisconnected(const std::string& deviceName, int deviceId)
{
CCLOG("onDisconnected %s,%d", deviceName.c_str(),deviceId);
auto iter = findController(deviceName, deviceId);
if (iter == Controller::s_allController.end())
{
CCLOGERROR("Could not find the controller!");
return;
}
(*iter)->onDisconnected();
Controller::s_allController.erase(iter);
}
static void onButtonEvent(const std::string& deviceName, int deviceId, int keyCode, bool isPressed, float value, bool isAnalog)
{
auto iter = findController(deviceName, deviceId);
if (iter == Controller::s_allController.end())
{
CCLOG("onButtonEvent:connect new controller.");
onConnected(deviceName, deviceId);
iter = findController(deviceName, deviceId);
}
(*iter)->onButtonEvent(keyCode, isPressed, value, isAnalog);
}
static void onAxisEvent(const std::string& deviceName, int deviceId, int axisCode, float value, bool isAnalog)
{
auto iter = findController(deviceName, deviceId);
if (iter == Controller::s_allController.end())
{
CCLOG("onAxisEvent:connect new controller.");
onConnected(deviceName, deviceId);
iter = findController(deviceName, deviceId);
}
(*iter)->onAxisEvent(axisCode, value, isAnalog);
}
private:
Controller* _controller;
};
void Controller::startDiscoveryController()
{
// Empty implementation on Android
}
void Controller::stopDiscoveryController()
{
// Empty implementation on Android
}
Controller::~Controller()
{
delete _impl;
delete _connectEvent;
delete _keyEvent;
delete _axisEvent;
}
void Controller::registerListeners()
{
}
bool Controller::isConnected() const
{
// If there is a controller instance, it means that the controller is connected.
// If a controller is disconnected, the instance will be destroyed.
// So always returns true for this method.
return true;
}
Controller::Controller()
: _controllerTag(TAG_UNSET)
, _impl(new ControllerImpl(this))
, _connectEvent(nullptr)
, _keyEvent(nullptr)
, _axisEvent(nullptr)
{
init();
}
void Controller::receiveExternalKeyEvent(int externalKeyCode,bool receive)
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, "org/cocos2dx/lib/GameControllerHelper", "receiveExternalKeyEvent", "(IIZ)V")) {
t.env->CallStaticVoidMethod(t.classID, t.methodID, _deviceId, externalKeyCode, receive);
t.env->DeleteLocalRef(t.classID);
}
}
NS_CC_END
extern "C" {
void Java_org_cocos2dx_lib_GameControllerAdapter_nativeControllerConnected(JNIEnv* env, jobject thiz, jstring deviceName, jint controllerID)
{
CCLOG("controller id: %d connected!", controllerID);
cocos2d::ControllerImpl::onConnected(cocos2d::JniHelper::jstring2string(deviceName), controllerID);
}
void Java_org_cocos2dx_lib_GameControllerAdapter_nativeControllerDisconnected(JNIEnv* env, jobject thiz, jstring deviceName, jint controllerID)
{
CCLOG("controller id: %d disconnected!", controllerID);
cocos2d::ControllerImpl::onDisconnected(cocos2d::JniHelper::jstring2string(deviceName), controllerID);
}
void Java_org_cocos2dx_lib_GameControllerAdapter_nativeControllerButtonEvent(JNIEnv* env, jobject thiz, jstring deviceName, jint controllerID, jint button, jboolean isPressed, jfloat value, jboolean isAnalog)
{
cocos2d::ControllerImpl::onButtonEvent(cocos2d::JniHelper::jstring2string(deviceName), controllerID, button, isPressed, value, isAnalog);
}
void Java_org_cocos2dx_lib_GameControllerAdapter_nativeControllerAxisEvent(JNIEnv* env, jobject thiz, jstring deviceName, jint controllerID, jint axis, jfloat value, jboolean isAnalog)
{
cocos2d::ControllerImpl::onAxisEvent(cocos2d::JniHelper::jstring2string(deviceName), controllerID, axis, value, isAnalog);
}
} // extern "C" {
#endif // #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
| 6,812
| 2,047
|
/*
* Copyright 2020 Tadashi G. Takaoka
*
* 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 "asm_i8086.h"
#include "error_reporter.h"
#include "reg_i8086.h"
#include "table_i8086.h"
namespace libasm {
namespace i8086 {
bool AsmI8086::parseStringInst(const char *scan, Operand &op) {
Insn _insn(0);
InsnI8086 insn(_insn);
const char *endName = _parser.scanSymbol(scan);
insn.setName(scan, endName);
insn.setAddrMode(M_NONE, M_NONE);
if (TableI8086.searchName(insn))
return false;
if (!insn.stringInst())
return false;
_scan = skipSpaces(endName);
op.val32 = insn.opCode();
op.mode = M_ISTR;
return true;
}
const char *AsmI8086::parsePointerSize(const char *scan, Operand &op) {
const char *p = scan;
const RegName reg = RegI8086::parseRegName(p);
if (reg == REG_BYTE || reg == REG_WORD) {
p = skipSpaces(p + RegI8086::regNameLen(reg));
// Pointer size override
if (RegI8086::parseRegName(p) == REG_PTR) {
op.ptr = reg;
return skipSpaces(p + RegI8086::regNameLen(REG_PTR));
}
setError(UNKNOWN_OPERAND);
return nullptr;
}
return scan;
}
const char *AsmI8086::parseSegmentOverride(const char *scan, Operand &op) {
const char *p = scan;
const RegName reg = RegI8086::parseRegName(p);
if (RegI8086::isSegmentReg(reg)) {
p = skipSpaces(p + RegI8086::regNameLen(reg));
// Segment Override
if (*p == ':') {
op.seg = reg;
return skipSpaces(p + 1);
}
}
return scan;
}
const char *AsmI8086::parseBaseRegister(const char *scan, Operand &op) {
const char *p = scan;
const RegName reg = RegI8086::parseRegName(p);
if (reg == REG_BX || reg == REG_BP) {
op.reg = reg;
return skipSpaces(p + RegI8086::regNameLen(reg));
}
return scan;
}
const char *AsmI8086::parseIndexRegister(const char *scan, Operand &op) {
const char *p = scan;
if (op.reg != REG_UNDEF) {
if (*p != '+')
return scan;
p = skipSpaces(p + 1);
}
const RegName reg = RegI8086::parseRegName(p);
if (reg == REG_SI || reg == REG_DI) {
op.index = reg;
return skipSpaces(p + RegI8086::regNameLen(reg));
}
return scan;
}
const char *AsmI8086::parseDisplacement(const char *scan, Operand &op) {
const char *p = scan;
if (endOfLine(p) || *p == ']')
return scan;
if (op.reg != REG_UNDEF || op.index != REG_UNDEF) {
if (*p != '+' && *p != '-') {
setError(UNKNOWN_OPERAND);
return nullptr;
}
}
op.val32 = parseExpr32(p);
if (parserError()) {
setError(parserError());
return nullptr;
}
if (overflowUint16(static_cast<int32_t>(op.val32))) {
setError(OVERFLOW_RANGE);
return nullptr;
}
op.setError(getError());
op.hasVal = true;
return skipSpaces(_scan);
}
Error AsmI8086::parseOperand(const char *scan, Operand &op) {
const char *p = skipSpaces(scan);
_scan = p;
if (endOfLine(p))
return OK;
if (parseStringInst(p, op))
return OK;
p = parsePointerSize(p, op);
if (p == nullptr)
return getError();
p = parseSegmentOverride(p, op);
if (*p == '[') {
p = skipSpaces(p + 1);
p = parseBaseRegister(p, op);
p = parseIndexRegister(p, op);
p = parseDisplacement(p, op);
if (p == nullptr)
return getError();
if (*p == ']') {
_scan = p + 1;
if (op.reg == REG_UNDEF && op.index == REG_UNDEF) {
if (op.hasVal) {
op.mode =
(op.ptr == REG_UNDEF) ? M_DIR : (op.ptr == REG_BYTE ? M_BDIR : M_WDIR);
return OK;
}
return setError(UNKNOWN_OPERAND);
}
op.mode = (op.ptr == REG_UNDEF) ? M_MEM : (op.ptr == REG_BYTE ? M_BMEM : M_WMEM);
return OK;
}
return setError(MISSING_CLOSING_PAREN);
}
if (op.ptr != REG_UNDEF || op.seg != REG_UNDEF)
return setError(UNKNOWN_OPERAND);
const RegName reg = RegI8086::parseRegName(p);
if (RegI8086::isGeneralReg(reg)) {
_scan = p + RegI8086::regNameLen(reg);
op.reg = reg;
switch (reg) {
case REG_AL:
op.mode = M_AL;
break;
case REG_CL:
op.mode = M_CL;
break;
case REG_AX:
op.mode = M_AX;
break;
case REG_DX:
op.mode = M_DX;
break;
default:
op.mode = (RegI8086::generalRegSize(reg) == SZ_BYTE) ? M_BREG : M_WREG;
break;
}
return OK;
}
if (RegI8086::isSegmentReg(reg)) {
_scan = p + RegI8086::regNameLen(reg);
op.reg = reg;
op.mode = (reg == REG_CS) ? M_CS : M_SREG;
return OK;
}
if (reg != REG_UNDEF)
return setError(UNKNOWN_OPERAND);
op.val32 = parseExpr32(p);
if (parserError())
return getError();
op.setError(getError());
p = skipSpaces(_scan);
if (*p == ':') {
if (op.val32 >= 0x10000UL)
return setError(OVERFLOW_RANGE);
op.seg16 = op.val32;
op.val32 = parseExpr32(p + 1);
if (op.val32 >= 0x10000UL)
return setError(OVERFLOW_RANGE);
if (parserError())
return getError();
op.setErrorIf(getError());
op.mode = M_FAR;
return OK;
}
op.mode = op.immediateMode();
if (op.mode == M_NONE)
return setError(OVERFLOW_RANGE);
return OK;
}
AddrMode AsmI8086::Operand::immediateMode() const {
if (getError())
return M_IMM;
if (val32 == 1)
return M_VAL1;
if (val32 == 3)
return M_VAL3;
if (!overflowUint8(val32))
return M_IMM8;
if (!overflowUint16(val32))
return M_IMM;
return M_NONE;
}
Error AsmI8086::emitImmediate(InsnI8086 &insn, OprSize size, uint32_t val) {
if (size == SZ_BYTE) {
if (overflowUint8(val))
return setError(OVERFLOW_RANGE);
insn.emitOperand8(val);
}
if (size == SZ_WORD) {
if (overflowUint16(val))
return setError(OVERFLOW_RANGE);
insn.emitOperand16(val);
}
return OK;
}
Error AsmI8086::emitRelative(InsnI8086 &insn, const Operand &op, AddrMode mode) {
const Config::uintptr_t base = insn.address() + (mode == M_REL8 ? 2 : 3);
const Config::uintptr_t target = op.getError() ? base : op.val32;
const Config::ptrdiff_t delta = target - base;
if (mode == M_REL8) {
const bool overflow = (delta < -0x80 || delta >= 0x80);
if (insn.opCode() == 0xEB && (overflow || op.getError())) {
insn.setOpCode(0xE9, 0);
return emitRelative(insn, op, M_REL);
}
if (overflow)
return setError(OPERAND_TOO_FAR);
insn.emitOperand8(static_cast<uint8_t>(delta));
return OK;
}
// M_REL
if (delta < -0x8000 || delta >= 0x8000)
return setError(OPERAND_TOO_FAR);
insn.emitOperand16(static_cast<uint16_t>(delta));
return OK;
}
Error AsmI8086::emitRegister(InsnI8086 &insn, const Operand &op, OprPos pos) {
const uint8_t num = RegI8086::encodeRegNum(op.reg);
switch (pos) {
case P_OREG:
insn.embed(num);
break;
case P_OSEG:
insn.embed(num << 3);
break;
case P_OMOD:
insn.embed(0300 | num);
break;
case P_REG:
insn.embedModReg(num << 3);
break;
case P_MOD:
insn.embedModReg(0300 | num);
break;
default:
break;
}
return OK;
}
uint8_t AsmI8086::Operand::encodeMod() const {
const bool needDisp =
(reg == REG_BP && index == REG_UNDEF) || (hasVal && (val32 || getError()));
if (needDisp) {
const int32_t val = static_cast<int32_t>(val32);
return (val < -0x80 || val >= 0x80 || getError()) ? 2 : 1;
}
return 0;
}
uint8_t AsmI8086::Operand::encodeR_m() const {
uint8_t r_m = 0;
if (reg == REG_UNDEF) {
r_m = (index == REG_SI) ? 4 : 5;
} else if (index == REG_UNDEF) {
r_m = (reg == REG_BP) ? 6 : 7;
} else {
if (reg == REG_BP)
r_m |= 2;
if (index == REG_DI)
r_m |= 1;
}
return r_m;
}
Config::opcode_t AsmI8086::encodeSegmentOverride(RegName seg, RegName base) {
if (seg == REG_UNDEF)
return 0;
const Config::opcode_t segPrefix = TableI8086.segOverridePrefix(seg);
if (_optimizeSegment) {
if (base == REG_BP || base == REG_SP)
return seg == REG_SS ? 0 : segPrefix;
return seg == REG_DS ? 0 : segPrefix;
}
return segPrefix;
}
Error AsmI8086::emitModReg(InsnI8086 &insn, const Operand &op, OprPos pos) {
uint8_t mod;
uint8_t modReg;
switch (op.mode) {
case M_AL:
case M_CL:
case M_AX:
case M_DX:
case M_BREG:
case M_WREG:
return emitRegister(insn, op, pos);
case M_BDIR:
case M_WDIR:
case M_DIR:
return emitDirect(insn, op, pos);
case M_BMEM:
case M_WMEM:
case M_MEM:
insn.setSegment(encodeSegmentOverride(op.seg, op.reg));
mod = op.encodeMod();
modReg = mod << 6;
modReg |= op.encodeR_m();
if (pos == P_OMOD) {
insn.embed(modReg);
} else {
insn.embedModReg(modReg);
}
if (mod == 1) {
if (overflowRel8(static_cast<int32_t>(op.val32)))
return setError(OVERFLOW_RANGE);
insn.emitOperand8(op.val32);
} else if (mod == 2) {
if (overflowUint16(static_cast<int32_t>(op.val32)))
return setError(OVERFLOW_RANGE);
insn.emitOperand16(op.val32);
}
break;
default:
break;
}
return OK;
}
Error AsmI8086::emitDirect(InsnI8086 &insn, const Operand &op, OprPos pos) {
insn.setSegment(encodeSegmentOverride(op.seg, REG_UNDEF));
if (pos == P_MOD)
insn.embedModReg(0006);
if (pos == P_OMOD)
insn.embed(0006);
return emitImmediate(insn, SZ_WORD, op.val32);
}
Error AsmI8086::emitOperand(InsnI8086 &insn, AddrMode mode, const Operand &op, OprPos pos) {
switch (mode) {
case M_CS:
if (pos == P_NONE) // POP CS
return setError(REGISTER_NOT_ALLOWED);
/* Fall-through */
case M_BREG:
case M_WREG:
case M_SREG:
return emitRegister(insn, op, pos);
case M_BMOD:
case M_WMOD:
case M_BMEM:
case M_WMEM:
return emitModReg(insn, op, pos);
case M_BDIR:
case M_WDIR:
return emitDirect(insn, op, P_OPR);
case M_UI16:
if (static_cast<int32_t>(op.val32) >= 0x10000 || static_cast<int32_t>(op.val32) < 0)
return setError(OVERFLOW_RANGE);
insn.emitOperand16(op.val32);
return OK;
case M_IMM:
return emitImmediate(insn, insn.oprSize(), op.val32);
case M_IOA:
if (op.val32 >= 0x100)
return setError(OVERFLOW_RANGE);
/* Fall-through */
case M_IMM8:
return emitImmediate(insn, SZ_BYTE, op.val32);
case M_REL:
case M_REL8:
return emitRelative(insn, op, mode);
case M_FAR:
if (op.val32 >= 0x10000)
return setError(OVERFLOW_RANGE);
emitImmediate(insn, SZ_WORD, op.val32);
return emitImmediate(insn, SZ_WORD, op.seg16);
case M_ISTR:
insn.emitOperand8(op.val32);
return OK;
default:
return OK;
}
}
Error AsmI8086::emitStringOperand(InsnI8086 &insn, const Operand &op, RegName seg, RegName index) {
if (op.mode == M_NONE)
return OK;
if (op.reg != REG_UNDEF || op.index != index || op.hasVal)
return setError(ILLEGAL_OPERAND);
if (seg == REG_ES && op.seg != REG_ES)
return setError(ILLEGAL_SEGMENT);
if (seg == REG_DS && op.seg != REG_UNDEF && op.seg != REG_DS)
insn.setSegment(TableI8086.segOverridePrefix(op.seg));
return OK;
}
Error AsmI8086::encodeStringInst(InsnI8086 &insn, const Operand &dst, const Operand &src) {
switch (insn.opCode() & ~1) {
case 0xA4: // MOVS ES:[DI],DS:[SI]
if (emitStringOperand(insn, dst, REG_ES, REG_DI))
return getError();
if (emitStringOperand(insn, src, REG_DS, REG_SI))
return getError();
/* Fall-through */
case 0xAA: // STOS ES:[DI]
case 0xAE: // SCAS ES:[DI]
if (emitStringOperand(insn, dst, REG_ES, REG_DI))
return getError();
break;
case 0xA6: // CMPS DS:[SI],ES:[DI]
if (emitStringOperand(insn, src, REG_ES, REG_DI))
return getError();
/* Fall-through */
case 0xAC: // LODS DS:[SI]
if (emitStringOperand(insn, dst, REG_DS, REG_SI))
return getError();
break;
}
insn.emitInsn();
return setOK();
}
Error AsmI8086::encode(Insn &_insn) {
InsnI8086 insn(_insn);
const char *endName = _parser.scanSymbol(_scan);
insn.setName(_scan, endName);
Operand dstOp, srcOp;
if (parseOperand(endName, dstOp))
return getError();
const char *p = skipSpaces(_scan);
if (*p == ',') {
if (parseOperand(p + 1, srcOp))
return getError();
p = skipSpaces(_scan);
}
if (!endOfLine(p))
return setError(GARBAGE_AT_END);
setError(dstOp.getError());
setErrorIf(srcOp.getError());
insn.setAddrMode(dstOp.mode, srcOp.mode);
if (TableI8086.searchName(insn))
return setError(TableI8086.getError());
insn.prepairModReg();
if (insn.stringInst())
return encodeStringInst(insn, dstOp, srcOp);
const AddrMode dst = insn.dstMode();
if (dst != M_NONE) {
if (emitOperand(insn, dst, dstOp, insn.dstPos()))
return getError();
}
const AddrMode src = insn.srcMode();
if (src != M_NONE) {
if (emitOperand(insn, src, srcOp, insn.srcPos()))
return getError();
}
insn.emitInsn();
return getError();
}
} // namespace i8086
} // namespace libasm
// Local Variables:
// mode: c++
// c-basic-offset: 4
// tab-width: 4
// End:
// vim: set ft=cpp et ts=4 sw=4:
| 14,863
| 5,758
|
/*************************************************************************/
/* resource_importer.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "resource_importer.h"
#include "core/config/project_settings.h"
#include "core/os/os.h"
#include "core/variant/variant_parser.h"
bool ResourceFormatImporter::SortImporterByName::operator()(const Ref<ResourceImporter> &p_a, const Ref<ResourceImporter> &p_b) const {
return p_a->get_importer_name() < p_b->get_importer_name();
}
Error ResourceFormatImporter::_get_path_and_type(const String &p_path, PathAndType &r_path_and_type, bool *r_valid) const {
Error err;
FileAccess *f = FileAccess::open(p_path + ".import", FileAccess::READ, &err);
if (!f) {
if (r_valid) {
*r_valid = false;
}
return err;
}
VariantParser::StreamFile stream;
stream.f = f;
String assign;
Variant value;
VariantParser::Tag next_tag;
if (r_valid) {
*r_valid = true;
}
int lines = 0;
String error_text;
bool path_found = false; //first match must have priority
while (true) {
assign = Variant();
next_tag.fields.clear();
next_tag.name = String();
err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, nullptr, true);
if (err == ERR_FILE_EOF) {
memdelete(f);
return OK;
} else if (err != OK) {
ERR_PRINT("ResourceFormatImporter::load - " + p_path + ".import:" + itos(lines) + " error: " + error_text);
memdelete(f);
return err;
}
if (assign != String()) {
if (!path_found && assign.begins_with("path.") && r_path_and_type.path == String()) {
String feature = assign.get_slicec('.', 1);
if (OS::get_singleton()->has_feature(feature)) {
r_path_and_type.path = value;
path_found = true; //first match must have priority
}
} else if (!path_found && assign == "path") {
r_path_and_type.path = value;
path_found = true; //first match must have priority
} else if (assign == "type") {
r_path_and_type.type = ClassDB::get_compatibility_remapped_class(value);
} else if (assign == "importer") {
r_path_and_type.importer = value;
} else if (assign == "group_file") {
r_path_and_type.group_file = value;
} else if (assign == "metadata") {
r_path_and_type.metadata = value;
} else if (assign == "valid") {
if (r_valid) {
*r_valid = value;
}
}
} else if (next_tag.name != "remap") {
break;
}
}
memdelete(f);
if (r_path_and_type.path == String() || r_path_and_type.type == String()) {
return ERR_FILE_CORRUPT;
}
return OK;
}
RES ResourceFormatImporter::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, bool p_no_cache) {
PathAndType pat;
Error err = _get_path_and_type(p_path, pat);
if (err != OK) {
if (r_error) {
*r_error = err;
}
return RES();
}
RES res = ResourceLoader::_load(pat.path, p_path, pat.type, p_no_cache, r_error, p_use_sub_threads, r_progress);
#ifdef TOOLS_ENABLED
if (res.is_valid()) {
res->set_import_last_modified_time(res->get_last_modified_time()); //pass this, if used
res->set_import_path(pat.path);
}
#endif
return res;
}
void ResourceFormatImporter::get_recognized_extensions(List<String> *p_extensions) const {
Set<String> found;
for (int i = 0; i < importers.size(); i++) {
List<String> local_exts;
importers[i]->get_recognized_extensions(&local_exts);
for (List<String>::Element *F = local_exts.front(); F; F = F->next()) {
if (!found.has(F->get())) {
p_extensions->push_back(F->get());
found.insert(F->get());
}
}
}
}
void ResourceFormatImporter::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const {
if (p_type == "") {
get_recognized_extensions(p_extensions);
return;
}
Set<String> found;
for (int i = 0; i < importers.size(); i++) {
String res_type = importers[i]->get_resource_type();
if (res_type == String()) {
continue;
}
if (!ClassDB::is_parent_class(res_type, p_type)) {
continue;
}
List<String> local_exts;
importers[i]->get_recognized_extensions(&local_exts);
for (List<String>::Element *F = local_exts.front(); F; F = F->next()) {
if (!found.has(F->get())) {
p_extensions->push_back(F->get());
found.insert(F->get());
}
}
}
}
bool ResourceFormatImporter::exists(const String &p_path) const {
return FileAccess::exists(p_path + ".import");
}
bool ResourceFormatImporter::recognize_path(const String &p_path, const String &p_for_type) const {
return FileAccess::exists(p_path + ".import");
}
bool ResourceFormatImporter::can_be_imported(const String &p_path) const {
return ResourceFormatLoader::recognize_path(p_path);
}
int ResourceFormatImporter::get_import_order(const String &p_path) const {
Ref<ResourceImporter> importer;
if (FileAccess::exists(p_path + ".import")) {
PathAndType pat;
Error err = _get_path_and_type(p_path, pat);
if (err == OK) {
importer = get_importer_by_name(pat.importer);
}
} else {
importer = get_importer_by_extension(p_path.get_extension().to_lower());
}
if (importer.is_valid()) {
return importer->get_import_order();
}
return 0;
}
bool ResourceFormatImporter::handles_type(const String &p_type) const {
for (int i = 0; i < importers.size(); i++) {
String res_type = importers[i]->get_resource_type();
if (res_type == String()) {
continue;
}
if (ClassDB::is_parent_class(res_type, p_type)) {
return true;
}
}
return true;
}
String ResourceFormatImporter::get_internal_resource_path(const String &p_path) const {
PathAndType pat;
Error err = _get_path_and_type(p_path, pat);
if (err != OK) {
return String();
}
return pat.path;
}
void ResourceFormatImporter::get_internal_resource_path_list(const String &p_path, List<String> *r_paths) {
Error err;
FileAccess *f = FileAccess::open(p_path + ".import", FileAccess::READ, &err);
if (!f) {
return;
}
VariantParser::StreamFile stream;
stream.f = f;
String assign;
Variant value;
VariantParser::Tag next_tag;
int lines = 0;
String error_text;
while (true) {
assign = Variant();
next_tag.fields.clear();
next_tag.name = String();
err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, nullptr, true);
if (err == ERR_FILE_EOF) {
memdelete(f);
return;
} else if (err != OK) {
ERR_PRINT("ResourceFormatImporter::get_internal_resource_path_list - " + p_path + ".import:" + itos(lines) + " error: " + error_text);
memdelete(f);
return;
}
if (assign != String()) {
if (assign.begins_with("path.")) {
r_paths->push_back(value);
} else if (assign == "path") {
r_paths->push_back(value);
}
} else if (next_tag.name != "remap") {
break;
}
}
memdelete(f);
}
String ResourceFormatImporter::get_import_group_file(const String &p_path) const {
bool valid = true;
PathAndType pat;
_get_path_and_type(p_path, pat, &valid);
return valid ? pat.group_file : String();
}
bool ResourceFormatImporter::is_import_valid(const String &p_path) const {
bool valid = true;
PathAndType pat;
_get_path_and_type(p_path, pat, &valid);
return valid;
}
String ResourceFormatImporter::get_resource_type(const String &p_path) const {
PathAndType pat;
Error err = _get_path_and_type(p_path, pat);
if (err != OK) {
return "";
}
return pat.type;
}
Variant ResourceFormatImporter::get_resource_metadata(const String &p_path) const {
PathAndType pat;
Error err = _get_path_and_type(p_path, pat);
if (err != OK) {
return Variant();
}
return pat.metadata;
}
void ResourceFormatImporter::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
PathAndType pat;
Error err = _get_path_and_type(p_path, pat);
if (err != OK) {
return;
}
ResourceLoader::get_dependencies(pat.path, p_dependencies, p_add_types);
}
Ref<ResourceImporter> ResourceFormatImporter::get_importer_by_name(const String &p_name) const {
for (int i = 0; i < importers.size(); i++) {
if (importers[i]->get_importer_name() == p_name) {
return importers[i];
}
}
return Ref<ResourceImporter>();
}
void ResourceFormatImporter::get_importers_for_extension(const String &p_extension, List<Ref<ResourceImporter>> *r_importers) {
for (int i = 0; i < importers.size(); i++) {
List<String> local_exts;
importers[i]->get_recognized_extensions(&local_exts);
for (List<String>::Element *F = local_exts.front(); F; F = F->next()) {
if (p_extension.to_lower() == F->get()) {
r_importers->push_back(importers[i]);
}
}
}
}
Ref<ResourceImporter> ResourceFormatImporter::get_importer_by_extension(const String &p_extension) const {
Ref<ResourceImporter> importer;
float priority = 0;
for (int i = 0; i < importers.size(); i++) {
List<String> local_exts;
importers[i]->get_recognized_extensions(&local_exts);
for (List<String>::Element *F = local_exts.front(); F; F = F->next()) {
if (p_extension.to_lower() == F->get() && importers[i]->get_priority() > priority) {
importer = importers[i];
priority = importers[i]->get_priority();
}
}
}
return importer;
}
String ResourceFormatImporter::get_import_base_path(const String &p_for_file) const {
return ProjectSettings::IMPORTED_FILES_PATH.plus_file(p_for_file.get_file() + "-" + p_for_file.md5_text());
}
bool ResourceFormatImporter::are_import_settings_valid(const String &p_path) const {
bool valid = true;
PathAndType pat;
_get_path_and_type(p_path, pat, &valid);
if (!valid) {
return false;
}
for (int i = 0; i < importers.size(); i++) {
if (importers[i]->get_importer_name() == pat.importer) {
if (!importers[i]->are_import_settings_valid(p_path)) { //importer thinks this is not valid
return false;
}
}
}
return true;
}
String ResourceFormatImporter::get_import_settings_hash() const {
Vector<Ref<ResourceImporter>> sorted_importers = importers;
sorted_importers.sort_custom<SortImporterByName>();
String hash;
for (int i = 0; i < sorted_importers.size(); i++) {
hash += ":" + sorted_importers[i]->get_importer_name() + ":" + sorted_importers[i]->get_import_settings_string();
}
return hash.md5_text();
}
ResourceFormatImporter *ResourceFormatImporter::singleton = nullptr;
ResourceFormatImporter::ResourceFormatImporter() {
singleton = this;
}
| 12,373
| 4,587
|
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/data/prefetch_autotuner.h"
#include <memory>
#include "tensorflow/core/framework/model.h"
namespace tensorflow {
namespace data {
PrefetchAutotuner::PrefetchAutotuner(std::shared_ptr<model::Model> model,
std::shared_ptr<model::Node> prefetch_node,
int64_t initial_buffer_size,
int64_t buffer_size_min)
: model_(model),
prefetch_node_(prefetch_node),
buffer_limit_(initial_buffer_size) {
if (initial_buffer_size == model::kAutotune) {
mode_ = Mode::kUpswing;
buffer_limit_ = std::max(int64_t{1}, buffer_size_min);
}
}
namespace {
// Determines what strategy to use for increasing the buffer size limit. For
// limits less than the threshold, an exponential increase is used, while for
// limits greater than or equal to the threshold, a linear increase is used.
size_t kBufferLimitThreshold = 2048;
} // namespace
void PrefetchAutotuner::RecordConsumption(size_t current_buffer_size) {
switch (mode_) {
case Mode::kDisabled:
return;
case Mode::kUpswing:
if (static_cast<int64_t>(current_buffer_size) == buffer_limit_) {
mode_ = Mode::kDownswing;
}
return;
case Mode::kDownswing:
if (current_buffer_size == 0) {
double new_buffer_limit = buffer_limit_;
if (buffer_limit_ >= static_cast<int64_t>(kBufferLimitThreshold)) {
new_buffer_limit += kBufferLimitThreshold;
} else {
new_buffer_limit *= 2;
}
if (model_ != nullptr && prefetch_node_ != nullptr &&
model_->AllocateBufferedBytes(
prefetch_node_->MaximumBufferedBytes() *
(new_buffer_limit - buffer_limit_) /
static_cast<double>(buffer_limit_))) {
buffer_limit_ = new_buffer_limit;
}
mode_ = Mode::kUpswing;
}
return;
}
}
} // namespace data
} // namespace tensorflow
| 2,684
| 803
|
// MESSAGE ALTITUDE support class
#pragma once
namespace mavlink {
namespace common {
namespace msg {
/**
* @brief ALTITUDE message
*
* The current system altitude.
*/
struct ALTITUDE : mavlink::Message {
static constexpr msgid_t MSG_ID = 141;
static constexpr size_t LENGTH = 32;
static constexpr size_t MIN_LENGTH = 32;
static constexpr uint8_t CRC_EXTRA = 47;
static constexpr auto NAME = "ALTITUDE";
uint64_t time_usec; /*< [us] Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude of the number. */
float altitude_monotonic; /*< [m] This altitude measure is initialized on system boot and monotonic (it is never reset, but represents the local altitude change). The only guarantee on this field is that it will never be reset and is consistent within a flight. The recommended value for this field is the uncorrected barometric altitude at boot time. This altitude will also drift and vary between flights. */
float altitude_amsl; /*< [m] This altitude measure is strictly above mean sea level and might be non-monotonic (it might reset on events like GPS lock or when a new QNH value is set). It should be the altitude to which global altitude waypoints are compared to. Note that it is *not* the GPS altitude, however, most GPS modules already output MSL by default and not the WGS84 altitude. */
float altitude_local; /*< [m] This is the local altitude in the local coordinate frame. It is not the altitude above home, but in reference to the coordinate origin (0, 0, 0). It is up-positive. */
float altitude_relative; /*< [m] This is the altitude above the home position. It resets on each change of the current home position. */
float altitude_terrain; /*< [m] This is the altitude above terrain. It might be fed by a terrain database or an altimeter. Values smaller than -1000 should be interpreted as unknown. */
float bottom_clearance; /*< [m] This is not the altitude, but the clear space below the system according to the fused clearance estimate. It generally should max out at the maximum range of e.g. the laser altimeter. It is generally a moving target. A negative value indicates no measurement available. */
inline std::string get_name(void) const override
{
return NAME;
}
inline Info get_message_info(void) const override
{
return { MSG_ID, LENGTH, MIN_LENGTH, CRC_EXTRA };
}
inline std::string to_yaml(void) const override
{
std::stringstream ss;
ss << NAME << ":" << std::endl;
ss << " time_usec: " << time_usec << std::endl;
ss << " altitude_monotonic: " << altitude_monotonic << std::endl;
ss << " altitude_amsl: " << altitude_amsl << std::endl;
ss << " altitude_local: " << altitude_local << std::endl;
ss << " altitude_relative: " << altitude_relative << std::endl;
ss << " altitude_terrain: " << altitude_terrain << std::endl;
ss << " bottom_clearance: " << bottom_clearance << std::endl;
return ss.str();
}
inline void serialize(mavlink::MsgMap &map) const override
{
map.reset(MSG_ID, LENGTH);
map << time_usec; // offset: 0
map << altitude_monotonic; // offset: 8
map << altitude_amsl; // offset: 12
map << altitude_local; // offset: 16
map << altitude_relative; // offset: 20
map << altitude_terrain; // offset: 24
map << bottom_clearance; // offset: 28
}
inline void deserialize(mavlink::MsgMap &map) override
{
map >> time_usec; // offset: 0
map >> altitude_monotonic; // offset: 8
map >> altitude_amsl; // offset: 12
map >> altitude_local; // offset: 16
map >> altitude_relative; // offset: 20
map >> altitude_terrain; // offset: 24
map >> bottom_clearance; // offset: 28
}
};
} // namespace msg
} // namespace common
} // namespace mavlink
| 4,252
| 1,245
|
#include <bits/stdc++.h>
const int MAXN = 21;
typedef long double db;
const db eps = 1e-8;
const db g = 9.80665;
int A[MAXN][MAXN];
int H, W, R, V;
int pw(int x) { return x * x; }
std::pair<db, db> normal(db a, db b) {
db L = sqrtl(a * a + b * b);
return std::make_pair(a / L, b / L);
}
bool judge(int sx, int sy, int dx, int dy) {
db L = R * sqrtl(pw(sx - dx) + pw(sy - dy));
db c = A[dx][dy] - A[sx][sy];
db a = g * L * L / 2 / V / V;
c += a;
db b = -L;
db dta = b * b - 4 * a * c;
if (dta < -eps) return false;
if (dta < 0) dta = 0;
dta = sqrtl(dta);
db vx, vy;
std::tie(vx, vy) = normal(a * 2, -b + dta);
vx *= V, vy *= V;
db T = L / vx;
int l = std::min(sx, dx);
int r = std::max(sx, dx);
for (int i = l; i < r; ++i) {
db sc = (((i + 1) - (sx + 0.5)) / (dx - sx));
db t = T * sc;
db y = sc * (dy - sy) + sy + 0.5;
db h = vy * t - g * t * t / 2 + A[sx][sy];
int mh = 0;
for (int j = (int) y - 1; j <= (int) y + 1; ++j)
if (j - eps <= y && y <= j + 1 + eps)
mh = std::max(mh, std::max(A[i][j], A[i + 1][j]));
if (h < mh - eps) return false;
}
l = std::min(sy, dy);
r = std::max(sy, dy);
for (int i = l; i < r; ++i) {
db sc = (((i + 1) - (sy + 0.5)) / (dy - sy));
db t = T * sc;
db x = sc * (dx - sx) + sx + 0.5;
db h = vy * t - g * t * t / 2 + A[sx][sy];
int mh = 0;
for (int j = (int) x - 1; j <= (int) x + 1; ++j)
if (j - eps <= x && x <= j + 1 + eps)
mh = std::max(mh, std::max(A[j][i], A[j][i + 1]));
if (h < mh - eps) return false;
}
return true;
}
int dis[MAXN][MAXN];
int main() {
std::ios_base::sync_with_stdio(false), std::cin.tie(0);
int sx, sy;
std::cin >> W >> H >> R >> V >> sy >> sx;
for (int i = 1; i <= H; ++i)
for (int j = 1; j <= W; ++j)
std::cin >> A[i][j];
memset(dis, -1, sizeof dis);
dis[sx][sy] = 0;
std::queue<std::pair<int, int> > que;
que.emplace(sx, sy);
while (!que.empty()) {
int x, y;
std::tie(x, y) = que.front();
que.pop();
for (int i = 1; i <= H; ++i)
for (int j = 1; j <= W; ++j)
if (dis[i][j] == -1 && judge(x, y, i, j)) {
dis[i][j] = dis[x][y] + 1;
que.emplace(i, j);
}
}
for (int i = 1; i <= H; ++i)
for (int j = 1; j <= W; ++j) {
if (dis[i][j] == -1)
std::cout << 'X';
else
std::cout << dis[i][j];
std::cout << (" \n" [j == W]);
}
return 0;
}
| 2,318
| 1,302
|
//
// Created by Saxion on 10/12/2018.
//
int main(){
}
| 58
| 33
|
// Copyright (C) 2007 Id Software, Inc.
//
#include "../precompiled.h"
#pragma hdrstop
#if defined( _DEBUG ) && !defined( ID_REDIRECT_NEWDELETE )
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#include "UserGroup.h"
#include "../Player.h"
#include "../guis/UIList.h"
typedef sdPair< const char*, userPermissionFlags_t > permissionName_t;
permissionName_t permissionNames[] = {
permissionName_t( "adminKick", PF_ADMIN_KICK ),
permissionName_t( "adminBan", PF_ADMIN_BAN ),
permissionName_t( "adminSetTeam", PF_ADMIN_SETTEAM ),
permissionName_t( "adminChangeCampaign", PF_ADMIN_CHANGE_CAMPAIGN ),
permissionName_t( "adminChangeMap", PF_ADMIN_CHANGE_MAP ),
permissionName_t( "adminGlobalMute", PF_ADMIN_GLOBAL_MUTE ),
permissionName_t( "adminGlobalVOIPMute", PF_ADMIN_GLOBAL_MUTE_VOIP ),
permissionName_t( "adminPlayerMute", PF_ADMIN_PLAYER_MUTE ),
permissionName_t( "adminPlayerVOIPMute", PF_ADMIN_PLAYER_MUTE_VOIP ),
permissionName_t( "adminWarn", PF_ADMIN_WARN ),
permissionName_t( "adminRestartMap", PF_ADMIN_RESTART_MAP ),
permissionName_t( "adminRestartCampaign", PF_ADMIN_RESTART_CAMPAIGN ),
permissionName_t( "adminStartMatch", PF_ADMIN_START_MATCH ),
permissionName_t( "adminExecConfig", PF_ADMIN_EXEC_CONFIG ),
permissionName_t( "adminShuffleTeams", PF_ADMIN_SHUFFLE_TEAMS ),
permissionName_t( "adminAddBot", PF_ADMIN_ADD_BOT ),
permissionName_t( "adminAdjustBots", PF_ADMIN_ADJUST_BOTS ),
permissionName_t( "adminDisableProficiency", PF_ADMIN_DISABLE_PROFICIENCY ),
permissionName_t( "adminSetTimeLimit", PF_ADMIN_SET_TIMELIMIT ),
permissionName_t( "adminSetTeamDamage", PF_ADMIN_SET_TEAMDAMAGE ),
permissionName_t( "adminSetTeamBalance", PF_ADMIN_SET_TEAMBALANCE ),
permissionName_t( "noBan", PF_NO_BAN ),
permissionName_t( "noKick", PF_NO_KICK ),
permissionName_t( "noMute", PF_NO_MUTE ),
permissionName_t( "noMuteVOIP", PF_NO_MUTE_VOIP ),
permissionName_t( "noWarn", PF_NO_WARN ),
permissionName_t( "quietLogin", PF_QUIET_LOGIN )
};
int numPermissionNames = _arraycount( permissionNames );
/*
===============================================================================
sdUserGroup
===============================================================================
*/
/*
============
sdUserGroup::sdUserGroup
============
*/
sdUserGroup::sdUserGroup( void ) : superUser( false ), voteLevel( -1 ), needsLogin( false ) {
}
/*
============
sdUserGroup::Write
============
*/
void sdUserGroup::Write( idBitMsg& msg ) const {
msg.WriteString( GetName() );
for ( int i = 0; i < flags.Size(); i++ ) {
msg.WriteLong( flags.GetDirect()[ i ] );
}
msg.WriteLong( controlGroups.Num() );
for ( int i = 0; i < controlGroups.Num(); i++ ) {
msg.WriteLong( controlGroups[ i ].second );
}
msg.WriteLong( voteLevel );
msg.WriteBool( needsLogin );
}
/*
============
sdUserGroup::Read
============
*/
void sdUserGroup::Read( const idBitMsg& msg ) {
char buffer[ 512 ];
msg.ReadString( buffer, sizeof( buffer ) );
SetName( buffer );
for ( int i = 0; i < flags.Size(); i++ ) {
flags.GetDirect()[ i ] = msg.ReadLong();
}
controlGroups.SetNum( msg.ReadLong() );
for ( int i = 0; i < controlGroups.Num(); i++ ) {
controlGroups[ i ].second = msg.ReadLong();
}
voteLevel = msg.ReadLong();
needsLogin = msg.ReadBool();
}
/*
============
sdUserGroup::Write
============
*/
void sdUserGroup::Write( idFile* file ) const {
file->WriteString( GetName() );
for ( int i = 0; i < flags.Size(); i++ ) {
file->WriteInt( flags.GetDirect()[ i ] );
}
file->WriteInt( controlGroups.Num() );
for ( int i = 0; i < controlGroups.Num(); i++ ) {
file->WriteInt( controlGroups[ i ].second );
}
file->WriteInt( voteLevel );
file->WriteBool( needsLogin );
}
/*
============
sdUserGroup::Read
============
*/
void sdUserGroup::Read( idFile* file ) {
file->ReadString( name );
for ( int i = 0; i < flags.Size(); i++ ) {
file->ReadInt( flags.GetDirect()[ i ] );
}
int count;
file->ReadInt( count );
controlGroups.SetNum( count );
for ( int i = 0; i < controlGroups.Num(); i++ ) {
file->ReadInt( controlGroups[ i ].second );
}
file->ReadInt( voteLevel );
file->ReadBool( needsLogin );
}
/*
============
sdUserGroup::ParseControl
============
*/
bool sdUserGroup::ParseControl( idLexer& src ) {
if ( !src.ExpectTokenString( "{" ) ) {
return false;
}
idToken token;
while ( true ) {
if ( !src.ReadToken( &token ) ) {
src.Warning( "Unexpected end of file" );
return false;
}
if ( token == "}" ) {
break;
}
sdPair< idStr, int >& control = controlGroups.Alloc();
control.first = token;
control.second = -1;
}
return true;
}
/*
============
sdUserGroup::Parse
============
*/
bool sdUserGroup::Parse( idLexer& src ) {
idToken token;
if ( !src.ReadToken( &token ) ) {
src.Warning( "No Name Specified" );
return false;
}
SetName( token );
if ( !src.ExpectTokenString( "{" ) ) {
return false;
}
while ( true ) {
if ( !src.ReadToken( &token ) ) {
src.Warning( "Unexpected end of file" );
return false;
}
if ( token == "}" ) {
break;
}
if ( token.Icmp( "password" ) == 0 ) {
if ( !src.ReadToken( &token ) ) {
src.Warning( "Unexpected end of file" );
return false;
}
// Gordon: The example file will have password set to password, this should never be a valid password
if ( token.Icmp( "password" ) != 0 ) {
SetPassword( token );
}
continue;
}
if ( token.Icmp( "control" ) == 0 ) {
if ( !ParseControl( src ) ) {
src.Warning( "Failed to parse control groups" );
return false;
}
continue;
}
if ( token.Icmp( "voteLevel" ) == 0 ) {
if ( !src.ReadToken( &token ) ) {
src.Warning( "Failed to parse voteLevel" );
return false;
}
voteLevel = token.GetIntValue();
continue;
}
int i;
for ( i = 0; i < numPermissionNames; i++ ) {
if ( idStr::Icmp( permissionNames[ i ].first, token ) ) {
continue;
}
GivePermission( permissionNames[ i ].second );
break;
}
if ( i != numPermissionNames ) {
continue;
}
src.Warning( "Unexpected token '%s'", token.c_str() );
return false;
}
return true;
}
/*
============
sdUserGroup::Parse
============
*/
void sdUserGroup::PostParseFixup( void ) {
sdUserGroupManagerLocal& groupManager = sdUserGroupManager::GetInstance();
for ( int i = 0; i < controlGroups.Num(); i++ ) {
sdPair< idStr, int >& control = controlGroups[ i ];
control.second = groupManager.FindGroup( control.first );
if ( control.second == -1 ) {
gameLocal.Warning( "sdUserGroup::PostParseFixup Control Group '%s' not found", control.first.c_str() );
}
}
}
/*
============
sdUserGroup::CanControl
============
*/
bool sdUserGroup::CanControl( const sdUserGroup& group ) const {
if ( superUser ) {
return true;
}
sdUserGroupManagerLocal& groupManager = sdUserGroupManager::GetInstance();
for ( int i = 0; i < controlGroups.Num(); i++ ) {
int index = controlGroups[ i ].second;
if ( index == -1 ) {
continue;
}
if ( &groupManager.GetGroup( index ) == &group ) {
return true;
}
}
return false;
}
/*
===============================================================================
sdUserGroupManagerLocal
===============================================================================
*/
/*
============
sdUserGroupManagerLocal::sdUserGroupManagerLocal
============
*/
sdUserGroupManagerLocal::sdUserGroupManagerLocal( void ) {
consoleGroup.SetName( "<CONSOLE>" ); // users coming from the console will use this user group which has full permissions
consoleGroup.MakeSuperUser();
defaultGroup = -1;
}
/*
============
sdUserGroupManagerLocal::sdUserGroupManagerLocal
============
*/
sdUserGroupManagerLocal::~sdUserGroupManagerLocal( void ) {
}
/*
============
sdUserGroupManagerLocal::Init
============
*/
void sdUserGroupManagerLocal::Init( void ) {
idStr groupNames[ MAX_CLIENTS ];
for ( int i = 0; i < MAX_CLIENTS; i++ ) {
nextLoginTime[ i ] = 0;
idPlayer* player = gameLocal.GetClient( i );
if ( !player ) {
continue;
}
groupNames[ i ] = GetGroup( player->GetUserGroup() ).GetName();
}
userGroups.Clear();
userGroups.Alloc().SetName( "<DEFAULT>" );
configs.Clear();
votes.Clear();
// load user groups
idLexer src( LEXFL_NOSTRINGCONCAT | LEXFL_NOSTRINGESCAPECHARS | LEXFL_ALLOWPATHNAMES | LEXFL_ALLOWMULTICHARLITERALS | LEXFL_ALLOWBACKSLASHSTRINGCONCAT | LEXFL_NOFATALERRORS );
src.LoadFile( "usergroups.dat" );
if ( !src.IsLoaded() ) {
return;
}
idToken token;
while ( true ) {
if ( !src.ReadToken( &token ) ) {
break;
}
if ( !token.Icmp( "group" ) ) {
sdUserGroup& group = userGroups.Alloc();
if ( !group.Parse( src ) ) {
src.Warning( "Error Parsing Group" );
break;
}
} else if ( !token.Icmp( "configs" ) ) {
if ( !configs.Parse( src ) ) {
src.Warning( "Error Parsing configs" );
break;
}
} else if ( !token.Icmp( "votes" ) ) {
if ( !votes.Parse( src ) ) {
src.Warning( "Error Parsing votes" );
break;
}
} else {
src.Warning( "Invalid Token '%s'", token.c_str() );
break;
}
}
defaultGroup = FindGroup( "default" );
if ( defaultGroup == -1 ) {
defaultGroup = 0;
}
for ( int i = 0; i < MAX_CLIENTS; i++ ) {
idPlayer* player = gameLocal.GetClient( i );
if ( !player ) {
continue;
}
player->SetUserGroup( FindGroup( groupNames[ i ] ) );
}
for ( int i = 0; i < userGroups.Num(); i++ ) {
userGroups[ i ].PostParseFixup();
}
if ( gameLocal.isServer ) {
WriteNetworkData( sdReliableMessageClientInfoAll() );
}
}
/*
============
sdUserGroupManagerLocal::FindGroup
============
*/
int sdUserGroupManagerLocal::FindGroup( const char* name ) {
for ( int i = 0; i < userGroups.Num(); i++ ) {
if ( idStr::Icmp( userGroups[ i ].GetName(), name ) ) {
continue;
}
return i;
}
return -1;
}
/*
============
sdUserGroupManagerLocal::Login
============
*/
bool sdUserGroupManagerLocal::Login( idPlayer* player, const char* password ) {
int now = MS2SEC( sys->Milliseconds() );
if ( now < nextLoginTime[ player->entityNumber ] ) {
return false;
}
nextLoginTime[ player->entityNumber ] = now + 5; // Gordon: limit password brute forcing
for ( int i = 0; i < userGroups.Num(); i++ ) {
if ( !userGroups[ i ].CheckPassword( password ) ) {
continue;
}
player->SetUserGroup( i );
return true;
}
return false;
}
/*
============
sdUserGroupManagerLocal::CanLogin
============
*/
bool sdUserGroupManagerLocal::CanLogin() const {
for ( int i = 0; i < userGroups.Num(); i++ ) {
if( userGroups[ i ].HasPassword() ) {
return true;
}
}
return false;
}
/*
============
sdUserGroupManagerLocal::ReadNetworkData
============
*/
void sdUserGroupManagerLocal::ReadNetworkData( const idBitMsg& msg ) {
userGroups.Clear();
userGroups.Alloc().SetName( "<DEFAULT>" );
int count = msg.ReadLong();
for ( int i = 0; i < count; i++ ) {
sdUserGroup& group = userGroups.Alloc();
group.Read( msg );
}
msg.ReadDeltaDict( configs, NULL );
msg.ReadDeltaDict( votes, NULL );
defaultGroup = FindGroup( "default" );
if ( defaultGroup == -1 ) {
defaultGroup = 0;
}
}
/*
============
sdUserGroupManagerLocal::WriteNetworkData
============
*/
void sdUserGroupManagerLocal::WriteNetworkData( const sdReliableMessageClientInfoBase& target ) {
sdReliableServerMessage msg( GAME_RELIABLE_SMESSAGE_USERGROUPS );
msg.WriteLong( userGroups.Num() - 1 );
for ( int i = 1; i < userGroups.Num(); i++ ) {
sdUserGroup& group = userGroups[ i ];
group.Write( msg );
}
msg.WriteDeltaDict( configs, NULL );
msg.WriteDeltaDict( votes, NULL );
msg.Send( target );
}
/*
============
sdUserGroupManagerLocal::CreateUserGroupList
============
*/
void sdUserGroupManagerLocal::CreateUserGroupList( sdUIList* list ) {
sdUIList::ClearItems( list );
idPlayer* localPlayer = gameLocal.GetLocalPlayer();
if ( !localPlayer ) {
return;
}
const sdUserGroup& localGroup = gameLocal.isClient ? GetGroup( localPlayer->GetUserGroup() ) : GetConsoleGroup();
int index = 0;
for ( int i = 1; i < userGroups.Num(); i++ ) {
if ( !localGroup.CanControl( userGroups[ i ] ) ) {
continue;
}
sdUIList::InsertItem( list, va( L"%hs", userGroups[ i ].GetName() ), index, 0 );
index++;
}
/*
for ( int i = 1; i < userGroups.Num(); i++ ) {
sdUIList::InsertItem( list, va( L"%hs", userGroups[ i ].GetName() ), i - 1, 0 );
}
*/
}
/*
============
sdUserGroupManagerLocal::CreateServerConfigList
============
*/
void sdUserGroupManagerLocal::CreateServerConfigList( sdUIList* list ) {
sdUIList::ClearItems( list );
for ( int i = 0; i < configs.GetNumKeyVals(); i++ ) {
const idKeyValue* kv = configs.GetKeyVal( i );
sdUIList::InsertItem( list, va( L"%hs", kv->GetKey().c_str() ), i, 0 );
}
}
/*
============
sdUserGroupManagerLocal::Write
============
*/
void sdUserGroupManagerLocal::Write( idFile* file ) const {
file->WriteInt( userGroups.Num() - 1 );
for ( int i = 1; i < userGroups.Num(); i++ ) {
const sdUserGroup& group = userGroups[ i ];
group.Write( file );
}
configs.WriteToFileHandle( file );
votes.WriteToFileHandle( file );
}
/*
============
sdUserGroupManagerLocal::Read
============
*/
void sdUserGroupManagerLocal::Read( idFile* file ) {
userGroups.Clear();
userGroups.Alloc().SetName( "<DEFAULT>" );
int count;
file->ReadInt( count );
for ( int i = 0; i < count; i++ ) {
sdUserGroup& group = userGroups.Alloc();
group.Read( file );
}
configs.ReadFromFileHandle( file );
votes.ReadFromFileHandle( file );
defaultGroup = FindGroup( "default" );
if ( defaultGroup == -1 ) {
defaultGroup = 0;
}
}
/*
============
sdUserGroupManagerLocal::GetVoteLevel
============
*/
int sdUserGroupManagerLocal::GetVoteLevel( const char* voteName ) {
return votes.GetInt( voteName, "-1" );
}
| 14,414
| 5,617
|
#include "binary_tree/binary_tree.hpp"
#include <catch2/catch_test_macros.hpp>
TEST_CASE("Binary tree tests with simple value type (int)", "[unit][binaryTree][binary_tree]") {
esc::data::BinaryTreeHeap<int> heap;
SECTION("Simple adding") {
heap.push(120);
heap.push(42);
heap.push(12);
heap.push(13);
heap.push(43);
heap.push(121);
REQUIRE(heap.size() == 6);
}
}
| 432
| 160
|
#include "window.hpp"
#include "selfdrive/hardware/hw.h"
MainWindow::MainWindow(QWidget *parent) : QWidget(parent) {
main_layout = new QStackedLayout;
main_layout->setMargin(0);
homeWindow = new HomeWindow(this);
main_layout->addWidget(homeWindow);
settingsWindow = new SettingsWindow(this);
main_layout->addWidget(settingsWindow);
onboardingWindow = new OnboardingWindow(this);
main_layout->addWidget(onboardingWindow);
QObject::connect(homeWindow, SIGNAL(openSettings()), this, SLOT(openSettings()));
QObject::connect(homeWindow, SIGNAL(closeSettings()), this, SLOT(closeSettings()));
QObject::connect(homeWindow, SIGNAL(offroadTransition(bool)), this, SLOT(offroadTransition(bool)));
QObject::connect(homeWindow, SIGNAL(offroadTransition(bool)), settingsWindow, SIGNAL(offroadTransition(bool)));
QObject::connect(settingsWindow, SIGNAL(closeSettings()), this, SLOT(closeSettings()));
QObject::connect(settingsWindow, SIGNAL(reviewTrainingGuide()), this, SLOT(reviewTrainingGuide()));
// start at onboarding
main_layout->setCurrentWidget(onboardingWindow);
QObject::connect(onboardingWindow, SIGNAL(onboardingDone()), this, SLOT(closeSettings()));
onboardingWindow->updateActiveScreen();
// no outline to prevent the focus rectangle
setLayout(main_layout);
setStyleSheet(R"(
* {
font-family: Inter;
outline: none;
}
)");
}
void MainWindow::offroadTransition(bool offroad){
if(!offroad){
closeSettings();
}
}
void MainWindow::openSettings() {
main_layout->setCurrentWidget(settingsWindow);
}
void MainWindow::closeSettings() {
main_layout->setCurrentWidget(homeWindow);
}
void MainWindow::reviewTrainingGuide() {
main_layout->setCurrentWidget(onboardingWindow);
onboardingWindow->updateActiveScreen();
}
bool MainWindow::eventFilter(QObject *obj, QEvent *event){
// wake screen on tap
if (event->type() == QEvent::MouseButtonPress) {
homeWindow->glWindow->wake();
}
// filter out touches while in android activity
#ifdef QCOM
const QList<QEvent::Type> filter_events = {QEvent::MouseButtonPress, QEvent::MouseMove, QEvent::TouchBegin, QEvent::TouchUpdate, QEvent::TouchEnd};
if (HardwareEon::launched_activity && filter_events.contains(event->type())) {
HardwareEon::check_activity();
if (HardwareEon::launched_activity) {
return true;
}
}
#endif
return false;
}
| 2,394
| 760
|
/*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "Test.h"
#include <cstdio>
using namespace std;
#ifdef __QNX__
GLESDebugDraw Test::m_debugDraw;
#endif
void DestructionListener::SayGoodbye(b2Joint* joint)
{
if (test->m_mouseJoint == joint)
{
test->m_mouseJoint = NULL;
}
else
{
test->JointDestroyed(joint);
}
}
Test::Test()
{
b2Vec2 gravity;
gravity.Set(0.0f, -10.0f);
m_world = new b2World(gravity);
m_bomb = NULL;
m_textLine = 30;
m_mouseJoint = NULL;
m_pointCount = 0;
m_destructionListener.test = this;
m_world->SetDestructionListener(&m_destructionListener);
m_world->SetContactListener(this);
m_world->SetDebugDraw(&m_debugDraw);
m_bombSpawning = false;
m_stepCount = 0;
b2BodyDef bodyDef;
m_groundBody = m_world->CreateBody(&bodyDef);
memset(&m_maxProfile, 0, sizeof(b2Profile));
memset(&m_totalProfile, 0, sizeof(b2Profile));
}
Test::~Test()
{
// By deleting the world, we delete the bomb, mouse joint, etc.
delete m_world;
m_world = NULL;
}
void Test::PreSolve(b2Contact* contact, const b2Manifold* oldManifold)
{
const b2Manifold* manifold = contact->GetManifold();
if (manifold->pointCount == 0)
{
return;
}
b2Fixture* fixtureA = contact->GetFixtureA();
b2Fixture* fixtureB = contact->GetFixtureB();
b2PointState state1[b2_maxManifoldPoints], state2[b2_maxManifoldPoints];
b2GetPointStates(state1, state2, oldManifold, manifold);
b2WorldManifold worldManifold;
contact->GetWorldManifold(&worldManifold);
for (int32 i = 0; i < manifold->pointCount && m_pointCount < k_maxContactPoints; ++i)
{
ContactPoint* cp = m_points + m_pointCount;
cp->fixtureA = fixtureA;
cp->fixtureB = fixtureB;
cp->position = worldManifold.points[i];
cp->normal = worldManifold.normal;
cp->state = state2[i];
++m_pointCount;
}
}
void Test::DrawTitle(int x, int y, const char *string)
{
m_debugDraw.DrawString(x, y, string);
}
class QueryCallback : public b2QueryCallback
{
public:
QueryCallback(const b2Vec2& point)
{
m_point = point;
m_fixture = NULL;
}
bool ReportFixture(b2Fixture* fixture)
{
b2Body* body = fixture->GetBody();
if (body->GetType() == b2_dynamicBody)
{
bool inside = fixture->TestPoint(m_point);
if (inside)
{
m_fixture = fixture;
// We are done, terminate the query.
return false;
}
}
// Continue the query.
return true;
}
b2Vec2 m_point;
b2Fixture* m_fixture;
};
void Test::MouseDown(const b2Vec2& p)
{
m_mouseWorld = p;
if (m_mouseJoint != NULL)
{
return;
}
// Make a small box.
b2AABB aabb;
b2Vec2 d;
d.Set(0.001f, 0.001f);
aabb.lowerBound = p - d;
aabb.upperBound = p + d;
// Query the world for overlapping shapes.
QueryCallback callback(p);
m_world->QueryAABB(&callback, aabb);
if (callback.m_fixture)
{
b2Body* body = callback.m_fixture->GetBody();
b2MouseJointDef md;
md.bodyA = m_groundBody;
md.bodyB = body;
md.target = p;
md.maxForce = 1000.0f * body->GetMass();
m_mouseJoint = (b2MouseJoint*)m_world->CreateJoint(&md);
body->SetAwake(true);
}
}
void Test::SpawnBomb(const b2Vec2& worldPt)
{
m_bombSpawnPoint = worldPt;
m_bombSpawning = true;
}
void Test::CompleteBombSpawn(const b2Vec2& p)
{
if (m_bombSpawning == false)
{
return;
}
const float multiplier = 30.0f;
b2Vec2 vel = m_bombSpawnPoint - p;
vel *= multiplier;
LaunchBomb(m_bombSpawnPoint,vel);
m_bombSpawning = false;
}
void Test::ShiftMouseDown(const b2Vec2& p)
{
m_mouseWorld = p;
if (m_mouseJoint != NULL)
{
return;
}
SpawnBomb(p);
}
void Test::MouseUp(const b2Vec2& p)
{
if (m_mouseJoint)
{
m_world->DestroyJoint(m_mouseJoint);
m_mouseJoint = NULL;
}
if (m_bombSpawning)
{
CompleteBombSpawn(p);
}
}
void Test::MouseMove(const b2Vec2& p)
{
m_mouseWorld = p;
if (m_mouseJoint)
{
m_mouseJoint->SetTarget(p);
}
}
void Test::LaunchBomb()
{
b2Vec2 p(RandomFloat(-15.0f, 15.0f), 30.0f);
b2Vec2 v = -5.0f * p;
LaunchBomb(p, v);
}
void Test::LaunchBomb(const b2Vec2& position, const b2Vec2& velocity)
{
if (m_bomb)
{
m_world->DestroyBody(m_bomb);
m_bomb = NULL;
}
b2BodyDef bd;
bd.type = b2_dynamicBody;
bd.position = position;
bd.bullet = true;
m_bomb = m_world->CreateBody(&bd);
m_bomb->SetLinearVelocity(velocity);
b2CircleShape circle;
circle.m_radius = 0.3f;
b2FixtureDef fd;
fd.shape = &circle;
fd.density = 20.0f;
fd.restitution = 0.0f;
b2Vec2 minV = position - b2Vec2(0.3f,0.3f);
b2Vec2 maxV = position + b2Vec2(0.3f,0.3f);
b2AABB aabb;
aabb.lowerBound = minV;
aabb.upperBound = maxV;
m_bomb->CreateFixture(&fd);
}
void Test::Step(Settings* settings)
{
float32 timeStep = settings->hz > 0.0f ? 1.0f / settings->hz : float32(0.0f);
if (settings->pause)
{
if (settings->singleStep)
{
settings->singleStep = 0;
}
else
{
timeStep = 0.0f;
}
m_debugDraw.DrawString(5, m_textLine, "****PAUSED****");
m_textLine += 15;
}
uint32 flags = 0;
flags += settings->drawShapes * b2Draw::e_shapeBit;
flags += settings->drawJoints * b2Draw::e_jointBit;
flags += settings->drawAABBs * b2Draw::e_aabbBit;
flags += settings->drawPairs * b2Draw::e_pairBit;
flags += settings->drawCOMs * b2Draw::e_centerOfMassBit;
m_debugDraw.SetFlags(flags);
m_world->SetWarmStarting(settings->enableWarmStarting > 0);
m_world->SetContinuousPhysics(settings->enableContinuous > 0);
m_world->SetSubStepping(settings->enableSubStepping > 0);
m_pointCount = 0;
m_world->Step(timeStep, settings->velocityIterations, settings->positionIterations);
m_world->DrawDebugData();
if (timeStep > 0.0f)
{
++m_stepCount;
}
if (settings->drawStats)
{
int32 bodyCount = m_world->GetBodyCount();
int32 contactCount = m_world->GetContactCount();
int32 jointCount = m_world->GetJointCount();
m_debugDraw.DrawString(5, m_textLine, "bodies/contacts/joints = %d/%d/%d", bodyCount, contactCount, jointCount);
m_textLine += 15;
int32 proxyCount = m_world->GetProxyCount();
int32 height = m_world->GetTreeHeight();
int32 balance = m_world->GetTreeBalance();
float32 quality = m_world->GetTreeQuality();
m_debugDraw.DrawString(5, m_textLine, "proxies/height/balance/quality = %d/%d/%d/%g", proxyCount, height, balance, quality);
m_textLine += 15;
}
// Track maximum profile times
{
const b2Profile& p = m_world->GetProfile();
m_maxProfile.step = b2Max(m_maxProfile.step, p.step);
m_maxProfile.collide = b2Max(m_maxProfile.collide, p.collide);
m_maxProfile.solve = b2Max(m_maxProfile.solve, p.solve);
m_maxProfile.solveInit = b2Max(m_maxProfile.solveInit, p.solveInit);
m_maxProfile.solveVelocity = b2Max(m_maxProfile.solveVelocity, p.solveVelocity);
m_maxProfile.solvePosition = b2Max(m_maxProfile.solvePosition, p.solvePosition);
m_maxProfile.solveTOI = b2Max(m_maxProfile.solveTOI, p.solveTOI);
m_maxProfile.broadphase = b2Max(m_maxProfile.broadphase, p.broadphase);
m_totalProfile.step += p.step;
m_totalProfile.collide += p.collide;
m_totalProfile.solve += p.solve;
m_totalProfile.solveInit += p.solveInit;
m_totalProfile.solveVelocity += p.solveVelocity;
m_totalProfile.solvePosition += p.solvePosition;
m_totalProfile.solveTOI += p.solveTOI;
m_totalProfile.broadphase += p.broadphase;
}
if (settings->drawProfile)
{
const b2Profile& p = m_world->GetProfile();
b2Profile aveProfile;
memset(&aveProfile, 0, sizeof(b2Profile));
if (m_stepCount > 0)
{
float32 scale = 1.0f / m_stepCount;
aveProfile.step = scale * m_totalProfile.step;
aveProfile.collide = scale * m_totalProfile.collide;
aveProfile.solve = scale * m_totalProfile.solve;
aveProfile.solveInit = scale * m_totalProfile.solveInit;
aveProfile.solveVelocity = scale * m_totalProfile.solveVelocity;
aveProfile.solvePosition = scale * m_totalProfile.solvePosition;
aveProfile.solveTOI = scale * m_totalProfile.solveTOI;
aveProfile.broadphase = scale * m_totalProfile.broadphase;
}
m_debugDraw.DrawString(5, m_textLine, "step [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.step, aveProfile.step, m_maxProfile.step);
m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "collide [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.collide, aveProfile.collide, m_maxProfile.collide);
m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "solve [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solve, aveProfile.solve, m_maxProfile.solve);
m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "solve init [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveInit, aveProfile.solveInit, m_maxProfile.solveInit);
m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "solve velocity [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveVelocity, aveProfile.solveVelocity, m_maxProfile.solveVelocity);
m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "solve position [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solvePosition, aveProfile.solvePosition, m_maxProfile.solvePosition);
m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "solveTOI [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveTOI, aveProfile.solveTOI, m_maxProfile.solveTOI);
m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "broad-phase [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.broadphase, aveProfile.broadphase, m_maxProfile.broadphase);
m_textLine += 15;
}
if (m_mouseJoint)
{
b2Vec2 p1 = m_mouseJoint->GetAnchorB();
b2Vec2 p2 = m_mouseJoint->GetTarget();
b2Color c;
c.Set(0.0f, 1.0f, 0.0f);
m_debugDraw.DrawPoint(p1, 4.0f, c);
m_debugDraw.DrawPoint(p2, 4.0f, c);
c.Set(0.8f, 0.8f, 0.8f);
m_debugDraw.DrawSegment(p1, p2, c);
}
if (m_bombSpawning)
{
b2Color c;
c.Set(0.0f, 0.0f, 1.0f);
m_debugDraw.DrawPoint(m_bombSpawnPoint, 4.0f, c);
c.Set(0.8f, 0.8f, 0.8f);
m_debugDraw.DrawSegment(m_mouseWorld, m_bombSpawnPoint, c);
}
if (settings->drawContactPoints)
{
//const float32 k_impulseScale = 0.1f;
const float32 k_axisScale = 0.3f;
for (int32 i = 0; i < m_pointCount; ++i)
{
ContactPoint* point = m_points + i;
if (point->state == b2_addState)
{
// Add
m_debugDraw.DrawPoint(point->position, 10.0f, b2Color(0.3f, 0.95f, 0.3f));
}
else if (point->state == b2_persistState)
{
// Persist
m_debugDraw.DrawPoint(point->position, 5.0f, b2Color(0.3f, 0.3f, 0.95f));
}
if (settings->drawContactNormals == 1)
{
b2Vec2 p1 = point->position;
b2Vec2 p2 = p1 + k_axisScale * point->normal;
m_debugDraw.DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.9f));
}
else if (settings->drawContactForces == 1)
{
//b2Vec2 p1 = point->position;
//b2Vec2 p2 = p1 + k_forceScale * point->normalForce * point->normal;
//DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.3f));
}
if (settings->drawFrictionForces == 1)
{
//b2Vec2 tangent = b2Cross(point->normal, 1.0f);
//b2Vec2 p1 = point->position;
//b2Vec2 p2 = p1 + k_forceScale * point->tangentForce * tangent;
//DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.3f));
}
}
}
}
| 12,236
| 5,415
|
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
#define ll long long
#define mem(Arr,x) memset(Arr,x,sizeof(Arr))
const int maxN=10010;
const int maxM=500010;
const int inf=2147483647;
class Queue_Data
{
public:
int u,dist;
};
bool operator < (Queue_Data A,Queue_Data B)
{
return A.dist>B.dist;
}
int n,m,S;
int cnt=0,Head[maxN],Next[maxM],V[maxM],W[maxM];
int Dist[maxN];
bool vis[maxN];
priority_queue<Queue_Data> Q;
int main()
{
mem(Head,-1);
scanf("%d%d%d",&n,&m,&S);
for (int i=1;i<=m;i++)
{
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
cnt++;Next[cnt]=Head[u];Head[u]=cnt;
V[cnt]=v;W[cnt]=w;
}
Queue_Data init;
for (int i=1;i<=n;i++) Dist[i]=inf;
Dist[S]=0;
init.u=S;init.dist=0;
Q.push(init);
do
{
int u=Q.top().u;
Q.pop();
if (vis[u]) continue;
vis[u]=1;
for (int i=Head[u];i!=-1;i=Next[i])
{
int v=V[i];
if ((Dist[u]+W[i]<Dist[v])&&(vis[v]==0))
{
Dist[v]=Dist[u]+W[i];
Q.push((Queue_Data){v,Dist[v]});
}
}
}
while (!Q.empty());
for (int i=1;i<=n;i++) printf("%d ",Dist[i]);
printf("\n");
return 0;
}
| 1,206
| 600
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <algorithm>
#include <queue>
#include "gtn/functions/compose.h"
namespace gtn {
namespace detail {
namespace {
inline size_t toIndex(int n1, int n2, const Graph& g) {
return n1 + g.numNodes() * n2;
}
/* Find any state in the new composed graph which can reach
* an accepting state. */
auto findReachable(
const Graph& first,
const Graph& second,
std::shared_ptr<ArcMatcher> matcher) {
std::vector<bool> reachable(first.numNodes() * second.numNodes(), false);
std::queue<std::pair<int, int>> toExplore;
for (auto f : first.accept()) {
for (auto s : second.accept()) {
toExplore.emplace(f, s);
reachable[toIndex(f, s, first)] = true;
}
}
while (!toExplore.empty()) {
auto curr = toExplore.front();
toExplore.pop();
bool epsilon_matched = false;
matcher->match(curr.first, curr.second, true);
int i, j;
while (matcher->hasNext()) {
std::tie(i, j) = matcher->next();
epsilon_matched |= (first.olabel(i) == epsilon);
auto un1 = first.srcNode(i);
auto un2 = second.srcNode(j);
auto idx = toIndex(un1, un2, first);
if (!reachable[idx]) {
// If we haven't seen this state before, explore it.
toExplore.emplace(un1, un2);
}
reachable[idx] = true;
}
if (!epsilon_matched) {
for (auto i : first.in(curr.first)) {
if (first.olabel(i) != epsilon) {
if (first.olabelSorted()) {
// epsilon < 0
break;
} else {
continue;
}
}
auto un1 = first.srcNode(i);
auto idx = toIndex(un1, curr.second, first);
if (!reachable[idx]) {
// If we haven't seen this state before, explore it.
toExplore.emplace(un1, curr.second);
}
reachable[idx] = true;
}
}
if (!epsilon_matched) {
for (auto j : second.in(curr.second)) {
if (second.ilabel(j) != epsilon) {
if (second.ilabelSorted()) {
// epsilon < 0
break;
} else {
continue;
}
}
auto un2 = second.srcNode(j);
auto idx = toIndex(curr.first, un2, first);
if (!reachable[idx]) {
// If we haven't seen this state before, explore it.
toExplore.emplace(curr.first, un2);
}
reachable[idx] = true;
}
}
}
return reachable;
}
} // namespace
void UnsortedMatcher::match(int lnode, int rnode, bool matchIn /* = false*/) {
auto& lv = matchIn ? g1_.in(lnode) : g1_.out(lnode);
auto& rv = matchIn ? g2_.in(rnode) : g2_.out(rnode);
lIt_ = lv.begin();
lItEnd_ = lv.end();
rItBegin_ = rIt_ = rv.begin();
rItEnd_ = rv.end();
}
bool UnsortedMatcher::hasNext() {
for (; lIt_ != lItEnd_; ++lIt_) {
for (; rIt_ != rItEnd_; ++rIt_) {
if (g1_.olabel(*lIt_) == g2_.ilabel(*rIt_)) {
return true;
}
}
rIt_ = rItBegin_;
}
return false;
}
std::pair<int, int> UnsortedMatcher::next() {
return std::make_pair(*lIt_, *rIt_++);
}
SinglySortedMatcher::SinglySortedMatcher(
const Graph& g1,
const Graph& g2,
bool searchG1 /* = false */)
: g1_(g1), g2_(g2), searchG1_(searchG1) {}
void SinglySortedMatcher::match(
int lnode,
int rnode,
bool matchIn /* = false */) {
auto& lv = matchIn ? g1_.in(lnode) : g1_.out(lnode);
auto& rv = matchIn ? g2_.in(rnode) : g2_.out(rnode);
searchItBegin_ = searchIt_ = lv.begin();
searchItEnd_ = lv.end();
queryIt_ = rv.begin();
queryItEnd_ = rv.end();
if (!searchG1_) {
searchItBegin_ = queryIt_;
std::swap(queryIt_, searchIt_);
std::swap(queryItEnd_, searchItEnd_);
}
}
bool SinglySortedMatcher::hasNext() {
if (queryIt_ == queryItEnd_) {
return false;
}
if (searchIt_ != searchItEnd_) {
auto ql = searchG1_ ? g2_.ilabel(*queryIt_) : g1_.olabel(*queryIt_);
auto sl = searchG1_ ? g1_.olabel(*searchIt_) : g2_.ilabel(*searchIt_);
if (ql == sl) {
return true;
}
}
if (searchIt_ != searchItBegin_) {
// Not at the start of the search
++queryIt_;
}
// Update the query pointer and the start of the search range pointer
for (; queryIt_ != queryItEnd_; ++queryIt_) {
auto ql = searchG1_ ? g2_.ilabel(*queryIt_) : g1_.olabel(*queryIt_);
// Set the comparison function appropriately
auto comparisonFn = [this](int arc, int val) {
return searchG1_ ? g1_.olabel(arc) < val : g2_.ilabel(arc) < val;
};
searchIt_ =
std::lower_bound(searchItBegin_, searchItEnd_, ql, comparisonFn);
if (searchIt_ == searchItEnd_) {
continue;
}
auto sl = searchG1_ ? g1_.olabel(*searchIt_) : g2_.ilabel(*searchIt_);
if (sl == ql) {
return true;
}
}
return false;
}
std::pair<int, int> SinglySortedMatcher::next() {
if (searchG1_) {
return std::make_pair(*searchIt_++, *queryIt_);
} else {
return std::make_pair(*queryIt_, *searchIt_++);
}
}
void DoublySortedMatcher::match(
int lnode,
int rnode,
bool matchIn /* = false */) {
auto& lv = matchIn ? g1_.in(lnode) : g1_.out(lnode);
auto& rv = matchIn ? g2_.in(rnode) : g2_.out(rnode);
searchItBegin_ = searchIt_ = lv.begin();
searchItEnd_ = lv.end();
queryIt_ = rv.begin();
queryItEnd_ = rv.end();
searchG1_ = lv.size() > rv.size();
if (!searchG1_) {
searchItBegin_ = queryIt_;
std::swap(queryIt_, searchIt_);
std::swap(queryItEnd_, searchItEnd_);
}
}
bool DoublySortedMatcher::hasNext() {
if (queryIt_ == queryItEnd_) {
return false;
}
if (searchIt_ != searchItEnd_) {
auto ql = searchG1_ ? g2_.ilabel(*queryIt_) : g1_.olabel(*queryIt_);
auto sl = searchG1_ ? g1_.olabel(*searchIt_) : g2_.ilabel(*searchIt_);
if (ql == sl) {
return true;
}
}
if (searchIt_ != searchItBegin_) {
// Not at the start of the search
++queryIt_;
}
// Update the query pointer and the start of the search range pointer
for (; queryIt_ != queryItEnd_; ++queryIt_) {
auto ql = searchG1_ ? g2_.ilabel(*queryIt_) : g1_.olabel(*queryIt_);
// Set the comparison function appropriately
auto comparisonFn = [this](int arc, int val) {
return searchG1_ ? g1_.olabel(arc) < val : g2_.ilabel(arc) < val;
};
// Allowed because the query vector is sorted.
searchItBegin_ =
std::lower_bound(searchItBegin_, searchItEnd_, ql, comparisonFn);
if (searchItBegin_ == searchItEnd_) {
return false;
}
auto sl =
searchG1_ ? g1_.olabel(*searchItBegin_) : g2_.ilabel(*searchItBegin_);
if (sl == ql) {
searchIt_ = searchItBegin_;
return true;
}
}
return false;
}
std::pair<int, int> DoublySortedMatcher::next() {
if (searchG1_) {
return std::make_pair(*searchIt_++, *queryIt_);
} else {
return std::make_pair(*queryIt_, *searchIt_++);
}
}
// Composes two graphs and returns a new graph
Graph compose(
const Graph& first,
const Graph& second,
std::shared_ptr<ArcMatcher> matcher) {
// Compute reachable nodes from any accept state in the new graph
auto reachable = findReachable(first, second, matcher);
// Compose the graphs
Graph ngraph(nullptr, {first, second});
std::vector<int> newNodes(first.numNodes() * second.numNodes(), -1);
std::queue<std::pair<int, int>> toExplore;
for (auto s1 : first.start()) {
for (auto s2 : second.start()) {
auto idx = toIndex(s1, s2, first);
if (reachable[idx]) {
newNodes[idx] =
ngraph.addNode(true, first.isAccept(s1) && second.isAccept(s2));
toExplore.emplace(s1, s2);
}
}
}
std::vector<std::pair<int, int>> gradInfo;
while (!toExplore.empty()) {
auto curr = toExplore.front();
toExplore.pop();
auto currNode = newNodes[toIndex(curr.first, curr.second, first)];
int i, j;
matcher->match(curr.first, curr.second);
while (matcher->hasNext()) {
std::tie(i, j) = matcher->next();
auto dn1 = first.dstNode(i);
auto dn2 = second.dstNode(j);
// Ignore if we can't get to an accept state.
auto idx = toIndex(dn1, dn2, first);
if (!reachable[idx]) {
continue;
}
// Build the node
if (newNodes[idx] < 0) {
newNodes[idx] = ngraph.addNode(
first.isStart(dn1) && second.isStart(dn2),
first.isAccept(dn1) && second.isAccept(dn2));
toExplore.emplace(dn1, dn2);
}
auto weight = first.weight(i) + second.weight(j);
auto newarc = ngraph.addArc(
currNode, newNodes[idx], first.ilabel(i), second.olabel(j), weight);
// Arcs remember where they came from for
// easy gradient computation.
gradInfo.emplace_back(i, j);
}
// Check for output epsilons in the first graph
for (auto i : first.out(curr.first)) {
if (first.olabel(i) != epsilon) {
if (first.olabelSorted()) {
// epsilon < 0
break;
} else {
continue;
}
}
// We only advance along the first arc.
auto dn1 = first.dstNode(i);
auto dn2 = curr.second;
auto idx = toIndex(dn1, dn2, first);
if (!reachable[idx]) {
continue;
}
if (newNodes[idx] < 0) {
newNodes[idx] = ngraph.addNode(
first.isStart(dn1) && second.isStart(dn2),
first.isAccept(dn1) && second.isAccept(dn2));
toExplore.emplace(dn1, dn2);
}
auto weight = first.weight(i);
auto newarc = ngraph.addArc(
currNode, newNodes[idx], first.ilabel(i), epsilon, weight);
gradInfo.emplace_back(i, -1);
}
// Check out input epsilons in the second graph
for (auto j : second.out(curr.second)) {
if (second.ilabel(j) != epsilon) {
if (second.ilabelSorted()) {
// epsilon < 0
break;
} else {
continue;
}
}
// We only advance along the second arc.
auto dn1 = curr.first;
auto dn2 = second.dstNode(j);
auto idx = toIndex(dn1, dn2, first);
if (!reachable[idx]) {
continue;
}
if (newNodes[idx] < 0) {
newNodes[idx] = ngraph.addNode(
first.isStart(dn1) && second.isStart(dn2),
first.isAccept(dn1) && second.isAccept(dn2));
toExplore.emplace(dn1, dn2);
}
auto weight = second.weight(j);
auto newarc = ngraph.addArc(
currNode, newNodes[idx], epsilon, second.olabel(j), weight);
gradInfo.emplace_back(-1, j);
}
}
/* Here we assume deltas is the output (e.g. ngraph) and we know where
* each arc came from. This makes it possible to disambiguate two arcs in the
* composed graph with the same label and the same src and destination nodes.
*/
auto gradFunc = [gradInfo = std::move(gradInfo)](
std::vector<Graph>& inputs, Graph deltas) {
// In this case the arc's parents are always from the
// first and second input graphs respectively.
bool calcGrad1 = inputs[0].calcGrad();
bool calcGrad2 = inputs[1].calcGrad();
auto grad1 = calcGrad1 ? std::vector<float>(inputs[0].numArcs(), 0.0)
: std::vector<float>{};
auto grad2 = calcGrad2 ? std::vector<float>(inputs[1].numArcs(), 0.0)
: std::vector<float>{};
for (int i = 0; i < gradInfo.size(); i++) {
auto arcGrad = deltas.weight(i);
auto& arcs = gradInfo[i];
if (calcGrad1 && arcs.first >= 0) {
grad1[arcs.first] += arcGrad;
}
if (calcGrad2 && arcs.second >= 0) {
grad2[arcs.second] += arcGrad;
}
}
inputs[0].addGrad(std::move(grad1));
inputs[1].addGrad(std::move(grad2));
};
ngraph.setGradFunc(std::move(gradFunc));
return ngraph;
}
} // namespace detail
} // namespace gtn
| 11,998
| 4,280
|
//
//
// Libs
#include <iostream>
#include <string>
// Project files
#include "MarchingCubes.h"
int main(int argc, char* argv[])
{
// Marcing cubes
tmc::MarchingCubes mc;
// parameters
std::string i_file = "";
std::string objF = "";
std::string offF = "";
const double i0 = 801.3;
mc(i0,i_file,true,true,objF,true,offF);
return 0;
}
| 358
| 156
|
#include "logger.h"
std::mutex Logger::log_m;
void Logger::log(const std::string& s) {
std::unique_lock<std::mutex> lock(log_m);
std::cout << s << std::endl;
}
void Logger::log(const char* ch) {
std::unique_lock<std::mutex> lock(log_m);
std::cout << ch << std::endl;
}
void Logger::log(const char* prefix, const std::string& s) {
std::unique_lock<std::mutex> lock(log_m);
std::cout << std::string(prefix) << " >>>>" << s << std::endl;
}
void Logger::log(const char* prefix, const char* ch) {
std::unique_lock<std::mutex> lock(log_m);
std::cout << std::string(prefix) << " >>>>" << ch << std::endl;
}
| 642
| 247
|
// Copyright Paul Dardeau, SwampBits LLC 2014
// BSD License
#include <string.h>
#include <string>
#include "TestStrUtils.h"
#include "StrUtils.h"
static const std::string emptyString = "";
using namespace chaudiere;
using namespace poivre;
//******************************************************************************
TestStrUtils::TestStrUtils() :
TestSuite("TestStrUtils") {
}
//******************************************************************************
void TestStrUtils::runTests() {
// parsing
testParseInt();
testParseLong();
testParseFloat();
testParseDouble();
// toString
testToStringWithInt();
testToStringWithLong();
testToStringWithULong();
// strip
testStrip();
testStripWithChar();
testStartsWith();
testEndsWith();
testContainsString();
// upper/lower case
testToUpperCase();
testToLowerCase();
// search & replace
testReplaceAll();
// strip
testStripInPlace();
testStripTrailing();
testStripLeading();
testTrimLeadingSpaces();
testTrim();
// padding
testPadRight();
testPadLeft();
// makeStringOfChar
testMakeStringOfChar();
// split
testSplit();
}
//******************************************************************************
class ParseRunner : public Runnable {
public:
explicit ParseRunner(const std::string& arg) :
m_arg(arg) {
}
ParseRunner(const ParseRunner& copy) :
m_arg(copy.m_arg) {
}
~ParseRunner() {}
ParseRunner& operator=(const ParseRunner& copy) {
if (this == ©) {
return *this;
}
m_arg = copy.m_arg;
return *this;
}
virtual void run() = 0;
protected:
std::string m_arg;
};
class ParseIntRunner : public ParseRunner {
public:
ParseIntRunner(const std::string& arg) :
ParseRunner(arg) {
}
virtual void run() {
StrUtils::parseInt(m_arg);
}
};
class ParseLongRunner : public ParseRunner {
public:
ParseLongRunner(const std::string& arg) :
ParseRunner(arg) {
}
virtual void run() {
StrUtils::parseLong(m_arg);
}
};
class ParseFloatRunner : public ParseRunner {
public:
ParseFloatRunner(const std::string& arg) :
ParseRunner(arg) {
}
virtual void run() {
StrUtils::parseFloat(m_arg);
}
};
class ParseDoubleRunner : public ParseRunner {
public:
ParseDoubleRunner(const std::string& arg) :
ParseRunner(arg) {
}
virtual void run() {
StrUtils::parseDouble(m_arg);
}
};
//*****************************************************************************
//*****************************************************************************
void TestStrUtils::testParseInt() {
TEST_CASE("parseInt");
require(3 == StrUtils::parseInt("3"), "1 digit positive integer");
require(-5 == StrUtils::parseInt("-5"), "1 digit negative integer");
require(0 == StrUtils::parseInt("0"), "zero");
require(35 == StrUtils::parseInt("35"), "2 digit positive integer");
require(121 == StrUtils::parseInt("121"), "3 digit positive integer");
require(4096 == StrUtils::parseInt("4096"), "4 digit positive integer");
require(65535 == StrUtils::parseInt("65535"), "5 digit positive integer");
// try largest (absolute value) signed value for 32 bits
require(2147483647 == StrUtils::parseInt("2147483647"),
"large positive int");
require(-2147483648UL == StrUtils::parseInt("-2147483648"),
"negative int with large absolute value");
requireException("NumberFormatException", new ParseIntRunner(""),
"empty string");
requireException("NumberFormatException", new ParseIntRunner("x"), "letter");
requireException("NumberFormatException", new ParseIntRunner("y123"),
"leading char");
requireException("NumberFormatException", new ParseIntRunner("456t"),
"trailing char");
}
//******************************************************************************
void TestStrUtils::testParseLong() {
TEST_CASE("parseLong");
require(3L == StrUtils::parseLong("3"), "1 digit positive long");
require(-5L == StrUtils::parseLong("-5"), "1 digit negative long");
require(0L == StrUtils::parseLong("0"), "zero");
require(35L == StrUtils::parseLong("35"), "2 digit positive long");
require(121L == StrUtils::parseLong("121"), "3 digit positive long");
require(4096L == StrUtils::parseLong("4096"), "4 digit positive long");
require(65535L == StrUtils::parseLong("65535"), "5 digit positive long");
// try largest (absolute value) signed value for 32 bits
require(2147483647L == StrUtils::parseLong("2147483647"),
"large positive long");
require(-2147483648UL == StrUtils::parseLong("-2147483648"),
"negative long with large absolute value");
requireException("NumberFormatException", new ParseLongRunner(""),
"empty string");
requireException("NumberFormatException", new ParseLongRunner("x"), "letter");
requireException("NumberFormatException", new ParseLongRunner("y123"),
"leading char");
requireException("NumberFormatException", new ParseLongRunner("456t"),
"trailing char");
}
//******************************************************************************
void TestStrUtils::testParseFloat() {
TEST_CASE("parseFloat");
require(3.0f == StrUtils::parseFloat("3"), "1 digit positive integral");
require(-5.0f == StrUtils::parseFloat("-5"), "1 digit negative integral");
require(0.0f == StrUtils::parseFloat("0"), "zero");
require(35.0f == StrUtils::parseFloat("35"), "2 digit positive integral");
require(121.0f == StrUtils::parseFloat("121"), "3 digit positive integral");
require(4096.0f == StrUtils::parseFloat("4096"), "4 digit positive integral");
require(65535.0f == StrUtils::parseFloat("65535"),
"5 digit positive integral");
require(3.1415f == StrUtils::parseFloat("3.1415"), "positive float value");
require(-1492.524f == StrUtils::parseFloat("-1492.524"),
"negative float value");
requireException("NumberFormatException", new ParseFloatRunner(""),
"empty string");
requireException("NumberFormatException", new ParseFloatRunner("x"),
"letter");
requireException("NumberFormatException", new ParseFloatRunner("y123"),
"leading char");
requireException("NumberFormatException", new ParseFloatRunner("456t"),
"trailing char");
}
//******************************************************************************
void TestStrUtils::testParseDouble() {
TEST_CASE("parseDouble");
require(3.0 == StrUtils::parseDouble("3"), "1 digit positive integral");
require(-5.0 == StrUtils::parseDouble("-5"), "1 digit negative integral");
require(0.0 == StrUtils::parseDouble("0"), "zero");
require(35.0 == StrUtils::parseDouble("35"), "2 digit positive integral");
require(121.0 == StrUtils::parseDouble("121"), "3 digit positive integral");
require(4096.0 == StrUtils::parseDouble("4096"), "4 digit positive integral");
require(65535.0 == StrUtils::parseDouble("65535"),
"5 digit positive integral");
require(3.1415 == StrUtils::parseDouble("3.1415"), "positive double value");
require(-1492.524 == StrUtils::parseDouble("-1492.524"),
"negative double value");
requireException("NumberFormatException", new ParseDoubleRunner(""),
"empty string");
requireException("NumberFormatException", new ParseDoubleRunner("x"),
"letter");
requireException("NumberFormatException", new ParseDoubleRunner("y123"),
"leading char");
requireException("NumberFormatException", new ParseDoubleRunner("456t"),
"trailing char");
}
//******************************************************************************
void TestStrUtils::testToStringWithInt() {
TEST_CASE("toStringWithInt");
requireStringEquals(StrUtils::toString(2112), "2112", "positive value");
requireStringEquals(StrUtils::toString(-57), "-57", "negative value");
requireStringEquals(StrUtils::toString(0), "0", "zero");
}
//******************************************************************************
void TestStrUtils::testToStringWithLong() {
TEST_CASE("toStringWithLong");
requireStringEquals(StrUtils::toString(2112L), "2112", "positive value");
requireStringEquals(StrUtils::toString(-57L), "-57", "negative value");
requireStringEquals(StrUtils::toString(0L), "0", "zero");
}
//******************************************************************************
void TestStrUtils::testToStringWithULong() {
TEST_CASE("toStringWithULong");
requireStringEquals(StrUtils::toString(2112UL), "2112", "non-zero value");
requireStringEquals(StrUtils::toString(0UL), "0", "zero");
}
//******************************************************************************
void TestStrUtils::testStrip() {
TEST_CASE("strip");
const std::string target = "now is the time";
std::string withSingleTrailingSpace = "now is the time ";
std::string withSingleLeadingTrailingSpace = " now is the time ";
std::string leadingAndTrailing = " now is the time ";
std::string alreadyTrimmed = "now is the time";
requireStringEquals(target, StrUtils::strip(withSingleTrailingSpace),
"single trailing space");
requireStringEquals(target, StrUtils::strip(withSingleLeadingTrailingSpace),
"single leading and trailing space");
requireStringEquals(target, StrUtils::strip(leadingAndTrailing),
"trimmed string has leading strip chars");
requireStringEquals(target, StrUtils::strip(alreadyTrimmed),
"no alteration of already trimmed string");
}
//******************************************************************************
void TestStrUtils::testStripWithChar() {
TEST_CASE("stripWithChar");
const std::string target = "now is the time";
std::string withSingleTrailingSpace = "now is the time ";
std::string withSingleLeadingTrailingSpace = " now is the time ";
std::string withSingleLeadingX = "xnow is the time";
std::string withSingleTrailingX = "now is the timex";
std::string withLeadingTrailingPunctuation = ",now is the time,";
std::string withTrailingPunctuation = "now is the time,";
std::string leadingAndTrailing = "...now is the time...";
std::string alreadyTrimmed = "now is the time";
requireStringEquals(target, StrUtils::strip(withSingleTrailingSpace, ' '),
"single trailing space");
requireStringEquals(target, StrUtils::strip(withSingleLeadingTrailingSpace,
' '),
"single leading and trailing space");
requireStringEquals(target, StrUtils::strip(withSingleLeadingX, 'x'),
"leading char");
requireStringEquals(target, StrUtils::strip(withSingleTrailingX, 'x'),
"trailing char");
requireStringEquals(target, StrUtils::strip(withTrailingPunctuation, ','),
"trailing punctuation");
requireStringEquals(target, StrUtils::strip(withLeadingTrailingPunctuation,
','),
"leading and trailing punctuation");
requireStringEquals(target, StrUtils::strip(leadingAndTrailing, '.'),
"leading and trailing strip chars");
requireStringEquals(target, StrUtils::strip(alreadyTrimmed, ' '),
"no alteration of already trimmed string");
}
//******************************************************************************
void TestStrUtils::testStartsWith() {
TEST_CASE("startsWith");
const std::string haystack = "abcdefg";
const std::string needle = "abc";
const std::string razor = "xyz";
const std::string upperNeedle = "ABC";
require(StrUtils::startsWith(haystack, needle),
"haystack contains needle at beginning");
requireFalse(StrUtils::startsWith(haystack, razor),
"haystack doesn't contain needle anywhere");
requireFalse(StrUtils::startsWith(haystack, emptyString),
"haystack doesn't start with empty string");
requireFalse(StrUtils::startsWith(emptyString, needle),
"empty haystack doesn't start with needle");
requireFalse(StrUtils::startsWith(haystack, upperNeedle),
"haystack doesn't start with upper needle");
}
//******************************************************************************
void TestStrUtils::testEndsWith() {
TEST_CASE("endsWith");
const std::string haystack = "abcdefg";
const std::string needle = "efg";
const std::string razor = "xyz";
const std::string upperNeedle = "EFG";
require(StrUtils::endsWith(haystack, needle),
"haystack contains needle at end");
requireFalse(StrUtils::endsWith(haystack, razor),
"haystack doesn't contain needle anywhere");
requireFalse(StrUtils::endsWith(haystack, emptyString),
"haystack doesn't end with empty string");
requireFalse(StrUtils::endsWith(emptyString, needle),
"empty haystack doesn't end with needle");
requireFalse(StrUtils::endsWith(haystack, upperNeedle),
"haystack doesn't end with upper needle");
}
//******************************************************************************
void TestStrUtils::testContainsString() {
TEST_CASE("containsString");
const std::string haystack =
"She said that it was he, and I said that it was she";
const std::string She = "She";
const std::string she = "she";
const std::string he = "he";
const std::string notThere = "continent";
require(StrUtils::containsString(haystack, She), "haystack contains needle");
require(StrUtils::containsString(haystack, she), "haystack contains needle");
require(StrUtils::containsString(haystack, he), "haystack contains needle");
requireFalse(StrUtils::containsString(haystack, notThere),
"haystack does not contain needle");
}
//******************************************************************************
void TestStrUtils::testToUpperCase() {
TEST_CASE("toUpperCase");
const std::string target = "NOW IS THE TIME";
std::string source = "now is the time";
StrUtils::toUpperCase(source);
requireStringEquals(target, source, "all lower should convert to all upper");
source = "Now Is The Time";
StrUtils::toUpperCase(source);
requireStringEquals(target, source, "mixed case should convert to all upper");
source = target;
StrUtils::toUpperCase(source);
requireStringEquals(target, source,
"no alteration of already uppercase string");
const std::string targetNonLetters = "1234;.,!";
source = targetNonLetters;
StrUtils::toUpperCase(source);
requireStringEquals(targetNonLetters, source,
"no alteration of string not containing letters");
}
//******************************************************************************
void TestStrUtils::testToLowerCase() {
TEST_CASE("toLowerCase");
const std::string target = "now is the time";
std::string source = "NOW IS THE TIME";
StrUtils::toLowerCase(source);
requireStringEquals(target, source, "all upper should convert to all lower");
source = "Now Is The Time";
StrUtils::toLowerCase(source);
requireStringEquals(target, source, "mixed case should convert to all lower");
source = target;
StrUtils::toLowerCase(source);
requireStringEquals(target, source,
"no alteration of already lowercase string");
const std::string targetNonLetters = "1234;.,!";
source = targetNonLetters;
StrUtils::toLowerCase(source);
requireStringEquals(targetNonLetters, source,
"no alteration of string not containing letters");
}
//******************************************************************************
void TestStrUtils::testReplaceAll() {
TEST_CASE("replaceAll");
const std::string source =
"She said that it was he, and I said that it was she";
const std::string target_she_She =
"She said that it was he, and I said that it was She";
const std::string target_She_she =
"she said that it was he, and I said that it was she";
const std::string target_She_He =
"He said that it was he, and I said that it was she";
const std::string target_he_she =
"Sshe said that it was she, and I said that it was sshe";
std::string target;
const std::string She = "She";
const std::string she = "she";
const std::string He = "He";
const std::string he = "he";
const std::string notThere = "or";
const std::string xyz = "xyz";
target = source;
requireStringEquals(target_she_She, StrUtils::replaceAll(target, she, She),
"replace 'she' with 'She'");
target = source;
requireStringEquals(target_She_she, StrUtils::replaceAll(target, She, she),
"replace 'She' with 'she'");
target = source;
requireStringEquals(target_She_He, StrUtils::replaceAll(target, She, He),
"replace 'She' with 'He'");
target = source;
requireStringEquals(target_he_she, StrUtils::replaceAll(target, he, she),
"replace 'he' with 'she'");
target = source;
requireStringEquals(target, StrUtils::replaceAll(target, notThere, xyz),
"no alteration of string with non-existent needle");
}
//******************************************************************************
void TestStrUtils::testStripInPlace() {
TEST_CASE("stripInPlace");
const std::string target = "now is the time";
std::string withSingleTrailingSpace = "now is the time ";
std::string withSingleLeadingTrailingSpace = " now is the time ";
std::string withSingleLeadingX = "xnow is the time";
std::string withSingleTrailingX = "now is the timex";
std::string withLeadingTrailingPunctuation = ",now is the time,";
std::string withTrailingPunctuation = "now is the time,";
std::string leadingAndTrailing = "...now is the time...";
std::string alreadyTrimmed = "now is the time";
requireStringEquals(target, StrUtils::strip(withSingleTrailingSpace, ' '),
"single trailing space");
requireStringEquals(target, StrUtils::strip(withSingleLeadingTrailingSpace,
' '),
"single leading and trailing space");
requireStringEquals(target, StrUtils::strip(withSingleLeadingX, 'x'),
"leading char");
requireStringEquals(target, StrUtils::strip(withSingleTrailingX, 'x'),
"trailing char");
requireStringEquals(target, StrUtils::strip(withTrailingPunctuation, ','),
"trailing punctuation");
requireStringEquals(target, StrUtils::strip(withLeadingTrailingPunctuation,
','),
"leading and trailing punctuation");
requireStringEquals(target, StrUtils::strip(leadingAndTrailing, '.'),
"leading and trailing strip chars");
requireStringEquals(target, StrUtils::strip(alreadyTrimmed, ' '),
"no alteration of already trimmed string");
}
//******************************************************************************
void TestStrUtils::testStripTrailing() {
TEST_CASE("stripTrailing");
const std::string target = "now is the time";
std::string withSingleTrailingSpace = "now is the time ";
std::string withSingleTrailingX = "now is the timex";
std::string withTrailingPunctuation = "now is the time,";
std::string leadingAndTrailing = "...now is the time...";
std::string alreadyTrimmed = "now is the time";
std::string onlyTrimChars = "xxxxxxxxxx";
const std::string empty = "";
requireStringEquals(target, StrUtils::stripTrailing(withSingleTrailingSpace,
' '),
"single trailing space");
requireStringEquals(target, StrUtils::stripTrailing(withSingleTrailingX,
'x'),
"trailing char");
requireStringEquals(target, StrUtils::stripTrailing(withTrailingPunctuation,
','),
"trailing punctuation");
require(target != StrUtils::stripTrailing(leadingAndTrailing, '.'),
"trimmed string has leading strip chars");
requireStringEquals(target, StrUtils::stripTrailing(alreadyTrimmed, ' '),
"no alteration of already trimmed string");
requireStringEquals(empty, StrUtils::stripTrailing(onlyTrimChars, 'x'),
"string containing only char to strip");
}
//******************************************************************************
void TestStrUtils::testStripLeading() {
TEST_CASE("stripLeading");
const std::string target = "now is the time";
std::string withSingleLeadingSpace = " now is the time";
std::string withSingleLeadingX = "xnow is the time";
std::string withLeadingPunctuation = ",now is the time";
std::string leadingAndTrailing = "...now is the time...";
std::string alreadyTrimmed = "now is the time";
requireStringEquals(target, StrUtils::stripLeading(withSingleLeadingSpace, ' '),
"single leading space");
requireStringEquals(target, StrUtils::stripLeading(withSingleLeadingX, 'x'),
"leading char");
requireStringEquals(target, StrUtils::stripLeading(withLeadingPunctuation, ','),
"leading punctuation");
require(target != StrUtils::stripLeading(leadingAndTrailing, '.'),
"trimmed string has trailing strip chars");
requireStringEquals(target, StrUtils::stripLeading(alreadyTrimmed, ' '),
"no alteration of already trimmed string");
}
//******************************************************************************
void TestStrUtils::testTrimLeadingSpaces() {
TEST_CASE("trimLeadingSpaces");
const std::string target = "now is the time";
std::string withSingleLeadingSpace = " now is the time";
std::string withLeadingSpaces = " now is the time";
std::string leadingAndTrailing = " now is the time ";
std::string alreadyTrimmed = "now is the time";
requireStringEquals(target, StrUtils::trimLeadingSpaces(withSingleLeadingSpace),
"single leading space");
requireStringEquals(target, StrUtils::trimLeadingSpaces(withLeadingSpaces),
"leading spaces");
require(target != StrUtils::trimLeadingSpaces(leadingAndTrailing),
"trimmed string has trailing spaces");
requireStringEquals(target, StrUtils::trimLeadingSpaces(alreadyTrimmed),
"no alteration of already trimmed string");
}
//******************************************************************************
void TestStrUtils::testTrim() {
TEST_CASE("trim");
// trim is just alias for strip. strip tested elsewhere
}
//******************************************************************************
void TestStrUtils::testPadRight() {
TEST_CASE("padRight");
std::string startedEmpty;
const std::string tenChars = "xxxxxxxxxx";
StrUtils::padRight(startedEmpty, 'x', 10);
requireStringEquals(tenChars, startedEmpty, "empty");
std::string noPaddingNeeded = "xxxxxxxxxx";
StrUtils::padRight(noPaddingNeeded, 'x', 10);
requireStringEquals(tenChars, noPaddingNeeded, "no padding needed");
std::string onePadCharNeeded = "...";
const std::string fourChars = "....";
StrUtils::padRight(onePadCharNeeded, '.', 4);
requireStringEquals(fourChars, onePadCharNeeded, "one pad char needed");
std::string threePadCharsNeeded = "888 ";
const std::string spacePadded = "888 ";
StrUtils::padRight(threePadCharsNeeded, ' ', 10);
requireStringEquals(spacePadded, threePadCharsNeeded,
"three pad chars needed");
}
//******************************************************************************
void TestStrUtils::testPadLeft() {
TEST_CASE("padLeft");
std::string startedEmpty;
const std::string tenChars = "xxxxxxxxxx";
StrUtils::padLeft(startedEmpty, 'x', 10);
requireStringEquals(tenChars, startedEmpty, "empty");
std::string noPaddingNeeded = "xxxxxxxxxx";
StrUtils::padLeft(noPaddingNeeded, 'x', 10);
requireStringEquals(tenChars, noPaddingNeeded, "no padding needed");
std::string onePadCharNeeded = "...";
const std::string fourChars = "....";
StrUtils::padLeft(onePadCharNeeded, '.', 4);
requireStringEquals(fourChars, onePadCharNeeded, "one pad char needed");
std::string threePadCharsNeeded = "888 ";
const std::string spacePadded = " 888 ";
StrUtils::padLeft(threePadCharsNeeded, ' ', 10);
requireStringEquals(spacePadded, threePadCharsNeeded,
"three pad chars needed");
}
//******************************************************************************
void TestStrUtils::testMakeStringOfChar() {
TEST_CASE("makeStringOfChar");
requireStringEquals(std::string("xxx"),
StrUtils::makeStringOfChar('x', 3),
"simple construction");
requireStringEquals(std::string(""),
StrUtils::makeStringOfChar('z', 0),
"zero-length");
}
//******************************************************************************
void TestStrUtils::testSplit() {
TEST_CASE("split");
std::vector<std::string> r;
r = StrUtils::split("comma,separated,values", ",");
require(r.size() == 3, "comma separated values");
r = StrUtils::split("/usr/local/bin", "/");
require(r.size() == 3, "leading delimiter");
r = StrUtils::split("/usr/local/bin", ":");
require(r.size() == 1, "missing delimiter");
r = StrUtils::split("abc:def:ghi:", ":");
require(r.size() == 3, "trailing delimiter");
}
//******************************************************************************
| 26,474
| 7,449
|
/*
* Copyright 2020 Xilinx, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _XF_AEC_HPP_
#define _XF_AEC_HPP_
#include "common/xf_common.hpp"
#include "hls_math.h"
#include "hls_stream.h"
#include "xf_bgr2hsv.hpp"
#include "xf_channel_combine.hpp"
#include "xf_channel_extract.hpp"
#include "xf_cvt_color.hpp"
#include "xf_cvt_color_1.hpp"
#include "xf_duplicateimage.hpp"
#include "xf_hist_equalize.hpp"
#include "xf_histogram.hpp"
template <typename T>
T xf_satcast_aec(int in_val){};
template <>
inline ap_uint<8> xf_satcast_aec<ap_uint<8> >(int v) {
v = (v > 255 ? 255 : v);
v = (v < 0 ? 0 : v);
return v;
};
template <>
inline ap_uint<10> xf_satcast_aec<ap_uint<10> >(int v) {
v = (v > 1023 ? 1023 : v);
v = (v < 0 ? 0 : v);
return v;
};
template <>
inline ap_uint<12> xf_satcast_aec<ap_uint<12> >(int v) {
v = (v > 4095 ? 4095 : v);
v = (v < 0 ? 0 : v);
return v;
};
template <>
inline ap_uint<16> xf_satcast_aec<ap_uint<16> >(int v) {
v = (v > 65535 ? 65535 : v);
v = (v < 0 ? 0 : v);
return v;
};
namespace xf {
namespace cv {
template <int SRC_T, int DST_T, int SIN_CHANNEL_TYPE, int ROWS, int COLS, int NPC = 1>
void autoexposurecorrection_mono(xf::cv::Mat<SRC_T, ROWS, COLS, NPC>& src,
xf::cv::Mat<DST_T, ROWS, COLS, NPC>& dst,
uint32_t hist_array1[1][256],
uint32_t hist_array2[1][256]) {
#pragma HLS INLINE OFF
int rows = src.rows;
int cols = src.cols;
uint16_t cols_shifted = cols >> (XF_BITSHIFT(NPC));
uint16_t rows_shifted = rows;
xf::cv::Mat<SIN_CHANNEL_TYPE, ROWS, COLS, NPC> vimage1(rows, cols);
xf::cv::Mat<SIN_CHANNEL_TYPE, ROWS, COLS, NPC> vimage2(rows, cols);
xf::cv::duplicateMat(src, vimage1, vimage2);
xFHistogramKernel<SIN_CHANNEL_TYPE, ROWS, COLS, XF_DEPTH(SIN_CHANNEL_TYPE, NPC), NPC,
XF_WORDWIDTH(SIN_CHANNEL_TYPE, NPC), ((COLS >> (XF_BITSHIFT(NPC))) >> 1),
XF_CHANNELS(SIN_CHANNEL_TYPE, NPC)>(vimage1, hist_array1, rows_shifted, cols_shifted);
xFEqualize<SIN_CHANNEL_TYPE, ROWS, COLS, XF_DEPTH(SIN_CHANNEL_TYPE, NPC), NPC, XF_WORDWIDTH(SIN_CHANNEL_TYPE, NPC),
(COLS >> XF_BITSHIFT(NPC))>(vimage2, hist_array2, dst, rows_shifted, cols_shifted);
}
template <int SRC_T, int DST_T, int SIN_CHANNEL_TYPE, int ROWS, int COLS, int NPC = 1>
void autoexposurecorrection(xf::cv::Mat<SRC_T, ROWS, COLS, NPC>& src,
xf::cv::Mat<DST_T, ROWS, COLS, NPC>& dst,
uint32_t hist_array1[1][256],
uint32_t hist_array2[1][256]) {
#pragma HLS INLINE OFF
int rows = src.rows;
int cols = src.cols;
uint16_t cols_shifted = cols >> (XF_BITSHIFT(NPC));
uint16_t rows_shifted = rows;
xf::cv::Mat<SRC_T, ROWS, COLS, NPC> bgr2hsv(rows, cols);
xf::cv::Mat<SRC_T, ROWS, COLS, NPC> hsvimg1(rows, cols);
xf::cv::Mat<SRC_T, ROWS, COLS, NPC> hsvimg2(rows, cols);
xf::cv::Mat<SRC_T, ROWS, COLS, NPC> hsvimg3(rows, cols);
xf::cv::Mat<SIN_CHANNEL_TYPE, ROWS, COLS, NPC> himage(rows, cols);
xf::cv::Mat<SIN_CHANNEL_TYPE, ROWS, COLS, NPC> simage(rows, cols);
xf::cv::Mat<SIN_CHANNEL_TYPE, ROWS, COLS, NPC> vimage(rows, cols);
xf::cv::Mat<SIN_CHANNEL_TYPE, ROWS, COLS, NPC> vimage1(rows, cols);
xf::cv::Mat<SIN_CHANNEL_TYPE, ROWS, COLS, NPC> vimage2(rows, cols);
xf::cv::Mat<SIN_CHANNEL_TYPE, ROWS, COLS, NPC> vimage_eq(rows, cols);
xf::cv::Mat<SRC_T, ROWS, COLS, NPC> imgHelper6(rows, cols);
assert(((rows <= ROWS) && (cols <= COLS)) && "ROWS and COLS should be greater than input image");
// clang-format off
#pragma HLS DATAFLOW
// clang-format on
// Convert RGBA to HSV:
xf::cv::bgr2hsv<SRC_T, ROWS, COLS, NPC>(src, bgr2hsv);
xf::cv::duplicateimages<SRC_T, ROWS, COLS, NPC>(bgr2hsv, hsvimg1, hsvimg2, hsvimg3);
xf::cv::extractChannel<SRC_T, SIN_CHANNEL_TYPE, ROWS, COLS, NPC>(hsvimg1, himage, 0);
xf::cv::extractChannel<SRC_T, SIN_CHANNEL_TYPE, ROWS, COLS, NPC>(hsvimg2, simage, 1);
xf::cv::extractChannel<SRC_T, SIN_CHANNEL_TYPE, ROWS, COLS, NPC>(hsvimg3, vimage, 2);
xf::cv::duplicateMat(vimage, vimage1, vimage2);
// xf::cv::equalizeHist<SIN_CHANNEL_TYPE, ROWS, COLS, NPC>(vimage1, vimage2,
// vimage_eq);
xFHistogramKernel<SIN_CHANNEL_TYPE, ROWS, COLS, XF_DEPTH(SIN_CHANNEL_TYPE, NPC), NPC,
XF_WORDWIDTH(SIN_CHANNEL_TYPE, NPC), ((COLS >> (XF_BITSHIFT(NPC))) >> 1),
XF_CHANNELS(SIN_CHANNEL_TYPE, NPC)>(vimage1, hist_array1, rows_shifted, cols_shifted);
xFEqualize<SIN_CHANNEL_TYPE, ROWS, COLS, XF_DEPTH(SIN_CHANNEL_TYPE, NPC), NPC, XF_WORDWIDTH(SIN_CHANNEL_TYPE, NPC),
(COLS >> XF_BITSHIFT(NPC))>(vimage2, hist_array2, vimage_eq, rows_shifted, cols_shifted);
xf::cv::merge<SIN_CHANNEL_TYPE, SRC_T, ROWS, COLS, NPC>(vimage_eq, simage, himage, imgHelper6);
xf::cv::hsv2bgr<SRC_T, SRC_T, ROWS, COLS, NPC>(imgHelper6, dst);
}
}
}
#endif
| 5,592
| 2,527
|
#ifndef TrackerConditions_StrawResponse_hh
#define TrackerConditions_StrawResponse_hh
//
// StrawResponse collects the net response features of straws
// used in reconstruction
//
#include <iostream>
#include <vector>
#include <array>
#include "TrackerGeom/inc/Straw.hh"
#include "DataProducts/inc/TrkTypes.hh"
#include "DataProducts/inc/StrawId.hh"
#include "TrackerConditions/inc/StrawDrift.hh"
#include "TrackerConditions/inc/StrawElectronics.hh"
#include "TrackerConditions/inc/StrawPhysics.hh"
#include "Mu2eInterfaces/inc/ProditionsEntity.hh"
namespace mu2e {
class Straw;
class StrawDrift;
class StrawId;
class StrawResponse : virtual public ProditionsEntity {
public:
typedef std::shared_ptr<StrawResponse> ptr_t;
typedef std::shared_ptr<const StrawResponse> cptr_t;
constexpr static const char* cxname = {"StrawResponse"};
explicit StrawResponse( StrawDrift::cptr_t strawDrift,
StrawElectronics::cptr_t strawElectronics,
StrawPhysics::cptr_t strawPhysics,
int eBins, double eBinWidth,
std::vector<double> edep, std::vector<double> halfvp,
double central, std::vector<double> centres,
std::vector<double> resslope, int totTBins, double totTBinWidth,
int totEBins, double totEBinWidth, std::vector<double> totdtime,
bool usederr, std::vector<double> derr,
bool usepderr, std::vector<double> parDriftDocas,
std::vector<double> parDriftOffsets, std::vector<double> parDriftRes,
double wbuf, double slfac, double errfac, bool usenonlindrift,
double lindriftvel, double rres_min, double rres_max,
double rres_rad, double mint0doca, double t0shift,
std::array<double, StrawId::_nustraws> pmpEnergyScale,
double electronicsTimeDelay, double gasGain,
std::array<double,StrawElectronics::npaths> analognoise,
std::array<double,StrawElectronics::npaths> dVdI,
double vsat, double ADCped, double pmpEnergyScaleAvg) :
ProditionsEntity(cxname),
_strawDrift(strawDrift),
_strawElectronics(strawElectronics),
_strawPhysics(strawPhysics),
_eBins(eBins), _eBinWidth(eBinWidth),
_edep(edep), _halfvp(halfvp), _central(central), _centres(centres),
_resslope(resslope), _totTBins(totTBins), _totTBinWidth(totTBinWidth),
_totEBins(totEBins), _totEBinWidth(totEBinWidth),
_totdtime(totdtime), _usederr(usederr),
_derr(derr), _usepderr(usepderr), _parDriftDocas(parDriftDocas),
_parDriftOffsets(parDriftOffsets), _parDriftRes(parDriftRes),
_wbuf(wbuf), _slfac(slfac), _errfac(errfac),
_usenonlindrift(usenonlindrift), _lindriftvel(lindriftvel),
_rres_min(rres_min), _rres_max(rres_max), _rres_rad(rres_rad),
_mint0doca(mint0doca), _t0shift(t0shift),
_pmpEnergyScale(pmpEnergyScale),
_electronicsTimeDelay(electronicsTimeDelay),
_gasGain(gasGain), _analognoise(analognoise),
_dVdI(dVdI), _vsat(vsat), _ADCped(ADCped),
_pmpEnergyScaleAvg(pmpEnergyScaleAvg) {}
virtual ~StrawResponse() {}
bool wireDistance(Straw const& straw, double edep, double dt,
double& wdist, double& wderr, double& halfpv) const;
bool useDriftError() const { return _usederr; }
bool useParameterizedDriftError() const { return _usepderr; }
bool useNonLinearDrift() const { return _usenonlindrift; }
double Mint0doca() const { return _mint0doca;}
double strawGain() const { return _strawPhysics->strawGain();}
double halfPropV(StrawId strawId, double kedep) const;
// this is used to update values from the database
void setOffsets( std::array<double, StrawId::_nupanels> timeOffsetPanel,
std::array<double, StrawId::_nustraws> timeOffsetStrawHV,
std::array<double, StrawId::_nustraws> timeOffsetStrawCal ) {
_timeOffsetPanel = timeOffsetPanel;
_timeOffsetStrawHV = timeOffsetStrawHV;
_timeOffsetStrawCal = timeOffsetStrawCal;
}
double driftDistanceToTime(StrawId strawId, double ddist, double phi) const;
double driftTimeToDistance(StrawId strawId, double dtime, double phi) const;
double driftInstantSpeed(StrawId strawId, double ddist, double phi) const;
double driftConstantSpeed() const {return _lindriftvel;} // constant value used for annealing errors, should be close to average velocity
double driftTimeMaxError() const {return _rres_max/_lindriftvel;} // constant value used for initialization
double driftDistanceError(StrawId strawId, double ddist, double phi, double DOCA) const;
double driftDistanceOffset(StrawId strawId, double ddist, double phi, double DOCA) const;
double driftTimeError(StrawId strawId, double ddist, double phi, double DOCA) const;
double driftTimeOffset(StrawId strawId, double ddist, double phi, double DOCA) const;
double peakMinusPedestalEnergyScale() const { return _pmpEnergyScaleAvg; }
double peakMinusPedestalEnergyScale(StrawId sid) const { return _pmpEnergyScale[sid.uniqueStraw()]; }
double analogNoise(StrawElectronics::Path ipath) const { return _analognoise[ipath]; } // incoherent noise
double fallTime(StrawElectronics::Path ipath) const { return 22.;} //FIXME
double currentToVoltage(StrawElectronics::Path ipath) const { return _dVdI[ipath]; }
double saturatedResponse(double vlin) const;
double ADCPedestal() const { return _ADCped; };
double t0shift() const { return _t0shift; }
// converts times from TDC times to time relative to Event Window
// removes channel to channel delays and overall electronics time delay
void calibrateTimes(TrkTypes::TDCValues const& tdc, TrkTypes::TDCTimes ×, const StrawId &id) const;
// approximate drift distatnce from ToT value
double driftTime(Straw const& straw, double tot, double edep) const;
double pathLength(Straw const& straw, double tot) const;
// double pathLength(StrawHit const& strawhit, double theta) const;
void print(std::ostream& os) const;
void printVector(std::ostream& os, std::string const& name,
std::vector<double> const& a) const;
template<typename T, size_t SIZE>
void printArray(std::ostream& os, std::string const& name,
std::array<T,SIZE> const& a) const;
// StrawElectronics functions we are allowed to use
inline size_t nADCPreSamples() const { return _strawElectronics->nADCPreSamples(); }
inline double adcLSB() const { return _strawElectronics->adcLSB(); }
inline double totLSB() const { return _strawElectronics->totLSB(); }
inline double adcPeriod() const { return _strawElectronics->adcPeriod(); }
inline uint16_t maxADC() const { return _strawElectronics->maxADC(); }
// StrawPhysics functions we are allowed to use
inline double ionizationEnergy(double q) const { return _strawPhysics->ionizationEnergy(q); }
double wpRes(double kedep, double wdist) const;
private:
// helper functions
static double PieceLine(std::vector<double> const& xvals,
std::vector<double> const& yvals, double xval);
StrawDrift::cptr_t _strawDrift;
StrawElectronics::cptr_t _strawElectronics;
StrawPhysics::cptr_t _strawPhysics;
// parametric data for calibration functions
// TD reconstruction uses 1/2 the propagation velocity and depends on the
// Dependence on position and straw length still needed FIXME!
// (reconstructed) energy deposit
bool _evenBins;
int _eBins;
double _eBinWidth;
std::vector<double> _edep; // energy deposit boundaries
std::vector<double> _halfvp; // effective 1/2 propagation velocity by edep
double _central; // max wire distance for central wire region
std::vector<double> _centres; // wire center resolution by edep
std::vector<double> _resslope; // resolution slope vs position by edep
size_t _totTBins;
double _totTBinWidth;
size_t _totEBins;
double _totEBinWidth;
std::vector<double> _totdtime;
bool _usederr; // flag to use the doca-dependent calibration of the drift error
std::vector<double> _derr; // parameters describing the drift error function
bool _usepderr; // flag to use calculated version of drift error calculation
std::vector<double> _parDriftDocas;
std::vector<double> _parDriftOffsets;
std::vector<double> _parDriftRes;
double _wbuf; // buffer at the edge of the straws, in terms of sigma
double _slfac; // factor of straw length to set 'missing cluster' hits
double _errfac; // error inflation for 'missing cluster' hits
bool _usenonlindrift;
double _lindriftvel;
double _rres_min;
double _rres_max;
double _rres_rad;
double _mint0doca; // minimum doca for t0 calculation. Note this is a SIGNED QUANTITITY
double _t0shift;
std::array<double, StrawId::_nustraws> _pmpEnergyScale;
std::array<double, StrawId::_nupanels> _timeOffsetPanel;
std::array<double, StrawId::_nustraws> _timeOffsetStrawHV;
std::array<double, StrawId::_nustraws> _timeOffsetStrawCal;
double _electronicsTimeDelay;
double _gasGain;
std::array<double,StrawElectronics::npaths> _analognoise; //noise (mVolt) from the straw itself
std::array<double,StrawElectronics::npaths> _dVdI; // scale factor between charge and voltage (milliVolts/picoCoulombs)
double _vsat;
double _ADCped;
double _pmpEnergyScaleAvg;
};
}
#endif
| 9,387
| 3,240
|
/******************************************************************************/
/* 0MQ Internal Use */
/******************************************************************************/
#define LIBZMQ_UNUSED(object) (void) object
#define LIBZMQ_DELETE(p_object) \
{ \
delete p_object; \
p_object = 0; \
}
/******************************************************************************/
#if !defined ZMQ_NOEXCEPT
#if defined ZMQ_HAVE_NOEXCEPT
#define ZMQ_NOEXCEPT noexcept
#else
#define ZMQ_NOEXCEPT
#endif
#endif
| 829
| 182
|
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <lib/ddk/debug.h>
#include <limits>
#include <memory>
#include <utility>
#include <fbl/alloc_checker.h>
#include <soc/aml-common/aml-pdm-audio.h>
// Filter configurations
// mode 1 lpf1
static const uint32_t lpf1m1[] = {
0x000014, 0xffffb2, 0xfffed9, 0xfffdce, 0xfffd45, 0xfffe32, 0x000147, 0x000645, 0x000b86,
0x000e21, 0x000ae3, 0x000000, 0xffeece, 0xffdca8, 0xffd212, 0xffd7d1, 0xfff2a7, 0x001f4c,
0x0050c2, 0x0072aa, 0x006ff1, 0x003c32, 0xffdc4e, 0xff6a18, 0xff0fef, 0xfefbaf, 0xff4c40,
0x000000, 0x00ebc8, 0x01c077, 0x02209e, 0x01c1a4, 0x008e60, 0xfebe52, 0xfcd690, 0xfb8fa5,
0xfba498, 0xfd9812, 0x0181ce, 0x06f5f3, 0x0d112f, 0x12a958, 0x169686, 0x18000e, 0x169686,
0x12a958, 0x0d112f, 0x06f5f3, 0x0181ce, 0xfd9812, 0xfba498, 0xfb8fa5, 0xfcd690, 0xfebe52,
0x008e60, 0x01c1a4, 0x02209e, 0x01c077, 0x00ebc8, 0x000000, 0xff4c40, 0xfefbaf, 0xff0fef,
0xff6a18, 0xffdc4e, 0x003c32, 0x006ff1, 0x0072aa, 0x0050c2, 0x001f4c, 0xfff2a7, 0xffd7d1,
0xffd212, 0xffdca8, 0xffeece, 0x000000, 0x000ae3, 0x000e21, 0x000b86, 0x000645, 0x000147,
0xfffe32, 0xfffd45, 0xfffdce, 0xfffed9, 0xffffb2, 0x000014,
};
constexpr uint32_t kLpf1m1Len = static_cast<uint32_t>(std::size(lpf1m1));
// mode 1 lpf3
static const uint32_t lpf3m1[] = {
0x000000, 0x000081, 0x000000, 0xfffedb, 0x000000, 0x00022d, 0x000000, 0xfffc46, 0x000000,
0x0005f7, 0x000000, 0xfff6eb, 0x000000, 0x000d4e, 0x000000, 0xffed1e, 0x000000, 0x001a1c,
0x000000, 0xffdcb0, 0x000000, 0x002ede, 0x000000, 0xffc2d1, 0x000000, 0x004ebe, 0x000000,
0xff9beb, 0x000000, 0x007dd7, 0x000000, 0xff633a, 0x000000, 0x00c1d2, 0x000000, 0xff11d5,
0x000000, 0x012368, 0x000000, 0xfe9c45, 0x000000, 0x01b252, 0x000000, 0xfdebf6, 0x000000,
0x0290b8, 0x000000, 0xfcca0d, 0x000000, 0x041d7c, 0x000000, 0xfa8152, 0x000000, 0x07e9c6,
0x000000, 0xf28fb5, 0x000000, 0x28b216, 0x3fffde, 0x28b216, 0x000000, 0xf28fb5, 0x000000,
0x07e9c6, 0x000000, 0xfa8152, 0x000000, 0x041d7c, 0x000000, 0xfcca0d, 0x000000, 0x0290b8,
0x000000, 0xfdebf6, 0x000000, 0x01b252, 0x000000, 0xfe9c45, 0x000000, 0x012368, 0x000000,
0xff11d5, 0x000000, 0x00c1d2, 0x000000, 0xff633a, 0x000000, 0x007dd7, 0x000000, 0xff9beb,
0x000000, 0x004ebe, 0x000000, 0xffc2d1, 0x000000, 0x002ede, 0x000000, 0xffdcb0, 0x000000,
0x001a1c, 0x000000, 0xffed1e, 0x000000, 0x000d4e, 0x000000, 0xfff6eb, 0x000000, 0x0005f7,
0x000000, 0xfffc46, 0x000000, 0x00022d, 0x000000, 0xfffedb, 0x000000, 0x000081, 0x000000,
};
constexpr uint32_t kLpf3m1Len = static_cast<uint32_t>(std::size(lpf3m1));
// osr64 lpf2
static const uint32_t lpf2osr64[] = {
0x00050a, 0xfff004, 0x0002c1, 0x003c12, 0xffa818, 0xffc87d, 0x010aef, 0xff5223, 0xfebd93,
0x028f41, 0xff5c0e, 0xfc63f8, 0x055f81, 0x000000, 0xf478a0, 0x11c5e3, 0x2ea74d, 0x11c5e3,
0xf478a0, 0x000000, 0x055f81, 0xfc63f8, 0xff5c0e, 0x028f41, 0xfebd93, 0xff5223, 0x010aef,
0xffc87d, 0xffa818, 0x003c12, 0x0002c1, 0xfff004, 0x00050a,
};
constexpr uint32_t kLpf2osr64Len = static_cast<uint32_t>(std::size(lpf2osr64));
// static
std::unique_ptr<AmlPdmDevice> AmlPdmDevice::Create(
fdf::MmioBuffer pdm_mmio, fdf::MmioBuffer audio_mmio, ee_audio_mclk_src_t pdm_clk_src,
uint32_t sysclk_div, uint32_t dclk_div, aml_toddr_t toddr_dev, metadata::AmlVersion version) {
// TODDR A has 256 64-bit lines in the FIFO, B and C have 128.
uint32_t fifo_depth = 128 * 8; // in bytes.
if (toddr_dev == TODDR_A) {
fifo_depth = 256 * 8;
}
fbl::AllocChecker ac;
auto pdm = std::unique_ptr<AmlPdmDevice>(
new (&ac) AmlPdmDevice(std::move(pdm_mmio), std::move(audio_mmio), pdm_clk_src, sysclk_div,
dclk_div, toddr_dev, fifo_depth, version));
if (!ac.check()) {
zxlogf(ERROR, "%s: Could not create AmlPdmDevice", __func__);
return nullptr;
}
pdm->InitRegs();
constexpr uint32_t default_frames_per_second = 48000;
pdm->ConfigFilters(default_frames_per_second);
return pdm;
}
void AmlPdmDevice::InitRegs() {
// Setup toddr block
switch (version_) {
case metadata::AmlVersion::kS905D2G:
audio_mmio_.Write32((0x30 << 16) | // Enable interrupts for FIFO errors.
(0x02 << 13) | // Right justified 16-bit
(31 << 8) | // msb position of data out of pdm
(16 << 3) | // lsb position of data out of pdm
(0x04 << 0), // select pdm as data source
GetToddrOffset(TODDR_CTRL0_OFFS));
audio_mmio_.Write32(((fifo_depth_ / 8 / 2) << 16) | // trigger ddr when fifo half full
(0x02 << 8), // STATUS2 source is ddr position
GetToddrOffset(TODDR_CTRL1_OFFS));
break;
case metadata::AmlVersion::kS905D3G:
audio_mmio_.Write32((0x02 << 13) | // Right justified 16-bit
(31 << 8) | // msb position of data out of pdm
(16 << 3), // lsb position of data out of pdm
GetToddrOffset(TODDR_CTRL0_OFFS));
audio_mmio_.Write32((0x04 << 28) | // select pdm as data source
((fifo_depth_ / 8 / 2) << 12) | // trigger ddr when fifo half full
(0x02 << 8), // STATUS2 source is ddr position
GetToddrOffset(TODDR_CTRL1_OFFS));
break;
}
//*To keep things simple, we are using the same clock source for both the
// pdm sysclk and dclk. Sysclk needs to be ~100-200MHz per AmLogic recommendations.
// dclk is osr*fs
//*Sysclk must be configured, enabled, and PDM audio clock gated prior to
// accessing any of the registers mapped via pdm_mmio. Writing without sysclk
// operating properly (and in range) will result in unknown results, reads
// will wedge the system.
audio_mmio_.Write32((clk_src_ << 24) | dclk_div_, EE_AUDIO_CLK_PDMIN_CTRL0);
audio_mmio_.Write32((1 << 31) | (clk_src_ << 24) | sysclk_div_, EE_AUDIO_CLK_PDMIN_CTRL1);
audio_mmio_.SetBits32((1 << 31) | (1 << toddr_ch_), EE_AUDIO_ARB_CTRL);
// Enable the audio domain clocks used by this instance.
AudioClkEna(EE_AUDIO_CLK_GATE_PDM | (EE_AUDIO_CLK_GATE_TODDRA << toddr_ch_) |
EE_AUDIO_CLK_GATE_ARB);
// It is now safe to write to pdm registers
// Ensure clocks are stable before accessing any of the pdm_mmio_ registers.
zx::nanosleep(zx::deadline_after(zx::msec(10)));
// Ensure system is in idle state in case we are re-initing hardware
// which was already running. Keep de-inited for 100ms with no pdm_dclk to
// ensure pdm microphones will start reliably.
Stop();
zx::nanosleep(zx::deadline_after(zx::msec(100)));
// Enable cts_pdm_clk gate (clock gate within pdm module)
pdm_mmio_.SetBits32(0x01, PDM_CLKG_CTRL);
pdm_mmio_.Write32((0x01 << 29), // 24bit output mode
PDM_CTRL);
// This sets the number of sysclk cycles between edge of dclk and when
// data is sampled. AmLogic material suggests this should be 3/4 of a
// dclk half-cycle. Go ahead and set all eight channels.
uint32_t samp_delay = 3 * (dclk_div_ + 1) / (4 * 2 * (sysclk_div_ + 1));
pdm_mmio_.Write32((samp_delay << 0) | (samp_delay << 8) | (samp_delay << 16) | (samp_delay << 24),
PDM_CHAN_CTRL);
pdm_mmio_.Write32((samp_delay << 0) | (samp_delay << 8) | (samp_delay << 16) | (samp_delay << 24),
PDM_CHAN_CTRL1);
}
void AmlPdmDevice::ConfigFilters(uint32_t frames_per_second) {
ZX_ASSERT(frames_per_second == 96000 || frames_per_second == 48000);
uint32_t gain_shift = (frames_per_second == 96000) ? 0xe : 0x15;
uint32_t downsample_rate = (frames_per_second == 96000) ? 0x4 : 0x8;
pdm_mmio_.Write32((1 << 31) | // Enable
(gain_shift << 24) | // Final gain shift parameter
(0x80 << 16) | // Final gain multiplier
(downsample_rate << 4) | // hcic downsample rate
(0x07 << 0), // hcic stage number (must be between 3-9)
PDM_HCIC_CTRL1);
// Note: The round mode field for the lowpass control registers is shown in AmLogic
// documentation to be occupying bits [16:15] fo the register. This was confirmed
// by amlogic to be an error in the datasheet and the correct position is [17:16]
pdm_mmio_.Write32((0x01 << 31) | // Enable filter
(0x01 << 16) | // Round mode
(0x02 << 12) | // Filter 1 downsample rate
(kLpf1m1Len << 0), // Number of taps in filter
PDM_F1_CTRL);
pdm_mmio_.Write32((0x01 << 31) | // Enable filter
(0x00 << 16) | // Round mode
(0x02 << 12) | // Filter 2 downsample rate
(kLpf2osr64Len << 0), // Number of taps in filter
PDM_F2_CTRL);
pdm_mmio_.Write32((0x01 << 31) | // Enable filter
(0x01 << 16) | // Round mode
(2 << 12) | // Filter 3 downsample rate
(kLpf3m1Len << 0), // Number of taps in filter
PDM_F3_CTRL);
pdm_mmio_.Write32((0x01 << 31) | // Enable filter
(0x0d << 16) | // Shift steps
(0x8000 << 0), // Output factor
PDM_HPF_CTRL);
// set coefficient index pointer to 0
pdm_mmio_.Write32(0x0000, PDM_COEFF_ADDR);
// Write coefficients to coefficient memory
// --these appear to be packed with the filter length in each filter
// control register being the mechanism that helps reference them
for (uint32_t i = 0; i < std::size(lpf1m1); i++) {
pdm_mmio_.Write32(lpf1m1[i], PDM_COEFF_DATA);
}
for (uint32_t i = 0; i < std::size(lpf2osr64); i++) {
pdm_mmio_.Write32(lpf2osr64[i], PDM_COEFF_DATA);
}
for (uint32_t i = 0; i < std::size(lpf3m1); i++) {
pdm_mmio_.Write32(lpf3m1[i], PDM_COEFF_DATA);
}
// set coefficient index pointer back to 0
pdm_mmio_.Write32(0x0000, PDM_COEFF_ADDR);
}
void AmlPdmDevice::SetMute(uint8_t mute_mask) {
pdm_mmio_.ModifyBits<uint32_t>(static_cast<uint32_t>(mute_mask) << 20, 0xff << 20, PDM_CTRL);
}
void AmlPdmDevice::SetRate(uint32_t frames_per_second) {
ZX_ASSERT(frames_per_second == 48000 || frames_per_second == 96000);
ConfigFilters(frames_per_second);
}
uint32_t AmlPdmDevice::GetRingPosition() {
uint32_t pos = audio_mmio_.Read32(GetToddrOffset(TODDR_STATUS2_OFFS));
uint32_t base = audio_mmio_.Read32(GetToddrOffset(TODDR_START_ADDR_OFFS));
return (pos - base);
}
uint32_t AmlPdmDevice::GetDmaStatus() {
return audio_mmio_.Read32(GetToddrOffset(TODDR_STATUS1_OFFS));
}
uint32_t AmlPdmDevice::GetPdmStatus() { return audio_mmio_.Read32(PDM_STS); }
void AmlPdmDevice::AudioClkEna(uint32_t audio_blk_mask) {
audio_mmio_.SetBits32(audio_blk_mask, EE_AUDIO_CLK_GATE_EN);
}
void AmlPdmDevice::AudioClkDis(uint32_t audio_blk_mask) {
audio_mmio_.ClearBits32(audio_blk_mask, EE_AUDIO_CLK_GATE_EN);
}
zx_status_t AmlPdmDevice::SetBuffer(zx_paddr_t buf, size_t len) {
// Ensure ring buffer resides in lower memory (dma pointers are 32-bit)
// and len is at least 8 (size of each dma operation)
if (((buf + len - 1) > std::numeric_limits<uint32_t>::max()) || (len < 8)) {
return ZX_ERR_INVALID_ARGS;
}
// Write32 the start and end pointers. Each fetch is 64-bits, so end pointer
// is pointer to the last 64-bit fetch (inclusive)
audio_mmio_.Write32(static_cast<uint32_t>(buf), GetToddrOffset(TODDR_START_ADDR_OFFS));
audio_mmio_.Write32(static_cast<uint32_t>(buf), GetToddrOffset(TODDR_INIT_ADDR_OFFS));
audio_mmio_.Write32(static_cast<uint32_t>(buf + len - 8), GetToddrOffset(TODDR_FINISH_ADDR_OFFS));
return ZX_OK;
}
// Stops the pdm from clocking
void AmlPdmDevice::PdmInDisable() {
audio_mmio_.ClearBits32(1 << 31, EE_AUDIO_CLK_PDMIN_CTRL0);
pdm_mmio_.ClearBits32((1 << 31) | (1 << 16), PDM_CTRL);
}
// Enables the pdm to clock data
void AmlPdmDevice::PdmInEnable() {
// Start pdm_dclk
audio_mmio_.SetBits32(1 << 31, EE_AUDIO_CLK_PDMIN_CTRL0);
pdm_mmio_.SetBits32((1 << 31) | (1 << 16), PDM_CTRL);
}
// Takes channels out of reset and enables them.
void AmlPdmDevice::ConfigPdmIn(uint8_t mask) {
pdm_mmio_.ModifyBits<uint32_t>((mask << 8) | (mask << 0), (0xff << 8) | (0xff << 0), PDM_CTRL);
}
void AmlPdmDevice::TODDREnable() {
// Set the load bit, will make sure things start from beginning of buffer
audio_mmio_.SetBits32(1 << 31, GetToddrOffset(TODDR_CTRL0_OFFS));
}
void AmlPdmDevice::TODDRDisable() {
// Clear the load bit (this is the bit that forces the initial fetch of
// start address into current ptr)
audio_mmio_.ClearBits32(1 << 31, GetToddrOffset(TODDR_CTRL0_OFFS));
audio_mmio_.ClearBits32(1 << 25, GetToddrOffset(TODDR_CTRL1_OFFS));
}
void AmlPdmDevice::Sync() {
pdm_mmio_.ClearBits32(1 << 16, PDM_CTRL);
pdm_mmio_.SetBits32(1 << 16, PDM_CTRL);
}
// Resets frddr mechanisms to start at beginning of buffer
// starts the frddr (this will fill the fifo)
// starts the tdm to clock out data on the bus
// returns the start time
uint64_t AmlPdmDevice::Start() {
uint64_t a, b;
Sync();
TODDREnable();
a = zx_clock_get_monotonic();
PdmInEnable();
b = zx_clock_get_monotonic();
return ((b - a) >> 1) + a;
}
void AmlPdmDevice::Stop() {
PdmInDisable();
TODDRDisable();
}
void AmlPdmDevice::Shutdown() { Stop(); }
| 13,865
| 6,819
|
#include "LeapMotionPrivatePCH.h"
class PrivateGesture
{
public:
Leap::Gesture Gesture;
};
ULeapGesture::ULeapGesture(const FObjectInitializer &ObjectInitializer) : UObject(ObjectInitializer), Private(new PrivateGesture())
{
}
ULeapGesture::~ULeapGesture()
{
delete Private;
}
ULeapFrame* ULeapGesture::Frame()
{
if (PFrame == nullptr)
{
PFrame = NewObject<ULeapFrame>(this);
}
PFrame->SetFrame(Private->Gesture.frame());
return (PFrame);
}
ULeapHandList* ULeapGesture::Hands()
{
if (PHands == nullptr)
{
PHands = NewObject<ULeapHandList>(this);
}
PHands->SetHandList(Private->Gesture.hands());
return (PHands);
}
ULeapPointableList* ULeapGesture::Pointables()
{
if (PPointables == nullptr)
{
PPointables = NewObject<ULeapPointableList>(this);
}
PPointables->SetPointableList(Private->Gesture.pointables());
return (PPointables);
}
LeapGestureState gestureState(Leap::Gesture::State State)
{
switch (State)
{
case Leap::Gesture::STATE_START:
return (GESTURE_STATE_START);
case Leap::Gesture::STATE_UPDATE:
return (GESTURE_STATE_UPDATE);
case Leap::Gesture::STATE_STOP:
return (GESTURE_STATE_STOP);
default:
return (GESTURE_STATE_INVALID);
}
}
LeapGestureType gestureType(Leap::Gesture::Type Type)
{
switch (Type)
{
case Leap::Gesture::TYPE_CIRCLE:
return (GESTURE_TYPE_CIRCLE);
case Leap::Gesture::TYPE_KEY_TAP:
return (GESTURE_TYPE_KEY_TAP);
case Leap::Gesture::TYPE_SCREEN_TAP:
return (GESTURE_TYPE_SCREEN_TAP);
case Leap::Gesture::TYPE_SWIPE:
return (GESTURE_TYPE_SWIPE);
default:
return (GESTURE_TYPE_INVALID);
}
}
void ULeapGesture::SetGesture(const Leap::Gesture &Gesture)
{
Private->Gesture = Gesture;
Duration = Private->Gesture.duration();
DurationSeconds = Private->Gesture.durationSeconds();
Id = Private->Gesture.id();
IsValid = Private->Gesture.isValid();
State = gestureState(Private->Gesture.state());
Type = gestureType(Private->Gesture.type());
}
| 1,936
| 739
|
/**
* service.cpp - Точка входа в программу.
*
* @mrrva - 2019
*/
#include "include/encryption.hpp"
#include "include/network.hpp"
#include "include/storage.hpp"
#include "include/struct.hpp"
int main()
{
using tgnstruct::secret_key;
using tgnstruct::public_key;
using tgnstorage::db;
std::string pub = db.get_var("PUBLIC_KEY");
std::string sec = db.get_var("SECRET_KEY");
const short hs = HASHSIZE * 2;
if (pub.length() == hs && sec.length() == hs) {
public_key = hex2bin<hs>(pub);
secret_key = hex2bin<hs>(sec);
}
else {
tgnencryption::new_keys();
pub = bin2hex<HASHSIZE>(public_key);
sec = bin2hex<HASHSIZE>(secret_key);
db.set_var("PUBLIC_KEY", pub);
db.set_var("SECRET_KEY", sec);
}
tgnstorage::nodes.select();
if (tgnstruct::nodes.size() == 0) {
std::cout << "[E] Node list is empty. Please "
<< "download database with current list "
<< "of nodes.\n";
return 1;
}
if (!tgnnetwork::socket.start()) {
std::cout << "[E] socket.start.\n";
return 1;
}
while (true) {
tgnstorage::neighbors.autocheck();
tgnstorage::clients.autoremove();
tgnstorage::garlic.autoremove();
tgnstorage::nodes.autocheck();
tgnstorage::routes.autoremove();
}
tgnnetwork::recv.join();
return 0;
}
| 1,241
| 529
|
// ***************************************************************
// Copyright (c) 2021 Jittor. All Rights Reserved.
// Maintainers: Dun Liang <randonlang@gmail.com>.
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
// ***************************************************************
#include <chrono>
#include <thread>
#ifndef _WIN32
#include <sys/mman.h>
#endif
#include "common.h"
#include "misc/ring_buffer.h"
namespace jittor {
RingBuffer::RingBuffer(uint64 size, bool multiprocess) : m(multiprocess), cv(multiprocess) {
int i=0;
for (;(1ll<<i)<size;i++);
size_mask = (1ll<<i)-1;
this->size = size_mask+1;
size_bit = i;
l = r = is_wait = is_stop = 0;
is_multiprocess = multiprocess;
}
void RingBuffer::stop() {
MutexScope _(m);
is_stop = 1;
cv.notify();
}
RingBuffer::~RingBuffer() {
stop();
}
RingBuffer* RingBuffer::make_ring_buffer(uint64 size, bool multiprocess, uint64 buffer, bool init) {
int i=0;
for (;(1ll<<i)<size;i++);
uint64 size_mask = (1ll<<i)-1;
size = size_mask+1;
uint64 total_size = sizeof(RingBuffer) + size;
void* ptr = multiprocess ?
// mmap(NULL, total_size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS | MAP_HUGETLB, -1, 0) :
#ifndef _WIN32
mmap(NULL, total_size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0)
#else
// TODO: multiprocess ring buffer in windows
(void*)buffer
#endif
:
// mmap(NULL, total_size, PROT_READ | PROT_WRITE, MAP_SHARED, -1, 0) :
(void*)malloc(total_size);
auto rb = (RingBuffer*)ptr;
if (!init) return rb;
std::memset(ptr, 0, total_size);
new (rb) RingBuffer(size, multiprocess);
return rb;
}
void RingBuffer::free_ring_buffer(RingBuffer* rb, uint64 buffer, bool init) {
uint64 total_size = sizeof(RingBuffer) + rb->size;
auto is_multiprocess = rb->is_multiprocess;
if (init)
rb->~RingBuffer();
if (is_multiprocess) {
#ifndef _WIN32
munmap(rb, total_size);
#else
if (!buffer)
free((void*)rb);
// this buffer is not owned by this obj
#endif
(void)total_size;
} else {
free((void*)rb);
}
}
// test
JIT_TEST(ring_buffer_benchmark) {
size_t n = 1ll << 20;
size_t size = 1<<15;
// size_t n = 1ll << 30;
// size_t size = 1<<20;
// size_t n = 1ll << 10;
// size_t size = 1<<5;
RingBuffer* rb = RingBuffer::make_ring_buffer(size, 0);
std::thread p([&]() {
for (size_t i=0; i<n; i++) {
rb->push_t<int>(i);
}
});
auto start = std::chrono::high_resolution_clock::now();
size_t s = 0;
for (size_t i=0; i<n; i++) {
auto x = rb->pop_t<int>();
s += x;
}
auto finish = std::chrono::high_resolution_clock::now();
auto tt = std::chrono::duration_cast<std::chrono::nanoseconds>(finish-start).count();
p.join();
expect_error([&]() { rb->push(size+1); });
RingBuffer::free_ring_buffer(rb);
LOGi << tt << tt*1.0/n;
LOGi << s << (n*(n-1)/2);
ASSERTop(s,==,(n*(n-1)/2));
ASSERTop(tt*1.0/n,<=,100);
}
}
| 3,254
| 1,281
|
#include "Heap.h"
#include "QHullMSTClusteringProcess.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
extern "C"
{
#include "qhull.h"
#include "mem.h"
#include "qset.h"
}
#define BUF_SIZE 2048
#define QHULL_COMMAND "qhull d QJ Tv "
//#define QHULL_COMMAND "qhull d QJ "
// For sorting cluster maps based on size (descending)
class MSTCluster
{
public:
unsigned int map;
unsigned int size;
MSTCluster() { this->map = 0; this->size = 0; }
~MSTCluster() { }
inline MSTCluster& operator=(const MSTCluster& c)
{ this->map = c.map; this->size = c.size; return (*this); }
inline bool operator<(const MSTCluster& c) const
{ return this->size > c.size; }
};
QHullMSTClusteringProcess
::QHullMSTClusteringProcess()
{
m_NumberOfVertices = 0;
m_MSTEdges = 0;
m_NodeAverages = 0;
m_SortFlag = false;
}
QHullMSTClusteringProcess
::~QHullMSTClusteringProcess()
{
delete [] m_MSTEdges;
delete [] m_NodeAverages;
}
void
QHullMSTClusteringProcess
::SetInputVertices(const VertexList& vlist)
{
m_NumberOfVertices = vlist.GetSize();
delete [] m_MSTEdges;
delete [] m_NodeAverages;
if (m_NumberOfVertices == 0)
return;
unsigned int dim = vlist[0].size();
m_MSTEdges = new MSTEdge[m_NumberOfVertices-1];
m_NodeAverages = new float[m_NumberOfVertices];
// Compute Delaunay triangulation and insert it to heap
Heap<MSTEdge> delaunayHeap;
int curlong, totlong, exitcode;
char options [BUF_SIZE];
coordT *points;
facetT *facet;
vertexT *vertex, **vertexp;
// Allocate memory to store elements of the list
points = (coordT*) malloc((dim+1)*m_NumberOfVertices*sizeof(coordT));
// Store each coordinate in an array element
for (unsigned int k = 0; k < m_NumberOfVertices; k++)
{
VertexType v = vlist[k];
long pos = k*(dim+1);
#if 1
double sumS = 0;
for (unsigned int j = 0; j < dim; j++)
{
points[pos+j] = v[j];
sumS += v[j] * v[j];
}
points[pos+dim] = sumS;
#else
points[pos+dim] = 0.0;
#endif
}
// Call out to qhull library to compute DeLaunay triangulation
qh_init_A(stdin, stdout, stderr, 0, NULL);
exitcode= setjmp(qh errexit);
if (!exitcode)
{
// Add extra options here
strcpy(options, QHULL_COMMAND);
qh_initflags(options);
qh_setdelaunay(dim+1, m_NumberOfVertices, points);
qh_init_B(points, m_NumberOfVertices, dim+1, False);
qh_qhull();
qh_check_output();
long numfacets = 0;
FORALLfacets
{
if (!facet->upperdelaunay)
{
numfacets++;
}
}
// Insert DT edges to heap
FORALLfacets
{
if (!facet->upperdelaunay)
{
DynArray<unsigned int> ids;
ids.Allocate(dim+1);
FOREACHvertex_(facet->vertices)
{
ids.Append( qh_pointid(vertex->point) );
}
for (unsigned int s = 0; s < ids.GetSize(); s++)
for (unsigned int t = s+1; t < ids.GetSize(); t++)
{
MSTEdge e;
e.i = ids[s];
e.j = ids[t];
VertexType dij = vlist[e.i] - vlist[e.j];
e.dist = dij.squared_magnitude();
delaunayHeap.Insert(e);
}
}
}
}
// Free allocated memory
qh NOerrexit= True;
qh_freeqhull (False);
qh_memfreeshort (&curlong, &totlong);
free(points);
if (curlong || totlong)
{
std::cerr << "qhull internal warning (main): did not free " << totlong
<< "bytes of long memory (" << curlong << "pieces)" << std::endl;
throw "QHull error";
}
// Map vertex to set (tree) it belongs to, for cycle test
unsigned int* treeMap = new unsigned int[m_NumberOfVertices];
for (unsigned int i = 0; i < m_NumberOfVertices; i++)
treeMap[i] = i;
// Number of edges in MST
unsigned int edgeCount = 0;
// Build MST using Kruskal's algorithm
//
// Edges added in ascending order
while (!delaunayHeap.IsEmpty())
{
MSTEdge minEdge = delaunayHeap.ExtractMinimum();
unsigned int a = minEdge.i;
unsigned int b = minEdge.j;
unsigned int map1 = treeMap[a];
unsigned int map2 = treeMap[b];
// Skip if they belong to the same tree (will form cycle)
if (map1 == map2)
continue;
// Merge trees
for (unsigned int k = 0; k < m_NumberOfVertices; k++)
{
if (treeMap[k] == map2)
treeMap[k] = map1;
}
m_MSTEdges[edgeCount] = minEdge;
edgeCount++;
// See if a tree is formed already
if (edgeCount == (m_NumberOfVertices-1))
break;
}
delete [] treeMap;
if (edgeCount != (m_NumberOfVertices-1))
{
std::cerr << "MST construction failed, E != (V-1)" << std::endl;
throw "MST construction failed, E != (V-1)";
}
// Compute node averages
for (unsigned int k = 0; k < m_NumberOfVertices; k++)
m_NodeAverages[k] = 0.0;
unsigned int* countArray = new unsigned int[m_NumberOfVertices];
for (unsigned int k = 0; k < m_NumberOfVertices; k++)
countArray[k] = 0;
DynArray< DynArray<double> > nodeDistances;
nodeDistances.Allocate(m_NumberOfVertices+1);
for (unsigned int i = 0; i <= m_NumberOfVertices+1; i++)
{
DynArray<double> dlist;
nodeDistances.Append(dlist);
}
for (unsigned int k = 0; k < (m_NumberOfVertices-1); k++)
{
unsigned int a = m_MSTEdges[k].i;
unsigned int b = m_MSTEdges[k].j;
m_NodeAverages[a] += m_MSTEdges[k].dist;
countArray[a]++;
m_NodeAverages[b] += m_MSTEdges[k].dist;
countArray[b]++;
nodeDistances[a].Append(m_MSTEdges[k].dist);
nodeDistances[b].Append(m_MSTEdges[k].dist);
}
for (unsigned int k = 0; k < m_NumberOfVertices; k++)
{
// Use mean OR...
//if (countArray[k] != 0)
// m_NodeAverages[k] /= countArray[k];
// Median instead?
if (countArray[k] != 0)
m_NodeAverages[k] =
heapMedian(nodeDistances[k].GetRawArray(), nodeDistances[k].GetSize());
}
delete [] countArray;
}
unsigned int
QHullMSTClusteringProcess
::GetClusters(unsigned int* treeMap, float T)
{
// Get number of vertices and edges
unsigned int v = m_NumberOfVertices;
unsigned int e = v - 1;
// Allocate edge break flag array
unsigned char* breakArray = new unsigned char[e];
for (unsigned int k = 0; k < e; k++)
breakArray[k] = 0;
// Break edges
unsigned int numBroken = 0;
for (unsigned int i = 0; i < v; i++)
{
float thres = T * m_NodeAverages[i];
// Break the coinciding long edges
for (unsigned int k = 0; k < e; k++)
{
if (breakArray[k] != 0)
continue;
unsigned int a = m_MSTEdges[k].i;
unsigned int b = m_MSTEdges[k].j;
bool incident = (i == a) || (i == b);
// Never break zero length edges
if (incident && (m_MSTEdges[k].dist > thres))
{
breakArray[k] = 1;
numBroken++;
}
}
}
if (numBroken == 0)
{
std::cerr << "No edges broken" << std::endl;
delete [] breakArray;
// TODO: FIXME:
//return whole tree with same label
return 0;
}
// Figure out distinct trees, merge connected vertices
for (unsigned int k = 0; k < v; k++)
treeMap[k] = k;
for (unsigned int i = 0; i < v; i++)
{
unsigned int map1 = treeMap[i];
// Check incident edges
for (unsigned int j = 0; j < e; j++)
{
if (breakArray[j] != 0)
continue;
unsigned int a = m_MSTEdges[j].i;
unsigned int b = m_MSTEdges[j].j;
bool incident = (i == a) || (i == b);
if (!incident)
continue;
// Get the map of the other id
unsigned int map2 = treeMap[b];
if (i == b)
map2 = treeMap[a];
if (map1 == map2)
continue;
for (unsigned int k = 0; k < v; k++)
if (treeMap[k] == map2)
treeMap[k] = map1;
} // for neighbors
} // for i
delete [] breakArray;
if (!m_SortFlag)
return numBroken+1;
//
// Sort the cluster maps based on cluster size (descending)
// Cluster 0 is the largest cluster
//
// Obtain cluster info
MSTCluster* clusters = new MSTCluster[v];
unsigned int numNonZero = 0;
for (unsigned int i = 0; i < v; i++)
{
clusters[i].map = i;
unsigned int s = 0;
for (unsigned int j = 0; j < v; j++)
if (treeMap[j] == i)
s++;
if (s > 0)
numNonZero++;
clusters[i].size = s;
}
Heap<MSTCluster> heap;
heap.Allocate(numNonZero);
for (unsigned int i = 0; i < v; i++)
if (clusters[i].size != 0)
heap.Insert(clusters[i]);
delete [] clusters;
unsigned int* sortedMap = new unsigned int[v];
for (unsigned int i = 0; i < numNonZero; i++)
{
MSTCluster c = heap.ExtractMinimum();
unsigned int m = c.map;
for (unsigned int j = 0; j < v; j++)
if (treeMap[j] == m)
sortedMap[j] = i;
}
for (unsigned int i = 0; i < v; i++)
treeMap[i] = sortedMap[i];
delete [] sortedMap;
return numBroken+1;
}
| 8,954
| 3,493
|
#include "ProjHelperFun.h"
#include "Constants.h"
#include "TridagPar.h"
void updateParams(const unsigned g, const REAL alpha, const REAL beta, const REAL nu, PrivGlobs& globs)
{
// parallelizable directly since all reads and writes are independent.
// Degree of parallelism: myX.size*myY.size
// Access to myVarX and myVarY is already coalesced.
// TODO: Examine how tiling/shared memory can be used.
for(unsigned i=0;i<globs.myX.size();++i) // par
for(unsigned j=0;j<globs.myY.size();++j) { // par
globs.myVarX[i][j] = exp(2.0*( beta*log(globs.myX[i])
+ globs.myY[j]
- 0.5*nu*nu*globs.myTimeline[g] )
);
globs.myVarY[i][j] = exp(2.0*( alpha*log(globs.myX[i])
+ globs.myY[j]
- 0.5*nu*nu*globs.myTimeline[g] )
); // nu*nu
}
}
void setPayoff(const REAL strike, PrivGlobs& globs )
{
// Assuming globs is local the loop can be parallelized since
// - reads independent
// - writes independent (not same as read array)
// Problem in payoff. Can be put inline (scalar variable), but this results
// in myX.size*myY.size mem accesses.
// If array expansion, only myX.size+myY.size mem accesses.
// TODO: To be determined based on myX.size and myY.size.
// Small dataset= NUM_X = 32 ; NUM_Y = 256
// 8192 vs 288 -- array expansion is preferable.
// Array expansion **DONE.
REAL payoff[globs.myX.size()];
for(unsigned i=0;i<globs.myX.size();++i)
payoff[i] = max(globs.myX[i]-strike, (REAL)0.0);
// Already coalesced.
for(unsigned i=0;i<globs.myX.size();++i) { // par
for(unsigned j=0;j<globs.myY.size();++j) // par
globs.myResult[i][j] = payoff[i];
}
}
// inline void tridag(
// vector<REAL>& a, // size [n]
// const vector<REAL>& b, // size [n]
// const vector<REAL>& c, // size [n]
// const vector<REAL>& r, // size [n]
// const int n,
// vector<REAL>& u, // size [n]
// vector<REAL>& uu // size [n] temporary
// ) {
// int i, offset;
// REAL beta;
//
// u[0] = r[0];
// uu[0] = b[0];
//
// // Can be parallelized by rewriting the loop into a series of scans on u and uu.
//
// /*
// for(i=1; i<n; i++) { // seq
// beta = a[i] / uu[i-1];
// uu[i] = b[i] - beta*c[i-1]; // uu[i] = b[i] - (a[i] / uu[i-1])*c[i-1] = b[i] - a[i]*c[i-1] / uu[i-1]
// u[i] = r[i] - beta*u[i-1]; // u[i] = r[i] - (a[i] / uu[i-1])*u[i-1]
// }
// */
//
// /*
// uu = - a*c
// uu' = b*uu''[-1]
//
// scanInc (/) head(uu)^2 uu
// */
// uu = vector<REAL>(b); //wrong
// for(i=1; i<n; i++) {
// uu[i] = uu[i] - a[i]*c[i-1];
// }
// scanIncDiv(uu[0]*uu[0], &uu); //id, array
//
// /*
// u = r
// uu' = [0] ++ u //do same for uu.....
// u = u - a / uu'
// - (a[i] / uu[i-1])*u[i-1]
//
// scanInc (*) 1 u
// */
// for(i=1; i<n; i++) {
//
// }
//
// #if 0
// // X) this is a backward recurrence
// u[n-1] = u[n-1] / uu[n-1];
//
// // Can be parallelized by rewriting the loop into a series of scans.
// for(i=n-2; i>=0; i--) { // seq
// u[i] = (u[i] - c[i]*u[i+1]) / uu[i];
// }
// #else
// // Hint: X) can be written smth like (once you make a non-constant)
// for(i=0; i<n; i++) // TODO: par
// a[i] = u[n-1-i]; // a = reverse u
//
// a[0] = a[0] / uu[n-1];
//
// // tridag can be re-written in terms of scans with 2x2 matrix multiplication and
// // linear function composition, as we shall discuss in class.
// for(i=1; i<n; i++) // TODO: Make it a scan bro.
// a[i] = (a[i] - c[n-1-i]*a[i-1]) / uu[n-1-i];
// //a[i] = (a[i] - c[n-1-i]*a[i-1]) / uu[n-1-i];
//
// for(i=0; i<n; i++) // TODO: par
// u[i] = a[n-1-i]; // u = reverse a
// #endif
// }
void
rollback( const unsigned g, PrivGlobs& globs ) {
unsigned numX = globs.myX.size(),
numY = globs.myY.size();
unsigned numZ = max(numX,numY);
unsigned i, j;
REAL dtInv = 1.0/(globs.myTimeline[g+1]-globs.myTimeline[g]);
vector<vector<REAL> > u(numY, vector<REAL>(numX)); // [numY][numX]
vector<vector<REAL> > uT(numX, vector<REAL>(numY)); // [numX][numY]
vector<vector<REAL> > v(numX, vector<REAL>(numY)); // [numX][numY]
//vector<REAL> a(numZ), b(numZ), c(numZ), y(numZ); // [max(numX,numY)]
//vector<REAL> y(numZ);
vector<vector<REAL> > y(numX, vector<REAL>(numZ)); // [numX][numZ]
vector<REAL> yy(numZ); // temporary used in tridag // [max(numX,numY)]
// explicit x
// parallelizable directly since all reads and writes are independent.
// Degree of parallelism: numX*numY.
// TODO: Examine how tiling/shared memory can be used on globs (.myResult).
// Reads are coalosced but writes are not.
// TODO: Coalesced access via matrix transposition of u/uT. **DONE
for(i=0;i<numX;i++) { //par
for(j=0;j<numY;j++) { //par
//TODO: This can be combined in the tridag kernel, in shared mem.
uT[i][j] = dtInv*globs.myResult[i][j];
if(i > 0) {
uT[i][j] += 0.5*( 0.5*globs.myVarX[i][j]*globs.myDxx[i][0] )
* globs.myResult[i-1][j];
}
uT[i][j] += 0.5*( 0.5*globs.myVarX[i][j]*globs.myDxx[i][1] )
* globs.myResult[i][j];
if(i < numX-1) {
uT[i][j] += 0.5*( 0.5*globs.myVarX[i][j]*globs.myDxx[i][2] )
* globs.myResult[i+1][j];
}
}
}
// explicit y
// parallelizable directly since all reads and writes are independent.
// Degree of parallelism: numY*numX.
// TODO: Examine how tiling/shared memory can be used on globs (.myResult).
// and u.?
// Reads are coalosced but writes are not.
// TODO: Coalesced access via matrix transposition.
// TODO: Interchange loop. **DONE
// Loop interchanged, u transposed used here also, further utilizing the
// time used on allocation.
// Loop interchange chosen over matrix transposition, as then both
// v, globs.myVarY and globs.myResult would have to be transposed (i.e.
// mem allocation and computation time on transposition), and we deem this
// overhead greater than that of globs.myDyy non-coalesced mem access (which
// can be avoided in transposition).
for(i=0;i<numX;i++) { //par
for(j=0;j<numY;j++) { //par
//TODO: This can be combined in the tridag kernel too, as parameters.
v[i][j] = 0.0;
if(j > 0) {
v[i][j] += ( 0.5*globs.myVarY[i][j]*globs.myDyy[j][0] )
* globs.myResult[i][j-1];
}
v[i][j] += ( 0.5*globs.myVarY[i][j]*globs.myDyy[j][1] )
* globs.myResult[i][j];
if(j < numY-1) {
v[i][j] += ( 0.5*globs.myVarY[i][j]*globs.myDyy[j][2] )
* globs.myResult[i][j+1];
}
uT[i][j] += v[i][j];
}
}
transpose(uT, &u, numY, numX);
vector<vector<REAL> > a(numY, vector<REAL>(numZ)), b(numY, vector<REAL>(numZ)), c(numY, vector<REAL>(numZ)); // [max(numX,numY)]
vector<vector<REAL> > aT(numZ, vector<REAL>(numY)), bT(numZ, vector<REAL>(numY)), cT(numZ, vector<REAL>(numY));
// implicit x
// ASSUMING tridag is independent.
// parallelizable directly since all reads and writes are independent.
// Degree of parallelism: numY*numX.
// TODO: MyDxx and myVarX is not coalesced. **DONE
/*
for(j=0;j<numY;j++) { // par
// parallelizable via loop distribution / array expansion.
for(i=0;i<numX;i++) { // par // here a, b,c should have size [numX]
a[i] = - 0.5*(0.5*globs.myVarX[i][j]*globs.myDxx[i][0]);
b[i] = dtInv - 0.5*(0.5*globs.myVarX[i][j]*globs.myDxx[i][1]);
c[i] = - 0.5*(0.5*globs.myVarX[i][j]*globs.myDxx[i][2]);
}
// here yy should have size [numX]
tridag(a,b,c,u[j],numX,u[j],yy);
} */
// parallelizable via loop distribution / array expansion.
for(i=0;i<numX;i++) { // par // here a, b,c should have size [numX]
for(j=0;j<numY;j++) { // par
aT[i][j] = - 0.5*(0.5*globs.myVarX[i][j]*globs.myDxx[i][0]);
bT[i][j] = dtInv - 0.5*(0.5*globs.myVarX[i][j]*globs.myDxx[i][1]);
cT[i][j] = - 0.5*(0.5*globs.myVarX[i][j]*globs.myDxx[i][2]);
}
}
transpose(aT, &a, numY, numZ);
transpose(bT, &b, numY, numZ);
transpose(cT, &c, numY, numZ);
for(j=0;j<numY;j++) { // par
// here yy should have size [numX]
tridagPar(&a[j][0],&b[j][0],&c[j][0],&u[j][0],numX,&u[j][0],&yy[0]);
}
// implicit y
// ASSUMING tridag is independent.
// parallelizable directly since all reads and writes are independent.
// Degree of parallelism: numY*numX.
// TODO: transpose myDyy and u for coalesced access. **DONE
// **DONE loop distributed (tridag part), uT mem reused (refilled with u),
// loop interchanged for mem colesced access, a,b,c matrices reused from
// prev allocation; used via matrix trandposition.
// myDyy is still not coalesced, same arguments as previus loop.
for(i=0;i<numX;i++) { // par
// parallelizable via loop distribution / array expansion.
for(j=0;j<numY;j++) { // par // here a, b, c should have size [numY]
aT[i][j] = - 0.5*(0.5*globs.myVarY[i][j]*globs.myDyy[j][0]);
bT[i][j] = dtInv - 0.5*(0.5*globs.myVarY[i][j]*globs.myDyy[j][1]);
cT[i][j] = - 0.5*(0.5*globs.myVarY[i][j]*globs.myDyy[j][2]);
}
}
transpose(aT, &a, numY, numZ);
transpose(bT, &b, numY, numZ);
transpose(cT, &c, numY, numZ);
transpose(u, &uT, numX, numY); //Must retranspose to uT because prev tridag
// modified u.
// Coalesced memory acces.
for(i=0;i<numX;i++) { // par
for(j=0;j<numY;j++) { // par
y[i][j] = dtInv * uT[i][j] - 0.5*v[i][j];
}
}
for(i=0;i<numX;i++) { // par
// here yy should have size [numX]
tridagPar(&aT[i][0],&bT[i][0],&cT[i][0],&y[i][0],numY,&globs.myResult[i][0],&yy[0]);
}
}
REAL value( PrivGlobs globs,
const REAL s0,
const REAL strike,
const REAL t,
const REAL alpha,
const REAL nu,
const REAL beta,
const unsigned int numX,
const unsigned int numY,
const unsigned int numT
) {
initGrid(s0,alpha,nu,t, numX, numY, numT, globs);
initOperator(globs.myX,globs.myDxx);
initOperator(globs.myY,globs.myDyy);
setPayoff(strike, globs);
// globs is global and cannot be privatized thus this loop cannot be
// parallelized yet.
// If updateParams and rollback is independent on i and globs, loop can be
// parallelized by privatization of initGrid, initOperator and setPayoff calls.
// If they write indepedently to globs, privatization is not needed.
for(int i = globs.myTimeline.size()-2;i>=0;--i) // seq, based on num_T indirectly.
{
updateParams(i,alpha,beta,nu,globs); // Updates all values in globs.myVarX and globs.myVarY. So not independent.
rollback(i, globs);
}
return globs.myResult[globs.myXindex][globs.myYindex];
}
void run_GPU(
const unsigned int& outer,
const unsigned int& numX,
const unsigned int& numY,
const unsigned int& numT,
const REAL& s0,
const REAL& t,
const REAL& alpha,
const REAL& nu,
const REAL& beta,
REAL* res // [outer] RESULT
) {
/*
// Outerloop - Technically parallelizable, but restricts further
// parallization further in.
// If strike and globs is privatized, the loop can be parallelized.
// Value is the limiting factor since most of the actual work is deeper in
// the function.
// Sequential loop (value) in between parallel loops (this loop).
// Move seq to outer loop via array expansion (globs) and distribution.
#pragma omp parallel for default(shared) schedule(static) if(outer>8)
for( unsigned i = 0; i < outer; ++ i ) {
REAL strike = 0.001*i;
PrivGlobs globs(numX, numY, numT);
res[i] = value( globs, s0, strike, t,
alpha, nu, beta,
numX, numY, numT );
}*/
// globs array expanded. Init moved to individual parallel loop
vector<PrivGlobs> globs(outer, PrivGlobs(numX, numY, numT));
#pragma omp parallel for default(shared) schedule(static) if(outer>8)
for( unsigned i = 0; i < outer; ++ i ) { //par
initGrid(s0,alpha,nu,t, numX, numY, numT, globs[i]);
initOperator(globs[i].myX,globs[i].myDxx);
initOperator(globs[i].myY,globs[i].myDyy);
REAL strike = 0.001*i;
setPayoff(strike, globs[i]);
}
// sequential loop distributed.
for(int i = numT-2;i>=0;--i){ //seq
// inner loop parallel on each outer (par) instead of each time step (seq).
#pragma omp parallel for default(shared) schedule(static) if(outer>8)
for( unsigned j = 0; j < outer; ++ j ) { //par
updateParams(i,alpha,beta,nu,globs[j]);
rollback(i, globs[j]);
}
}
// parallel assignment of results.
#pragma omp parallel for default(shared) schedule(static) if(outer>8)
for( unsigned j = 0; j < outer; ++ j ) { //par
res[j] = globs[j].myResult[globs[j].myXindex][globs[j].myYindex];
}
}
//#endif // PROJ_CORE_ORIG
| 14,193
| 5,470
|
/*
* 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
*
*/
#include <SkinnedMeshExampleComponent.h>
#include <SampleComponentManager.h>
#include <SampleComponentConfig.h>
#include <Automation/ScriptableImGui.h>
#include <Atom/Feature/SkinnedMesh/SkinnedMeshInputBuffers.h>
#include <Atom/Component/DebugCamera/NoClipControllerComponent.h>
#include <Atom/Component/DebugCamera/NoClipControllerBus.h>
#include <AzCore/Script/ScriptTimePoint.h>
#include <Atom/RPI.Public/View.h>
#include <Atom/RPI.Public/Image/StreamingImage.h>
#include <Atom/RPI.Reflect/Asset/AssetUtils.h>
#include <Atom/RPI.Reflect/Model/ModelAsset.h>
#include <Atom/RPI.Reflect/Material/MaterialAsset.h>
#include <RHI/BasicRHIComponent.h>
namespace AtomSampleViewer
{
void SkinnedMeshExampleComponent::Reflect(AZ::ReflectContext* context)
{
if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
{
serializeContext->Class < SkinnedMeshExampleComponent, AZ::Component>()
->Version(0)
;
}
}
void SkinnedMeshExampleComponent::Activate()
{
CreateSkinnedMeshContainer();
m_skinnedMeshContainer->SetActiveSkinnedMeshCount(1);
AZ::TickBus::Handler::BusConnect();
m_imguiSidebar.Activate();
ConfigureCamera();
AddImageBasedLight();
}
void SkinnedMeshExampleComponent::CreatePlaneObject()
{
auto meshAsset = AZ::RPI::AssetUtils::GetAssetByProductPath<AZ::RPI::ModelAsset>("objects/plane.azmodel");
m_planeMeshHandle = GetMeshFeatureProcessor()->AcquireMesh(AZ::Render::MeshHandleDescriptor{ meshAsset });
GetMeshFeatureProcessor()->SetTransform(m_planeMeshHandle, AZ::Transform::CreateIdentity());
}
void SkinnedMeshExampleComponent::Deactivate()
{
m_skinnedMeshContainer = nullptr;
AZ::TickBus::Handler::BusDisconnect();
m_imguiSidebar.Deactivate();
GetMeshFeatureProcessor()->ReleaseMesh(m_planeMeshHandle);
m_defaultIbl.Reset();
}
void SkinnedMeshExampleComponent::AddImageBasedLight()
{
m_defaultIbl.Init(m_scene);
}
void SkinnedMeshExampleComponent::ConfigureCamera()
{
AZ::Debug::CameraControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::CameraControllerRequestBus::Events::Enable,
azrtti_typeid<AZ::Debug::NoClipControllerComponent>());
AZ::Debug::NoClipControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::NoClipControllerRequestBus::Events::SetPosition, AZ::Vector3(0.0f, -1.0f, 1.0f));
AZ::Debug::NoClipControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::NoClipControllerRequestBus::Events::SetPitch, -0.8f);
}
void SkinnedMeshExampleComponent::OnTick(float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint timePoint)
{
m_runTime += deltaTime;
DrawSidebar();
if (!m_useFixedTime)
{
m_skinnedMeshContainer->UpdateAnimation(m_runTime, m_useOutOfSyncBoneAnimation);
}
if (m_drawBones)
{
m_skinnedMeshContainer->DrawBones();
}
}
void SkinnedMeshExampleComponent::DrawSidebar()
{
if (!m_imguiSidebar.Begin())
{
return;
}
SkinnedMeshConfig config = m_skinnedMeshContainer->GetSkinnedMeshConfig();
bool configWasModified = false;
// Imgui limits slider range to half the natural range of the type
float segmentCountFloat = static_cast<float>(config.m_segmentCount);
configWasModified |= ScriptableImGui::SliderFloat("Segments Per-Mesh", &segmentCountFloat, 2.0f, 2048.0f, "%.0f", ImGuiSliderFlags_Logarithmic);
configWasModified |= ScriptableImGui::SliderInt("Vertices Per-Segment", &config.m_verticesPerSegment, 4, 2048);
configWasModified |= ScriptableImGui::SliderInt("Bones Per-Mesh", &config.m_boneCount, 4, 256);
configWasModified |= ScriptableImGui::SliderInt("Influences Per-Vertex", &config.m_influencesPerVertex, 4, 4);
configWasModified |= ScriptableImGui::SliderInt("Sub-mesh count", &config.m_subMeshCount, 1, 128);
if (configWasModified)
{
config.m_segmentCount = static_cast<int>(segmentCountFloat);
m_skinnedMeshContainer->SetSkinnedMeshConfig(config);
}
bool animationWasModified = configWasModified;
animationWasModified |= ScriptableImGui::Checkbox("Use Fixed Animation Time", &m_useFixedTime);
animationWasModified |= ScriptableImGui::SliderFloat("Fixed Animation Time", &m_fixedAnimationTime, 0.0f, 20.0f);
animationWasModified |= ScriptableImGui::Checkbox("Use Out of Sync Bone Animation", &m_useOutOfSyncBoneAnimation);
if (m_useFixedTime && animationWasModified)
{
m_skinnedMeshContainer->UpdateAnimation(m_fixedAnimationTime, m_useOutOfSyncBoneAnimation);
}
ScriptableImGui::Checkbox("Draw bones", &m_drawBones);
m_imguiSidebar.End();
}
void SkinnedMeshExampleComponent::CreateSkinnedMeshContainer()
{
const auto skinnedMeshFeatureProcessor = m_scene->GetFeatureProcessor<AZ::Render::SkinnedMeshFeatureProcessorInterface>();
const auto meshFeatureProcessor = m_scene->GetFeatureProcessor<AZ::Render::MeshFeatureProcessorInterface>();
// Default settings for the sample
SkinnedMeshConfig config;
config.m_segmentCount = 10;
config.m_verticesPerSegment = 7;
config.m_boneCount = 4;
config.m_influencesPerVertex = 4;
m_skinnedMeshContainer = AZStd::make_unique<SkinnedMeshContainer>(skinnedMeshFeatureProcessor, meshFeatureProcessor, config);
}
}
| 5,911
| 1,883
|
#include "InAreaSearchSession.h"
#include "InAreaSearchSession_P.h"
OsmAnd::InAreaSearchSession::InAreaSearchSession(const QList< std::shared_ptr<const ISearchEngine::IDataSource> >& dataSources)
: BaseSearchSession(new InAreaSearchSession_P(this), dataSources)
, _p(std::static_pointer_cast<InAreaSearchSession_P>(BaseSearchSession::_p.shared_ptr()))
{
}
OsmAnd::InAreaSearchSession::~InAreaSearchSession()
{
}
void OsmAnd::InAreaSearchSession::setArea(const AreaI64& area)
{
_p->setArea(area);
}
OsmAnd::AreaI64 OsmAnd::InAreaSearchSession::getArea() const
{
return _p->getArea();
}
| 605
| 217
|
// --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2018.
//
// This software is released under a three-clause BSD license:
// * 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 any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// 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 ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS 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.
//
// --------------------------------------------------------------------------
// $Maintainer: Samuel Wein $
// $Authors: Samuel Wein, Timo Sachsenberg, Hendrik Weisser $
// --------------------------------------------------------------------------
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/CHEMISTRY/NASequence.h>
#include <OpenMS/CHEMISTRY/RibonucleotideDB.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/CONCEPT/Macros.h>
#include <map>
#include <string>
using namespace std;
namespace OpenMS
{
NASequence::NASequence(vector<const Ribonucleotide*> seq,
const RibonucleotideChainEnd* five_prime,
const RibonucleotideChainEnd* three_prime)
{
seq_ = seq;
five_prime_ = five_prime;
three_prime_ = three_prime;
}
bool NASequence::operator==(const NASequence& rhs) const
{
return (tie(seq_, five_prime_, three_prime_) ==
tie(rhs.seq_, rhs.five_prime_, rhs.three_prime_));
}
bool NASequence::operator!=(const NASequence& rhs) const
{
return !(operator==(rhs));
}
bool NASequence::operator<(const NASequence& rhs) const
{
// can't use std::tie here as we might prefer sorting by string instead of pointer address
// compare 5' mod
if (five_prime_ != rhs.five_prime_) return (five_prime_ < rhs.five_prime_);
// compare sequence length
if (seq_.size() != rhs.seq_.size()) return (seq_.size() < rhs.seq_.size());
// compare pointers. If different, we compare the more expensive code (string)
for (size_t i = 0; i != seq_.size(); ++i)
{
if (seq_[i] != rhs.seq_[i])
{
return (seq_[i]->getCode() < rhs.seq_[i]->getCode());
}
}
// compare 3' mod
if (three_prime_ != rhs.three_prime_)
{
return (three_prime_ < rhs.three_prime_);
}
// exactly equal
return false;
}
void NASequence::setSequence(const vector<const Ribonucleotide*>& seq)
{
seq_ = seq;
}
bool NASequence::empty() const
{
return seq_.empty();
}
NASequence NASequence::getPrefix(Size length) const
{
if (length >= seq_.size())
{
throw Exception::IndexOverflow(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
length, seq_.size() - 1);
}
return NASequence({seq_.begin(), seq_.begin() + length}, five_prime_, nullptr);
}
NASequence NASequence::getSuffix(Size length) const
{
if (length >= seq_.size())
{
throw Exception::IndexOverflow(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
length, seq_.size() - 1);
}
return NASequence({seq_.end() - length, seq_.end()}, nullptr, three_prime_);
}
NASequence NASequence::getSubsequence(Size start, Size length) const
{
if (start >= size())
{
throw Exception::IndexOverflow(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, start, size());
}
if (length > size() - start) length = size() - start;
const RibonucleotideChainEnd* five_prime = ((start == 0) ? five_prime_ :
nullptr);
const RibonucleotideChainEnd* three_prime = ((start + length == size()) ?
three_prime_ : nullptr);
vector<const Ribonucleotide*>::const_iterator it = seq_.begin() + start;
return NASequence({it, it + length}, five_prime, three_prime);
}
EmpiricalFormula NASequence::getFormula(NASFragmentType type, Int charge) const
{
static const EmpiricalFormula H_form = EmpiricalFormula("H");
static const EmpiricalFormula internal_to_full = EmpiricalFormula("H2O");
// static const EmpiricalFormula five_prime_to_full = EmpiricalFormula("HPO3");
// static const EmpiricalFormula three_prime_to_full = EmpiricalFormula("");
static const EmpiricalFormula a_ion_to_full = EmpiricalFormula("H-2O-1");
static const EmpiricalFormula b_ion_to_full = EmpiricalFormula("");
static const EmpiricalFormula c_ion_to_full = EmpiricalFormula("H-1PO2");
static const EmpiricalFormula d_ion_to_full = EmpiricalFormula("HPO3");
static const EmpiricalFormula w_ion_to_full = EmpiricalFormula("HPO3");
static const EmpiricalFormula x_ion_to_full = EmpiricalFormula("H-1PO2");
static const EmpiricalFormula y_ion_to_full = EmpiricalFormula("");
static const EmpiricalFormula z_ion_to_full = EmpiricalFormula("H-2O-1");
static const EmpiricalFormula aminusB_ion_to_full = EmpiricalFormula("H-4O-2");
static const EmpiricalFormula phosphate_form = EmpiricalFormula("HPO3");
// static const EmpiricalFormula abasicform_RNA = EmpiricalFormula("C5H8O4");
// static const EmpiricalFormula abasicform_DNA = EmpiricalFormula("C5H7O5P");
if (seq_.empty()) return EmpiricalFormula();
EmpiricalFormula our_form;
// Add all the ribonucleotide masses
for (const auto& i : seq_)
{
our_form += i->getFormula();
}
// phosphates linking nucleosides:
our_form += (phosphate_form - internal_to_full) * (seq_.size() - 1);
EmpiricalFormula local_three_prime, local_five_prime;
// Make local copies of the formulas for the terminal mods so we don't get into trouble dereferencing nullptrs
if (three_prime_ != nullptr)
{
local_three_prime = three_prime_->getFormula() - H_form;
}
if (five_prime_ != nullptr)
{
local_five_prime = five_prime_->getFormula() - H_form;
}
switch (type)
{
case Full:
return our_form + (H_form * charge) + local_five_prime + local_three_prime;
// case FivePrime:
// return our_form - five_prime_to_full + OH_form + (H_form * charge) + local_three_prime;
case AminusB:
return our_form + (H_form * charge) + local_five_prime + aminusB_ion_to_full - seq_.back()->getFormula() + seq_.back()->getBaselossFormula();
case AIon:
return our_form + (H_form * charge) + local_five_prime + a_ion_to_full;
case BIon:
return our_form + (H_form * charge) + local_five_prime + b_ion_to_full;
case CIon:
return our_form + (H_form * charge) + local_five_prime + c_ion_to_full;
case DIon:
return our_form + (H_form * charge) + local_five_prime + d_ion_to_full;
case WIon:
return our_form + (H_form * charge) + local_three_prime + w_ion_to_full;
case XIon:
return our_form + (H_form * charge) + local_three_prime + x_ion_to_full;
case YIon:
return our_form + (H_form * charge) + local_three_prime + y_ion_to_full;
case ZIon:
return our_form + (H_form * charge) + local_three_prime + z_ion_to_full;
default:
OPENMS_LOG_ERROR << "NASequence::getFormula: unsupported NASFragmentType" << endl;
}
return our_form;
}
void NASequence::set(size_t index, const Ribonucleotide* r)
{
seq_[index] = r;
}
bool NASequence::hasFivePrimeMod() const
{
return (five_prime_ != nullptr);
}
void NASequence::setFivePrimeMod(const RibonucleotideChainEnd* r)
{
five_prime_= r;
}
const RibonucleotideChainEnd* NASequence::getFivePrimeMod() const
{
return five_prime_;
}
bool NASequence::hasThreePrimeMod() const
{
return (three_prime_ != nullptr);
}
void NASequence::setThreePrimeMod(const RibonucleotideChainEnd* r)
{
three_prime_= r;
}
const RibonucleotideChainEnd* NASequence::getThreePrimeMod() const
{
return three_prime_;
}
double NASequence::getMonoWeight(NASFragmentType type, Int charge) const
{
return getFormula(type, charge).getMonoWeight();
}
double NASequence::getAverageWeight(NASFragmentType type, Int charge) const
{
return getFormula(type, charge).getAverageWeight();
}
size_t NASequence::size() const
{
return seq_.size();
}
NASequence NASequence::fromString(const char* s)
{
NASequence nas;
parseString_(String(s), nas);
return nas;
}
NASequence NASequence::fromString(const String& s)
{
NASequence nas;
parseString_(s, nas);
return nas;
}
string NASequence::toString() const
{
string s;
if (five_prime_)
{
const String& code = five_prime_->getCode();
if (code == "5'-p")
{
s = "p";
}
else
{
s = "[" + code + "]";
}
}
for (const auto& r : seq_)
{
const String& code = r->getCode();
if (code.size() == 1)
{
s += code;
}
else
{
s += "[" + code + "]"; // add brackets around non-standard ribos
}
}
if (three_prime_)
{
const String& code = three_prime_->getCode();
if (code == "3'-p")
{
s += "p";
}
else
{
s += "[" + code + "]";
}
}
return s;
}
void NASequence::clear()
{
seq_.clear();
three_prime_ = nullptr;
five_prime_ = nullptr;
}
void NASequence::parseString_(const String& s, NASequence& nas)
{
nas.clear();
if (s.empty()) return;
static RibonucleotideDB* rdb = RibonucleotideDB::getInstance();
String::ConstIterator str_it = s.begin();
if (*str_it == 'p') // special case for 5' phosphate
{
nas.setFivePrimeMod(rdb->getRibonucleotide("5'-p"));
++str_it;
}
String::ConstIterator stop = s.end();
if ((s.size() > 1) && (s.back() == 'p')) // special case for 3' phosphate
{
nas.setThreePrimeMod(rdb->getRibonucleotide("3'-p"));
--stop;
}
for (; str_it != stop; ++str_it)
{
// skip spaces
if (*str_it == ' ') continue;
// default case: add unmodified, standard ribonucleotide
if (*str_it != '[')
{
try
{
ConstRibonucleotidePtr r = rdb->getRibonucleotide(string(1, *str_it));
nas.seq_.push_back(r);
}
catch (Exception::ElementNotFound)
{
String msg = "Cannot convert string to nucleic acid sequence: invalid character '" + String(*str_it) + "'";
throw Exception::ParseError(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, s, msg);
}
}
else // if (*str_it == '[') // non-standard ribonucleotide
{
// parse modified ribonucleotide and add it to the sequence:
str_it = parseMod_(str_it, s, nas);
}
}
}
String::ConstIterator NASequence::parseMod_(
const String::ConstIterator str_it, const String& str, NASequence& nas)
{
static RibonucleotideDB* rdb = RibonucleotideDB::getInstance();
OPENMS_PRECONDITION(*str_it == '[', "Modification must start with '['.");
String::ConstIterator mod_start(str_it);
String::ConstIterator mod_end(++mod_start);
while ((mod_end != str.end()) && (*mod_end != ']')) ++mod_end; // advance to closing bracket
string mod(mod_start, mod_end);
if (mod_end == str.end())
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, str, "Cannot convert string to modified ribonucleotide: missing ']'");
}
ConstRibonucleotidePtr r = rdb->getRibonucleotide(mod);
// @TODO: check if position is actually 5'/3' and there's no mod already
if (r->getTermSpecificity() == Ribonucleotide::FIVE_PRIME)
{
nas.setFivePrimeMod(r);
}
else if (r->getTermSpecificity() == Ribonucleotide::THREE_PRIME)
{
nas.setThreePrimeMod(r);
}
else
{
nas.seq_.push_back(r);
}
return mod_end;
}
OPENMS_DLLAPI ostream& operator<<(ostream& os, const NASequence& seq)
{
return (os << seq.toString());
}
}
| 13,491
| 4,636
|
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef SORALOG_FALLBACKCONFIGURATOR
#define SORALOG_FALLBACKCONFIGURATOR
#include <soralog/configurator.hpp>
#include <soralog/logging_system.hpp>
namespace soralog {
/**
* @class FallbackConfigurator
* @brief Fallback configurator of Logging System. Creates just one sink (to
* console) and default group '*'. Constructor accepts detalisation level and
* flag to shitch on color in console
*/
class FallbackConfigurator : public Configurator {
public:
explicit FallbackConfigurator(Level level = Level::INFO,
bool with_color = false)
: level_(level), with_color_(with_color) {}
~FallbackConfigurator() override = default;
Result applyOn(LoggingSystem &system) const override;
private:
Level level_ = Level::INFO;
bool with_color_ = false;
};
} // namespace soralog
#endif // SORALOG_FALLBACKCONFIGURATOR
| 1,008
| 329
|
/// @ref core
/// @file glm/ext/vector_uint2_precision.hpp
#pragma once
#include "../detail/type_vec2.hpp"
namespace glm {
/// @addtogroup core_vector_precision
/// @{
/// 2 components vector of high qualifier unsigned integer numbers.
///
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.5 Vectors</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.7.2 Precision Qualifier</a>
typedef vec<2, unsigned int, highp> highp_uvec2;
/// 2 components vector of medium qualifier unsigned integer numbers.
///
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.5 Vectors</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.7.2 Precision Qualifier</a>
typedef vec<2, unsigned int, mediump> mediump_uvec2;
/// 2 components vector of low qualifier unsigned integer numbers.
///
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.5 Vectors</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.7.2 Precision Qualifier</a>
typedef vec<2, unsigned int, lowp> lowp_uvec2;
/// @}
}//namespace glm
| 1,484
| 583
|
/**************************************************************
*
* 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.
*
*************************************************************/
#ifndef INCLUDED_SVGIO_SVGREADER_SVGDOCUMENTHANDLER_HXX
#define INCLUDED_SVGIO_SVGREADER_SVGDOCUMENTHANDLER_HXX
#include <svgio/svgiodllapi.h>
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#include <svgio/svgreader/svgdocument.hxx>
//////////////////////////////////////////////////////////////////////////////
// predefines
namespace svgio { namespace svgreader { class SvgCharacterNode; }}
//////////////////////////////////////////////////////////////////////////////
namespace svgio
{
namespace svgreader
{
class SvgDocHdl : public cppu::WeakImplHelper1< com::sun::star::xml::sax::XDocumentHandler >
{
private:
// the complete SVG Document
SvgDocument maDocument;
// current node for parsing
SvgNode* mpTarget;
// text collector string stack for css styles
std::vector< rtl::OUString > maCssContents;
public:
SvgDocHdl(const rtl::OUString& rAbsolutePath);
~SvgDocHdl();
// Methods XDocumentHandler
virtual void SAL_CALL startDocument( ) throw (com::sun::star::xml::sax::SAXException, com::sun::star::uno::RuntimeException);
virtual void SAL_CALL endDocument( ) throw (com::sun::star::xml::sax::SAXException, com::sun::star::uno::RuntimeException);
virtual void SAL_CALL startElement( const ::rtl::OUString& aName, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttribs ) throw (com::sun::star::xml::sax::SAXException, com::sun::star::uno::RuntimeException);
virtual void SAL_CALL endElement( const ::rtl::OUString& aName ) throw (com::sun::star::xml::sax::SAXException, com::sun::star::uno::RuntimeException);
virtual void SAL_CALL characters( const ::rtl::OUString& aChars ) throw (com::sun::star::xml::sax::SAXException, com::sun::star::uno::RuntimeException);
virtual void SAL_CALL ignorableWhitespace( const ::rtl::OUString& aWhitespaces ) throw (com::sun::star::xml::sax::SAXException, com::sun::star::uno::RuntimeException);
virtual void SAL_CALL processingInstruction( const ::rtl::OUString& aTarget, const ::rtl::OUString& aData ) throw (com::sun::star::xml::sax::SAXException, com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setDocumentLocator( const com::sun::star::uno::Reference< com::sun::star::xml::sax::XLocator >& xLocator ) throw (com::sun::star::xml::sax::SAXException, com::sun::star::uno::RuntimeException);
const SvgDocument& getSvgDocument() const { return maDocument; }
};
} // end of namespace svgreader
} // end of namespace svgio
//////////////////////////////////////////////////////////////////////////////
#endif //INCLUDED_SVGIO_SVGREADER_SVGDOCUMENTHANDLER_HXX
// eof
| 3,829
| 1,108
|
/*!
* Parts of this software are based on cryptocoinjs/secp256k1-node:
*
* https://github.com/cryptocoinjs/secp256k1-node
*
* The MIT License (MIT)
*
* Copyright (c) 2014-2016 secp256k1-node contributors
*
* Parts of this software are based on bn.js, elliptic, hash.js
* Copyright (c) 2014-2016 Fedor Indutny
*
* 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.
*
* Parts of this software are based on bitcoin-core/secp256k1:
*
* https://github.com/bitcoin-core/secp256k1
*
* Copyright (c) 2013 Pieter Wuille
*
* 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 <node.h>
#include <nan.h>
#include <memory>
#include "secp256k1.h"
#include "secp256k1/include/secp256k1.h"
#include "secp256k1/include/secp256k1_ecdh.h"
#include "secp256k1/include/secp256k1_recovery.h"
#include "secp256k1/include/secp256k1_schnorrleg.h"
#include "secp256k1/include/secp256k1_elligator.h"
#include "secp256k1/include/secp256k1_extra.h"
#include "secp256k1/contrib/lax_der_privatekey_parsing.h"
#include "secp256k1/contrib/lax_der_parsing.h"
#define ALLOCATION_FAILURE "allocation failed"
#define RANDOMIZATION_FAILURE "randomization failed"
#define COMPRESSED_TYPE_INVALID "compressed must be a boolean"
#define EC_PRIVATE_KEY_TYPE_INVALID "private key must be a Buffer"
#define EC_PRIVATE_KEY_LENGTH_INVALID "private key length is invalid"
#define EC_PRIVATE_KEY_RANGE_INVALID "private key range is invalid"
#define EC_PRIVATE_KEY_TWEAK_ADD_FAIL \
"tweak out of range or resulting private key is invalid"
#define EC_PRIVATE_KEY_TWEAK_MUL_FAIL "tweak out of range"
#define EC_PRIVATE_KEY_EXPORT_FAIL "couldn't export private key"
#define EC_PRIVATE_KEY_IMPORT_FAIL "couldn't import private key"
#define EC_PUBLIC_KEYS_TYPE_INVALID "public keys must be an Array"
#define EC_PUBLIC_KEYS_LENGTH_INVALID \
"public keys Array must have at least 1 element"
#define EC_PUBLIC_KEY_TYPE_INVALID "public key must be a Buffer"
#define EC_PUBLIC_KEY_LENGTH_INVALID "public key length is invalid"
#define EC_PUBLIC_KEY_PARSE_FAIL \
"the public key could not be parsed or is invalid"
#define EC_PUBLIC_KEY_CREATE_FAIL "private was invalid, try again"
#define EC_PUBLIC_KEY_TWEAK_ADD_FAIL \
"tweak out of range or resulting public key is invalid"
#define EC_PUBLIC_KEY_TWEAK_MUL_FAIL "tweak out of range"
#define EC_PUBLIC_KEY_COMBINE_FAIL "the sum of the public keys is not valid"
#define EC_PUBLIC_KEY_NEGATE_FAIL "public key negation failed"
#define EC_PUBLIC_KEY_INVERT_FAIL "public key inversion failed"
#define EC_PUBLIC_KEY_EXPORT_FAIL "couldn't export public key"
#define EC_PUBLIC_KEY_IMPORT_FAIL "couldn't import public key"
#define ECDH_FAIL "scalar was invalid (zero or overflow)"
#define EC_SIGNATURE_TYPE_INVALID "signature must be a Buffer"
#define EC_SIGNATURE_LENGTH_INVALID "signature length is invalid"
#define EC_SIGNATURE_PARSE_FAIL "couldn't parse signature"
#define EC_SIGNATURE_PARSE_DER_FAIL "couldn't parse DER signature"
#define EC_SIGNATURE_SERIALIZE_DER_FAIL \
"couldn't serialize signature to DER format"
#define EC_SIGN_FAIL \
"nonce generation function failed or private key is invalid"
#define EC_RECOVER_FAIL "couldn't recover public key from signature"
#define MSG_TYPE_INVALID "message must be a Buffer"
#define MSG_LENGTH_INVALID "message length is invalid"
#define RECOVERY_ID_TYPE_INVALID "recovery must be a Number"
#define RECOVERY_ID_VALUE_INVALID "recovery value must be in [0,3]"
#define SIGN_TYPE_INVALID "sign must be a Boolean"
#define COORD_TYPE_INVALID "coordinate must be a Buffer"
#define HINT_TYPE_INVALID "hint must be a Number"
#define TWEAK_TYPE_INVALID "tweak must be a Buffer"
#define TWEAK_LENGTH_INVALID "tweak length is invalid"
#define ENTROPY_TYPE_INVALID "entropy must be a Buffer"
#define ENTROPY_LENGTH_INVALID "entropy length is invalid"
#define BATCH_TYPE_INVALID "batch must be an Array"
#define BATCH_ITEM_TYPE_INVALID "batch item must be an Array"
#define BATCH_ITEM_LENGTH_INVALID "batch item must consist of 3 members"
#define COPY_BUFFER(data, datalen) \
Nan::CopyBuffer((const char *)data, (uint32_t)datalen).ToLocalChecked()
#define UPDATE_COMPRESSED_VALUE(compressed, value, v_true, v_false) { \
if (!value->IsUndefined() && !value->IsNull()) { \
CHECK_TYPE_BOOLEAN(value, COMPRESSED_TYPE_INVALID); \
compressed = Nan::To<bool>(value).FromJust() ? v_true : v_false; \
} \
}
// TypeError
#define CHECK_TYPE_ARRAY(value, message) do { \
if (!value->IsArray()) \
return Nan::ThrowTypeError(message); \
} while (0)
#define CHECK_TYPE_BOOLEAN(value, message) do { \
if (!value->IsBoolean() && !value->IsBooleanObject()) \
return Nan::ThrowTypeError(message); \
} while (0)
#define CHECK_TYPE_BUFFER(value, message) do { \
if (!node::Buffer::HasInstance(value)) \
return Nan::ThrowTypeError(message); \
} while (0)
#define CHECK_TYPE_FUNCTION(value, message) do { \
if (!value->IsFunction()) \
return Nan::ThrowTypeError(message); \
} while (0)
#define CHECK_TYPE_NUMBER(value, message) do { \
if (!value->IsNumber() && !value->IsNumberObject()) \
return Nan::ThrowTypeError(message); \
} while (0)
#define CHECK_TYPE_OBJECT(value, message) do { \
if (!value->IsObject()) \
return Nan::ThrowTypeError(message); \
} while (0)
// RangeError
#define CHECK_BUFFER_LENGTH(buffer, length, message) do { \
if (node::Buffer::Length(buffer) != length) \
return Nan::ThrowRangeError(message); \
} while (0)
#define CHECK_BUFFER_LENGTH2(buffer, length1, length2, message) do { \
if (node::Buffer::Length(buffer) != length1 && \
node::Buffer::Length(buffer) != length2) { \
return Nan::ThrowRangeError(message); \
} \
} while (0)
#define CHECK_BUFFER_LENGTH_GT_ZERO(buffer, message) do { \
if (node::Buffer::Length(buffer) == 0) \
return Nan::ThrowRangeError(message); \
} while (0)
#define CHECK_LENGTH_GT_ZERO(value, message) do { \
if (value->Length() == 0) \
return Nan::ThrowRangeError(message); \
} while (0)
#define CHECK_NUMBER_IN_INTERVAL(number, x, y, message) do { \
if (Nan::To<int64_t>(number).FromJust() <= x || \
Nan::To<int64_t>(number).FromJust() >= y) { \
return Nan::ThrowRangeError(message); \
} \
} while (0)
static Nan::Persistent<v8::FunctionTemplate> secp256k1_constructor;
BSecp256k1::BSecp256k1() {
ctx = NULL;
scratch = NULL;
}
BSecp256k1::~BSecp256k1() {
if (ctx != NULL) {
secp256k1_context_destroy(ctx);
ctx = NULL;
}
if (scratch != NULL) {
secp256k1_scratch_space_destroy(scratch);
scratch = NULL;
}
}
void
BSecp256k1::Init(v8::Local<v8::Object> &target) {
Nan::HandleScope scope;
v8::Local<v8::FunctionTemplate> tpl =
Nan::New<v8::FunctionTemplate>(BSecp256k1::New);
secp256k1_constructor.Reset(tpl);
tpl->SetClassName(Nan::New("Secp256k1").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// internal
Nan::SetPrototypeMethod(tpl, "_randomize", BSecp256k1::Randomize);
// secret key
Nan::SetPrototypeMethod(tpl, "privateKeyGenerate", BSecp256k1::PrivateKeyGenerate);
Nan::SetPrototypeMethod(tpl, "privateKeyVerify", BSecp256k1::PrivateKeyVerify);
Nan::SetPrototypeMethod(tpl, "privateKeyExport", BSecp256k1::PrivateKeyExport);
Nan::SetPrototypeMethod(tpl, "privateKeyImport", BSecp256k1::PrivateKeyImport);
Nan::SetPrototypeMethod(tpl, "privateKeyReduce", BSecp256k1::PrivateKeyReduce);
Nan::SetPrototypeMethod(tpl, "privateKeyNegate", BSecp256k1::PrivateKeyNegate);
Nan::SetPrototypeMethod(tpl, "privateKeyInvert", BSecp256k1::PrivateKeyInvert);
Nan::SetPrototypeMethod(tpl, "privateKeyTweakAdd", BSecp256k1::PrivateKeyTweakAdd);
Nan::SetPrototypeMethod(tpl, "privateKeyTweakMul", BSecp256k1::PrivateKeyTweakMul);
// public key
Nan::SetPrototypeMethod(tpl, "publicKeyCreate", BSecp256k1::PublicKeyCreate);
Nan::SetPrototypeMethod(tpl, "publicKeyConvert", BSecp256k1::PublicKeyConvert);
Nan::SetPrototypeMethod(tpl, "publicKeyFromUniform", BSecp256k1::PublicKeyFromUniform);
Nan::SetPrototypeMethod(tpl, "publicKeyToUniform", BSecp256k1::PublicKeyToUniform);
Nan::SetPrototypeMethod(tpl, "publicKeyFromHash", BSecp256k1::PublicKeyFromHash);
Nan::SetPrototypeMethod(tpl, "publicKeyToHash", BSecp256k1::PublicKeyToHash);
Nan::SetPrototypeMethod(tpl, "publicKeyVerify", BSecp256k1::PublicKeyVerify);
Nan::SetPrototypeMethod(tpl, "publicKeyExport", BSecp256k1::PublicKeyExport);
Nan::SetPrototypeMethod(tpl, "publicKeyImport", BSecp256k1::PublicKeyImport);
Nan::SetPrototypeMethod(tpl, "publicKeyTweakAdd", BSecp256k1::PublicKeyTweakAdd);
Nan::SetPrototypeMethod(tpl, "publicKeyTweakMul", BSecp256k1::PublicKeyTweakMul);
Nan::SetPrototypeMethod(tpl, "publicKeyCombine", BSecp256k1::PublicKeyCombine);
Nan::SetPrototypeMethod(tpl, "publicKeyNegate", BSecp256k1::PublicKeyNegate);
// signature
Nan::SetPrototypeMethod(tpl, "signatureNormalize", BSecp256k1::SignatureNormalize);
Nan::SetPrototypeMethod(tpl, "signatureNormalizeDER", BSecp256k1::SignatureNormalizeDER);
Nan::SetPrototypeMethod(tpl, "signatureExport", BSecp256k1::SignatureExport);
Nan::SetPrototypeMethod(tpl, "signatureImport", BSecp256k1::SignatureImport);
Nan::SetPrototypeMethod(tpl, "isLowS", BSecp256k1::IsLowS);
Nan::SetPrototypeMethod(tpl, "isLowDER", BSecp256k1::IsLowDER);
// ecdsa
Nan::SetPrototypeMethod(tpl, "sign", BSecp256k1::Sign);
Nan::SetPrototypeMethod(tpl, "signRecoverable", BSecp256k1::SignRecoverable);
Nan::SetPrototypeMethod(tpl, "signDER", BSecp256k1::SignDER);
Nan::SetPrototypeMethod(tpl, "signRecoverableDER", BSecp256k1::SignRecoverableDER);
Nan::SetPrototypeMethod(tpl, "verify", BSecp256k1::Verify);
Nan::SetPrototypeMethod(tpl, "verifyDER", BSecp256k1::VerifyDER);
Nan::SetPrototypeMethod(tpl, "recover", BSecp256k1::Recover);
Nan::SetPrototypeMethod(tpl, "recoverDER", BSecp256k1::RecoverDER);
// ecdh
Nan::SetPrototypeMethod(tpl, "derive", BSecp256k1::Derive);
// schnorr
Nan::SetPrototypeMethod(tpl, "schnorrSign", BSecp256k1::SchnorrSign);
Nan::SetPrototypeMethod(tpl, "schnorrVerify", BSecp256k1::SchnorrVerify);
Nan::SetPrototypeMethod(tpl, "schnorrVerifyBatch", BSecp256k1::SchnorrVerifyBatch);
v8::Local<v8::FunctionTemplate> ctor =
Nan::New<v8::FunctionTemplate>(secp256k1_constructor);
Nan::Set(target, Nan::New("Secp256k1").ToLocalChecked(),
Nan::GetFunction(ctor).ToLocalChecked());
}
NAN_METHOD(BSecp256k1::New) {
if (!info.IsConstructCall())
return Nan::ThrowError("Could not create Secp256k1 instance.");
secp256k1_context *ctx = secp256k1_context_create(
SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY);
if (ctx == NULL)
return Nan::ThrowError("Could not create Secp256k1 instance.");
BSecp256k1 *secp = new BSecp256k1();
secp->ctx = ctx;
secp->scratch = NULL;
secp->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
NAN_METHOD(BSecp256k1::Randomize) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> entropy_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(entropy_buf, ENTROPY_TYPE_INVALID);
CHECK_BUFFER_LENGTH(entropy_buf, 32, ENTROPY_LENGTH_INVALID);
const unsigned char *entropy =
(const unsigned char *)node::Buffer::Data(entropy_buf);
if (!secp256k1_context_randomize(secp->ctx, entropy))
return Nan::ThrowError(RANDOMIZATION_FAILURE);
info.GetReturnValue().Set(info.Holder());
}
NAN_METHOD(BSecp256k1::PrivateKeyGenerate) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> entropy_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(entropy_buf, ENTROPY_TYPE_INVALID);
CHECK_BUFFER_LENGTH(entropy_buf, 32, ENTROPY_LENGTH_INVALID);
const unsigned char *entropy =
(const unsigned char *)node::Buffer::Data(entropy_buf);
unsigned char out[32];
assert(secp256k1_ec_privkey_generate(secp->ctx, out, entropy));
info.GetReturnValue().Set(COPY_BUFFER(out, 32));
}
NAN_METHOD(BSecp256k1::PrivateKeyVerify) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> priv_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(priv_buf, EC_PRIVATE_KEY_TYPE_INVALID);
const unsigned char *priv =
(const unsigned char *)node::Buffer::Data(priv_buf);
if (node::Buffer::Length(priv_buf) != 32)
return info.GetReturnValue().Set(Nan::New<v8::Boolean>(false));
int result = secp256k1_ec_seckey_verify(secp->ctx, priv);
info.GetReturnValue().Set(Nan::New<v8::Boolean>(result));
}
NAN_METHOD(BSecp256k1::PrivateKeyExport) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> priv_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(priv_buf, EC_PRIVATE_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH(priv_buf, 32, EC_PRIVATE_KEY_LENGTH_INVALID);
const unsigned char *priv =
(const unsigned char *)node::Buffer::Data(priv_buf);
unsigned char out[32];
if (!secp256k1_ec_privkey_export(secp->ctx, out, priv))
return Nan::ThrowError(EC_PRIVATE_KEY_EXPORT_FAIL);
info.GetReturnValue().Set(COPY_BUFFER(out, 32));
}
NAN_METHOD(BSecp256k1::PrivateKeyImport) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> inp_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(inp_buf, EC_PRIVATE_KEY_TYPE_INVALID);
const unsigned char *inp = (const unsigned char *)node::Buffer::Data(inp_buf);
size_t inp_len = node::Buffer::Length(inp_buf);
unsigned char priv[32];
if (!secp256k1_ec_privkey_import(secp->ctx, priv, inp, inp_len))
return Nan::ThrowError(EC_PRIVATE_KEY_IMPORT_FAIL);
info.GetReturnValue().Set(COPY_BUFFER(priv, 32));
}
NAN_METHOD(BSecp256k1::PrivateKeyReduce) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> priv_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(priv_buf, EC_PRIVATE_KEY_TYPE_INVALID);
unsigned char out[32];
const unsigned char *priv =
(const unsigned char *)node::Buffer::Data(priv_buf);
size_t priv_len = (size_t)node::Buffer::Length(priv_buf);
if (!secp256k1_ec_privkey_reduce(secp->ctx, out, priv, priv_len))
return Nan::ThrowError(EC_PRIVATE_KEY_RANGE_INVALID);
info.GetReturnValue().Set(COPY_BUFFER(out, 32));
}
NAN_METHOD(BSecp256k1::PrivateKeyNegate) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> priv_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(priv_buf, EC_PRIVATE_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH(priv_buf, 32, EC_PRIVATE_KEY_LENGTH_INVALID);
unsigned char priv[32];
memcpy(priv, node::Buffer::Data(priv_buf), 32);
if (!secp256k1_ec_privkey_negate_safe(secp->ctx, priv))
return Nan::ThrowError(EC_PRIVATE_KEY_RANGE_INVALID);
info.GetReturnValue().Set(COPY_BUFFER(priv, 32));
}
NAN_METHOD(BSecp256k1::PrivateKeyInvert) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> priv_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(priv_buf, EC_PRIVATE_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH(priv_buf, 32, EC_PRIVATE_KEY_LENGTH_INVALID);
unsigned char priv[32];
memcpy(priv, node::Buffer::Data(priv_buf), 32);
if (!secp256k1_ec_privkey_invert(secp->ctx, priv))
return Nan::ThrowError(EC_PRIVATE_KEY_RANGE_INVALID);
info.GetReturnValue().Set(COPY_BUFFER(priv, 32));
}
NAN_METHOD(BSecp256k1::PrivateKeyTweakAdd) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> priv_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(priv_buf, EC_PRIVATE_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH(priv_buf, 32, EC_PRIVATE_KEY_LENGTH_INVALID);
unsigned char priv[32];
memcpy(priv, node::Buffer::Data(priv_buf), 32);
v8::Local<v8::Object> tweak_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(tweak_buf, TWEAK_TYPE_INVALID);
CHECK_BUFFER_LENGTH(tweak_buf, 32, TWEAK_LENGTH_INVALID);
const unsigned char *tweak =
(const unsigned char *)node::Buffer::Data(tweak_buf);
if (!secp256k1_ec_privkey_tweak_add(secp->ctx, priv, tweak))
return Nan::ThrowError(EC_PRIVATE_KEY_TWEAK_ADD_FAIL);
info.GetReturnValue().Set(COPY_BUFFER(priv, 32));
}
NAN_METHOD(BSecp256k1::PrivateKeyTweakMul) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> priv_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(priv_buf, EC_PRIVATE_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH(priv_buf, 32, EC_PRIVATE_KEY_LENGTH_INVALID);
unsigned char priv[32];
memcpy(priv, node::Buffer::Data(priv_buf), 32);
v8::Local<v8::Object> tweak_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(tweak_buf, TWEAK_TYPE_INVALID);
CHECK_BUFFER_LENGTH(tweak_buf, 32, TWEAK_LENGTH_INVALID);
const unsigned char *tweak =
(const unsigned char *)node::Buffer::Data(tweak_buf);
if (!secp256k1_ec_privkey_tweak_mul(secp->ctx, priv, tweak))
return Nan::ThrowError(EC_PRIVATE_KEY_TWEAK_MUL_FAIL);
info.GetReturnValue().Set(COPY_BUFFER(priv, 32));
}
NAN_METHOD(BSecp256k1::PublicKeyCreate) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> priv_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(priv_buf, EC_PRIVATE_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH(priv_buf, 32, EC_PRIVATE_KEY_LENGTH_INVALID);
const unsigned char *priv =
(const unsigned char *)node::Buffer::Data(priv_buf);
unsigned int flags = SECP256K1_EC_COMPRESSED;
UPDATE_COMPRESSED_VALUE(flags, info[1], SECP256K1_EC_COMPRESSED,
SECP256K1_EC_UNCOMPRESSED);
secp256k1_pubkey pub;
if (!secp256k1_ec_pubkey_create(secp->ctx, &pub, priv))
return Nan::ThrowError(EC_PUBLIC_KEY_CREATE_FAIL);
unsigned char out[65];
size_t out_len = 65;
secp256k1_ec_pubkey_serialize(secp->ctx, out, &out_len, &pub, flags);
info.GetReturnValue().Set(COPY_BUFFER(out, out_len));
}
NAN_METHOD(BSecp256k1::PublicKeyConvert) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> inp_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(inp_buf, EC_PUBLIC_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH2(inp_buf, 33, 65, EC_PUBLIC_KEY_LENGTH_INVALID);
const unsigned char *inp = (const unsigned char *)node::Buffer::Data(inp_buf);
size_t inp_len = node::Buffer::Length(inp_buf);
unsigned int flags = SECP256K1_EC_COMPRESSED;
UPDATE_COMPRESSED_VALUE(flags, info[1], SECP256K1_EC_COMPRESSED,
SECP256K1_EC_UNCOMPRESSED);
secp256k1_pubkey pub;
if (!secp256k1_ec_pubkey_parse(secp->ctx, &pub, inp, inp_len))
return Nan::ThrowError(EC_PUBLIC_KEY_PARSE_FAIL);
unsigned char out[65];
size_t out_len = 65;
secp256k1_ec_pubkey_serialize(secp->ctx, out, &out_len, &pub, flags);
info.GetReturnValue().Set(COPY_BUFFER(out, out_len));
}
NAN_METHOD(BSecp256k1::PublicKeyFromUniform) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> data_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(data_buf, TWEAK_TYPE_INVALID);
CHECK_BUFFER_LENGTH(data_buf, 32, TWEAK_LENGTH_INVALID);
const unsigned char *data =
(const unsigned char *)node::Buffer::Data(data_buf);
unsigned int flags = SECP256K1_EC_COMPRESSED;
UPDATE_COMPRESSED_VALUE(flags, info[1], SECP256K1_EC_COMPRESSED,
SECP256K1_EC_UNCOMPRESSED);
secp256k1_pubkey pub;
assert(secp256k1_pubkey_from_uniform(secp->ctx, &pub, data) == 1);
unsigned char out[65];
size_t out_len = 65;
secp256k1_ec_pubkey_serialize(secp->ctx, out, &out_len, &pub, flags);
info.GetReturnValue().Set(COPY_BUFFER(out, out_len));
}
NAN_METHOD(BSecp256k1::PublicKeyToUniform) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> inp_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(inp_buf, EC_PUBLIC_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH2(inp_buf, 33, 65, EC_PUBLIC_KEY_LENGTH_INVALID);
const unsigned char *inp = (const unsigned char *)node::Buffer::Data(inp_buf);
size_t inp_len = node::Buffer::Length(inp_buf);
v8::Local<v8::Object> hint_object = info[1].As<v8::Object>();
CHECK_TYPE_NUMBER(hint_object, HINT_TYPE_INVALID);
unsigned int hint = (unsigned int)Nan::To<uint32_t>(hint_object).FromJust();
secp256k1_pubkey pub;
if (!secp256k1_ec_pubkey_parse(secp->ctx, &pub, inp, inp_len))
return Nan::ThrowError(EC_PUBLIC_KEY_PARSE_FAIL);
unsigned char out[32];
if (!secp256k1_pubkey_to_uniform(secp->ctx, out, &pub, hint))
return Nan::ThrowError(EC_PUBLIC_KEY_INVERT_FAIL);
info.GetReturnValue().Set(COPY_BUFFER(out, 32));
}
NAN_METHOD(BSecp256k1::PublicKeyFromHash) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> data_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(data_buf, TWEAK_TYPE_INVALID);
CHECK_BUFFER_LENGTH(data_buf, 64, TWEAK_LENGTH_INVALID);
const unsigned char *data =
(const unsigned char *)node::Buffer::Data(data_buf);
unsigned int flags = SECP256K1_EC_COMPRESSED;
UPDATE_COMPRESSED_VALUE(flags, info[1], SECP256K1_EC_COMPRESSED,
SECP256K1_EC_UNCOMPRESSED);
secp256k1_pubkey pub;
if (!secp256k1_pubkey_from_hash(secp->ctx, &pub, data))
return Nan::ThrowError(EC_PUBLIC_KEY_COMBINE_FAIL);
unsigned char out[65];
size_t out_len = 65;
secp256k1_ec_pubkey_serialize(secp->ctx, out, &out_len, &pub, flags);
info.GetReturnValue().Set(COPY_BUFFER(out, out_len));
}
NAN_METHOD(BSecp256k1::PublicKeyToHash) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> inp_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(inp_buf, EC_PUBLIC_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH2(inp_buf, 33, 65, EC_PUBLIC_KEY_LENGTH_INVALID);
v8::Local<v8::Object> entropy_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(entropy_buf, ENTROPY_TYPE_INVALID);
CHECK_BUFFER_LENGTH(entropy_buf, 32, ENTROPY_LENGTH_INVALID);
const unsigned char *inp = (const unsigned char *)node::Buffer::Data(inp_buf);
size_t inp_len = node::Buffer::Length(inp_buf);
const unsigned char *entropy =
(const unsigned char *)node::Buffer::Data(entropy_buf);
secp256k1_pubkey pub;
if (!secp256k1_ec_pubkey_parse(secp->ctx, &pub, inp, inp_len))
return Nan::ThrowError(EC_PUBLIC_KEY_PARSE_FAIL);
unsigned char out[64];
if (!secp256k1_pubkey_to_hash(secp->ctx, out, &pub, entropy))
return Nan::ThrowError(EC_PUBLIC_KEY_INVERT_FAIL);
info.GetReturnValue().Set(COPY_BUFFER(out, 64));
}
NAN_METHOD(BSecp256k1::PublicKeyVerify) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> inp_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(inp_buf, EC_PUBLIC_KEY_TYPE_INVALID);
const unsigned char *inp = (const unsigned char *)node::Buffer::Data(inp_buf);
size_t inp_len = node::Buffer::Length(inp_buf);
secp256k1_pubkey pub;
int result = secp256k1_ec_pubkey_parse(secp->ctx, &pub, inp, inp_len);
info.GetReturnValue().Set(Nan::New<v8::Boolean>(result));
}
NAN_METHOD(BSecp256k1::PublicKeyExport) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> inp_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(inp_buf, EC_PUBLIC_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH2(inp_buf, 33, 65, EC_PUBLIC_KEY_LENGTH_INVALID);
const uint8_t *inp = (const uint8_t *)node::Buffer::Data(inp_buf);
size_t inp_len = node::Buffer::Length(inp_buf);
secp256k1_pubkey pub;
uint8_t x[32];
uint8_t y[32];
if (!secp256k1_ec_pubkey_parse(secp->ctx, &pub, inp, inp_len))
return Nan::ThrowError(EC_PUBLIC_KEY_PARSE_FAIL);
if (!secp256k1_ec_pubkey_export(secp->ctx, x, y, &pub))
return Nan::ThrowError(EC_PUBLIC_KEY_EXPORT_FAIL);
v8::Local<v8::Array> ret = Nan::New<v8::Array>();
Nan::Set(ret, 0, COPY_BUFFER(x, 32));
Nan::Set(ret, 1, COPY_BUFFER(y, 32));
return info.GetReturnValue().Set(ret);
}
NAN_METHOD(BSecp256k1::PublicKeyImport) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
const uint8_t *x = NULL;
size_t x_len = 0;
const uint8_t *y = NULL;
size_t y_len = 0;
int sign = -1;
if (!info[0]->IsUndefined() && !info[0]->IsNull()) {
v8::Local<v8::Object> xbuf = info[0].As<v8::Object>();
if (!node::Buffer::HasInstance(xbuf))
return Nan::ThrowTypeError(COORD_TYPE_INVALID);
x = (const uint8_t *)node::Buffer::Data(xbuf);
x_len = node::Buffer::Length(xbuf);
}
if (!info[1]->IsUndefined() && !info[1]->IsNull()) {
v8::Local<v8::Object> ybuf = info[1].As<v8::Object>();
if (!node::Buffer::HasInstance(ybuf))
return Nan::ThrowTypeError(COORD_TYPE_INVALID);
y = (const uint8_t *)node::Buffer::Data(ybuf);
y_len = node::Buffer::Length(ybuf);
}
if (!info[2]->IsUndefined() && !info[2]->IsNull()) {
if (!info[2]->IsBoolean())
return Nan::ThrowTypeError(SIGN_TYPE_INVALID);
sign = (int)Nan::To<bool>(info[2]).FromJust();
}
unsigned int flags = SECP256K1_EC_COMPRESSED;
UPDATE_COMPRESSED_VALUE(flags, info[3], SECP256K1_EC_COMPRESSED,
SECP256K1_EC_UNCOMPRESSED);
secp256k1_pubkey pub;
if (!secp256k1_ec_pubkey_import(secp->ctx, &pub, x, x_len, y, y_len, sign))
return Nan::ThrowError(EC_PUBLIC_KEY_IMPORT_FAIL);
unsigned char out[65];
size_t out_len = 65;
secp256k1_ec_pubkey_serialize(secp->ctx, out, &out_len, &pub, flags);
info.GetReturnValue().Set(COPY_BUFFER(out, out_len));
}
NAN_METHOD(BSecp256k1::PublicKeyTweakAdd) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> inp_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(inp_buf, EC_PUBLIC_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH2(inp_buf, 33, 65, EC_PUBLIC_KEY_LENGTH_INVALID);
const unsigned char *inp = (const unsigned char *)node::Buffer::Data(inp_buf);
size_t inp_len = node::Buffer::Length(inp_buf);
v8::Local<v8::Object> tweak_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(tweak_buf, TWEAK_TYPE_INVALID);
CHECK_BUFFER_LENGTH(tweak_buf, 32, TWEAK_LENGTH_INVALID);
const unsigned char *tweak =
(const unsigned char *)node::Buffer::Data(tweak_buf);
unsigned int flags = SECP256K1_EC_COMPRESSED;
UPDATE_COMPRESSED_VALUE(flags, info[2], SECP256K1_EC_COMPRESSED,
SECP256K1_EC_UNCOMPRESSED);
secp256k1_pubkey pub;
if (!secp256k1_ec_pubkey_parse(secp->ctx, &pub, inp, inp_len))
return Nan::ThrowError(EC_PUBLIC_KEY_PARSE_FAIL);
if (!secp256k1_ec_pubkey_tweak_add(secp->ctx, &pub, tweak))
return Nan::ThrowError(EC_PUBLIC_KEY_TWEAK_ADD_FAIL);
unsigned char out[65];
size_t out_len = 65;
secp256k1_ec_pubkey_serialize(secp->ctx, out, &out_len, &pub, flags);
info.GetReturnValue().Set(COPY_BUFFER(out, out_len));
}
NAN_METHOD(BSecp256k1::PublicKeyTweakMul) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> inp_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(inp_buf, EC_PUBLIC_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH2(inp_buf, 33, 65, EC_PUBLIC_KEY_LENGTH_INVALID);
const unsigned char *inp = (const unsigned char *)node::Buffer::Data(inp_buf);
size_t inp_len = node::Buffer::Length(inp_buf);
v8::Local<v8::Object> tweak_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(tweak_buf, TWEAK_TYPE_INVALID);
CHECK_BUFFER_LENGTH(tweak_buf, 32, TWEAK_LENGTH_INVALID);
const unsigned char *tweak =
(const unsigned char *)node::Buffer::Data(tweak_buf);
unsigned int flags = SECP256K1_EC_COMPRESSED;
UPDATE_COMPRESSED_VALUE(flags, info[2], SECP256K1_EC_COMPRESSED,
SECP256K1_EC_UNCOMPRESSED);
secp256k1_pubkey pub;
if (!secp256k1_ec_pubkey_parse(secp->ctx, &pub, inp, inp_len))
return Nan::ThrowError(EC_PUBLIC_KEY_PARSE_FAIL);
if (!secp256k1_ec_pubkey_tweak_mul(secp->ctx, &pub, tweak))
return Nan::ThrowError(EC_PUBLIC_KEY_TWEAK_MUL_FAIL);
unsigned char out[65];
size_t out_len = 65;
secp256k1_ec_pubkey_serialize(secp->ctx, out, &out_len, &pub, flags);
info.GetReturnValue().Set(COPY_BUFFER(out, out_len));
}
NAN_METHOD(BSecp256k1::PublicKeyCombine) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Array> inp_buffers = info[0].As<v8::Array>();
CHECK_TYPE_ARRAY(inp_buffers, EC_PUBLIC_KEYS_TYPE_INVALID);
CHECK_LENGTH_GT_ZERO(inp_buffers, EC_PUBLIC_KEYS_LENGTH_INVALID);
size_t len = (size_t)inp_buffers->Length();
unsigned int flags = SECP256K1_EC_COMPRESSED;
UPDATE_COMPRESSED_VALUE(flags, info[1], SECP256K1_EC_COMPRESSED,
SECP256K1_EC_UNCOMPRESSED);
secp256k1_pubkey **pubs =
(secp256k1_pubkey **)malloc(len * sizeof(secp256k1_pubkey *));
secp256k1_pubkey *pub_data =
(secp256k1_pubkey *)malloc(len * sizeof(secp256k1_pubkey));
#define FREE_BATCH do { \
if (pubs != NULL) free(pubs); \
if (pub_data != NULL) free(pub_data); \
} while (0)
if (pubs == NULL || pub_data == NULL) {
FREE_BATCH;
return Nan::ThrowError(ALLOCATION_FAILURE);
}
for (size_t i = 0; i < len; i++) {
v8::Local<v8::Object> pub_buf =
Nan::Get(inp_buffers, i).ToLocalChecked().As<v8::Object>();
CHECK_TYPE_BUFFER(pub_buf, EC_PUBLIC_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH2(pub_buf, 33, 65, EC_PUBLIC_KEY_LENGTH_INVALID);
const unsigned char *inp =
(const unsigned char *)node::Buffer::Data(pub_buf);
size_t inp_len = node::Buffer::Length(pub_buf);
if (!secp256k1_ec_pubkey_parse(secp->ctx, &pub_data[i], inp, inp_len)) {
FREE_BATCH;
return Nan::ThrowError(EC_PUBLIC_KEY_PARSE_FAIL);
}
pubs[i] = &pub_data[i];
}
secp256k1_pubkey pub;
if (!secp256k1_ec_pubkey_combine(secp->ctx, &pub, pubs, len)) {
FREE_BATCH;
return Nan::ThrowError(EC_PUBLIC_KEY_COMBINE_FAIL);
}
FREE_BATCH;
#undef FREE_BATCH
unsigned char out[65];
size_t out_len = 65;
secp256k1_ec_pubkey_serialize(secp->ctx, out, &out_len, &pub, flags);
info.GetReturnValue().Set(COPY_BUFFER(out, out_len));
}
NAN_METHOD(BSecp256k1::PublicKeyNegate) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> inp_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(inp_buf, EC_PUBLIC_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH2(inp_buf, 33, 65, EC_PUBLIC_KEY_LENGTH_INVALID);
const unsigned char *inp = (const unsigned char *)node::Buffer::Data(inp_buf);
size_t inp_len = node::Buffer::Length(inp_buf);
unsigned int flags = SECP256K1_EC_COMPRESSED;
UPDATE_COMPRESSED_VALUE(flags, info[1], SECP256K1_EC_COMPRESSED,
SECP256K1_EC_UNCOMPRESSED);
secp256k1_pubkey pub;
if (!secp256k1_ec_pubkey_parse(secp->ctx, &pub, inp, inp_len))
return Nan::ThrowError(EC_PUBLIC_KEY_PARSE_FAIL);
if (!secp256k1_ec_pubkey_negate(secp->ctx, &pub))
return Nan::ThrowError(EC_PUBLIC_KEY_NEGATE_FAIL);
unsigned char out[65];
size_t out_len = 65;
secp256k1_ec_pubkey_serialize(secp->ctx, out, &out_len, &pub, flags);
info.GetReturnValue().Set(COPY_BUFFER(out, out_len));
}
NAN_METHOD(BSecp256k1::SignatureNormalize) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> inp_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(inp_buf, EC_SIGNATURE_TYPE_INVALID);
CHECK_BUFFER_LENGTH(inp_buf, 64, EC_SIGNATURE_LENGTH_INVALID);
const unsigned char *inp = (const unsigned char *)node::Buffer::Data(inp_buf);
secp256k1_ecdsa_signature sigin;
if (!secp256k1_ecdsa_signature_parse_compact(secp->ctx, &sigin, inp))
return Nan::ThrowError(EC_SIGNATURE_PARSE_FAIL);
secp256k1_ecdsa_signature sigout;
secp256k1_ecdsa_signature_normalize(secp->ctx, &sigout, &sigin);
unsigned char out[64];
secp256k1_ecdsa_signature_serialize_compact(secp->ctx, out, &sigout);
info.GetReturnValue().Set(COPY_BUFFER(out, 64));
}
NAN_METHOD(BSecp256k1::SignatureNormalizeDER) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> inp_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(inp_buf, EC_SIGNATURE_TYPE_INVALID);
CHECK_BUFFER_LENGTH_GT_ZERO(inp_buf, EC_SIGNATURE_LENGTH_INVALID);
const unsigned char *inp = (const unsigned char *)node::Buffer::Data(inp_buf);
size_t inp_len = node::Buffer::Length(inp_buf);
secp256k1_ecdsa_signature sigin;
if (!ecdsa_signature_parse_der_lax(secp->ctx, &sigin, inp, inp_len))
return Nan::ThrowError(EC_SIGNATURE_PARSE_DER_FAIL);
secp256k1_ecdsa_signature sigout;
secp256k1_ecdsa_signature_normalize(secp->ctx, &sigout, &sigin);
unsigned char out[72];
size_t out_len = 72;
if (!secp256k1_ecdsa_signature_serialize_der(secp->ctx, out,
&out_len, &sigout)) {
return Nan::ThrowError(EC_SIGNATURE_SERIALIZE_DER_FAIL);
}
info.GetReturnValue().Set(COPY_BUFFER(out, out_len));
}
NAN_METHOD(BSecp256k1::SignatureExport) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> inp_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(inp_buf, EC_SIGNATURE_TYPE_INVALID);
CHECK_BUFFER_LENGTH(inp_buf, 64, EC_SIGNATURE_LENGTH_INVALID);
const unsigned char *inp = (const unsigned char *)node::Buffer::Data(inp_buf);
secp256k1_ecdsa_signature sig;
if (!secp256k1_ecdsa_signature_parse_compact(secp->ctx, &sig, inp))
return Nan::ThrowError(EC_SIGNATURE_PARSE_FAIL);
unsigned char out[72];
size_t out_len = 72;
if (!secp256k1_ecdsa_signature_serialize_der(secp->ctx, out,
&out_len, &sig)) {
return Nan::ThrowError(EC_SIGNATURE_SERIALIZE_DER_FAIL);
}
info.GetReturnValue().Set(COPY_BUFFER(out, out_len));
}
NAN_METHOD(BSecp256k1::SignatureImport) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> inp_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(inp_buf, EC_SIGNATURE_TYPE_INVALID);
CHECK_BUFFER_LENGTH_GT_ZERO(inp_buf, EC_SIGNATURE_LENGTH_INVALID);
const unsigned char *inp = (const unsigned char *)node::Buffer::Data(inp_buf);
size_t inp_len = node::Buffer::Length(inp_buf);
secp256k1_ecdsa_signature sig;
if (!ecdsa_signature_parse_der_lax(secp->ctx, &sig, inp, inp_len))
return Nan::ThrowError(EC_SIGNATURE_PARSE_DER_FAIL);
unsigned char out[64];
secp256k1_ecdsa_signature_serialize_compact(secp->ctx, out, &sig);
info.GetReturnValue().Set(COPY_BUFFER(out, 64));
}
NAN_METHOD(BSecp256k1::IsLowS) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> inp_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(inp_buf, EC_SIGNATURE_TYPE_INVALID);
const unsigned char *inp = (const unsigned char *)node::Buffer::Data(inp_buf);
size_t inp_len = node::Buffer::Length(inp_buf);
if (inp_len != 64)
return info.GetReturnValue().Set(Nan::New<v8::Boolean>(false));
secp256k1_ecdsa_signature sig;
if (!secp256k1_ecdsa_signature_parse_compact(secp->ctx, &sig, inp))
return info.GetReturnValue().Set(Nan::New<v8::Boolean>(false));
int result = !secp256k1_ecdsa_signature_normalize(secp->ctx, NULL, &sig);
return info.GetReturnValue().Set(Nan::New<v8::Boolean>(result));
}
NAN_METHOD(BSecp256k1::IsLowDER) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> inp_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(inp_buf, EC_SIGNATURE_TYPE_INVALID);
const unsigned char *inp = (const unsigned char *)node::Buffer::Data(inp_buf);
size_t inp_len = node::Buffer::Length(inp_buf);
secp256k1_ecdsa_signature sig;
if (!ecdsa_signature_parse_der_lax(secp->ctx, &sig, inp, inp_len))
return info.GetReturnValue().Set(Nan::New<v8::Boolean>(false));
int result = !secp256k1_ecdsa_signature_normalize(secp->ctx, NULL, &sig);
return info.GetReturnValue().Set(Nan::New<v8::Boolean>(result));
}
NAN_METHOD(BSecp256k1::Sign) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> msg_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(msg_buf, MSG_TYPE_INVALID);
const unsigned char *msg = (const unsigned char *)node::Buffer::Data(msg_buf);
size_t msg_len = node::Buffer::Length(msg_buf);
v8::Local<v8::Object> priv_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(priv_buf, EC_PRIVATE_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH(priv_buf, 32, EC_PRIVATE_KEY_LENGTH_INVALID);
const unsigned char *priv =
(const unsigned char *)node::Buffer::Data(priv_buf);
unsigned char msg32[32];
secp256k1_nonce_function noncefn = secp256k1_nonce_function_rfc6979;
secp256k1_ecdsa_signature sig;
secp256k1_ecdsa_reduce(secp->ctx, msg32, msg, msg_len);
if (!secp256k1_ecdsa_sign(secp->ctx, &sig, msg32, priv, noncefn, NULL))
return Nan::ThrowError(EC_SIGN_FAIL);
unsigned char out[64];
secp256k1_ecdsa_signature_serialize_compact(secp->ctx, out, &sig);
info.GetReturnValue().Set(COPY_BUFFER(out, 64));
}
NAN_METHOD(BSecp256k1::SignRecoverable) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> msg_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(msg_buf, MSG_TYPE_INVALID);
const unsigned char *msg = (const unsigned char *)node::Buffer::Data(msg_buf);
size_t msg_len = node::Buffer::Length(msg_buf);
v8::Local<v8::Object> priv_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(priv_buf, EC_PRIVATE_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH(priv_buf, 32, EC_PRIVATE_KEY_LENGTH_INVALID);
const unsigned char *priv =
(const unsigned char *)node::Buffer::Data(priv_buf);
unsigned char msg32[32];
secp256k1_nonce_function noncefn = secp256k1_nonce_function_rfc6979;
secp256k1_ecdsa_recoverable_signature sig;
secp256k1_ecdsa_reduce(secp->ctx, msg32, msg, msg_len);
if (!secp256k1_ecdsa_sign_recoverable(secp->ctx, &sig, msg32,
priv, noncefn, NULL)) {
return Nan::ThrowError(EC_SIGN_FAIL);
}
int recid;
unsigned char out[64];
secp256k1_ecdsa_recoverable_signature_serialize_compact(secp->ctx, out,
&recid, &sig);
v8::Local<v8::Array> ret = Nan::New<v8::Array>();
Nan::Set(ret, 0, COPY_BUFFER(out, 64));
Nan::Set(ret, 1, Nan::New<v8::Number>(recid));
info.GetReturnValue().Set(ret);
}
NAN_METHOD(BSecp256k1::SignDER) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> msg_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(msg_buf, MSG_TYPE_INVALID);
const unsigned char *msg = (const unsigned char *)node::Buffer::Data(msg_buf);
size_t msg_len = node::Buffer::Length(msg_buf);
v8::Local<v8::Object> priv_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(priv_buf, EC_PRIVATE_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH(priv_buf, 32, EC_PRIVATE_KEY_LENGTH_INVALID);
const unsigned char *priv =
(const unsigned char *)node::Buffer::Data(priv_buf);
unsigned char msg32[32];
secp256k1_nonce_function noncefn = secp256k1_nonce_function_rfc6979;
secp256k1_ecdsa_signature sig;
secp256k1_ecdsa_reduce(secp->ctx, msg32, msg, msg_len);
if (!secp256k1_ecdsa_sign(secp->ctx, &sig, msg32, priv, noncefn, NULL))
return Nan::ThrowError(EC_SIGN_FAIL);
unsigned char out[72];
size_t out_len = 72;
if (!secp256k1_ecdsa_signature_serialize_der(secp->ctx, out,
&out_len, &sig)) {
return Nan::ThrowError(EC_SIGNATURE_SERIALIZE_DER_FAIL);
}
info.GetReturnValue().Set(COPY_BUFFER(out, out_len));
}
NAN_METHOD(BSecp256k1::SignRecoverableDER) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> msg_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(msg_buf, MSG_TYPE_INVALID);
const unsigned char *msg = (const unsigned char *)node::Buffer::Data(msg_buf);
size_t msg_len = node::Buffer::Length(msg_buf);
v8::Local<v8::Object> priv_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(priv_buf, EC_PRIVATE_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH(priv_buf, 32, EC_PRIVATE_KEY_LENGTH_INVALID);
const unsigned char *priv =
(const unsigned char *)node::Buffer::Data(priv_buf);
unsigned char msg32[32];
secp256k1_nonce_function noncefn = secp256k1_nonce_function_rfc6979;
secp256k1_ecdsa_recoverable_signature sig;
secp256k1_ecdsa_reduce(secp->ctx, msg32, msg, msg_len);
if (!secp256k1_ecdsa_sign_recoverable(secp->ctx, &sig, msg32,
priv, noncefn, NULL)) {
return Nan::ThrowError(EC_SIGN_FAIL);
}
int recid;
unsigned char out[72];
size_t out_len = 72;
secp256k1_ecdsa_recoverable_signature_serialize_compact(secp->ctx, out,
&recid, &sig);
secp256k1_ecdsa_signature sig_;
if (!secp256k1_ecdsa_signature_parse_compact(secp->ctx, &sig_, out))
return Nan::ThrowError(EC_SIGNATURE_PARSE_FAIL);
if (!secp256k1_ecdsa_signature_serialize_der(secp->ctx, out,
&out_len, &sig_)) {
return Nan::ThrowError(EC_SIGNATURE_SERIALIZE_DER_FAIL);
}
v8::Local<v8::Array> ret = Nan::New<v8::Array>();
Nan::Set(ret, 0, COPY_BUFFER(out, out_len));
Nan::Set(ret, 1, Nan::New<v8::Number>(recid));
info.GetReturnValue().Set(ret);
}
NAN_METHOD(BSecp256k1::Verify) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> msg_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(msg_buf, MSG_TYPE_INVALID);
const unsigned char *msg = (const unsigned char *)node::Buffer::Data(msg_buf);
size_t msg_len = node::Buffer::Length(msg_buf);
v8::Local<v8::Object> sig_inp_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(sig_inp_buf, EC_SIGNATURE_TYPE_INVALID);
CHECK_BUFFER_LENGTH(sig_inp_buf, 64, EC_SIGNATURE_LENGTH_INVALID);
const unsigned char *sig_inp =
(const unsigned char *)node::Buffer::Data(sig_inp_buf);
v8::Local<v8::Object> pub_buf = info[2].As<v8::Object>();
CHECK_TYPE_BUFFER(pub_buf, EC_PUBLIC_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH2(pub_buf, 33, 65, EC_PUBLIC_KEY_LENGTH_INVALID);
const unsigned char *pub_inp =
(const unsigned char *)node::Buffer::Data(pub_buf);
size_t pub_inp_len = node::Buffer::Length(pub_buf);
secp256k1_ecdsa_signature sig;
if (!secp256k1_ecdsa_signature_parse_compact(secp->ctx, &sig, sig_inp))
return Nan::ThrowError(EC_SIGNATURE_PARSE_FAIL);
unsigned char msg32[32];
secp256k1_ecdsa_reduce(secp->ctx, msg32, msg, msg_len);
secp256k1_pubkey pub;
if (!secp256k1_ec_pubkey_parse(secp->ctx, &pub, pub_inp, pub_inp_len))
return Nan::ThrowError(EC_PUBLIC_KEY_PARSE_FAIL);
secp256k1_ecdsa_signature_normalize(secp->ctx, &sig, &sig);
int result = secp256k1_ecdsa_verify(secp->ctx, &sig, msg32, &pub);
info.GetReturnValue().Set(Nan::New<v8::Boolean>(result));
}
NAN_METHOD(BSecp256k1::VerifyDER) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> msg_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(msg_buf, MSG_TYPE_INVALID);
const unsigned char *msg = (const unsigned char *)node::Buffer::Data(msg_buf);
size_t msg_len = node::Buffer::Length(msg_buf);
v8::Local<v8::Object> sig_inp_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(sig_inp_buf, EC_SIGNATURE_TYPE_INVALID);
CHECK_BUFFER_LENGTH_GT_ZERO(sig_inp_buf, EC_SIGNATURE_LENGTH_INVALID);
const unsigned char *sig_inp =
(const unsigned char *)node::Buffer::Data(sig_inp_buf);
size_t sig_inp_len = node::Buffer::Length(sig_inp_buf);
v8::Local<v8::Object> pub_buf = info[2].As<v8::Object>();
CHECK_TYPE_BUFFER(pub_buf, EC_PUBLIC_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH2(pub_buf, 33, 65, EC_PUBLIC_KEY_LENGTH_INVALID);
const unsigned char *pub_inp =
(const unsigned char *)node::Buffer::Data(pub_buf);
size_t pub_inp_len = node::Buffer::Length(pub_buf);
secp256k1_ecdsa_signature sig;
if (!ecdsa_signature_parse_der_lax(secp->ctx, &sig, sig_inp, sig_inp_len))
return Nan::ThrowError(EC_SIGNATURE_PARSE_DER_FAIL);
unsigned char msg32[32];
secp256k1_ecdsa_reduce(secp->ctx, msg32, msg, msg_len);
secp256k1_pubkey pub;
if (!secp256k1_ec_pubkey_parse(secp->ctx, &pub, pub_inp, pub_inp_len))
return Nan::ThrowError(EC_PUBLIC_KEY_PARSE_FAIL);
secp256k1_ecdsa_signature_normalize(secp->ctx, &sig, &sig);
int result = secp256k1_ecdsa_verify(secp->ctx, &sig, msg32, &pub);
info.GetReturnValue().Set(Nan::New<v8::Boolean>(result));
}
NAN_METHOD(BSecp256k1::Recover) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> msg_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(msg_buf, MSG_TYPE_INVALID);
const unsigned char *msg = (const unsigned char *)node::Buffer::Data(msg_buf);
size_t msg_len = node::Buffer::Length(msg_buf);
v8::Local<v8::Object> sig_inp_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(sig_inp_buf, EC_SIGNATURE_TYPE_INVALID);
CHECK_BUFFER_LENGTH(sig_inp_buf, 64, EC_SIGNATURE_LENGTH_INVALID);
const unsigned char *sig_inp =
(const unsigned char *)node::Buffer::Data(sig_inp_buf);
v8::Local<v8::Object> recid_object = info[2].As<v8::Object>();
CHECK_TYPE_NUMBER(recid_object, RECOVERY_ID_TYPE_INVALID);
CHECK_NUMBER_IN_INTERVAL(recid_object, -1, 4, RECOVERY_ID_VALUE_INVALID);
int recid = (int)Nan::To<int64_t>(recid_object).FromJust();
unsigned int flags = SECP256K1_EC_COMPRESSED;
UPDATE_COMPRESSED_VALUE(flags, info[3], SECP256K1_EC_COMPRESSED,
SECP256K1_EC_UNCOMPRESSED);
secp256k1_ecdsa_recoverable_signature sig;
if (!secp256k1_ecdsa_recoverable_signature_parse_compact(secp->ctx,
&sig,
sig_inp,
recid)) {
return Nan::ThrowError(EC_SIGNATURE_PARSE_FAIL);
}
unsigned char msg32[32];
secp256k1_ecdsa_reduce(secp->ctx, msg32, msg, msg_len);
secp256k1_pubkey pub;
if (!secp256k1_ecdsa_recover(secp->ctx, &pub, &sig, msg32))
return Nan::ThrowError(EC_RECOVER_FAIL);
unsigned char out[65];
size_t out_len = 65;
secp256k1_ec_pubkey_serialize(secp->ctx, out, &out_len,
&pub, flags);
info.GetReturnValue().Set(COPY_BUFFER(out, out_len));
}
NAN_METHOD(BSecp256k1::RecoverDER) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> msg_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(msg_buf, MSG_TYPE_INVALID);
const unsigned char *msg = (const unsigned char *)node::Buffer::Data(msg_buf);
size_t msg_len = node::Buffer::Length(msg_buf);
v8::Local<v8::Object> sig_inp_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(sig_inp_buf, EC_SIGNATURE_TYPE_INVALID);
CHECK_BUFFER_LENGTH_GT_ZERO(sig_inp_buf, EC_SIGNATURE_LENGTH_INVALID);
const unsigned char *sig_inp =
(const unsigned char *)node::Buffer::Data(sig_inp_buf);
size_t sig_inp_len = node::Buffer::Length(sig_inp_buf);
v8::Local<v8::Object> recid_object = info[2].As<v8::Object>();
CHECK_TYPE_NUMBER(recid_object, RECOVERY_ID_TYPE_INVALID);
CHECK_NUMBER_IN_INTERVAL(recid_object, -1, 4, RECOVERY_ID_VALUE_INVALID);
int recid = (int)Nan::To<int64_t>(recid_object).FromJust();
unsigned int flags = SECP256K1_EC_COMPRESSED;
UPDATE_COMPRESSED_VALUE(flags, info[3], SECP256K1_EC_COMPRESSED,
SECP256K1_EC_UNCOMPRESSED);
secp256k1_ecdsa_signature orig;
if (!ecdsa_signature_parse_der_lax(secp->ctx, &orig, sig_inp, sig_inp_len))
return Nan::ThrowError(EC_SIGNATURE_PARSE_DER_FAIL);
unsigned char compact[64];
secp256k1_ecdsa_signature_serialize_compact(secp->ctx, compact, &orig);
secp256k1_ecdsa_recoverable_signature sig;
if (!secp256k1_ecdsa_recoverable_signature_parse_compact(secp->ctx,
&sig,
compact,
recid)) {
return Nan::ThrowError(EC_SIGNATURE_PARSE_FAIL);
}
unsigned char msg32[32];
secp256k1_ecdsa_reduce(secp->ctx, msg32, msg, msg_len);
secp256k1_pubkey pub;
if (!secp256k1_ecdsa_recover(secp->ctx, &pub, &sig, msg32))
return Nan::ThrowError(EC_RECOVER_FAIL);
unsigned char out[65];
size_t out_len = 65;
secp256k1_ec_pubkey_serialize(secp->ctx, out, &out_len, &pub, flags);
info.GetReturnValue().Set(COPY_BUFFER(out, out_len));
}
static int
ecdh_hash_function_raw(unsigned char *out,
const unsigned char *x,
const unsigned char *y,
void *data) {
unsigned int flags = *((unsigned int *)data);
if (flags == SECP256K1_EC_COMPRESSED) {
out[0] = 0x02 | (y[31] & 1);
memcpy(out + 1, x, 32);
} else {
out[0] = 0x04;
memcpy(out + 1, x, 32);
memcpy(out + 33, y, 32);
}
return 1;
}
NAN_METHOD(BSecp256k1::Derive) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> pub_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(pub_buf, EC_PUBLIC_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH2(pub_buf, 33, 65, EC_PUBLIC_KEY_LENGTH_INVALID);
const unsigned char *pub_inp =
(const unsigned char *)node::Buffer::Data(pub_buf);
size_t pub_inp_len = node::Buffer::Length(pub_buf);
v8::Local<v8::Object> priv_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(priv_buf, EC_PRIVATE_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH(priv_buf, 32, EC_PRIVATE_KEY_LENGTH_INVALID);
const unsigned char *priv =
(const unsigned char *)node::Buffer::Data(priv_buf);
secp256k1_pubkey pub;
if (!secp256k1_ec_pubkey_parse(secp->ctx, &pub, pub_inp, pub_inp_len))
return Nan::ThrowError(EC_PUBLIC_KEY_PARSE_FAIL);
unsigned int flags = SECP256K1_EC_COMPRESSED;
UPDATE_COMPRESSED_VALUE(flags, info[2], SECP256K1_EC_COMPRESSED,
SECP256K1_EC_UNCOMPRESSED);
unsigned char out[65];
size_t out_len = 65;
secp256k1_ecdh_hash_function hashfp = ecdh_hash_function_raw;
if (!secp256k1_ecdh(secp->ctx, out, &pub, priv, hashfp, &flags))
return Nan::ThrowError(ECDH_FAIL);
if (flags == SECP256K1_EC_COMPRESSED)
out_len = 33;
info.GetReturnValue().Set(COPY_BUFFER(out, out_len));
}
NAN_METHOD(BSecp256k1::SchnorrSign) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> msg_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(msg_buf, MSG_TYPE_INVALID);
const unsigned char *msg =
(const unsigned char *)node::Buffer::Data(msg_buf);
size_t msg_len = node::Buffer::Length(msg_buf);
v8::Local<v8::Object> priv_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(priv_buf, EC_PRIVATE_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH(priv_buf, 32, EC_PRIVATE_KEY_LENGTH_INVALID);
const unsigned char *priv =
(const unsigned char *)node::Buffer::Data(priv_buf);
secp256k1_schnorrleg sig;
if (!secp256k1_schnorrleg_sign(secp->ctx, &sig, msg, msg_len, priv))
return Nan::ThrowError(EC_SIGN_FAIL);
unsigned char out[64];
secp256k1_schnorrleg_serialize(secp->ctx, out, &sig);
info.GetReturnValue().Set(COPY_BUFFER(out, 64));
}
NAN_METHOD(BSecp256k1::SchnorrVerify) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> msg_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(msg_buf, MSG_TYPE_INVALID);
const unsigned char *msg =
(const unsigned char *)node::Buffer::Data(msg_buf);
size_t msg_len = node::Buffer::Length(msg_buf);
v8::Local<v8::Object> sig_inp_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(sig_inp_buf, EC_SIGNATURE_TYPE_INVALID);
CHECK_BUFFER_LENGTH(sig_inp_buf, 64, EC_SIGNATURE_LENGTH_INVALID);
const unsigned char *sig_inp =
(const unsigned char *)node::Buffer::Data(sig_inp_buf);
v8::Local<v8::Object> pub_buf = info[2].As<v8::Object>();
CHECK_TYPE_BUFFER(pub_buf, EC_PUBLIC_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH2(pub_buf, 33, 65, EC_PUBLIC_KEY_LENGTH_INVALID);
const unsigned char *pub_inp =
(const unsigned char *)node::Buffer::Data(pub_buf);
size_t pub_inp_len = node::Buffer::Length(pub_buf);
secp256k1_schnorrleg sig;
if (!secp256k1_schnorrleg_parse(secp->ctx, &sig, sig_inp))
return Nan::ThrowError(EC_SIGNATURE_PARSE_FAIL);
secp256k1_pubkey pub;
if (!secp256k1_ec_pubkey_parse(secp->ctx, &pub, pub_inp, pub_inp_len))
return Nan::ThrowError(EC_PUBLIC_KEY_PARSE_FAIL);
int result = secp256k1_schnorrleg_verify(secp->ctx, &sig, msg, msg_len, &pub);
info.GetReturnValue().Set(Nan::New<v8::Boolean>(result));
}
NAN_METHOD(BSecp256k1::SchnorrVerifyBatch) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
if (!info[0]->IsArray())
return Nan::ThrowTypeError(BATCH_TYPE_INVALID);
v8::Local<v8::Array> batch = info[0].As<v8::Array>();
size_t len = (size_t)batch->Length();
if (len == 0)
return info.GetReturnValue().Set(Nan::New<v8::Boolean>(true));
const unsigned char **msgs =
(const unsigned char **)malloc(len * sizeof(unsigned char *));
size_t *msg_lens = (size_t *)malloc(len * sizeof(size_t));
secp256k1_schnorrleg **sigs =
(secp256k1_schnorrleg **)malloc(len * sizeof(secp256k1_schnorrleg *));
secp256k1_pubkey **pubs =
(secp256k1_pubkey **)malloc(len * sizeof(secp256k1_pubkey *));
secp256k1_schnorrleg *sig_data =
(secp256k1_schnorrleg *)malloc(len * sizeof(secp256k1_schnorrleg));
secp256k1_pubkey *pub_data =
(secp256k1_pubkey *)malloc(len * sizeof(secp256k1_pubkey));
#define FREE_BATCH do { \
if (msgs != NULL) free(msgs); \
if (msg_lens != NULL) free(msg_lens); \
if (sigs != NULL) free(sigs); \
if (pubs != NULL) free(pubs); \
if (sig_data != NULL) free(sig_data); \
if (pub_data != NULL) free(pub_data); \
} while (0)
if (msgs == NULL || msg_lens == NULL || sigs == NULL
|| pubs == NULL || sig_data == NULL || pub_data == NULL) {
FREE_BATCH;
return Nan::ThrowError(ALLOCATION_FAILURE);
}
for (size_t i = 0; i < len; i++) {
v8::Local<v8::Value> val = Nan::Get(batch, i).ToLocalChecked();
if (!val->IsArray()) {
FREE_BATCH;
return Nan::ThrowTypeError(BATCH_ITEM_TYPE_INVALID);
}
v8::Local<v8::Array> item = val.As<v8::Array>();
if (item->Length() != 3) {
FREE_BATCH;
return Nan::ThrowTypeError(BATCH_ITEM_LENGTH_INVALID);
}
v8::Local<v8::Object> msg_buf = Nan::Get(item, 0).ToLocalChecked()
.As<v8::Object>();
v8::Local<v8::Object> sig_buf = Nan::Get(item, 1).ToLocalChecked()
.As<v8::Object>();
v8::Local<v8::Object> pub_buf = Nan::Get(item, 2).ToLocalChecked()
.As<v8::Object>();
if (!node::Buffer::HasInstance(msg_buf)) {
FREE_BATCH;
return Nan::ThrowTypeError(MSG_TYPE_INVALID);
}
if (!node::Buffer::HasInstance(sig_buf)) {
FREE_BATCH;
return Nan::ThrowTypeError(EC_SIGNATURE_TYPE_INVALID);
}
if (!node::Buffer::HasInstance(pub_buf)) {
FREE_BATCH;
return Nan::ThrowTypeError(EC_PUBLIC_KEY_TYPE_INVALID);
}
const unsigned char *msg =
(const unsigned char *)node::Buffer::Data(msg_buf);
size_t msg_len = node::Buffer::Length(msg_buf);
const unsigned char *sig =
(const unsigned char *)node::Buffer::Data(sig_buf);
size_t sig_len = node::Buffer::Length(sig_buf);
const unsigned char *pub =
(const unsigned char *)node::Buffer::Data(pub_buf);
size_t pub_len = node::Buffer::Length(pub_buf);
if (sig_len != 64) {
FREE_BATCH;
return Nan::ThrowRangeError(EC_SIGNATURE_LENGTH_INVALID);
}
if (pub_len != 33 && pub_len != 65) {
FREE_BATCH;
return Nan::ThrowRangeError(EC_PUBLIC_KEY_LENGTH_INVALID);
}
if (!secp256k1_schnorrleg_parse(secp->ctx, &sig_data[i], sig)) {
FREE_BATCH;
return Nan::ThrowError(EC_SIGNATURE_PARSE_FAIL);
}
if (!secp256k1_ec_pubkey_parse(secp->ctx, &pub_data[i], pub, pub_len)) {
FREE_BATCH;
return Nan::ThrowError(EC_PUBLIC_KEY_PARSE_FAIL);
}
msgs[i] = msg;
msg_lens[i] = msg_len;
sigs[i] = &sig_data[i];
pubs[i] = &pub_data[i];
}
// Lazy allocation for scratch space. See:
// https://github.com/ElementsProject/secp256k1-zkp/issues/69
// https://github.com/bitcoin-core/secp256k1/pull/638
if (secp->scratch == NULL) {
secp256k1_scratch_space *scratch =
secp256k1_scratch_space_create(secp->ctx, 1024 * 1024);
if (scratch == NULL) {
FREE_BATCH;
return Nan::ThrowError(ALLOCATION_FAILURE);
}
secp->scratch = scratch;
}
int result = secp256k1_schnorrleg_verify_batch(secp->ctx, secp->scratch,
sigs, msgs, msg_lens, pubs,
len);
FREE_BATCH;
#undef FREE_BATCH
info.GetReturnValue().Set(Nan::New<v8::Boolean>(result));
}
| 61,007
| 25,275
|
// MIT License
//
// Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved.
//
// 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 <iostream>
#include <vector>
#include <algorithm>
// Google Test
#include <gtest/gtest.h>
// HIP API
#include <hip/hip_runtime.h>
#include <hip/hip_hcc.h>
// rocPRIM API
#include <rocprim/rocprim.hpp>
#include "test_utils.hpp"
#define HIP_CHECK(error) \
ASSERT_EQ(static_cast<hipError_t>(error),hipSuccess)
namespace rp = rocprim;
// Params for tests
template<
class KeyType,
class ValueType = KeyType
>
struct DeviceSortParams
{
using key_type = KeyType;
using value_type = ValueType;
};
// ---------------------------------------------------------
// Test for reduce ops taking single input value
// ---------------------------------------------------------
template<class Params>
class RocprimDeviceSortTests : public ::testing::Test
{
public:
using key_type = typename Params::key_type;
using value_type = typename Params::value_type;
const bool debug_synchronous = false;
};
typedef ::testing::Types<
DeviceSortParams<int>,
DeviceSortParams<test_utils::custom_test_type<int>>,
DeviceSortParams<unsigned long>,
DeviceSortParams<float, int>,
DeviceSortParams<int, float>,
DeviceSortParams<int, test_utils::custom_test_type<float>>
> RocprimDeviceSortTestsParams;
std::vector<size_t> get_sizes()
{
std::vector<size_t> sizes = {
1, 10, 53, 211,
1024, 2048, 5096,
34567, (1 << 17) - 1220
};
const std::vector<size_t> random_sizes = test_utils::get_random_data<size_t>(2, 1, 16384);
sizes.insert(sizes.end(), random_sizes.begin(), random_sizes.end());
std::sort(sizes.begin(), sizes.end());
return sizes;
}
TYPED_TEST_CASE(RocprimDeviceSortTests, RocprimDeviceSortTestsParams);
TYPED_TEST(RocprimDeviceSortTests, SortKey)
{
using key_type = typename TestFixture::key_type;
const bool debug_synchronous = TestFixture::debug_synchronous;
const std::vector<size_t> sizes = get_sizes();
for(auto size : sizes)
{
hipStream_t stream = 0; // default
SCOPED_TRACE(testing::Message() << "with size = " << size);
// Generate data
std::vector<key_type> input = test_utils::get_random_data<key_type>(size, 0, size);
std::vector<key_type> output(size, 0);
key_type * d_input;
key_type * d_output;
HIP_CHECK(hipMalloc(&d_input, input.size() * sizeof(key_type)));
HIP_CHECK(hipMalloc(&d_output, output.size() * sizeof(key_type)));
HIP_CHECK(
hipMemcpy(
d_input, input.data(),
input.size() * sizeof(key_type),
hipMemcpyHostToDevice
)
);
HIP_CHECK(hipDeviceSynchronize());
// Calculate expected results on host
std::vector<key_type> expected(input);
std::sort(
expected.begin(),
expected.end()
);
// compare function
::rocprim::less<key_type> lesser_op;
// temp storage
size_t temp_storage_size_bytes;
void * d_temp_storage = nullptr;
// Get size of d_temp_storage
HIP_CHECK(
rocprim::merge_sort(
d_temp_storage, temp_storage_size_bytes,
d_input, d_output, input.size(),
lesser_op, stream, debug_synchronous
)
);
// temp_storage_size_bytes must be >0
ASSERT_GT(temp_storage_size_bytes, 0);
// allocate temporary storage
HIP_CHECK(hipMalloc(&d_temp_storage, temp_storage_size_bytes));
HIP_CHECK(hipDeviceSynchronize());
// Run
HIP_CHECK(
rocprim::merge_sort(
d_temp_storage, temp_storage_size_bytes,
d_input, d_output, input.size(),
lesser_op, stream, debug_synchronous
)
);
HIP_CHECK(hipPeekAtLastError());
HIP_CHECK(hipDeviceSynchronize());
// Copy output to host
HIP_CHECK(
hipMemcpy(
output.data(), d_output,
output.size() * sizeof(key_type),
hipMemcpyDeviceToHost
)
);
HIP_CHECK(hipDeviceSynchronize());
// Check if output values are as expected
for(size_t i = 0; i < output.size(); i++)
{
ASSERT_NO_FATAL_FAILURE(test_utils::assert_near(output[i], expected[i], 0.01f));
}
hipFree(d_input);
hipFree(d_output);
hipFree(d_temp_storage);
}
}
TYPED_TEST(RocprimDeviceSortTests, SortKeyValue)
{
using key_type = typename TestFixture::key_type;
using value_type = typename TestFixture::value_type;
const bool debug_synchronous = TestFixture::debug_synchronous;
const std::vector<size_t> sizes = get_sizes();
for(auto size : sizes)
{
hipStream_t stream = 0; // default
SCOPED_TRACE(testing::Message() << "with size = " << size);
// Generate data
std::vector<key_type> keys_input(size);
std::iota(keys_input.begin(), keys_input.end(), 0);
std::shuffle(
keys_input.begin(),
keys_input.end(),
std::mt19937{std::random_device{}()}
);
std::vector<value_type> values_input = test_utils::get_random_data<value_type>(size, -1000, 1000);
std::vector<key_type> keys_output(size, key_type(0));
std::vector<value_type> values_output(size, value_type(0));
key_type * d_keys_input;
key_type * d_keys_output;
HIP_CHECK(hipMalloc(&d_keys_input, keys_input.size() * sizeof(key_type)));
HIP_CHECK(hipMalloc(&d_keys_output, keys_output.size() * sizeof(key_type)));
HIP_CHECK(
hipMemcpy(
d_keys_input, keys_input.data(),
keys_input.size() * sizeof(key_type),
hipMemcpyHostToDevice
)
);
HIP_CHECK(hipDeviceSynchronize());
value_type * d_values_input;
value_type * d_values_output;
HIP_CHECK(hipMalloc(&d_values_input, values_input.size() * sizeof(value_type)));
HIP_CHECK(hipMalloc(&d_values_output, values_output.size() * sizeof(value_type)));
HIP_CHECK(
hipMemcpy(
d_values_input, values_input.data(),
values_input.size() * sizeof(value_type),
hipMemcpyHostToDevice
)
);
HIP_CHECK(hipDeviceSynchronize());
// Calculate expected results on host
using key_value = std::pair<key_type, value_type>;
std::vector<key_value> expected(size);
for(size_t i = 0; i < size; i++)
{
expected[i] = key_value(keys_input[i], values_input[i]);
}
std::sort(
expected.begin(),
expected.end()
);
// compare function
::rocprim::less<key_type> lesser_op;
// temp storage
size_t temp_storage_size_bytes;
void * d_temp_storage = nullptr;
// Get size of d_temp_storage
HIP_CHECK(
rocprim::merge_sort(
d_temp_storage, temp_storage_size_bytes,
d_keys_input, d_keys_output,
d_values_input, d_values_output, keys_input.size(),
lesser_op, stream, debug_synchronous
)
);
// temp_storage_size_bytes must be >0
ASSERT_GT(temp_storage_size_bytes, 0);
// allocate temporary storage
HIP_CHECK(hipMalloc(&d_temp_storage, temp_storage_size_bytes));
HIP_CHECK(hipDeviceSynchronize());
// Run
HIP_CHECK(
rocprim::merge_sort(
d_temp_storage, temp_storage_size_bytes,
d_keys_input, d_keys_output,
d_values_input, d_values_output, keys_input.size(),
lesser_op, stream, debug_synchronous
)
);
HIP_CHECK(hipPeekAtLastError());
HIP_CHECK(hipDeviceSynchronize());
// Copy output to host
HIP_CHECK(
hipMemcpy(
keys_output.data(), d_keys_output,
keys_output.size() * sizeof(key_type),
hipMemcpyDeviceToHost
)
);
HIP_CHECK(
hipMemcpy(
values_output.data(), d_values_output,
values_output.size() * sizeof(value_type),
hipMemcpyDeviceToHost
)
);
HIP_CHECK(hipDeviceSynchronize());
// Check if output values are as expected
for(size_t i = 0; i < keys_output.size(); i++)
{
ASSERT_EQ(keys_output[i], expected[i].first);
ASSERT_EQ(values_output[i], expected[i].second);
}
hipFree(d_keys_input);
hipFree(d_keys_output);
hipFree(d_values_input);
hipFree(d_values_output);
hipFree(d_temp_storage);
}
}
| 10,044
| 3,200
|
/*
* (c) 2014-2015 Sam Nazarko
* email@samnazarko.co.uk
*/
#include "downloadprogress.h"
#include "ui_downloadprogress.h"
#include <QFileInfo>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QString>
#include <QStringList>
#include <QUrl>
#include <QFile>
#include <QDir>
#include <QMessageBox>
#include "utils.h"
#ifdef Q_OS_LINUX
#include <unistd.h>
#endif
/* With thanks to http://qt-project.org/doc/qt-4.8/network-downloadmanager-downloadmanager-cpp.html */
DownloadProgress::DownloadProgress(QWidget *parent) :
QWidget(parent),
ui(new Ui::DownloadProgress)
{
ui->setupUi(this);
}
void DownloadProgress::download(QUrl URL, bool isOnline)
{
QString filelocation(URL.toString());
if (isOnline == false)
{
/* sanitize local filename */
#if defined(Q_OS_MAC) || defined(Q_OS_LINUX)
filelocation.replace("file://","");
#endif
/* Emit and bail! */
emit downloadCompleted(filelocation);
return;
}
utils::writeLog("Downloading " + filelocation);
QStringList urlSeg = filelocation.split("/");
fileName = urlSeg.at((urlSeg.count() - 1));
/* Do we have the file or an uncompressed version? */
bool uncompressed = QFile(QDir::homePath() + "/" + fileName).exists();
bool decompressed = QFile(QDir::homePath() + "/" + QString(fileName).remove(".gz")).exists();
if (uncompressed)
{
if (! utils::promptYesNo(tr("Image found"), tr("Do you want to re-download this image?")))
{
if(decompressed) {
if (! utils::promptYesNo(tr("Image found"), tr("Do you want to extract again?")))
{
emit downloadCompleted(QDir::homePath() + "/" + QString(fileName).remove(".gz"));
return;
}
}
emit downloadCompleted(QDir::homePath() + "/" + fileName);
return;
}
}
else if (decompressed) {
if (! utils::promptYesNo(tr("Uncompressed Image found"), tr("Do you want to re-download this image?")))
{
emit downloadCompleted(QDir::homePath() + "/" + QString(fileName).remove(".gz"));
return;
}
}
fileName = QDir::homePath() + "/" + fileName;
output.setFileName(fileName);
if (!output.open(QIODevice::WriteOnly))
{
utils::writeLog("Can't open file for writing -- is it open by another process?");
failDownload(false);
}
else
{
#ifdef Q_OS_LINUX
// Set the owner and group the same as the home path
QFileInfo info(QDir::homePath());
fchown(output.handle(),info.ownerId(),info.groupId());
#endif
QNetworkRequest request(URL);
currentDownload = manager.get(request);
connect(currentDownload, SIGNAL(downloadProgress(qint64,qint64)),SLOT(downloadProgress(qint64,qint64)));
connect(currentDownload, SIGNAL(finished()), SLOT(downloadFinished()));
connect(currentDownload, SIGNAL(readyRead()), SLOT(downloadReadyRead()));
downloadTime.start();
}
}
void DownloadProgress::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
/* Download speed */
double speed = bytesReceived * 1000.0 / downloadTime.elapsed();
QString unit;
if (speed < 1024) {
unit = "bytes/sec";
} else if (speed < 1024*1024) {
speed /= 1024;
unit = "kB/s";
} else {
speed /= 1024*1024;
unit = "MB/s";
}
ui->downloadDetailsLabel->setText(QString::fromLatin1("%1 %2").arg(speed, 3, 'f', 1).arg(unit));
/* Update progress */
ui->downloadProgressBar->setMaximum(bytesTotal);
ui->downloadProgressBar->setValue(bytesReceived);
}
void DownloadProgress::downloadFinished()
{
output.close();
if (currentDownload->error()) {
utils::writeLog("Error occured downloading file:");
utils::writeLog(currentDownload->errorString());
failDownload(true);
} else {
utils::writeLog("Download successful");
emit downloadCompleted(fileName);
}
}
void DownloadProgress::downloadReadyRead() { output.write(currentDownload->readAll()); }
void DownloadProgress::failDownload(bool wasNetwork)
{
ui->downloadProgressBar->setValue(0);
if (wasNetwork)
ui->downloadDetailsLabel->setText(tr("Download failed! Please check your network connection"));
else
ui->downloadDetailsLabel->setText(tr("Download failed! Could not write to disk"));
}
DownloadProgress::~DownloadProgress()
{
delete ui;
}
| 4,568
| 1,408
|
// -*- C++ -*-
// $Id: Updater_Receiver_exec.cpp 95859 2012-06-11 12:40:54Z johnnyw $
/**
* Code generated by the The ACE ORB (TAO) IDL Compiler v1.8.3
* TAO and the TAO IDL Compiler have been developed by:
* Center for Distributed Object Computing
* Washington University
* St. Louis, MO
* USA
* http://www.cs.wustl.edu/~schmidt/doc-center.html
* and
* Distributed Object Computing Laboratory
* University of California at Irvine
* Irvine, CA
* USA
* and
* Institute for Software Integrated Systems
* Vanderbilt University
* Nashville, TN
* USA
* http://www.isis.vanderbilt.edu/
*
* Information about TAO is available at:
* http://www.cs.wustl.edu/~schmidt/TAO.html
**/
#include "Updater_Receiver_exec.h"
#include "dds4ccm/impl/dds4ccm_conf.h"
namespace CIAO_Updater_Receiver_Impl
{
/**
* Facet Executor Implementation Class: info_out_data_listener_exec_i
*/
info_out_data_listener_exec_i::info_out_data_listener_exec_i (
::Updater::CCM_Receiver_Context_ptr ctx,
ACE_Thread_ID &thread_id)
: ciao_context_ (
::Updater::CCM_Receiver_Context::_duplicate (ctx))
, thread_id_ (thread_id)
{
}
info_out_data_listener_exec_i::~info_out_data_listener_exec_i (void)
{
}
// Operations from ::Updater::UpdaterConnector::Listener
void
info_out_data_listener_exec_i::on_one_data (const ::TestTopic & datum,
const ::CCM_DDS::ReadInfo & info)
{
ACE_Thread_ID t_id;
this->thread_id_ = t_id;
ACE_DEBUG ((LM_DEBUG, "ListenOneByOneTest_Listener_exec_i::on_one_data: "
"key <%C> - iteration <%d>\n",
datum.key.in (),
datum.x));
if (::DDS::HANDLE_NIL == info.instance_handle)
{
ACE_ERROR ((LM_ERROR, "ERROR: ListenOneByOneTest_Listener_exec_i::on_one_data: "
"instance handle seems to be invalid "
"key <%C> - iteration <%d>\n",
datum.key.in (),
datum.x));
}
if (info.source_timestamp.sec == 0 &&
info.source_timestamp.nanosec == 0)
{
ACE_ERROR ((LM_ERROR, "ERROR: ListenOneByOneTest_Listener_exec_i::on_one_data: "
"source timestamp seems to be invalid (nil) "
"key <%C> - iteration <%d>\n",
datum.key.in (),
datum.x));
}
}
void
info_out_data_listener_exec_i::on_many_data (const ::TestTopicSeq & /* data */,
const ::CCM_DDS::ReadInfoSeq & /* infos */)
{
/* Your code here. */
}
/**
* Facet Executor Implementation Class: info_out_status_exec_i
*/
info_out_status_exec_i::info_out_status_exec_i (
::Updater::CCM_Receiver_Context_ptr ctx)
: ciao_context_ (
::Updater::CCM_Receiver_Context::_duplicate (ctx))
{
}
info_out_status_exec_i::~info_out_status_exec_i (void)
{
}
// Operations from ::CCM_DDS::PortStatusListener
void
info_out_status_exec_i::on_requested_deadline_missed (::DDS::DataReader_ptr /* the_reader */,
const ::DDS::RequestedDeadlineMissedStatus & /* status */)
{
/* Your code here. */
}
void
info_out_status_exec_i::on_sample_lost (::DDS::DataReader_ptr /* the_reader */,
const ::DDS::SampleLostStatus & /* status */)
{
/* Your code here. */
}
/**
* Component Executor Implementation Class: Receiver_exec_i
*/
Receiver_exec_i::Receiver_exec_i (void)
: thread_id_listener_ (0, 0)
{
}
Receiver_exec_i::~Receiver_exec_i (void)
{
}
// Supported operations and attributes.
// Component attributes and port operations.
::Updater::UpdaterConnector::CCM_Listener_ptr
Receiver_exec_i::get_info_out_data_listener (void)
{
if ( ::CORBA::is_nil (this->ciao_info_out_data_listener_.in ()))
{
info_out_data_listener_exec_i *tmp = 0;
ACE_NEW_RETURN (
tmp,
info_out_data_listener_exec_i (
this->ciao_context_.in (),
this->thread_id_listener_),
::Updater::UpdaterConnector::CCM_Listener::_nil ());
this->ciao_info_out_data_listener_ = tmp;
}
return
::Updater::UpdaterConnector::CCM_Listener::_duplicate (
this->ciao_info_out_data_listener_.in ());
}
::CCM_DDS::CCM_PortStatusListener_ptr
Receiver_exec_i::get_info_out_status (void)
{
if ( ::CORBA::is_nil (this->ciao_info_out_status_.in ()))
{
info_out_status_exec_i *tmp = 0;
ACE_NEW_RETURN (
tmp,
info_out_status_exec_i (
this->ciao_context_.in ()),
::CCM_DDS::CCM_PortStatusListener::_nil ());
this->ciao_info_out_status_ = tmp;
}
return
::CCM_DDS::CCM_PortStatusListener::_duplicate (
this->ciao_info_out_status_.in ());
}
// Operations from Components::SessionComponent.
void
Receiver_exec_i::set_session_context (
::Components::SessionContext_ptr ctx)
{
this->ciao_context_ =
::Updater::CCM_Receiver_Context::_narrow (ctx);
if ( ::CORBA::is_nil (this->ciao_context_.in ()))
{
throw ::CORBA::INTERNAL ();
}
}
void
Receiver_exec_i::configuration_complete (void)
{
/* Your code here. */
}
void
Receiver_exec_i::ccm_activate (void)
{
::CCM_DDS::DataListenerControl_var dlc =
this->ciao_context_->get_connection_info_out_data_control ();
dlc->mode (::CCM_DDS::ONE_BY_ONE);
}
void
Receiver_exec_i::ccm_passivate (void)
{
/* Your code here. */
}
void
Receiver_exec_i::ccm_remove (void)
{
char ccm_buf [65];
ACE_Thread_ID ccm_thread_id;
ccm_thread_id.to_string (ccm_buf);
char list_buf [65];
this->thread_id_listener_.to_string(list_buf);
if (this->thread_id_listener_.id() == 0)
{
ACE_ERROR ((LM_ERROR, "ERROR: "
"Thread ID for ReaderListener not set!\n"));
}
#if (CIAO_DDS4CCM_CONTEXT_SWITCH == 1)
else if (this->thread_id_listener_ == ccm_thread_id)
{
ACE_DEBUG ((LM_DEBUG, "ONE_BY_ONE: "
"Thread switch for ReaderListener seems OK. "
"(DDS uses the CCM thread for its callback) "
"listener <%C> - component <%C>\n",
list_buf,
ccm_buf));
}
else
{
ACE_ERROR ((LM_ERROR, "ERROR: ONE_BY_ONE: "
"Thread switch for ReaderListener "
"doesn't seem to work! "
"listener <%C> - component <%C>\n",
list_buf,
ccm_buf));
}
#else
else if (this->thread_id_listener_ == ccm_thread_id)
{
ACE_ERROR ((LM_ERROR, "ERROR: ONE_BY_ONE: ReaderListener: "
"DDS seems to use a CCM thread for its callback: "
"listener <%C> - component <%C>\n",
list_buf,
ccm_buf));
}
else
{
ACE_DEBUG ((LM_DEBUG, "ONE_BY_ONE: ReaderListener: "
"DDS seems to use its own thread for its callback: "
"listener <%C> - component <%C>\n",
list_buf,
ccm_buf));
}
#endif
}
extern "C" RECEIVER_EXEC_Export ::Components::EnterpriseComponent_ptr
create_Updater_Receiver_Impl (void)
{
::Components::EnterpriseComponent_ptr retval =
::Components::EnterpriseComponent::_nil ();
ACE_NEW_NORETURN (
retval,
Receiver_exec_i);
return retval;
}
}
| 7,914
| 2,741
|
#ifndef CONFIG_HPP_E468759B_688C_4D45_A5BA_CF1D4FCC9A08
#define CONFIG_HPP_E468759B_688C_4D45_A5BA_CF1D4FCC9A08
#pragma once
/*
config.hpp
Конфигурация
*/
/*
Copyright © 1996 Eugene Roshal
Copyright © 2000 Far Group
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. The name of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Internal:
#include "palette.hpp"
#include "plugin.hpp"
// Platform:
// Common:
#include "common/multifunction.hpp"
#include "common/monitored.hpp"
#include "common/utility.hpp"
// External:
//----------------------------------------------------------------------------
struct FarSettingsItem;
class GeneralConfig;
class RegExp;
struct PanelViewSettings;
struct hash_icase_t;
struct equal_icase_t;
struct column;
struct FARConfigItem;
enum class panel_sort: int
{
UNSORTED,
BY_NAME,
BY_EXT,
BY_MTIME,
BY_CTIME,
BY_ATIME,
BY_SIZE,
BY_DIZ,
BY_OWNER,
BY_COMPRESSEDSIZE,
BY_NUMLINKS,
BY_NUMSTREAMS,
BY_STREAMSSIZE,
BY_NAMEONLY,
BY_CHTIME,
COUNT,
BY_USER = 100000
};
enum class sort_order: int
{
first,
flip_or_default = first,
keep,
ascend,
descend,
last = descend
};
enum
{
CASR_PANEL = 0_bit,
CASR_EDITOR = 1_bit,
CASR_VIEWER = 2_bit,
CASR_HELP = 3_bit,
CASR_DIALOG = 4_bit,
};
enum ExcludeCmdHistoryType
{
EXCLUDECMDHISTORY_NOTWINASS = 0_bit, // не помещать в историю команды ассоциаций Windows
EXCLUDECMDHISTORY_NOTFARASS = 1_bit, // не помещать в историю команды выполнения ассоциаций файлов
EXCLUDECMDHISTORY_NOTPANEL = 2_bit, // не помещать в историю команды выполнения с панели
EXCLUDECMDHISTORY_NOTCMDLINE = 3_bit, // не помещать в историю команды выполнения с ком.строки
//EXCLUDECMDHISTORY_NOTAPPLYCMD = 4_bit, // не помещать в историю команды выполнения из "Apply Command"
};
enum QUOTEDNAMETYPE
{
QUOTEDNAME_INSERT = 0_bit, // кавычить при сбросе в командную строку, в диалогах и редакторе
QUOTEDNAME_CLIPBOARD = 1_bit, // кавычить при помещении в буфер обмена
};
enum
{
DMOUSEBUTTON_LEFT = 0_bit,
DMOUSEBUTTON_RIGHT = 1_bit,
};
enum
{
VMENUCLICK_IGNORE = 0,
VMENUCLICK_CANCEL = 1,
VMENUCLICK_APPLY = 2,
};
enum DIZUPDATETYPE
{
DIZ_NOT_UPDATE,
DIZ_UPDATE_IF_DISPLAYED,
DIZ_UPDATE_ALWAYS
};
enum disk_menu_mode
{
DRIVE_SHOW_TYPE = 0_bit,
DRIVE_SHOW_ASSOCIATED_PATH = 1_bit,
DRIVE_SHOW_LABEL = 2_bit,
DRIVE_SHOW_FILESYSTEM = 3_bit,
DRIVE_SHOW_SIZE = 4_bit,
DRIVE_SHOW_REMOVABLE = 5_bit,
DRIVE_SHOW_PLUGINS = 6_bit,
DRIVE_SHOW_CDROM = 7_bit,
DRIVE_SHOW_SIZE_FLOAT = 8_bit,
DRIVE_SHOW_REMOTE = 9_bit,
DRIVE_SORT_PLUGINS_BY_HOTKEY = 10_bit,
DRIVE_SHOW_LABEL_USE_SHELL = 11_bit,
DRIVE_SHOW_VIRTUAL = 12_bit,
DRIVE_SHOW_UNMOUNTED_VOLUMES = 13_bit,
};
class Option
{
public:
virtual ~Option() = default;
[[nodiscard]]
virtual string toString() const = 0;
[[nodiscard]]
virtual bool TryParse(const string& value) = 0;
[[nodiscard]]
virtual string ExInfo() const = 0;
[[nodiscard]]
virtual string_view GetType() const = 0;
[[nodiscard]]
virtual bool IsDefault(const std::any& Default) const = 0;
virtual void SetDefault(const std::any& Default) = 0;
[[nodiscard]]
virtual bool Edit(class DialogBuilder* Builder, int Width, int Param) = 0;
virtual void Export(FarSettingsItem& To) const = 0;
[[nodiscard]]
bool Changed() const { return m_Value.touched(); }
protected:
COPY_CONSTRUCTIBLE(Option);
COPY_ASSIGNABLE_DEFAULT(Option);
template<class T>
explicit Option(const T& Value): m_Value(Value) {}
template<class T>
[[nodiscard]]
const T& GetT() const { return std::any_cast<const T&>(m_Value.value().value); }
template<class T>
void SetT(const T& NewValue) { if (GetT<T>() != NewValue) m_Value = NewValue; }
private:
friend class Options;
virtual void StoreValue(GeneralConfig* Storage, string_view KeyName, string_view ValueName, bool always) const = 0;
virtual bool ReceiveValue(const GeneralConfig* Storage, string_view KeyName, string_view ValueName, const std::any& Default) = 0;
void MakeUnchanged() { m_Value.forget(); }
// Workaround for https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91630
struct any
{
std::any value;
template<typename T>
any(T&& Value):
value(FWD(Value))
{
}
template<typename T>
auto& operator=(T&& Value)
{
value = FWD(Value);
}
};
monitored<any> m_Value;
};
namespace option
{
class validator_tag{};
class notifier_tag{};
template<typename callable>
auto validator(callable&& Callable)
{
return overload
{
[Callable = FWD(Callable)](validator_tag, const auto& Value){ return Callable(Value); },
[](notifier_tag, const auto&){}
};
}
template<typename callable>
auto notifier(callable&& Callable)
{
return overload
{
[](validator_tag, const auto& Value){ return Value; },
[Callable = FWD(Callable)](notifier_tag, const auto& Value){ Callable(Value); }
};
}
}
namespace detail
{
template<class base_type, class derived>
class OptionImpl: public Option
{
public:
using underlying_type = base_type;
using impl_type = OptionImpl<base_type, derived>;
using callback_type = multifunction<
base_type(option::validator_tag, const base_type&),
void(option::notifier_tag, const base_type&)
>;
void SetCallback(const callback_type& Callback)
{
assert(!m_Callback);
m_Callback = Callback;
}
[[nodiscard]]
const auto& Get() const { return GetT<base_type>(); }
void Set(const base_type& Value) { SetT(Validate(Value)); Notify(); }
[[nodiscard]]
bool TrySet(const base_type& Value)
{
if (Validate(Value) != Value)
{
return false;
}
SetT(Value);
Notify();
return true;
}
[[nodiscard]]
string ExInfo() const override { return {}; }
[[nodiscard]]
bool IsDefault(const std::any& Default) const override { return Get() == std::any_cast<base_type>(Default); }
void SetDefault(const std::any& Default) override { Set(std::any_cast<base_type>(Default)); }
[[nodiscard]]
bool ReceiveValue(const GeneralConfig* Storage, string_view KeyName, string_view ValueName, const std::any& Default) override;
void StoreValue(GeneralConfig* Storage, string_view KeyName, string_view ValueName, bool always) const override;
//operator const base_type&() const { return Get(); }
protected:
OptionImpl():
Option(base_type())
{
static_assert(std::is_base_of_v<OptionImpl, derived>);
}
auto& operator=(const base_type& Value)
{
Set(Value);
return static_cast<derived&>(*this);
}
private:
[[nodiscard]]
base_type Validate(const base_type& Value) const
{
return m_Callback?
m_Callback(option::validator_tag{}, Value) :
Value;
}
void Notify() const
{
if (m_Callback)
m_Callback(option::notifier_tag{}, Get());
}
callback_type m_Callback;
};
}
class BoolOption: public detail::OptionImpl<bool, BoolOption>
{
public:
using impl_type::OptionImpl;
using impl_type::operator=;
[[nodiscard]]
string toString() const override { return Get() ? L"true"s : L"false"s; }
[[nodiscard]]
bool TryParse(const string& value) override;
[[nodiscard]]
string_view GetType() const override { return L"boolean"sv; }
[[nodiscard]]
bool Edit(class DialogBuilder* Builder, int Width, int Param) override;
void Export(FarSettingsItem& To) const override;
[[nodiscard]]
operator bool() const { return Get(); }
};
class Bool3Option: public detail::OptionImpl<long long, Bool3Option>
{
public:
using impl_type::OptionImpl;
using impl_type::operator=;
[[nodiscard]]
string toString() const override { const auto v = Get(); return v == BSTATE_CHECKED? L"true"s : v == BSTATE_UNCHECKED? L"false"s : L"other"s; }
[[nodiscard]]
bool TryParse(const string& value) override;
[[nodiscard]]
string_view GetType() const override { return L"3-state"sv; }
[[nodiscard]]
bool Edit(class DialogBuilder* Builder, int Width, int Param) override;
void Export(FarSettingsItem& To) const override;
[[nodiscard]]
operator FARCHECKEDSTATE() const { return static_cast<FARCHECKEDSTATE>(Get()); }
};
class IntOption: public detail::OptionImpl<long long, IntOption>
{
public:
using impl_type::OptionImpl;
using impl_type::operator=;
[[nodiscard]]
string toString() const override;
[[nodiscard]]
bool TryParse(const string& value) override;
[[nodiscard]]
string ExInfo() const override;
[[nodiscard]]
string_view GetType() const override { return L"integer"sv; }
[[nodiscard]]
bool Edit(class DialogBuilder* Builder, int Width, int Param) override;
void Export(FarSettingsItem& To) const override;
IntOption& operator|=(long long Value){Set(Get()|Value); return *this;}
IntOption& operator&=(long long Value){Set(Get()&Value); return *this;}
IntOption& operator%=(long long Value){Set(Get()%Value); return *this;}
IntOption& operator^=(long long Value){Set(Get()^Value); return *this;}
IntOption& operator--(){Set(Get()-1); return *this;}
IntOption& operator++(){Set(Get()+1); return *this;}
[[nodiscard]]
operator long long() const { return Get(); }
};
class StringOption: public detail::OptionImpl<string, StringOption>
{
public:
using impl_type::OptionImpl;
using impl_type::operator=;
[[nodiscard]]
string toString() const override { return Get(); }
[[nodiscard]]
bool TryParse(const string& value) override { Set(value); return true; }
[[nodiscard]]
string_view GetType() const override { return L"string"sv; }
[[nodiscard]]
bool Edit(class DialogBuilder* Builder, int Width, int Param) override;
void Export(FarSettingsItem& To) const override;
StringOption& operator+=(const string& Value) {Set(Get()+Value); return *this;}
[[nodiscard]]
wchar_t operator[] (size_t index) const { return Get()[index]; }
[[nodiscard]]
const wchar_t* c_str() const { return Get().c_str(); }
void clear() { Set({}); }
[[nodiscard]]
bool empty() const { return Get().empty(); }
[[nodiscard]]
size_t size() const { return Get().size(); }
[[nodiscard]]
operator const string&() const { return Get(); }
[[nodiscard]]
operator string_view() const { return Get(); }
};
class Options: noncopyable
{
enum class config_type
{
roaming,
local,
};
public:
struct ViewerOptions;
struct EditorOptions;
Options();
~Options();
void ShellOptions(bool LastCommand, const MOUSE_EVENT_RECORD *MouseEvent);
using overrides = std::unordered_map<string, string, hash_icase_t, equal_icase_t>;
void Load(overrides&& Overrides);
void Save(bool Manual);
const Option* GetConfigValue(string_view Key, string_view Name) const;
const Option* GetConfigValue(size_t Root, string_view Name) const;
bool AdvancedConfig(config_type Mode = config_type::roaming);
void LocalViewerConfig(ViewerOptions &ViOptRef) {return ViewerConfig(ViOptRef, true);}
void LocalEditorConfig(EditorOptions &EdOptRef) {return EditorConfig(EdOptRef, true);}
void SetSearchColumns(string_view Columns, string_view Widths);
struct SortingOptions
{
enum class collation
{
ordinal = 0,
invariant = 1,
linguistic = 2,
};
IntOption Collation;
BoolOption DigitsAsNumbers;
BoolOption CaseSensitive;
};
struct PanelOptions
{
IntOption m_Type;
BoolOption Visible;
IntOption ViewMode;
IntOption SortMode;
BoolOption ReverseSortOrder;
BoolOption SortGroups;
BoolOption ShowShortNames;
BoolOption SelectedFirst;
BoolOption DirectoriesFirst;
StringOption Folder;
StringOption CurFile;
};
struct AutoCompleteOptions
{
BoolOption ShowList;
BoolOption ModalList;
BoolOption AppendCompletion;
Bool3Option UseFilesystem;
Bool3Option UseHistory;
Bool3Option UsePath;
Bool3Option UseEnvironment;
};
struct PluginConfirmation
{
Bool3Option OpenFilePlugin;
BoolOption StandardAssociation;
BoolOption EvenIfOnlyOnePlugin;
BoolOption SetFindList;
BoolOption Prefix;
};
struct Confirmation
{
BoolOption Copy;
BoolOption Move;
BoolOption RO;
BoolOption Drag;
BoolOption Delete;
BoolOption DeleteFolder;
BoolOption Exit;
BoolOption Esc;
BoolOption EscTwiceToInterrupt;
BoolOption RemoveConnection;
BoolOption AllowReedit;
BoolOption HistoryClear;
BoolOption RemoveSUBST;
BoolOption RemoveHotPlug;
BoolOption DetachVHD;
};
struct DizOptions
{
StringOption strListNames;
BoolOption ROUpdate;
IntOption UpdateMode;
BoolOption SetHidden;
IntOption StartPos;
BoolOption AnsiByDefault;
BoolOption SaveInUTF;
};
struct CodeXLAT
{
HKL Layouts[10]{};
StringOption strLayouts;
StringOption Rules[3]; // правила:
// [0] "если предыдущий символ латинский"
// [1] "если предыдущий символ нелатинский символ"
// [2] "если предыдущий символ не рус/lat"
StringOption Table[2]; // [0] non-english буквы, [1] english буквы
StringOption strWordDivForXlat;
IntOption Flags;
mutable int CurrentLayout{};
};
struct EditorOptions
{
IntOption TabSize;
IntOption ExpandTabs;
BoolOption PersistentBlocks;
BoolOption DelRemovesBlocks;
BoolOption AutoIndent;
BoolOption AutoDetectCodePage;
IntOption DefaultCodePage;
StringOption strF8CPs;
BoolOption CursorBeyondEOL;
BoolOption BSLikeDel;
IntOption CharCodeBase;
BoolOption SavePos;
BoolOption SaveShortPos;
BoolOption AllowEmptySpaceAfterEof;
IntOption ReadOnlyLock;
IntOption UndoSize;
BoolOption UseExternalEditor;
IntOption FileSizeLimit;
BoolOption ShowKeyBar;
BoolOption ShowTitleBar;
BoolOption ShowScrollBar;
BoolOption EditOpenedForWrite;
BoolOption SearchSelFound;
BoolOption SearchCursorAtEnd;
BoolOption SearchRegexp;
Bool3Option ShowWhiteSpace;
StringOption strWordDiv;
BoolOption KeepEOL;
BoolOption AddUnicodeBOM;
BoolOption NewFileUnixEOL;
BoolOption SaveSafely;
BoolOption CreateBackups;
};
struct ViewerOptions
{
enum
{
eMinLineSize = 1*1000,
eDefLineSize = 10*1000,
eMaxLineSize = 100*1000
};
BoolOption AutoDetectCodePage;
BoolOption DetectDumpMode;
IntOption DefaultCodePage;
StringOption strF8CPs;
IntOption MaxLineSize; // 1000..100000, default=10000
BoolOption PersistentBlocks;
BoolOption SaveCodepage;
BoolOption SavePos;
BoolOption SaveShortPos;
BoolOption SaveViewMode;
BoolOption SaveWrapMode;
BoolOption SearchEditFocus; // auto-focus on edit text/hex window
BoolOption SearchRegexp;
Bool3Option SearchWrapStop; // [NonStop] / {Start-End} / [Full Cycle]
BoolOption ShowArrows;
BoolOption ShowKeyBar;
BoolOption ShowScrollbar;
BoolOption ShowTitleBar;
IntOption TabSize;
BoolOption UseExternalViewer;
BoolOption ViewerIsWrap; // (Wrap|WordWarp)=1 | UnWrap=0
BoolOption ViewerWrap; // Wrap=0|WordWarp=1
BoolOption Visible0x00;
IntOption ZeroChar;
};
struct PoliciesOptions
{
BoolOption ShowHiddenDrives; // показывать скрытые логические диски
};
struct DialogsOptions
{
BoolOption EditBlock; // Постоянные блоки в строках ввода
BoolOption EditHistory; // Добавлять в историю?
BoolOption AutoComplete; // Разрешено автодополнение?
BoolOption EULBsClear; // = 1 - BS в диалогах для UnChanged строки удаляет такую строку также, как и Del
IntOption MouseButton; // Отключение восприятие правой/левой кнопки мыши как команд закрытия окна диалога
BoolOption DelRemovesBlocks;
IntOption CBoxMaxHeight; // максимальный размер открываемого списка (по умолчанию=8)
};
struct VMenuOptions
{
IntOption LBtnClick;
IntOption RBtnClick;
IntOption MBtnClick;
};
struct CommandLineOptions
{
BoolOption EditBlock;
BoolOption DelRemovesBlocks;
BoolOption AutoComplete;
BoolOption UsePromptFormat;
StringOption strPromptFormat;
};
struct NowellOptions
{
// перед операцией Move снимать R/S/H атрибуты, после переноса - выставлять обратно
BoolOption MoveRO;
};
struct ScreenSizes
{
// на сколько поз. изменить размеры для распахнутого экрана
IntOption DeltaX;
IntOption DeltaY;
};
struct LoadPluginsOptions
{
// путь для поиска плагинов, указанный в /p
string strCustomPluginsPath;
string strPersonalPluginsPath;
// true - использовать стандартный путь к основным плагинам
bool MainPluginDir{};
// set by '/co' switch, not saved
bool PluginsCacheOnly{};
bool PluginsPersonal{};
#ifndef NO_WRAPPER
BoolOption OEMPluginsSupport;
#endif // NO_WRAPPER
BoolOption ScanSymlinks;
};
struct FindFileOptions
{
IntOption FileSearchMode;
BoolOption FindFolders;
BoolOption FindSymLinks;
BoolOption UseFilter;
BoolOption FindAlternateStreams;
StringOption strSearchInFirstSize;
StringOption strSearchOutFormat;
StringOption strSearchOutFormatWidth;
std::vector<column> OutColumns;
};
struct InfoPanelOptions
{
IntOption ComputerNameFormat;
IntOption UserNameFormat;
BoolOption ShowPowerStatus;
StringOption strShowStatusInfo;
StringOption strFolderInfoFiles;
BoolOption ShowCDInfo;
};
struct TreeOptions
{
BoolOption TurnOffCompletely; // Turn OFF SlowlyAndBuglyTreeView
IntOption MinTreeCount; // Минимальное количество папок для сохранения дерева в файле.
BoolOption AutoChangeFolder; // Автосмена папок при перемещении по дереву
IntOption TreeFileAttr; // Файловые атрибуты для файлов-деревях
#if defined(TREEFILE_PROJECT)
BoolOption LocalDisk; // Хранить файл структуры папок для локальных дисков
BoolOption NetDisk; // Хранить файл структуры папок для сетевых дисков
BoolOption NetPath; // Хранить файл структуры папок для сетевых путей
BoolOption RemovableDisk; // Хранить файл структуры папок для сменных дисков
BoolOption CDDisk; // Хранить файл структуры папок для CD/DVD/BD/etc дисков
StringOption strLocalDisk; // шаблон имени файла-деревяхи для локальных дисков
StringOption strNetDisk; // шаблон имени файла-деревяхи для сетевых дисков
StringOption strNetPath; // шаблон имени файла-деревяхи для сетевых путей
StringOption strRemovableDisk; // шаблон имени файла-деревяхи для сменных дисков
StringOption strCDDisk; // шаблон имени файла-деревяхи для CD/DVD/BD/etc дисков
StringOption strExceptPath; // для перечисленных здесь не хранить
StringOption strSaveLocalPath; // сюда сохраняем локальные диски
StringOption strSaveNetPath; // сюда сохраняем сетевые диски
#endif
};
struct CopyMoveOptions
{
BoolOption UseSystemCopy; // использовать системную функцию копирования
BoolOption CopyOpened; // копировать открытые на запись файлы
BoolOption CopyShowTotal; // показать общий индикатор копирования
BoolOption MultiCopy; // "разрешить мультикопирование/перемещение/создание связей"
BoolOption PreserveTimestamps;
IntOption CopySecurityOptions; // для операции Move - что делать с опцией "Copy access rights"
IntOption CopyTimeRule; // $ 30.01.2001 VVM Показывает время копирования,оставшееся время и среднюю скорость
IntOption BufferSize;
};
struct DeleteOptions
{
BoolOption ShowTotal; // показать общий индикатор удаления
BoolOption HighlightSelected;
IntOption ShowSelected;
};
struct MacroOptions
{
// параметры /m или /ma или /m....
int DisableMacro{};
// config
StringOption strKeyMacroCtrlDot, strKeyMacroRCtrlDot; // аля KEY_CTRLDOT/KEY_RCTRLDOT
StringOption strKeyMacroCtrlShiftDot, strKeyMacroRCtrlShiftDot; // аля KEY_CTRLSHIFTDOT/KEY_RCTRLSHIFTDOT
// internal
unsigned
KeyMacroCtrlDot{},
KeyMacroRCtrlDot{},
KeyMacroCtrlShiftDot{},
KeyMacroRCtrlShiftDot{};
StringOption strDateFormat; // Для $Date
BoolOption ShowPlayIndicator; // показать вывод 'P' во время проигрывания макроса
};
struct KnownModulesIDs
{
struct UuidOption
{
UUID Id{};
StringOption StrId;
string_view Default;
}
Network,
Emenu,
Arclite,
Luamacro,
Netbox,
ProcList,
TmpPanel;
};
struct ExecuteOptions
{
BoolOption RestoreCPAfterExecute;
BoolOption ExecuteUseAppPath;
BoolOption ExecuteFullTitle;
StringOption strExecuteBatchType;
StringOption strExcludeCmds;
StringOption Comspec;
StringOption ComspecArguments;
struct
{
string Pattern;
std::unique_ptr<RegExp> Re;
}
ComspecConditionRe;
StringOption ComspecCondition;
BoolOption UseHomeDir; // cd ~
StringOption strHomeDir; // cd ~
};
SortingOptions Sort;
palette Palette;
BoolOption Clock;
BoolOption Mouse;
BoolOption ShowKeyBar;
BoolOption ScreenSaver;
IntOption ScreenSaverTime;
BoolOption ShowHidden;
BoolOption ShortcutAlwaysChdir;
BoolOption Highlight;
BoolOption RightClickSelect;
BoolOption ShowBytes;
BoolOption SelectFolders;
BoolOption AllowReverseSort;
BoolOption ReverseSortCharCompat;
BoolOption SortFolderExt;
BoolOption DeleteToRecycleBin;
IntOption WipeSymbol; // символ заполнитель для "ZAP-операции"
CopyMoveOptions CMOpt;
DeleteOptions DelOpt;
BoolOption MultiMakeDir; // Опция создания нескольких каталогов за один сеанс
BoolOption UseRegisteredTypes;
BoolOption ViewerEditorClock;
BoolOption SaveViewHistory;
IntOption ViewHistoryCount;
IntOption ViewHistoryLifetime;
StringOption strExternalEditor;
EditorOptions EdOpt;
StringOption strExternalViewer;
ViewerOptions ViOpt;
// alias for EdOpt.strWordDiv
StringOption& strWordDiv;
StringOption strQuotedSymbols;
IntOption QuotedName;
BoolOption AutoSaveSetup;
IntOption ChangeDriveMode;
BoolOption ChangeDriveDisconnectMode;
BoolOption SaveHistory;
IntOption HistoryCount;
IntOption HistoryLifetime;
BoolOption SaveFoldersHistory;
IntOption FoldersHistoryCount;
IntOption FoldersHistoryLifetime;
IntOption DialogsHistoryCount;
IntOption DialogsHistoryLifetime;
FindFileOptions FindOpt;
IntOption LeftHeightDecrement;
IntOption RightHeightDecrement;
IntOption WidthDecrement;
BoolOption ShowColumnTitles;
BoolOption ShowPanelStatus;
BoolOption ShowPanelTotals;
BoolOption ShowPanelFree;
BoolOption PanelDetailedJunction;
BoolOption ShowUnknownReparsePoint;
BoolOption ShowPanelScrollbar;
BoolOption ShowMenuScrollbar;
Bool3Option ShowScreensNumber;
BoolOption ShowSortMode;
BoolOption ShowMenuBar;
StringOption FormatNumberSeparators;
Confirmation Confirm;
PluginConfirmation PluginConfirm;
DizOptions Diz;
BoolOption ShellRightLeftArrowsRule;
PanelOptions LeftPanel;
PanelOptions RightPanel;
BoolOption LeftFocus;
AutoCompleteOptions AutoComplete;
// выше этого количество автоматически не обновлять панели.
IntOption AutoUpdateLimit;
BoolOption AutoUpdateRemoteDrive;
StringOption strLanguage;
BoolOption SetIcon;
IntOption IconIndex;
BoolOption SetAdminIcon;
IntOption PanelRightClickRule;
IntOption PanelCtrlAltShiftRule;
// поведение Ctrl-F. Если = 0, то штампуется файл как есть, иначе - с учетом отображения на панели
BoolOption PanelCtrlFRule;
/*
поведение Ctrl-Alt-Shift
бит установлен - функция включена:
0 - Panel
1 - Edit
2 - View
3 - Help
4 - Dialog
*/
IntOption AllCtrlAltShiftRule;
IntOption CASRule; // 18.12.2003 - Пробуем различать левый и правый CAS (попытка #1).
/*
задает поведение Esc для командной строки:
=1 - Не изменять положение в History, если после Ctrl-E/Ctrl/-X
нажали ESC (поведение - аля VC).
=0 - поведение как и было - изменять положение в History
*/
BoolOption CmdHistoryRule;
IntOption ExcludeCmdHistory;
BoolOption SubstPluginPrefix; // 1 = подстанавливать префикс плагина (для Ctrl-[ и ему подобные)
BoolOption SetAttrFolderRules;
BoolOption ExceptUsed;
StringOption strExceptEventSvc;
IntOption CursorSize[4];
CodeXLAT XLat;
StringOption ConsoleDetachKey; // Комбинация клавиш для детача Far'овской консоли от длятельного неинтерактивного процесса в ней запущенного.
StringOption strHelpLanguage;
BoolOption FullScreenHelp;
IntOption HelpTabSize;
IntOption HelpURLRules; // =0 отключить возможность запуска URL-приложений
BoolOption HelpSearchRegexp;
// запоминать логические диски и не опрашивать каждый раз. Для предотвращения "просыпания" "зеленых" винтов.
BoolOption RememberLogicalDrives;
BoolOption FlagPosixSemantics;
IntOption MsWheelDelta; // задает смещение для прокрутки
IntOption MsWheelDeltaView;
IntOption MsWheelDeltaEdit;
IntOption MsWheelDeltaHelp;
// горизонтальная прокрутка
IntOption MsHWheelDelta;
IntOption MsHWheelDeltaView;
IntOption MsHWheelDeltaEdit;
/*
битовая маска:
0 - если установлен, то опрашивать сменные диски при GetSubstName()
1 - если установлен, то опрашивать все остальные при GetSubstName()
*/
IntOption SubstNameRule;
/* $ 23.05.2001 AltF9
+ Флаг позволяет выбрать механизм работы комбинации Alt-F9
(Изменение размера экрана) в оконном режиме. По умолчанию - 1.
0 - использовать механизм, совместимый с FAR версии 1.70 beta 3 и
ниже, т.е. переключение 25/50 линий.
1 - использовать усовершенствованный механизм - окно FAR Manager
будет переключаться с нормального на максимально доступный размер
консольного окна и обратно.*/
BoolOption AltF9;
BoolOption VirtualTerminalRendering;
Bool3Option ClearType;
Bool3Option PgUpChangeDisk;
BoolOption ShowDotsInRoot;
BoolOption ShowCheckingFile;
BoolOption UpdateEnvironment;
ExecuteOptions Exec;
IntOption PluginMaxReadData;
BoolOption ScanJunction;
IntOption RedrawTimeout;
LoadPluginsOptions LoadPlug;
DialogsOptions Dialogs;
VMenuOptions VMenu;
CommandLineOptions CmdLine;
PoliciesOptions Policies;
NowellOptions Nowell;
ScreenSizes ScrSize;
MacroOptions Macro;
IntOption FindCodePage;
TreeOptions Tree;
InfoPanelOptions InfoPanel;
BoolOption CPMenuMode;
StringOption strNoAutoDetectCP;
// Перечисленные здесь кодовые страницы будут исключены из детектирования nsUniversalDetectorEx.
// Автодетект юникодных страниц от этого не зависит, поэтому UTF-8 будет определяться даже если
// 65001 здесь присутствует. Если UniversalDetector выдаст страницу из этого списка, она будет
// заменена на умолчательную ANSI или OEM, в зависимости от настроек.
// пример: L"1250,1252,1253,1255,855,10005,28592,28595,28597,28598,38598,65001"
// Если строка пустая никакой фильтрации кодовых страниц в UCD детекте не будет.
// Если "-1", то в зависимости от CPMenuMode (Ctrl-H в меню кодовых страниц) фильтрация UCD либо будет
// отключена, либо будут разрешенны только избранные и системные (OEM ANSI) кодовые страницы.
StringOption strTitleAddons;
StringOption strEditorTitleFormat;
StringOption strViewerTitleFormat;
IntOption StoredElevationMode;
BoolOption StoredWindowMode;
string ProfilePath;
string LocalProfilePath;
string TemplateProfilePath;
string GlobalUserMenuDir;
KnownModulesIDs KnownIDs;
StringOption strBoxSymbols;
BoolOption SmartFolderMonitor; // def: 0=always monitor panel folder(s), 1=only when FAR has input focus
int ReadOnlyConfig{-1};
int UseExceptionHandler{};
long long ElevationMode{};
int WindowMode{-1};
BoolOption WindowModeStickyX;
BoolOption WindowModeStickyY;
std::vector<std::vector<std::pair<panel_sort, sort_order>>> PanelSortLayers;
const std::vector<PanelViewSettings>& ViewSettings;
class farconfig;
private:
void InitConfigs();
void InitConfigsData();
farconfig& GetConfig(config_type Type);
const farconfig& GetConfig(config_type Type) const;
static intptr_t AdvancedConfigDlgProc(class Dialog* Dlg, intptr_t Msg, intptr_t Param1, void* Param2);
void SystemSettings();
void PanelSettings();
void InterfaceSettings();
void DialogSettings();
void VMenuSettings();
void CmdlineSettings();
void SetConfirmations();
void PluginsManagerSettings();
void SetDizConfig();
void ViewerConfig(ViewerOptions &ViOptRef, bool Local = false);
void EditorConfig(EditorOptions &EdOptRef, bool Local = false);
void SetFolderInfoFiles();
void InfoPanelSettings();
static void MaskGroupsSettings();
void AutoCompleteSettings();
void TreeSettings();
void SetFilePanelModes();
void SetViewSettings(size_t Index, PanelViewSettings&& Data);
void AddViewSettings(size_t Index, PanelViewSettings&& Data);
void DeleteViewSettings(size_t Index);
void ReadPanelModes();
void SavePanelModes(bool always);
void SetDriveMenuHotkeys();
void ReadSortLayers();
void SaveSortLayers(bool Always);
std::vector<farconfig> m_Configs;
std::vector<PanelViewSettings> m_ViewSettings;
bool m_ViewSettingsChanged{};
};
string GetFarIniString(string_view AppName, string_view KeyName, string_view Default);
int GetFarIniInt(string_view AppName, string_view KeyName, int Default);
std::chrono::steady_clock::duration GetRedrawTimeout() noexcept;
#endif // CONFIG_HPP_E468759B_688C_4D45_A5BA_CF1D4FCC9A08
| 29,832
| 11,083
|
#include "source/extensions/filters/common/original_src/original_src_socket_option.h"
#include "envoy/config/core/v3/base.pb.h"
#include "source/common/common/assert.h"
namespace Envoy {
namespace Extensions {
namespace Filters {
namespace Common {
namespace OriginalSrc {
OriginalSrcSocketOption::OriginalSrcSocketOption(
Network::Address::InstanceConstSharedPtr src_address)
: src_address_(std::move(src_address)) {
// Source transparency only works on IP connections.
ASSERT(src_address_->type() == Network::Address::Type::Ip);
}
bool OriginalSrcSocketOption::setOption(
Network::Socket& socket, envoy::config::core::v3::SocketOption::SocketState state) const {
if (state == envoy::config::core::v3::SocketOption::STATE_PREBIND) {
socket.connectionInfoProvider().setLocalAddress(src_address_);
}
return true;
}
/**
* Inserts an address, already in network order, to a byte array.
*/
template <typename T> void addressIntoVector(std::vector<uint8_t>& vec, const T& address) {
const uint8_t* byte_array = reinterpret_cast<const uint8_t*>(&address);
vec.insert(vec.end(), byte_array, byte_array + sizeof(T));
}
void OriginalSrcSocketOption::hashKey(std::vector<uint8_t>& key) const {
// Note: we're assuming that there cannot be a conflict between IPv6 addresses here. If an IPv4
// address is mapped into an IPv6 address using an IPv4-Mapped IPv6 Address (RFC4921), then it's
// possible the hashes will be different despite the IP address used by the connection being
// the same.
if (src_address_->ip()->version() == Network::Address::IpVersion::v4) {
// note raw_address is already in network order
uint32_t raw_address = src_address_->ip()->ipv4()->address();
addressIntoVector(key, raw_address);
} else if (src_address_->ip()->version() == Network::Address::IpVersion::v6) {
// note raw_address is already in network order
absl::uint128 raw_address = src_address_->ip()->ipv6()->address();
addressIntoVector(key, raw_address);
}
}
absl::optional<Network::Socket::Option::Details> OriginalSrcSocketOption::getOptionDetails(
const Network::Socket&, envoy::config::core::v3::SocketOption::SocketState) const {
// no details for this option.
return absl::nullopt;
}
} // namespace OriginalSrc
} // namespace Common
} // namespace Filters
} // namespace Extensions
} // namespace Envoy
| 2,377
| 746
|
#include <moveit/task_constructor/task.h>
#include <moveit/task_constructor/stages/current_state.h>
#include <moveit/task_constructor/stages/generate_grasp_pose.h>
#include <moveit/task_constructor/stages/simple_grasp.h>
#include <moveit/task_constructor/stages/pick.h>
#include <moveit/task_constructor/stages/connect.h>
#include <moveit/task_constructor/solvers/pipeline_planner.h>
#include <ros/ros.h>
#include <moveit/planning_scene_interface/planning_scene_interface.h>
#include <gtest/gtest.h>
using namespace moveit::task_constructor;
void spawnObject() {
moveit::planning_interface::PlanningSceneInterface psi;
moveit_msgs::CollisionObject o;
o.id = "object";
o.header.frame_id = "table_top";
o.primitive_poses.resize(1);
o.primitive_poses[0].position.x = -0.2;
o.primitive_poses[0].position.y = 0.13;
o.primitive_poses[0].position.z = 0.12;
o.primitive_poses[0].orientation.w = 1.0;
o.primitives.resize(1);
o.primitives[0].type = shape_msgs::SolidPrimitive::CYLINDER;
o.primitives[0].dimensions.resize(2);
o.primitives[0].dimensions[0] = 0.23;
o.primitives[0].dimensions[1] = 0.03;
psi.applyCollisionObject(o);
}
TEST(UR5, pick) {
Task t;
Stage* initial_stage = nullptr;
auto initial = std::make_unique<stages::CurrentState>("current state");
initial_stage = initial.get();
t.add(std::move(initial));
// planner used for connect
auto pipeline = std::make_shared<solvers::PipelinePlanner>();
pipeline->setPlannerId("RRTConnectkConfigDefault");
// connect to pick
stages::Connect::GroupPlannerVector planners = { { "arm", pipeline }, { "gripper", pipeline } };
auto connect = std::make_unique<stages::Connect>("connect", planners);
connect->properties().configureInitFrom(Stage::PARENT);
t.add(std::move(connect));
// grasp generator
auto grasp_generator = new stages::GenerateGraspPose("generate grasp pose");
grasp_generator->setAngleDelta(.2);
grasp_generator->setPreGraspPose("open");
grasp_generator->setGraspPose("closed");
grasp_generator->setMonitoredStage(initial_stage);
auto grasp = std::make_unique<stages::SimpleGrasp>(std::unique_ptr<MonitoringGenerator>(grasp_generator));
grasp->setIKFrame(Eigen::Translation3d(.03, 0, 0), "s_model_tool0");
grasp->setMaxIKSolutions(8);
auto pick = std::make_unique<stages::Pick>(std::move(grasp));
pick->setProperty("eef", std::string("gripper"));
pick->setProperty("object", std::string("object"));
geometry_msgs::TwistStamped approach;
approach.header.frame_id = "s_model_tool0";
approach.twist.linear.x = 1.0;
pick->setApproachMotion(approach, 0.03, 0.1);
geometry_msgs::TwistStamped lift;
lift.header.frame_id = "world";
lift.twist.linear.z = 1.0;
pick->setLiftMotion(lift, 0.03, 0.05);
t.add(std::move(pick));
try {
spawnObject();
t.plan();
} catch (const InitStageException& e) {
ADD_FAILURE() << "planning failed with exception" << std::endl << e << t;
}
auto solutions = t.solutions().size();
EXPECT_GE(solutions, 30u);
EXPECT_LE(solutions, 60u);
}
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
ros::init(argc, argv, "ur5");
ros::AsyncSpinner spinner(1);
spinner.start();
// wait some time for move_group to come up
ros::WallDuration(5.0).sleep();
return RUN_ALL_TESTS();
}
| 3,251
| 1,268
|
#include <iostream>
using namespace std;
//The keyword this: represents a pointer to the object whose member function is being executed. It is used within a class's
//member function to refer to the object itself.
class Dummy {
public:
bool isitme (Dummy& param);
};
bool Dummy::isitme (Dummy& param)
{
if(¶m == this) return true;
else return false;
}
int main()
{
Dummy a;
Dummy* b = &a;
if(b->isitme(a))
cout << "yes, &a is b\n";
return 0;
}
| 489
| 168
|
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2005-2012, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Industrial Light & Magic nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
//
// class Semaphore -- implementation for Windows
//
//-----------------------------------------------------------------------------
#include "IlmBaseConfig.h"
#if defined(_WIN32) && !defined(HAVE_PTHREAD) && !defined(HAVE_POSIX_SEMAPHORES)
#include "IlmThreadSemaphore.h"
#include "Iex.h"
#include <string>
#include <assert.h>
#include <iostream>
ILMTHREAD_INTERNAL_NAMESPACE_SOURCE_ENTER
using namespace IEX_NAMESPACE;
namespace {
std::string
errorString ()
{
LPSTR messageBuffer;
DWORD bufferLength;
std::string message;
//
// Call FormatMessage() to allow for message
// text to be acquired from the system.
//
if (bufferLength = FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_FROM_SYSTEM,
0,
GetLastError (),
MAKELANGID (LANG_NEUTRAL,
SUBLANG_DEFAULT),
(LPSTR) &messageBuffer,
0,
NULL))
{
message = messageBuffer;
LocalFree (messageBuffer);
}
return message;
}
} // namespace
Semaphore::Semaphore (unsigned int value)
{
if ((_semaphore = ::CreateSemaphore (0, value, 0x7fffffff, 0)) == 0)
{
THROW (LogicExc, "Could not create semaphore "
"(" << errorString() << ").");
}
}
Semaphore::~Semaphore()
{
bool ok = ::CloseHandle (_semaphore) != FALSE;
assert (ok);
}
void
Semaphore::wait()
{
if (::WaitForSingleObject (_semaphore, INFINITE) != WAIT_OBJECT_0)
{
THROW (LogicExc, "Could not wait on semaphore "
"(" << errorString() << ").");
}
}
bool
Semaphore::tryWait()
{
return ::WaitForSingleObject (_semaphore, 0) == WAIT_OBJECT_0;
}
void
Semaphore::post()
{
if (!::ReleaseSemaphore (_semaphore, 1, 0))
{
THROW (LogicExc, "Could not post on semaphore "
"(" << errorString() << ").");
}
}
int
Semaphore::value() const
{
LONG v = -1;
if (!::ReleaseSemaphore (_semaphore, 0, &v) || v < 0)
{
THROW (LogicExc, "Could not get value of semaphore "
"(" << errorString () << ").");
}
return v;
}
ILMTHREAD_INTERNAL_NAMESPACE_SOURCE_EXIT
#endif
| 4,189
| 1,509
|
#include <fstream>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <cstdlib> // srand and rand
#include <ctime> // time
#include <algorithm>
#include <iomanip>
#include <sstream>
#include <string>
#include <conio.h>
using namespace std;
const char* mFile = "man.txt";
const char* wFile = "woman.txt";
const char* sFile = "surname.txt";
const char* oFile1 = "randomStudent.txt";
const char* oFile2 = "sequentialGano.txt";
const char* oFile3 = "sortedGano.txt";
const char* oFile4 = "sortedStudentNumber.txt";
const char* oFile5 = "sortedGenderMan.txt";
const char* oFile6 = "sortedGenderWoman.txt";
const char* oFile7 = "sortedClass1.txt";
const char* oFile8 = "sortedClass2.txt";
const char* oFile9 = "sortedClass3.txt";
const char* oFile10 = "sortedClass4.txt";
ofstream o1(oFile1, ios::out);
ofstream o2(oFile2, ios::out);
ofstream o3(oFile3, ios::out);
ofstream o4(oFile4, ios::out);
ofstream o5(oFile5, ios::out);
ofstream o6(oFile6, ios::out);
ofstream o7(oFile7, ios::out);
ofstream o8(oFile8, ios::out);
ofstream o9(oFile9, ios::out);
ofstream o10(oFile10, ios::out);
ifstream mF(mFile, ios::in);
ifstream wF(wFile, ios::in);
ifstream sF(sFile, ios::in);
ifstream oP2(oFile2, ios::in);
ifstream oP3(oFile2, ios::in);
std::clock_t start1, start2, start3, start4, start5;
double duration1 = 0, duration2 = 0, duration3 = 0, duration4 = 0, duration5 = 0;
struct people{
string name;
string surName;
string gender;
int studentNumber;
int classNumber;
int classSequenceNumber;
int sectionSequenceNumber;
float gano;
}student[10000];
bool here(int studentNumberTemp)
{
bool back = false;
for(int i = 0 ; i < 10000; i++)
{
if(student[i].studentNumber == studentNumberTemp)
{
back = false;
}
else
{
back = true;
break;
}
}
return back;
}
int checkSectionNumber(int studentNumber)
{
int h = 0, studentNumberTemp = 0, sectionSequenceNumberTemp = 0, checkedSectionNumber = 0, k = 0;
string word, line;
ifstream oP9(oFile3, ios::in);
if (!oP9)
{
cout << "ERROR!! - FILE CAN NOT OPEN - oP9 " << endl;
//return (-1);
}
while (getline(oP9, line) && (k == 0))
{
stringstream ss(line);
while (getline(ss, word, ';'))
{
if (h == 0)
{
studentNumberTemp = atoi(word.c_str());
}
else if (h == 6)
{
sectionSequenceNumberTemp = atoi(word.c_str());
}
else if (h == 7)
{
if ((studentNumberTemp == studentNumber))
{
checkedSectionNumber = sectionSequenceNumberTemp;
k = 1;
return checkedSectionNumber;
break;
}
h = 0;
continue;
}
h++;
}
}
oP9.close();
}
int checkClassNumber(int studentNumber, int classNumber)
{
int k = 0, h = 0, checkedClassNumber = 0, studentNumberTemp = 0, classSequenceNumberTemp = 0;
string word, line;
const char* oFile15 = "sortedClass1.txt";
const char* oFile16 = "sortedClass2.txt";
const char* oFile17 = "sortedClass3.txt";
const char* oFile18 = "sortedClass4.txt";
if (classNumber == 1)
{
ifstream oP10(oFile7, ios::in);
if (!oP10)
{
cout << "ERROR!! - FILE CAN NOT OPEN - oP10 " << endl;
return (-1);
}
while (getline(oP10, line) && (k == 0))
{
stringstream ss(line);
while (getline(ss, word, ';'))
{
if (h == 0)
{
studentNumberTemp = atoi(word.c_str());
}
else if (h == 7)
{
classSequenceNumberTemp = atoi(word.c_str());
if ((studentNumberTemp == studentNumber))
{
checkedClassNumber = classSequenceNumberTemp;
k = 1;
return checkedClassNumber;
break;
}
h = 0;
continue;
}
h++;
}
}
oP10.close();
}
else if (classNumber == 2)
{
ifstream oP11(oFile8, ios::in);
if (!oP11)
{
cout << "ERROR!! - FILE CAN NOT OPEN - oP11 " << endl;
return (-1);
}
while (getline(oP11, line) && (k == 0))
{
stringstream ss(line);
while (getline(ss, word, ';'))
{
if (h == 0)
{
studentNumberTemp = atoi(word.c_str());
}
else if (h == 7)
{
classSequenceNumberTemp = atoi(word.c_str());
if ((studentNumberTemp == studentNumber))
{
checkedClassNumber = classSequenceNumberTemp;
k = 1;
return checkedClassNumber;
break;
}
h = 0;
continue;
}
h++;
}
}
oP11.close();
}
else if (classNumber == 3)
{
ifstream oP12(oFile9, ios::in);
if (!oP12)
{
cout << "ERROR!! - FILE CAN NOT OPEN - oP12 " << endl;
return (-1);
}
while (getline(oP12, line) && (k == 0))
{
stringstream ss(line);
while (getline(ss, word, ';'))
{
if (h == 0)
{
studentNumberTemp = atoi(word.c_str());
}
else if (h == 7)
{
classSequenceNumberTemp = atoi(word.c_str());
if ((studentNumberTemp == studentNumber))
{
checkedClassNumber = classSequenceNumberTemp;
k = 1;
return checkedClassNumber;
break;
}
h = 0;
continue;
}
h++;
}
}
oP12.close();
}
else if (classNumber == 4)
{
ifstream oP13(oFile10, ios::in);
if (!oP13)
{
cout << "ERROR!! - FILE CAN NOT OPEN - oP13 " << endl;
return (-1);
}
while (getline(oP13, line) && (k == 0))
{
stringstream ss(line);
while (getline(ss, word, ';'))
{
if (h == 0)
{
studentNumberTemp = atoi(word.c_str());
}
else if (h == 7)
{
classSequenceNumberTemp = atoi(word.c_str());
if ((studentNumberTemp == studentNumber))
{
checkedClassNumber = classSequenceNumberTemp;
k = 1;
return checkedClassNumber;
break;
}
h = 0;
continue;
}
h++;
}
}
oP13.close();
}
}
int callGano()
{
start5 = std::clock();
int c1 = 0;
int c2 = 2500;
int c3 = 5000;
int c4 = 7500;
string word, line, line2, nameTemp, surnameTemp, genderTemp, ganoTemp, temp, x;
string ganoReady2[4001];
int h = 0, studentNumberTemp = 0, classNumberTemp = 0, s = 0, b = 0, l = 0, p = 0, m = 0, sectionSequenceNumberTemp = 0, classSequenceNumberTemp = 0;
float gano[10000];
float ganoTemp2 = 0.000;
double ganoReady[4001];
for (double y = 0.000; y <= 4.000; y = y + 0.001) //for gano numbers
{
ganoReady[s] = y;
s++;
}
if(!o2)
{
cout << "ERROR!! - FILE CAN NOT OPEN - 3" << endl;
return -1;
}
else // gano numbers text
{
for( int i = 0; i < 4001; i++)
{
o2 << fixed << setprecision(3) << ganoReady[i] << endl;
}
}
o2.close();
if ( (!oP3) )
{
cout << "ERROR!! - FILE CAN NOT OPEN - 9" << endl;
}
else if (oP3.is_open())
{
while (getline(oP3, line2))
{
ganoReady2[b] = line2;
b++;
}
}
for (int i = 0; i < 4001; i++) //test for gano numbers.
{
//cout << fixed << setprecision(3) << ganoReady2[i] << endl;
}
for (float i = 0.000; i <= 4.000; (i = i + 0.001))
{
ifstream oP7(oFile1, ios::in);
if (!oP7)
{
cout << "ERROR!! - FILE CAN NOT OPEN - 10 " << endl;
return (-1);
}
while (getline(oP7, line)) //class sort with gano sort
{
stringstream ss(line);
while (getline(ss, word, ';'))
{
if (h == 0)
{
studentNumberTemp = atoi(word.c_str());
}
else if (h == 1)
{
classNumberTemp = atoi(word.c_str());
}
else if (h == 2)
{
nameTemp = word;
}
else if (h == 3)
{
surnameTemp = word;
}
else if (h == 4)
{
genderTemp = word;
}
else if (h == 5)
{
x = word;
istringstream iss(word);
iss >> ganoTemp2;
}
else if (h == 6)
{
sectionSequenceNumberTemp = atoi(word.c_str());
}
else if (h == 7)
{
classSequenceNumberTemp = atoi(word.c_str());
if (ganoReady2[p] == x)
{
if (classNumberTemp == 1)
{
student[c1].studentNumber = studentNumberTemp;
student[c1].classNumber = classNumberTemp;
student[c1].name = nameTemp;
student[c1].surName = surnameTemp;
student[c1].gender = genderTemp;
student[c1].gano = ganoTemp2;
student[c1].sectionSequenceNumber = sectionSequenceNumberTemp;
student[c1].classSequenceNumber = classSequenceNumberTemp;
//cout << c1 << " " << student[c1].studentNumber << " " << student[c1].classNumber << " " << student[c1].name << " " << student[c1].surName << " " << student[c1].gender << " " << fixed << setprecision(3) << student[c1].gano << endl;
c1++;
}
else if ((classNumberTemp == 2))
{
student[c2].studentNumber = studentNumberTemp;
student[c2].classNumber = classNumberTemp;
student[c2].name = nameTemp;
student[c2].surName = surnameTemp;
student[c2].gender = genderTemp;
student[c2].gano = ganoTemp2;
student[c2].sectionSequenceNumber = sectionSequenceNumberTemp;
student[c2].classSequenceNumber = classSequenceNumberTemp;
//cout << c2 << " " << student[c2].studentNumber << " " << student[c2].classNumber << " " << student[c2].name << " " << student[c2].surName << " " << student[c2].gender << " " << fixed << setprecision(3) << student[c2].gano << endl;
c2++;
}
else if ((classNumberTemp == 3))
{
student[c3].studentNumber = studentNumberTemp;
student[c3].classNumber = classNumberTemp;
student[c3].name = nameTemp;
student[c3].surName = surnameTemp;
student[c3].gender = genderTemp;
student[c3].gano = ganoTemp2;
student[c3].sectionSequenceNumber = sectionSequenceNumberTemp;
student[c3].classSequenceNumber = classSequenceNumberTemp;
//cout << c3 << " " << student[c3].studentNumber << " " << student[c3].classNumber << " " << student[c3].name << " " << student[c3].surName << " " << student[c3].gender << " " << fixed << setprecision(3) << student[c3].gano << endl;
c3++;
}
else if ((classNumberTemp == 4))
{
student[c4].studentNumber = studentNumberTemp;
student[c4].classNumber = classNumberTemp;
student[c4].name = nameTemp;
student[c4].surName = surnameTemp;
student[c4].gender = genderTemp;
student[c4].gano = ganoTemp2;
student[c4].sectionSequenceNumber = sectionSequenceNumberTemp;
student[c4].classSequenceNumber = classSequenceNumberTemp;
//cout << c4 << " " << student[c4].studentNumber << " " << student[c4].classNumber << " " << student[c4].name << " " << student[c4].surName << " " << student[c4].gender << " " << fixed << setprecision(3) << student[c4].gano << endl;
c4++;
}
}
h = 0;
continue;
}
h++;
}
}
p++;
oP7.close();
}
for (int i = 0; i < 10000; i++)
{
if (i < 2500)
{
student[i].classSequenceNumber = 2500 - i;
}
else if (i >= 2500 && i < 5000)
{
student[i].classSequenceNumber = 5000 - i;
}
else if (i >= 5000 && i < 7500)
{
student[i].classSequenceNumber = 7500 - i;
}
else if ( i >= 7500)
{
student[i].classSequenceNumber = 10000 - i;
}
}
if (!o7 || !o8 || !o9 || !o10)
{
cout << "ERROR!! - FILE CAN NOT OPEN 6" << endl;
return -1;
}
else
{
int q = 0;
for (int i = 0; i < 10000; i++) // sorting gano
{
//q = checkSectionNumber(student[i].studentNumber);
if ( i < 2500)
{
q = checkSectionNumber(student[i].studentNumber);
o7 << student[i].studentNumber << ";" << student[i].classNumber << ";" << student[i].name << ";" << student[i].surName << ";" << student[i].gender << ";" << fixed << setprecision(3) << student[i].gano << ";" << q << ";" << student[i].classSequenceNumber <<endl;
}
else if ( i >= 2500 && i < 5000)
{
q = checkSectionNumber(student[i].studentNumber);
o8 << student[i].studentNumber << ";" << student[i].classNumber << ";" << student[i].name << ";" << student[i].surName << ";" << student[i].gender << ";" << fixed << setprecision(3) << student[i].gano << ";" << q << ";" << student[i].classSequenceNumber <<endl;
}
else if ( i >= 5000 && i < 7500)
{
q = checkSectionNumber(student[i].studentNumber);
o9 << student[i].studentNumber << ";" << student[i].classNumber << ";" << student[i].name << ";" << student[i].surName << ";" << student[i].gender << ";" << fixed << setprecision(3) << student[i].gano << ";" << q << ";" << student[i].classSequenceNumber <<endl;
}
else if ( i >= 7500)
{
q = checkSectionNumber(student[i].studentNumber);
o10 << student[i].studentNumber << ";" << student[i].classNumber << ";" << student[i].name << ";" << student[i].surName << ";" << student[i].gender << ";" << fixed << setprecision(3) << student[i].gano << ";" << q << ";" << student[i].classSequenceNumber <<endl;
}
}
}
duration5 = ( std::clock() - start5 ) / (double) CLOCKS_PER_SEC;
cout << "Time of sorting Gano with Class Numbers : " << fixed << duration5 << endl;
}
int main(int argc, char** argv)
{
start1 = std::clock();
setlocale(LC_ALL, "Turkish");
string manName[5000];
string womanName[5000];
string surName[2446];
string word, line, line2, nameTemp, surnameTemp, genderTemp, ganoTemp, temp, x;
string ganoReady2[4001];
int studentNumber[10000];
int classNumber[10000];
int m = 0, w = 0, p = 0, k = 0, h = 0, l = 0, j = 0, g = 0, t = 0, kS = 0, eS = 0, studentNumberTemp = 0, classNumberTemp = 0, b = 0, s = 0, v = 0, classSequenceNumberTemp = 0, sectionSequenceNumberTemp = 0;
float gano[10000];
float ganoTemp2 = 0.000;
double ganoReady[4001];
bool back;
if (!mF || !wF || !sF)
{
cout << "ERROR!! - FILE CAN NOT OPEN - 1";
return(-1);
}
else if (mF.is_open() || wF.is_open() || sF.is_open()) //for names and surnames
{
int k = 1;
for (int i = 0; i < k; i++)
{
if ( mF.eof() )
{
mF.close();
}
else if( (!(mF.eof())) && (mF.is_open()) )
{
mF >> manName[i];
}
if ( wF.eof() )
{
wF.close();
}
else if( (!(wF.eof())) && (wF.is_open()) )
{
wF >> womanName[i];
}
if ( sF.eof() )
{
sF.close();
}
else if( (!(sF.eof())) && (sF.is_open()) )
{
sF >> surName[i];
}
if ( (wF.eof()) && (mF.eof()) && (sF.eof()) )
{
break;
}
k++;
}
}
for (int i = 0; i < 10000; i++) //for class numbers
{
if (i < 2500)
{
classNumber[i] = 1;
}
else if (i >= 2500 && i < 5000)
{
classNumber[i] = 2;
}
else if (i >= 5000 && i < 7500)
{
classNumber[i] = 3;
}
else
{
classNumber[i] = 4;
}
}
for(int i = 0; i < 10000; i++) // for student numbers
{
studentNumber[i] = i + 1;
}
srand(time(NULL));
for ( int i = 0; i < 10000; i++) //suffle
{
int random1, random2, random3, random4, random5, random6, random7, random8, random9, random10, number1;
string name1;
random1 = rand() % 5000;
random2 = rand() % 5000;
random3 = rand() % 5000;
random4 = rand() % 5000;
random5 = rand() % 2445;
random6 = rand() % 2445;
random7 = rand() % 10000;
random8 = rand() % 10000;
random9 = rand() % 10000;
random10 = rand() % 10000;
name1 = manName[random1];
manName[random1] = manName[random2];
manName[random2] = name1;
name1 = womanName[random3];
womanName[random3] = womanName[random4];
womanName[random4] = name1;
name1 = surName[random5];
surName[random5] = surName[random6];
surName[random6] = name1;
number1 = classNumber[random7];
classNumber[random7] = classNumber[random8];
classNumber[random8] = number1;
number1 = studentNumber[random9];
studentNumber[random9] = studentNumber[random10];
studentNumber[random10] = number1;
}
cout.precision(3); // after point three digit
for ( int i = 0; i < 10000; i++ ) //for gano
{
gano[i] = (4.0 * (rand() / (double)RAND_MAX));
//cout << gano[i] << fixed << endl;
}
for (int i = 0; i < 5000; i++) //test for names
{
//cout << womanName[i] << endl;
//cout << manName[i] << endl;
}
for (int i = 0; i < 2445; i++) // test for surnames
{
//cout << surName[i] << endl;
}
for (int i = 0; i < 10000; i++) //test for classNumber and studentNumber
{
//cout << classNumber[i] << endl;
//cout << studentNumber[i] << endl;
}
if (!o1)
{
cout << "ERROR!! - FILE CAN NOT OPEN - 2" << endl;
return -1;
}
else if( o1.is_open() ) // first output1 - random students
{
for (int i = 0; i < 10000; i++)
{
int surNameRandom, genderRandom;
surNameRandom = rand() % 2445;
genderRandom = rand() % 2;
if ( ( (genderRandom == 0) && (m < 5000) ) || (w > 4999) )
{
o1 << studentNumber[i] << ";" << classNumber[i] << ";" << manName[m] << ";" << surName[surNameRandom] << ";" << "E" << ";" << fixed << setprecision(3) << gano[i] << ";" << "0" << ";" << "0" << endl;
m++;
}
else if ( ( (genderRandom == 1) && (w < 5000) ) || (m > 4999) )
{
o1 << studentNumber[i] << ";" << classNumber[i] << ";" << womanName[w] << ";" << surName[surNameRandom] << ";" << "K" << ";" << fixed << setprecision(3) << gano[i] << ";" << "0" << ";" << "0" << endl;
w++;
}
}
}
o1.close();
for (double y = 0.000; y <= 4.000; y = y + 0.001) //for gano numbers
{
ganoReady[s] = y;
s++;
}
if(!o2)
{
cout<< "ERROR!! - FILE CAN NOT OPEN - 3" << endl;
return -1;
}
else // gano numbers text
{
for( int i = 0; i < 4001; i++)
{
o2 << fixed << setprecision(3) << ganoReady[i] << endl;
}
}
o2.close();
if ( (!oP2) )
{
cout << "ERROR!! - FILE CAN NOT OPEN - 4" << endl;
}
else if (oP2.is_open())
{
while (getline(oP2, line2))
{
ganoReady2[b] = line2;
b++;
}
}
for (int i = 0; i < 4001; i++) //test for gano numbers.
{
// cout << fixed << setprecision(3) << ganoReady2[i] << endl;
}
duration1 = ( std::clock() - start1 ) / (double) CLOCKS_PER_SEC;
cout << "Time of Shuffle : " << duration1 << endl;
start2 = std::clock();
for (float i = 0.000; i <= 4.000; (i = i + 0.001)) //0.001
{
ifstream oP1(oFile1, ios::in);
if (!oP1)
{
cout << "ERROR!! - FILE CAN NOT OPEN - 5 " << endl;
return (-1);
}
while (getline(oP1, line))
{
stringstream ss(line);
while (getline(ss, word, ';'))
{
if (h == 0)
{
studentNumberTemp = atoi(word.c_str());
}
else if (h == 1)
{
classNumberTemp = atoi(word.c_str());
}
else if (h == 2)
{
nameTemp = word;
}
else if (h == 3)
{
surnameTemp = word;
}
else if (h == 4)
{
genderTemp = word;
}
else if (h == 5)
{
x = word;
istringstream iss(word);
iss >> ganoTemp2;
}
else if (h == 6)
{
sectionSequenceNumberTemp = atoi(word.c_str());
}
else if (h == 7)
{
classSequenceNumberTemp = atoi(word.c_str());
if ((ganoReady2[p] == x)) //gano sorting
{
student[l].studentNumber = studentNumberTemp;
student[l].classNumber = classNumberTemp;
student[l].name = nameTemp;
student[l].surName = surnameTemp;
student[l].gender = genderTemp;
student[l].gano = ganoTemp2;
student[l].sectionSequenceNumber = sectionSequenceNumberTemp;
student[l].classSequenceNumber = classSequenceNumberTemp;
//cout << l << " ---- " << student[l].studentNumber << ";" << student[l].classNumber << ";" << student[l].name << ";" << student[l].surName << ";" << student[l].gender << ";" << fixed << setprecision(3) << student[l].gano << ";" << student[l].sectionSequenceNumber << ";" << student[l].classSequenceNumber << endl;
l++;
}
h = 0;
continue;
}
h++;
}
}
p++;
oP1.close();
duration2 = ( std::clock() - start2 ) / (double) CLOCKS_PER_SEC;
}
cout << "Time of sorting Gano : " << fixed << duration2 << endl;
for (int i = 10000; i > 0; i--)
{
student[t].sectionSequenceNumber = i;
t++;
//cout << i << "----" << student[i].sectionSequenceNumber << endl;
}
if (!o3)
{
cout << "ERROR!! - FILE CAN NOT OPEN 6" << endl;
return -1;
}
else
{
for (int i = 0; i < 10000; i++) // sorting gano
{
//cout << i << " ---- " << student[i].studentNumber << ";" << student[i].classNumber << ";" << student[i].name << ";" << student[i].surName << ";" << student[i].gender << ";" << fixed << setprecision(3) << student[i].gano << ";" << student[i].sectionSequenceNumber << ";" << student[i].classSequenceNumber << endl;
o3 << student[i].studentNumber << ";" << student[i].classNumber << ";" << student[i].name
<< ";" << student[i].surName << ";" << student[i].gender << ";" << fixed
<< setprecision(3) << student[i].gano << ";" << student[i].sectionSequenceNumber << ";" << student[i].classSequenceNumber << endl;
}
}
o3.close();
callGano();
int r = 0;
start4 = std::clock();
for (int i = 0; i < 1 ; i++) // sorting gender
{
int eS = 0;
int kS = 5000;
ifstream oP5(oFile1, ios::in);
while ( getline(oP5, line) )
{
stringstream ss(line);
while ( getline(ss, word, ';') )
{
//cout << "word" << word << endl;
if (r == 0)
{
studentNumberTemp = atoi(word.c_str());
}
else if (r == 1)
{
classNumberTemp = atoi(word.c_str());
}
else if (r == 2)
{
nameTemp = word;
}
else if (r == 3)
{
surnameTemp = word;
}
else if (r == 4)
{
genderTemp = word;
//cout << "gendertemp" << word << endl;
}
else if (r == 5)
{
istringstream iss(word);
iss >> ganoTemp2;
}
else if (r == 6)
{
}
else if (r == 7)
{
back = here(studentNumberTemp);
if( (genderTemp == "E") && (back == true) )
{
student[eS].studentNumber = studentNumberTemp;
student[eS].classNumber = classNumberTemp;
student[eS].name = nameTemp;
student[eS].surName = surnameTemp;
student[eS].gender = genderTemp;
student[eS].gano = ganoTemp2;
//cout << eS << " " << student[eS].studentNumber << " " << student[eS].classNumber << " " << student[eS].name << " " << student[eS].surName << " " << student[eS].gender << " " << fixed << setprecision(3) << student[eS].gano << " " << student[eS].sectionSequenceNumber << " " << student[eS].classSequenceNumber << endl;
eS++;
}
else if ( (genderTemp == "K") && (back == true) )
{
student[kS].studentNumber = studentNumberTemp;
student[kS].classNumber = classNumberTemp;
student[kS].name = nameTemp;
student[kS].surName = surnameTemp;
student[kS].gender = genderTemp;
student[kS].gano = ganoTemp2;
//cout << kS << " " << genderW[kS].studentNumber << " " << genderW[kS].classNumber << " " << genderW[kS].name << " " << genderW[kS].surName << " " << genderW[kS].gender << " " << fixed << setprecision(3) << genderW[kS].gano << endl;
kS++;
}
r = 0;
continue;
}
r++;
}
}
oP5.close();
}
if (!o5 && !o6)
{
cout << "ERROR!! - FILE CAN NOT OPEN 6" << endl;
return -1;
}
else
{
int d, f;
for( int i = 0; i <= 4999; i++)
{
d = checkClassNumber(student[i].studentNumber, student[i].classNumber);
f = checkSectionNumber(student[i].studentNumber);
o5 << student[i].studentNumber << ";" << student[i].classNumber << ";" << student[i].name
<< ";" << student[i].surName << ";" << student[i].gender << ";" << fixed
<< setprecision(3) << student[i].gano << ";" << f << ";" << d <<endl;
}
for( int m = 5000 ; m <= 9999; m++)
{
d = checkClassNumber(student[m].studentNumber, student[m].classNumber);
f = checkSectionNumber(student[m].studentNumber);
o6 << student[m].studentNumber << ";" << student[m].classNumber << ";" << student[m].name
<< ";" << student[m].surName << ";" << student[m].gender << ";" << fixed
<< setprecision(3) << student[m].gano << ";" << f << ";" << d << endl;
}
duration4 = ( std::clock() - start4 ) / (double) CLOCKS_PER_SEC;
}
cout << "Time of sorting Gender : " << fixed << duration4 << endl;
start3 = std::clock();
for (int i = 0; i <= 10000 ; i++) //sorting student number
{
ifstream oP3(oFile1, ios::in);
while ( getline(oP3, line) )
{
stringstream ss(line);
while ( getline(ss, word, ';') )
{
if (g == 0)
{
studentNumberTemp = atoi(word.c_str());
}
else if (g == 1)
{
classNumberTemp = atoi(word.c_str());
}
else if (g == 2)
{
nameTemp = word;
}
else if (g == 3)
{
surnameTemp = word;
}
else if (g == 4)
{
genderTemp = word;
}
else if (g == 5)
{
x = word;
istringstream iss(word);
iss >> ganoTemp2;
}
else if (g == 6)
{
//sectionSequenceNumberTemp = atoi(word.c_str());
}
else if (g == 7)
{
if( (i == studentNumberTemp ) )
{
student[v].studentNumber = studentNumberTemp;
student[v].classNumber = classNumberTemp;
student[v].name = nameTemp;
student[v].surName = surnameTemp;
student[v].gender = genderTemp;
student[v].gano = ganoTemp2;
//cout << v << " " << student[v].studentNumber << " " << student[v].classNumber << " " << student[v].name << " " << student[v].surName << " " << student[v].gender << " " << fixed << setprecision(3) << student[v].gano << endl;
v++;
}
g = 0;
continue;
}
g++;
}
}
oP3.close();
duration3 = ( std::clock() - start3 ) / (double) CLOCKS_PER_SEC;
}
cout << "Time of sorting Student Number : " << fixed << duration3 << endl;
if (!o4)
{
cout << "ERROR!! - FILE CAN NOT OPEN 6" << endl;
return -1;
}
else
{
int d, f;
for (int i = 0; i < 10000; i++) // sorting studentNumber
{
d = checkClassNumber(student[i].studentNumber, student[i].classNumber);
f = checkSectionNumber(student[i].studentNumber);
o4 << student[i].studentNumber << ";" << student[i].classNumber << ";" << student[i].name
<< ";" << student[i].surName << ";" << student[i].gender << ";" << fixed
<< setprecision(3) << student[i].gano << ";" << f << ";" << d << endl;
}
}
o4.close();
return 0;
}
| 32,684
| 12,841
|
// Circumference and area of a circle with radius 2.5
#include <iostream>
using namespace std;
const double pi = 3.141593;
int main()
{
double area, circuit, radius = 1.5;
area = pi * radius * radius;
circuit = 2 * pi * radius;
cout << "\nTo Evaluate a Circle\n" << endl;
cout << "Radius:
" << radius
<< "Circumference: " << circuit
<< "Area:
" << area
<< endl
<< endl
<< endl;
return 0;
}
| 390
| 145
|
#include <EditorPluginProcGenPCH.h>
#include <EditorEngineProcessFramework/EngineProcess/EngineProcessMessages.h>
#include <EditorPluginProcGen/ProcGenGraphAsset/ProcGenGraphAsset.h>
#include <EditorPluginProcGen/ProcGenGraphAsset/ProcGenGraphQt.h>
#include <Foundation/Strings/StringBuilder.h>
#include <Foundation/Strings/TranslationLookup.h>
#include <GameEngine/VisualScript/VisualScriptInstance.h>
#include <GuiFoundation/NodeEditor/Pin.h>
#include <GuiFoundation/UIServices/UIServices.moc.h>
#include <ToolsFoundation/Command/NodeCommands.h>
#include <QAction>
#include <QMenu>
#include <QPainter>
#include <QTimer>
namespace
{
static ezColorGammaUB CategoryColor(const char* szCategory)
{
if (ezStringUtils::IsEqual(szCategory, "Input"))
return ezColorGammaUB(38, 105, 0);
else if (ezStringUtils::IsEqual(szCategory, "Output"))
return ezColorGammaUB(0, 101, 105);
else if (ezStringUtils::IsEqual(szCategory, "Math"))
return ezColorGammaUB(0, 53, 91);
return ezColor::DarkOliveGreen;
}
} // namespace
//////////////////////////////////////////////////////////////////////////
ezQtProcGenNode::ezQtProcGenNode()
{
// this costs too much performance :-(
EnableDropShadow(false);
}
void ezQtProcGenNode::InitNode(const ezDocumentNodeManager* pManager, const ezDocumentObject* pObject)
{
ezQtNode::InitNode(pManager, pObject);
const ezRTTI* pRtti = pObject->GetType();
if (const ezCategoryAttribute* pAttr = pRtti->GetAttributeByType<ezCategoryAttribute>())
{
ezColorGammaUB color = CategoryColor(pAttr->GetCategory());
m_HeaderColor = qRgb(color.r, color.g, color.b);
}
}
void ezQtProcGenNode::UpdateState()
{
ezStringBuilder sTitle;
const ezRTTI* pRtti = GetObject()->GetType();
auto& typeAccessor = GetObject()->GetTypeAccessor();
if (const ezTitleAttribute* pAttr = pRtti->GetAttributeByType<ezTitleAttribute>())
{
ezStringBuilder temp;
ezStringBuilder temp2;
ezHybridArray<ezAbstractProperty*, 32> properties;
GetObject()->GetType()->GetAllProperties(properties);
sTitle = pAttr->GetTitle();
for (const auto& pin : GetInputPins())
{
temp.Set("{", pin->GetPin()->GetName(), "}");
if (pin->HasAnyConnections())
{
sTitle.ReplaceAll(temp, pin->GetPin()->GetName());
}
else
{
temp2.Set("{Input", pin->GetPin()->GetName(), "}");
sTitle.ReplaceAll(temp, temp2);
}
}
ezVariant val;
ezStringBuilder sVal;
ezStringBuilder sEnumVal;
for (const auto& prop : properties)
{
if (prop->GetCategory() == ezPropertyCategory::Set)
{
sVal = "{";
ezHybridArray<ezVariant, 16> values;
typeAccessor.GetValues(prop->GetPropertyName(), values);
for (auto& setVal : values)
{
if (sVal.GetElementCount() > 1)
{
sVal.Append(", ");
}
sVal.Append(setVal.ConvertTo<ezString>().GetView());
}
sVal.Append("}");
}
else
{
val = typeAccessor.GetValue(prop->GetPropertyName());
if (prop->GetSpecificType()->IsDerivedFrom<ezEnumBase>() || prop->GetSpecificType()->IsDerivedFrom<ezBitflagsBase>())
{
ezReflectionUtils::EnumerationToString(prop->GetSpecificType(), val.ConvertTo<ezInt64>(), sEnumVal);
sVal = ezTranslate(sEnumVal);
}
else if (prop->GetSpecificType() == ezGetStaticRTTI<bool>())
{
sVal = val.Get<bool>() ? "[x]" : "[ ]";
if (ezStringUtils::IsEqual(prop->GetPropertyName(), "Active"))
{
SetActive(val.Get<bool>());
}
}
else if (val.CanConvertTo<ezString>())
{
sVal = val.ConvertTo<ezString>();
}
}
temp.Set("{", prop->GetPropertyName(), "}");
sTitle.ReplaceAll(temp, sVal);
}
}
else
{
sTitle = pRtti->GetTypeName();
if (sTitle.StartsWith_NoCase("ezProcGen"))
{
sTitle.Shrink(9, 0);
}
}
m_pLabel->setPlainText(sTitle.GetData());
}
//////////////////////////////////////////////////////////////////////////
ezQtProcGenPin::ezQtProcGenPin() = default;
ezQtProcGenPin::~ezQtProcGenPin() = default;
void ezQtProcGenPin::ExtendContextMenu(QMenu& menu)
{
QAction* pAction = new QAction("Debug", &menu);
pAction->setCheckable(true);
pAction->setChecked(m_bDebug);
pAction->connect(pAction, &QAction::triggered, [this](bool bChecked) { SetDebug(bChecked); });
menu.addAction(pAction);
}
void ezQtProcGenPin::keyPressEvent(QKeyEvent* event)
{
if (event->key() == Qt::Key_D || event->key() == Qt::Key_F9)
{
SetDebug(!m_bDebug);
}
}
void ezQtProcGenPin::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
ezQtPin::paint(painter, option, widget);
painter->save();
painter->setPen(QPen(QColor(220, 0, 0), 3.5f, Qt::DotLine));
painter->setBrush(Qt::NoBrush);
if (m_bDebug)
{
float pad = 3.5f;
QRectF bounds = path().boundingRect().adjusted(-pad, -pad, pad, pad);
painter->drawEllipse(bounds);
}
painter->restore();
}
QRectF ezQtProcGenPin::boundingRect() const
{
QRectF bounds = ezQtPin::boundingRect();
return bounds.adjusted(-6, -6, 6, 6);
}
void ezQtProcGenPin::SetDebug(bool bDebug)
{
if (m_bDebug != bDebug)
{
m_bDebug = bDebug;
auto pScene = static_cast<ezQtProcGenScene*>(scene());
pScene->SetDebugPin(bDebug ? this : nullptr);
update();
}
}
//////////////////////////////////////////////////////////////////////////
ezQtProcGenScene::ezQtProcGenScene(QObject* parent /*= nullptr*/)
: ezQtNodeScene(parent)
{
}
ezQtProcGenScene::~ezQtProcGenScene() = default;
void ezQtProcGenScene::SetDebugPin(ezQtProcGenPin* pDebugPin)
{
if (m_pDebugPin == pDebugPin)
return;
if (m_pDebugPin != nullptr)
{
m_pDebugPin->SetDebug(false);
}
m_pDebugPin = pDebugPin;
if (ezQtDocumentWindow* window = qobject_cast<ezQtDocumentWindow*>(parent()))
{
auto document = static_cast<ezProcGenGraphAssetDocument*>(window->GetDocument());
document->SetDebugPin(pDebugPin != nullptr ? pDebugPin->GetPin() : nullptr);
}
}
ezStatus ezQtProcGenScene::RemoveNode(ezQtNode* pNode)
{
auto pins = pNode->GetInputPins();
pins.PushBackRange(pNode->GetOutputPins());
for (auto pPin : pins)
{
if (pPin == m_pDebugPin)
{
m_pDebugPin->SetDebug(false);
}
}
return ezQtNodeScene::RemoveNode(pNode);
}
| 6,494
| 2,267
|
/** @file
A brief file description
@section license License
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.
*/
/************************************************************************
Net.cc
************************************************************************/
#include "P_Net.h"
#include <utility>
RecRawStatBlock *net_rsb = nullptr;
// All in milli-seconds
int net_config_poll_timeout = -1; // This will get set via either command line or records.config.
int net_event_period = 10;
int net_accept_period = 10;
int net_retry_delay = 10;
int net_throttle_delay = 50; /* milliseconds */
// For the in/out congestion control: ToDo: this probably would be better as ports: specifications
std::string_view net_ccp_in;
std::string_view net_ccp_out;
static inline void
configure_net()
{
REC_RegisterConfigUpdateFunc("proxy.config.net.connections_throttle", change_net_connections_throttle, nullptr);
REC_ReadConfigInteger(fds_throttle, "proxy.config.net.connections_throttle");
REC_EstablishStaticConfigInt32(net_retry_delay, "proxy.config.net.retry_delay");
REC_EstablishStaticConfigInt32(net_throttle_delay, "proxy.config.net.throttle_delay");
// These are not reloadable
REC_ReadConfigInteger(net_event_period, "proxy.config.net.event_period");
REC_ReadConfigInteger(net_accept_period, "proxy.config.net.accept_period");
// This is kinda fugly, but better than it was before (on every connection in and out)
// Note that these would need to be ats_free()'d if we ever want to clean that up, but
// we have no good way of dealing with that on such globals I think?
RecString ccp;
REC_ReadConfigStringAlloc(ccp, "proxy.config.net.tcp_congestion_control_in");
if (ccp && *ccp != '\0') {
net_ccp_in = ccp;
}
REC_ReadConfigStringAlloc(ccp, "proxy.config.net.tcp_congestion_control_out");
if (ccp && *ccp != '\0') {
net_ccp_out = ccp;
}
}
static inline void
register_net_stats()
{
const std::pair<const char *, Net_Stats> persistent[] = {
{"proxy.process.net.calls_to_read", net_calls_to_read_stat},
{"proxy.process.net.calls_to_read_nodata", net_calls_to_read_nodata_stat},
{"proxy.process.net.calls_to_readfromnet", net_calls_to_readfromnet_stat},
{"proxy.process.net.calls_to_readfromnet_afterpoll", net_calls_to_readfromnet_afterpoll_stat},
{"proxy.process.net.calls_to_write", net_calls_to_write_stat},
{"proxy.process.net.calls_to_write_nodata", net_calls_to_write_nodata_stat},
{"proxy.process.net.calls_to_writetonet", net_calls_to_writetonet_stat},
{"proxy.process.net.calls_to_writetonet_afterpoll", net_calls_to_writetonet_afterpoll_stat},
{"proxy.process.net.inactivity_cop_lock_acquire_failure", inactivity_cop_lock_acquire_failure_stat},
{"proxy.process.net.net_handler_run", net_handler_run_stat},
{"proxy.process.net.read_bytes", net_read_bytes_stat},
{"proxy.process.net.write_bytes", net_write_bytes_stat},
{"proxy.process.net.fastopen_out.attempts", net_fastopen_attempts_stat},
{"proxy.process.net.fastopen_out.successes", net_fastopen_successes_stat},
{"proxy.process.socks.connections_successful", socks_connections_successful_stat},
{"proxy.process.socks.connections_unsuccessful", socks_connections_unsuccessful_stat},
};
const std::pair<const char *, Net_Stats> non_persistent[] = {
{"proxy.process.net.accepts_currently_open", net_accepts_currently_open_stat},
{"proxy.process.net.connections_currently_open", net_connections_currently_open_stat},
{"proxy.process.net.default_inactivity_timeout_applied", default_inactivity_timeout_stat},
{"proxy.process.net.dynamic_keep_alive_timeout_in_count", keep_alive_queue_timeout_count_stat},
{"proxy.process.net.dynamic_keep_alive_timeout_in_total", keep_alive_queue_timeout_total_stat},
{"proxy.process.socks.connections_currently_open", socks_connections_currently_open_stat},
};
for (auto &p : persistent) {
RecRegisterRawStat(net_rsb, RECT_PROCESS, p.first, RECD_INT, RECP_PERSISTENT, p.second, RecRawStatSyncSum);
}
for (auto &p : non_persistent) {
RecRegisterRawStat(net_rsb, RECT_PROCESS, p.first, RECD_INT, RECP_NON_PERSISTENT, p.second, RecRawStatSyncSum);
}
NET_CLEAR_DYN_STAT(net_handler_run_stat);
NET_CLEAR_DYN_STAT(net_connections_currently_open_stat);
NET_CLEAR_DYN_STAT(net_accepts_currently_open_stat);
NET_CLEAR_DYN_STAT(net_calls_to_readfromnet_stat);
NET_CLEAR_DYN_STAT(net_calls_to_readfromnet_afterpoll_stat);
NET_CLEAR_DYN_STAT(net_calls_to_read_stat);
NET_CLEAR_DYN_STAT(net_calls_to_read_nodata_stat);
NET_CLEAR_DYN_STAT(net_calls_to_writetonet_stat);
NET_CLEAR_DYN_STAT(net_calls_to_writetonet_afterpoll_stat);
NET_CLEAR_DYN_STAT(net_calls_to_write_stat);
NET_CLEAR_DYN_STAT(net_calls_to_write_nodata_stat);
NET_CLEAR_DYN_STAT(socks_connections_currently_open_stat);
NET_CLEAR_DYN_STAT(keep_alive_queue_timeout_total_stat);
NET_CLEAR_DYN_STAT(keep_alive_queue_timeout_count_stat);
NET_CLEAR_DYN_STAT(default_inactivity_timeout_stat);
RecRegisterRawStat(net_rsb, RECT_PROCESS, "proxy.process.tcp.total_accepts", RECD_INT, RECP_NON_PERSISTENT,
static_cast<int>(net_tcp_accept_stat), RecRawStatSyncSum);
NET_CLEAR_DYN_STAT(net_tcp_accept_stat);
RecRegisterRawStat(net_rsb, RECT_PROCESS, "proxy.process.net.connections_throttled_in", RECD_INT, RECP_PERSISTENT,
(int)net_connections_throttled_in_stat, RecRawStatSyncSum);
RecRegisterRawStat(net_rsb, RECT_PROCESS, "proxy.process.net.connections_throttled_out", RECD_INT, RECP_PERSISTENT,
(int)net_connections_throttled_out_stat, RecRawStatSyncSum);
}
void
ink_net_init(ts::ModuleVersion version)
{
static int init_called = 0;
ink_release_assert(version.check(NET_SYSTEM_MODULE_INTERNAL_VERSION));
if (!init_called) {
// do one time stuff
// create a stat block for NetStats
net_rsb = RecAllocateRawStatBlock(static_cast<int>(Net_Stat_Count));
configure_net();
register_net_stats();
}
init_called = 1;
}
| 6,819
| 2,495
|
/*BEGIN_LEGAL
Intel Open Source License
Copyright (c) 2002-2012 Intel Corporation. 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 Intel Corporation nor the names of its contributors may be used to
endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL 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.
END_LEGAL */
/*
This application causes exception in indirect call instruction and catches it in caller.
The call instruction is located in code region being replaced by Pin probe.
Pin translation should not affect propagation of the exception to the C++ exception handler.
*/
#ifndef TARGET_LINUX
#include <windows.h>
#endif
#include <stdio.h>
#ifndef TARGET_LINUX
#define FASTCALL __fastcall
#define DLLEXPORT __declspec(dllexport)
#else
#define FASTCALL
#define DLLEXPORT
#endif
bool destructed = false;
// cpp exceptions - Exercise windows exception mechanism
class MyClass
{
public:
~MyClass()
{
destructed = true;
}
};
static int (*pBar)() = 0;
int bar()
{
return 0;
}
extern "C"
DLLEXPORT
int foo()
{
#ifdef TARGET_LINUX
if (!pBar) throw(0);
#endif
// May cause exception due to NULL pointer
return pBar();
}
int main()
{
int i = 2;
int local = 1;
try
{
MyClass ins;
i = foo();
local = 0;
}
catch(...)
{
// If Pin translated probed code properly, exception will reach the handler
printf("Exception\n");
}
// Check that destructor was called and local var value was not changed when exception was handled
if (!destructed || (local != 1))
{
return 1;
}
pBar = bar;
try
{
i = foo();
}
catch(...)
{
// No exception expected
printf("Exception\n");
}
return i;
}
| 3,002
| 1,005
|
//==--- InstrEmitter.cpp - Emit MachineInstrs for the SelectionDAG class ---==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This implements the Emit routines for the SelectionDAG class, which creates
// MachineInstrs based on the decisions of the SelectionDAG instruction
// selection.
//
//===----------------------------------------------------------------------===//
#include "InstrEmitter.h"
#include "SDNodeDbgValue.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/StackMaps.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetLowering.h"
#include "llvm/Target/TargetSubtargetInfo.h"
using namespace llvm;
#define DEBUG_TYPE "instr-emitter"
/// MinRCSize - Smallest register class we allow when constraining virtual
/// registers. If satisfying all register class constraints would require
/// using a smaller register class, emit a COPY to a new virtual register
/// instead.
const unsigned MinRCSize = 4;
/// CountResults - The results of target nodes have register or immediate
/// operands first, then an optional chain, and optional glue operands (which do
/// not go into the resulting MachineInstr).
unsigned InstrEmitter::CountResults(SDNode *Node) {
unsigned N = Node->getNumValues();
while (N && Node->getValueType(N - 1) == MVT::Glue)
--N;
if (N && Node->getValueType(N - 1) == MVT::Other)
--N; // Skip over chain result.
return N;
}
/// countOperands - The inputs to target nodes have any actual inputs first,
/// followed by an optional chain operand, then an optional glue operand.
/// Compute the number of actual operands that will go into the resulting
/// MachineInstr.
///
/// Also count physreg RegisterSDNode and RegisterMaskSDNode operands preceding
/// the chain and glue. These operands may be implicit on the machine instr.
static unsigned countOperands(SDNode *Node, unsigned NumExpUses,
unsigned &NumImpUses) {
unsigned N = Node->getNumOperands();
while (N && Node->getOperand(N - 1).getValueType() == MVT::Glue)
--N;
if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
--N; // Ignore chain if it exists.
// Count RegisterSDNode and RegisterMaskSDNode operands for NumImpUses.
NumImpUses = N - NumExpUses;
for (unsigned I = N; I > NumExpUses; --I) {
if (isa<RegisterMaskSDNode>(Node->getOperand(I - 1)))
continue;
if (RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Node->getOperand(I - 1)))
if (TargetRegisterInfo::isPhysicalRegister(RN->getReg()))
continue;
NumImpUses = N - I;
break;
}
return N;
}
/// EmitCopyFromReg - Generate machine code for an CopyFromReg node or an
/// implicit physical register output.
void InstrEmitter::
EmitCopyFromReg(SDNode *Node, unsigned ResNo, bool IsClone, bool IsCloned,
unsigned SrcReg, DenseMap<SDValue, unsigned> &VRBaseMap) {
unsigned VRBase = 0;
if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
// Just use the input register directly!
SDValue Op(Node, ResNo);
if (IsClone)
VRBaseMap.erase(Op);
bool isNew = VRBaseMap.insert(std::make_pair(Op, SrcReg)).second;
(void)isNew; // Silence compiler warning.
assert(isNew && "Node emitted out of order - early");
return;
}
// If the node is only used by a CopyToReg and the dest reg is a vreg, use
// the CopyToReg'd destination register instead of creating a new vreg.
bool MatchReg = true;
const TargetRegisterClass *UseRC = nullptr;
MVT VT = Node->getSimpleValueType(ResNo);
// Stick to the preferred register classes for legal types.
if (TLI->isTypeLegal(VT))
UseRC = TLI->getRegClassFor(VT);
if (!IsClone && !IsCloned)
for (SDNode *User : Node->uses()) {
bool Match = true;
if (User->getOpcode() == ISD::CopyToReg &&
User->getOperand(2).getNode() == Node &&
User->getOperand(2).getResNo() == ResNo) {
unsigned DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
VRBase = DestReg;
Match = false;
} else if (DestReg != SrcReg)
Match = false;
} else {
for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
SDValue Op = User->getOperand(i);
if (Op.getNode() != Node || Op.getResNo() != ResNo)
continue;
MVT VT = Node->getSimpleValueType(Op.getResNo());
if (VT == MVT::Other || VT == MVT::Glue)
continue;
Match = false;
if (User->isMachineOpcode()) {
const MCInstrDesc &II = TII->get(User->getMachineOpcode());
const TargetRegisterClass *RC = nullptr;
if (i+II.getNumDefs() < II.getNumOperands()) {
RC = TRI->getAllocatableClass(
TII->getRegClass(II, i+II.getNumDefs(), TRI, *MF));
}
if (!UseRC)
UseRC = RC;
else if (RC) {
const TargetRegisterClass *ComRC =
TRI->getCommonSubClass(UseRC, RC, VT.SimpleTy);
// If multiple uses expect disjoint register classes, we emit
// copies in AddRegisterOperand.
if (ComRC)
UseRC = ComRC;
}
}
}
}
MatchReg &= Match;
if (VRBase)
break;
}
const TargetRegisterClass *SrcRC = nullptr, *DstRC = nullptr;
SrcRC = TRI->getMinimalPhysRegClass(SrcReg, VT);
// Figure out the register class to create for the destreg.
if (VRBase) {
DstRC = MRI->getRegClass(VRBase);
} else if (UseRC) {
assert(UseRC->hasType(VT) && "Incompatible phys register def and uses!");
DstRC = UseRC;
} else {
DstRC = TLI->getRegClassFor(VT);
}
// If all uses are reading from the src physical register and copying the
// register is either impossible or very expensive, then don't create a copy.
if (MatchReg && SrcRC->getCopyCost() < 0) {
VRBase = SrcReg;
} else {
// Create the reg, emit the copy.
VRBase = MRI->createVirtualRegister(DstRC);
BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
VRBase).addReg(SrcReg);
}
SDValue Op(Node, ResNo);
if (IsClone)
VRBaseMap.erase(Op);
bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
(void)isNew; // Silence compiler warning.
assert(isNew && "Node emitted out of order - early");
}
/// getDstOfCopyToRegUse - If the only use of the specified result number of
/// node is a CopyToReg, return its destination register. Return 0 otherwise.
unsigned InstrEmitter::getDstOfOnlyCopyToRegUse(SDNode *Node,
unsigned ResNo) const {
if (!Node->hasOneUse())
return 0;
SDNode *User = *Node->use_begin();
if (User->getOpcode() == ISD::CopyToReg &&
User->getOperand(2).getNode() == Node &&
User->getOperand(2).getResNo() == ResNo) {
unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
if (TargetRegisterInfo::isVirtualRegister(Reg))
return Reg;
}
return 0;
}
void InstrEmitter::CreateVirtualRegisters(SDNode *Node,
MachineInstrBuilder &MIB,
const MCInstrDesc &II,
bool IsClone, bool IsCloned,
DenseMap<SDValue, unsigned> &VRBaseMap) {
assert(Node->getMachineOpcode() != TargetOpcode::IMPLICIT_DEF &&
"IMPLICIT_DEF should have been handled as a special case elsewhere!");
unsigned NumResults = CountResults(Node);
for (unsigned i = 0; i < II.getNumDefs(); ++i) {
// If the specific node value is only used by a CopyToReg and the dest reg
// is a vreg in the same register class, use the CopyToReg'd destination
// register instead of creating a new vreg.
unsigned VRBase = 0;
const TargetRegisterClass *RC =
TRI->getAllocatableClass(TII->getRegClass(II, i, TRI, *MF));
// Always let the value type influence the used register class. The
// constraints on the instruction may be too lax to represent the value
// type correctly. For example, a 64-bit float (X86::FR64) can't live in
// the 32-bit float super-class (X86::FR32).
if (i < NumResults && TLI->isTypeLegal(Node->getSimpleValueType(i))) {
const TargetRegisterClass *VTRC =
TLI->getRegClassFor(Node->getSimpleValueType(i));
if (RC)
VTRC = TRI->getCommonSubClass(RC, VTRC);
if (VTRC)
RC = VTRC;
}
if (II.OpInfo[i].isOptionalDef()) {
// Optional def must be a physical register.
unsigned NumResults = CountResults(Node);
VRBase = cast<RegisterSDNode>(Node->getOperand(i-NumResults))->getReg();
assert(TargetRegisterInfo::isPhysicalRegister(VRBase));
MIB.addReg(VRBase, RegState::Define);
}
if (!VRBase && !IsClone && !IsCloned)
for (SDNode *User : Node->uses()) {
if (User->getOpcode() == ISD::CopyToReg &&
User->getOperand(2).getNode() == Node &&
User->getOperand(2).getResNo() == i) {
unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
if (TargetRegisterInfo::isVirtualRegister(Reg)) {
const TargetRegisterClass *RegRC = MRI->getRegClass(Reg);
if (RegRC == RC) {
VRBase = Reg;
MIB.addReg(VRBase, RegState::Define);
break;
}
}
}
}
// Create the result registers for this node and add the result regs to
// the machine instruction.
if (VRBase == 0) {
assert(RC && "Isn't a register operand!");
VRBase = MRI->createVirtualRegister(RC);
MIB.addReg(VRBase, RegState::Define);
}
// If this def corresponds to a result of the SDNode insert the VRBase into
// the lookup map.
if (i < NumResults) {
SDValue Op(Node, i);
if (IsClone)
VRBaseMap.erase(Op);
bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
(void)isNew; // Silence compiler warning.
assert(isNew && "Node emitted out of order - early");
}
}
}
/// getVR - Return the virtual register corresponding to the specified result
/// of the specified node.
unsigned InstrEmitter::getVR(SDValue Op,
DenseMap<SDValue, unsigned> &VRBaseMap) {
if (Op.isMachineOpcode() &&
Op.getMachineOpcode() == TargetOpcode::IMPLICIT_DEF) {
// Add an IMPLICIT_DEF instruction before every use.
unsigned VReg = getDstOfOnlyCopyToRegUse(Op.getNode(), Op.getResNo());
// IMPLICIT_DEF can produce any type of result so its MCInstrDesc
// does not include operand register class info.
if (!VReg) {
const TargetRegisterClass *RC =
TLI->getRegClassFor(Op.getSimpleValueType());
VReg = MRI->createVirtualRegister(RC);
}
BuildMI(*MBB, InsertPos, Op.getDebugLoc(),
TII->get(TargetOpcode::IMPLICIT_DEF), VReg);
return VReg;
}
DenseMap<SDValue, unsigned>::iterator I = VRBaseMap.find(Op);
assert(I != VRBaseMap.end() && "Node emitted out of order - late");
return I->second;
}
/// AddRegisterOperand - Add the specified register as an operand to the
/// specified machine instr. Insert register copies if the register is
/// not in the required register class.
void
InstrEmitter::AddRegisterOperand(MachineInstrBuilder &MIB,
SDValue Op,
unsigned IIOpNum,
const MCInstrDesc *II,
DenseMap<SDValue, unsigned> &VRBaseMap,
bool IsDebug, bool IsClone, bool IsCloned) {
assert(Op.getValueType() != MVT::Other &&
Op.getValueType() != MVT::Glue &&
"Chain and glue operands should occur at end of operand list!");
// Get/emit the operand.
unsigned VReg = getVR(Op, VRBaseMap);
const MCInstrDesc &MCID = MIB->getDesc();
bool isOptDef = IIOpNum < MCID.getNumOperands() &&
MCID.OpInfo[IIOpNum].isOptionalDef();
// If the instruction requires a register in a different class, create
// a new virtual register and copy the value into it, but first attempt to
// shrink VReg's register class within reason. For example, if VReg == GR32
// and II requires a GR32_NOSP, just constrain VReg to GR32_NOSP.
if (II) {
const TargetRegisterClass *DstRC = nullptr;
if (IIOpNum < II->getNumOperands())
DstRC = TRI->getAllocatableClass(TII->getRegClass(*II,IIOpNum,TRI,*MF));
assert((!DstRC || TargetRegisterInfo::isVirtualRegister(VReg)) &&
"Expected VReg");
if (DstRC && !MRI->constrainRegClass(VReg, DstRC, MinRCSize)) {
unsigned NewVReg = MRI->createVirtualRegister(DstRC);
BuildMI(*MBB, InsertPos, Op.getNode()->getDebugLoc(),
TII->get(TargetOpcode::COPY), NewVReg).addReg(VReg);
VReg = NewVReg;
}
}
// If this value has only one use, that use is a kill. This is a
// conservative approximation. InstrEmitter does trivial coalescing
// with CopyFromReg nodes, so don't emit kill flags for them.
// Avoid kill flags on Schedule cloned nodes, since there will be
// multiple uses.
// Tied operands are never killed, so we need to check that. And that
// means we need to determine the index of the operand.
bool isKill = Op.hasOneUse() &&
Op.getNode()->getOpcode() != ISD::CopyFromReg &&
!IsDebug &&
!(IsClone || IsCloned);
if (isKill) {
unsigned Idx = MIB->getNumOperands();
while (Idx > 0 &&
MIB->getOperand(Idx-1).isReg() &&
MIB->getOperand(Idx-1).isImplicit())
--Idx;
bool isTied = MCID.getOperandConstraint(Idx, MCOI::TIED_TO) != -1;
if (isTied)
isKill = false;
}
MIB.addReg(VReg, getDefRegState(isOptDef) | getKillRegState(isKill) |
getDebugRegState(IsDebug));
}
/// AddOperand - Add the specified operand to the specified machine instr. II
/// specifies the instruction information for the node, and IIOpNum is the
/// operand number (in the II) that we are adding.
void InstrEmitter::AddOperand(MachineInstrBuilder &MIB,
SDValue Op,
unsigned IIOpNum,
const MCInstrDesc *II,
DenseMap<SDValue, unsigned> &VRBaseMap,
bool IsDebug, bool IsClone, bool IsCloned) {
if (Op.isMachineOpcode()) {
AddRegisterOperand(MIB, Op, IIOpNum, II, VRBaseMap,
IsDebug, IsClone, IsCloned);
} else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
MIB.addImm(C->getSExtValue());
} else if (ConstantFPSDNode *F = dyn_cast<ConstantFPSDNode>(Op)) {
MIB.addFPImm(F->getConstantFPValue());
} else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
// Turn additional physreg operands into implicit uses on non-variadic
// instructions. This is used by call and return instructions passing
// arguments in registers.
bool Imp = II && (IIOpNum >= II->getNumOperands() && !II->isVariadic());
MIB.addReg(R->getReg(), getImplRegState(Imp));
} else if (RegisterMaskSDNode *RM = dyn_cast<RegisterMaskSDNode>(Op)) {
MIB.addRegMask(RM->getRegMask());
} else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
MIB.addGlobalAddress(TGA->getGlobal(), TGA->getOffset(),
TGA->getTargetFlags());
} else if (BasicBlockSDNode *BBNode = dyn_cast<BasicBlockSDNode>(Op)) {
MIB.addMBB(BBNode->getBasicBlock());
} else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
MIB.addFrameIndex(FI->getIndex());
} else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
MIB.addJumpTableIndex(JT->getIndex(), JT->getTargetFlags());
} else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
int Offset = CP->getOffset();
unsigned Align = CP->getAlignment();
Type *Type = CP->getType();
// MachineConstantPool wants an explicit alignment.
if (Align == 0) {
Align = MF->getDataLayout().getPrefTypeAlignment(Type);
if (Align == 0) {
// Alignment of vector types. FIXME!
Align = MF->getDataLayout().getTypeAllocSize(Type);
}
}
unsigned Idx;
MachineConstantPool *MCP = MF->getConstantPool();
if (CP->isMachineConstantPoolEntry())
Idx = MCP->getConstantPoolIndex(CP->getMachineCPVal(), Align);
else
Idx = MCP->getConstantPoolIndex(CP->getConstVal(), Align);
MIB.addConstantPoolIndex(Idx, Offset, CP->getTargetFlags());
} else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
MIB.addExternalSymbol(ES->getSymbol(), ES->getTargetFlags());
} else if (auto *SymNode = dyn_cast<MCSymbolSDNode>(Op)) {
MIB.addSym(SymNode->getMCSymbol());
} else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(Op)) {
MIB.addBlockAddress(BA->getBlockAddress(),
BA->getOffset(),
BA->getTargetFlags());
} else if (TargetIndexSDNode *TI = dyn_cast<TargetIndexSDNode>(Op)) {
MIB.addTargetIndex(TI->getIndex(), TI->getOffset(), TI->getTargetFlags());
} else {
assert(Op.getValueType() != MVT::Other &&
Op.getValueType() != MVT::Glue &&
"Chain and glue operands should occur at end of operand list!");
AddRegisterOperand(MIB, Op, IIOpNum, II, VRBaseMap,
IsDebug, IsClone, IsCloned);
}
}
unsigned InstrEmitter::ConstrainForSubReg(unsigned VReg, unsigned SubIdx,
MVT VT, const DebugLoc &DL) {
const TargetRegisterClass *VRC = MRI->getRegClass(VReg);
const TargetRegisterClass *RC = TRI->getSubClassWithSubReg(VRC, SubIdx);
// RC is a sub-class of VRC that supports SubIdx. Try to constrain VReg
// within reason.
if (RC && RC != VRC)
RC = MRI->constrainRegClass(VReg, RC, MinRCSize);
// VReg has been adjusted. It can be used with SubIdx operands now.
if (RC)
return VReg;
// VReg couldn't be reasonably constrained. Emit a COPY to a new virtual
// register instead.
RC = TRI->getSubClassWithSubReg(TLI->getRegClassFor(VT), SubIdx);
assert(RC && "No legal register class for VT supports that SubIdx");
unsigned NewReg = MRI->createVirtualRegister(RC);
BuildMI(*MBB, InsertPos, DL, TII->get(TargetOpcode::COPY), NewReg)
.addReg(VReg);
return NewReg;
}
/// EmitSubregNode - Generate machine code for subreg nodes.
///
void InstrEmitter::EmitSubregNode(SDNode *Node,
DenseMap<SDValue, unsigned> &VRBaseMap,
bool IsClone, bool IsCloned) {
unsigned VRBase = 0;
unsigned Opc = Node->getMachineOpcode();
// If the node is only used by a CopyToReg and the dest reg is a vreg, use
// the CopyToReg'd destination register instead of creating a new vreg.
for (SDNode *User : Node->uses()) {
if (User->getOpcode() == ISD::CopyToReg &&
User->getOperand(2).getNode() == Node) {
unsigned DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
VRBase = DestReg;
break;
}
}
}
if (Opc == TargetOpcode::EXTRACT_SUBREG) {
// EXTRACT_SUBREG is lowered as %dst = COPY %src:sub. There are no
// constraints on the %dst register, COPY can target all legal register
// classes.
unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
const TargetRegisterClass *TRC =
TLI->getRegClassFor(Node->getSimpleValueType(0));
unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
MachineInstr *DefMI = MRI->getVRegDef(VReg);
unsigned SrcReg, DstReg, DefSubIdx;
if (DefMI &&
TII->isCoalescableExtInstr(*DefMI, SrcReg, DstReg, DefSubIdx) &&
SubIdx == DefSubIdx &&
TRC == MRI->getRegClass(SrcReg)) {
// Optimize these:
// r1025 = s/zext r1024, 4
// r1026 = extract_subreg r1025, 4
// to a copy
// r1026 = copy r1024
VRBase = MRI->createVirtualRegister(TRC);
BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
TII->get(TargetOpcode::COPY), VRBase).addReg(SrcReg);
MRI->clearKillFlags(SrcReg);
} else {
// VReg may not support a SubIdx sub-register, and we may need to
// constrain its register class or issue a COPY to a compatible register
// class.
VReg = ConstrainForSubReg(VReg, SubIdx,
Node->getOperand(0).getSimpleValueType(),
Node->getDebugLoc());
// Create the destreg if it is missing.
if (VRBase == 0)
VRBase = MRI->createVirtualRegister(TRC);
// Create the extract_subreg machine instruction.
BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
TII->get(TargetOpcode::COPY), VRBase).addReg(VReg, 0, SubIdx);
}
} else if (Opc == TargetOpcode::INSERT_SUBREG ||
Opc == TargetOpcode::SUBREG_TO_REG) {
SDValue N0 = Node->getOperand(0);
SDValue N1 = Node->getOperand(1);
SDValue N2 = Node->getOperand(2);
unsigned SubIdx = cast<ConstantSDNode>(N2)->getZExtValue();
// Figure out the register class to create for the destreg. It should be
// the largest legal register class supporting SubIdx sub-registers.
// RegisterCoalescer will constrain it further if it decides to eliminate
// the INSERT_SUBREG instruction.
//
// %dst = INSERT_SUBREG %src, %sub, SubIdx
//
// is lowered by TwoAddressInstructionPass to:
//
// %dst = COPY %src
// %dst:SubIdx = COPY %sub
//
// There is no constraint on the %src register class.
//
const TargetRegisterClass *SRC = TLI->getRegClassFor(Node->getSimpleValueType(0));
SRC = TRI->getSubClassWithSubReg(SRC, SubIdx);
assert(SRC && "No register class supports VT and SubIdx for INSERT_SUBREG");
if (VRBase == 0 || !SRC->hasSubClassEq(MRI->getRegClass(VRBase)))
VRBase = MRI->createVirtualRegister(SRC);
// Create the insert_subreg or subreg_to_reg machine instruction.
MachineInstrBuilder MIB =
BuildMI(*MF, Node->getDebugLoc(), TII->get(Opc), VRBase);
// If creating a subreg_to_reg, then the first input operand
// is an implicit value immediate, otherwise it's a register
if (Opc == TargetOpcode::SUBREG_TO_REG) {
const ConstantSDNode *SD = cast<ConstantSDNode>(N0);
MIB.addImm(SD->getZExtValue());
} else
AddOperand(MIB, N0, 0, nullptr, VRBaseMap, /*IsDebug=*/false,
IsClone, IsCloned);
// Add the subregster being inserted
AddOperand(MIB, N1, 0, nullptr, VRBaseMap, /*IsDebug=*/false,
IsClone, IsCloned);
MIB.addImm(SubIdx);
MBB->insert(InsertPos, MIB);
} else
llvm_unreachable("Node is not insert_subreg, extract_subreg, or subreg_to_reg");
SDValue Op(Node, 0);
bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
(void)isNew; // Silence compiler warning.
assert(isNew && "Node emitted out of order - early");
}
/// EmitCopyToRegClassNode - Generate machine code for COPY_TO_REGCLASS nodes.
/// COPY_TO_REGCLASS is just a normal copy, except that the destination
/// register is constrained to be in a particular register class.
///
void
InstrEmitter::EmitCopyToRegClassNode(SDNode *Node,
DenseMap<SDValue, unsigned> &VRBaseMap) {
unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
// Create the new VReg in the destination class and emit a copy.
unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
const TargetRegisterClass *DstRC =
TRI->getAllocatableClass(TRI->getRegClass(DstRCIdx));
unsigned NewVReg = MRI->createVirtualRegister(DstRC);
BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
NewVReg).addReg(VReg);
SDValue Op(Node, 0);
bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second;
(void)isNew; // Silence compiler warning.
assert(isNew && "Node emitted out of order - early");
}
/// EmitRegSequence - Generate machine code for REG_SEQUENCE nodes.
///
void InstrEmitter::EmitRegSequence(SDNode *Node,
DenseMap<SDValue, unsigned> &VRBaseMap,
bool IsClone, bool IsCloned) {
unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx);
unsigned NewVReg = MRI->createVirtualRegister(TRI->getAllocatableClass(RC));
const MCInstrDesc &II = TII->get(TargetOpcode::REG_SEQUENCE);
MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(), II, NewVReg);
unsigned NumOps = Node->getNumOperands();
assert((NumOps & 1) == 1 &&
"REG_SEQUENCE must have an odd number of operands!");
for (unsigned i = 1; i != NumOps; ++i) {
SDValue Op = Node->getOperand(i);
if ((i & 1) == 0) {
RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node->getOperand(i-1));
// Skip physical registers as they don't have a vreg to get and we'll
// insert copies for them in TwoAddressInstructionPass anyway.
if (!R || !TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
unsigned SubIdx = cast<ConstantSDNode>(Op)->getZExtValue();
unsigned SubReg = getVR(Node->getOperand(i-1), VRBaseMap);
const TargetRegisterClass *TRC = MRI->getRegClass(SubReg);
const TargetRegisterClass *SRC =
TRI->getMatchingSuperRegClass(RC, TRC, SubIdx);
if (SRC && SRC != RC) {
MRI->setRegClass(NewVReg, SRC);
RC = SRC;
}
}
}
AddOperand(MIB, Op, i+1, &II, VRBaseMap, /*IsDebug=*/false,
IsClone, IsCloned);
}
MBB->insert(InsertPos, MIB);
SDValue Op(Node, 0);
bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second;
(void)isNew; // Silence compiler warning.
assert(isNew && "Node emitted out of order - early");
}
/// EmitDbgValue - Generate machine instruction for a dbg_value node.
///
MachineInstr *
InstrEmitter::EmitDbgValue(SDDbgValue *SD,
DenseMap<SDValue, unsigned> &VRBaseMap) {
uint64_t Offset = SD->getOffset();
MDNode *Var = SD->getVariable();
MDNode *Expr = SD->getExpression();
DebugLoc DL = SD->getDebugLoc();
assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
"Expected inlined-at fields to agree");
if (SD->getKind() == SDDbgValue::FRAMEIX) {
// Stack address; this needs to be lowered in target-dependent fashion.
// EmitTargetCodeForFrameDebugValue is responsible for allocation.
return BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE))
.addFrameIndex(SD->getFrameIx())
.addImm(Offset)
.addMetadata(Var)
.addMetadata(Expr);
}
// Otherwise, we're going to create an instruction here.
const MCInstrDesc &II = TII->get(TargetOpcode::DBG_VALUE);
MachineInstrBuilder MIB = BuildMI(*MF, DL, II);
if (SD->getKind() == SDDbgValue::SDNODE) {
SDNode *Node = SD->getSDNode();
SDValue Op = SDValue(Node, SD->getResNo());
// It's possible we replaced this SDNode with other(s) and therefore
// didn't generate code for it. It's better to catch these cases where
// they happen and transfer the debug info, but trying to guarantee that
// in all cases would be very fragile; this is a safeguard for any
// that were missed.
DenseMap<SDValue, unsigned>::iterator I = VRBaseMap.find(Op);
if (I==VRBaseMap.end())
MIB.addReg(0U); // undef
else
AddOperand(MIB, Op, (*MIB).getNumOperands(), &II, VRBaseMap,
/*IsDebug=*/true, /*IsClone=*/false, /*IsCloned=*/false);
} else if (SD->getKind() == SDDbgValue::CONST) {
const Value *V = SD->getConst();
if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
if (CI->getBitWidth() > 64)
MIB.addCImm(CI);
else
MIB.addImm(CI->getSExtValue());
} else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
MIB.addFPImm(CF);
} else {
// Could be an Undef. In any case insert an Undef so we can see what we
// dropped.
MIB.addReg(0U);
}
} else {
// Insert an Undef so we can see what we dropped.
MIB.addReg(0U);
}
// Indirect addressing is indicated by an Imm as the second parameter.
if (SD->isIndirect())
MIB.addImm(Offset);
else {
assert(Offset == 0 && "direct value cannot have an offset");
MIB.addReg(0U, RegState::Debug);
}
MIB.addMetadata(Var);
MIB.addMetadata(Expr);
return &*MIB;
}
/// EmitMachineNode - Generate machine code for a target-specific node and
/// needed dependencies.
///
void InstrEmitter::
EmitMachineNode(SDNode *Node, bool IsClone, bool IsCloned,
DenseMap<SDValue, unsigned> &VRBaseMap) {
unsigned Opc = Node->getMachineOpcode();
// Handle subreg insert/extract specially
if (Opc == TargetOpcode::EXTRACT_SUBREG ||
Opc == TargetOpcode::INSERT_SUBREG ||
Opc == TargetOpcode::SUBREG_TO_REG) {
EmitSubregNode(Node, VRBaseMap, IsClone, IsCloned);
return;
}
// Handle COPY_TO_REGCLASS specially.
if (Opc == TargetOpcode::COPY_TO_REGCLASS) {
EmitCopyToRegClassNode(Node, VRBaseMap);
return;
}
// Handle REG_SEQUENCE specially.
if (Opc == TargetOpcode::REG_SEQUENCE) {
EmitRegSequence(Node, VRBaseMap, IsClone, IsCloned);
return;
}
if (Opc == TargetOpcode::IMPLICIT_DEF)
// We want a unique VR for each IMPLICIT_DEF use.
return;
const MCInstrDesc &II = TII->get(Opc);
unsigned NumResults = CountResults(Node);
unsigned NumDefs = II.getNumDefs();
const MCPhysReg *ScratchRegs = nullptr;
// Handle STACKMAP and PATCHPOINT specially and then use the generic code.
if (Opc == TargetOpcode::STACKMAP || Opc == TargetOpcode::PATCHPOINT) {
// Stackmaps do not have arguments and do not preserve their calling
// convention. However, to simplify runtime support, they clobber the same
// scratch registers as AnyRegCC.
unsigned CC = CallingConv::AnyReg;
if (Opc == TargetOpcode::PATCHPOINT) {
CC = Node->getConstantOperandVal(PatchPointOpers::CCPos);
NumDefs = NumResults;
}
ScratchRegs = TLI->getScratchRegisters((CallingConv::ID) CC);
}
unsigned NumImpUses = 0;
unsigned NodeOperands =
countOperands(Node, II.getNumOperands() - NumDefs, NumImpUses);
bool HasPhysRegOuts = NumResults > NumDefs && II.getImplicitDefs()!=nullptr;
#ifndef NDEBUG
unsigned NumMIOperands = NodeOperands + NumResults;
if (II.isVariadic())
assert(NumMIOperands >= II.getNumOperands() &&
"Too few operands for a variadic node!");
else
assert(NumMIOperands >= II.getNumOperands() &&
NumMIOperands <= II.getNumOperands() + II.getNumImplicitDefs() +
NumImpUses &&
"#operands for dag node doesn't match .td file!");
#endif
// Create the new machine instruction.
MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(), II);
// Add result register values for things that are defined by this
// instruction.
if (NumResults)
CreateVirtualRegisters(Node, MIB, II, IsClone, IsCloned, VRBaseMap);
// Emit all of the actual operands of this instruction, adding them to the
// instruction as appropriate.
bool HasOptPRefs = NumDefs > NumResults;
assert((!HasOptPRefs || !HasPhysRegOuts) &&
"Unable to cope with optional defs and phys regs defs!");
unsigned NumSkip = HasOptPRefs ? NumDefs - NumResults : 0;
for (unsigned i = NumSkip; i != NodeOperands; ++i)
AddOperand(MIB, Node->getOperand(i), i-NumSkip+NumDefs, &II,
VRBaseMap, /*IsDebug=*/false, IsClone, IsCloned);
// Add scratch registers as implicit def and early clobber
if (ScratchRegs)
for (unsigned i = 0; ScratchRegs[i]; ++i)
MIB.addReg(ScratchRegs[i], RegState::ImplicitDefine |
RegState::EarlyClobber);
// Transfer all of the memory reference descriptions of this instruction.
MIB.setMemRefs(cast<MachineSDNode>(Node)->memoperands_begin(),
cast<MachineSDNode>(Node)->memoperands_end());
// Insert the instruction into position in the block. This needs to
// happen before any custom inserter hook is called so that the
// hook knows where in the block to insert the replacement code.
MBB->insert(InsertPos, MIB);
// The MachineInstr may also define physregs instead of virtregs. These
// physreg values can reach other instructions in different ways:
//
// 1. When there is a use of a Node value beyond the explicitly defined
// virtual registers, we emit a CopyFromReg for one of the implicitly
// defined physregs. This only happens when HasPhysRegOuts is true.
//
// 2. A CopyFromReg reading a physreg may be glued to this instruction.
//
// 3. A glued instruction may implicitly use a physreg.
//
// 4. A glued instruction may use a RegisterSDNode operand.
//
// Collect all the used physreg defs, and make sure that any unused physreg
// defs are marked as dead.
SmallVector<unsigned, 8> UsedRegs;
// Additional results must be physical register defs.
if (HasPhysRegOuts) {
for (unsigned i = NumDefs; i < NumResults; ++i) {
unsigned Reg = II.getImplicitDefs()[i - NumDefs];
if (!Node->hasAnyUseOfValue(i))
continue;
// This implicitly defined physreg has a use.
UsedRegs.push_back(Reg);
EmitCopyFromReg(Node, i, IsClone, IsCloned, Reg, VRBaseMap);
}
}
// Scan the glue chain for any used physregs.
if (Node->getValueType(Node->getNumValues()-1) == MVT::Glue) {
for (SDNode *F = Node->getGluedUser(); F; F = F->getGluedUser()) {
if (F->getOpcode() == ISD::CopyFromReg) {
UsedRegs.push_back(cast<RegisterSDNode>(F->getOperand(1))->getReg());
continue;
} else if (F->getOpcode() == ISD::CopyToReg) {
// Skip CopyToReg nodes that are internal to the glue chain.
continue;
}
// Collect declared implicit uses.
const MCInstrDesc &MCID = TII->get(F->getMachineOpcode());
UsedRegs.append(MCID.getImplicitUses(),
MCID.getImplicitUses() + MCID.getNumImplicitUses());
// In addition to declared implicit uses, we must also check for
// direct RegisterSDNode operands.
for (unsigned i = 0, e = F->getNumOperands(); i != e; ++i)
if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(F->getOperand(i))) {
unsigned Reg = R->getReg();
if (TargetRegisterInfo::isPhysicalRegister(Reg))
UsedRegs.push_back(Reg);
}
}
}
// Finally mark unused registers as dead.
if (!UsedRegs.empty() || II.getImplicitDefs())
MIB->setPhysRegsDeadExcept(UsedRegs, *TRI);
// Run post-isel target hook to adjust this instruction if needed.
if (II.hasPostISelHook())
TLI->AdjustInstrPostInstrSelection(*MIB, Node);
}
/// EmitSpecialNode - Generate machine code for a target-independent node and
/// needed dependencies.
void InstrEmitter::
EmitSpecialNode(SDNode *Node, bool IsClone, bool IsCloned,
DenseMap<SDValue, unsigned> &VRBaseMap) {
switch (Node->getOpcode()) {
default:
#ifndef NDEBUG
Node->dump();
#endif
llvm_unreachable("This target-independent node should have been selected!");
case ISD::EntryToken:
llvm_unreachable("EntryToken should have been excluded from the schedule!");
case ISD::MERGE_VALUES:
case ISD::TokenFactor: // fall thru
break;
case ISD::CopyToReg: {
unsigned SrcReg;
SDValue SrcVal = Node->getOperand(2);
if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(SrcVal))
SrcReg = R->getReg();
else
SrcReg = getVR(SrcVal, VRBaseMap);
unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
if (SrcReg == DestReg) // Coalesced away the copy? Ignore.
break;
BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
DestReg).addReg(SrcReg);
break;
}
case ISD::CopyFromReg: {
unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
EmitCopyFromReg(Node, 0, IsClone, IsCloned, SrcReg, VRBaseMap);
break;
}
case ISD::EH_LABEL: {
MCSymbol *S = cast<EHLabelSDNode>(Node)->getLabel();
BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
TII->get(TargetOpcode::EH_LABEL)).addSym(S);
break;
}
case ISD::LIFETIME_START:
case ISD::LIFETIME_END: {
unsigned TarOp = (Node->getOpcode() == ISD::LIFETIME_START) ?
TargetOpcode::LIFETIME_START : TargetOpcode::LIFETIME_END;
FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Node->getOperand(1));
BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TarOp))
.addFrameIndex(FI->getIndex());
break;
}
case ISD::INLINEASM: {
unsigned NumOps = Node->getNumOperands();
if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
--NumOps; // Ignore the glue operand.
// Create the inline asm machine instruction.
MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(),
TII->get(TargetOpcode::INLINEASM));
// Add the asm string as an external symbol operand.
SDValue AsmStrV = Node->getOperand(InlineAsm::Op_AsmString);
const char *AsmStr = cast<ExternalSymbolSDNode>(AsmStrV)->getSymbol();
MIB.addExternalSymbol(AsmStr);
// Add the HasSideEffect, isAlignStack, AsmDialect, MayLoad and MayStore
// bits.
int64_t ExtraInfo =
cast<ConstantSDNode>(Node->getOperand(InlineAsm::Op_ExtraInfo))->
getZExtValue();
MIB.addImm(ExtraInfo);
// Remember to operand index of the group flags.
SmallVector<unsigned, 8> GroupIdx;
// Remember registers that are part of early-clobber defs.
SmallVector<unsigned, 8> ECRegs;
// Add all of the operand registers to the instruction.
for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
unsigned Flags =
cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
const unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
GroupIdx.push_back(MIB->getNumOperands());
MIB.addImm(Flags);
++i; // Skip the ID value.
switch (InlineAsm::getKind(Flags)) {
default: llvm_unreachable("Bad flags!");
case InlineAsm::Kind_RegDef:
for (unsigned j = 0; j != NumVals; ++j, ++i) {
unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
// FIXME: Add dead flags for physical and virtual registers defined.
// For now, mark physical register defs as implicit to help fast
// regalloc. This makes inline asm look a lot like calls.
MIB.addReg(Reg, RegState::Define |
getImplRegState(TargetRegisterInfo::isPhysicalRegister(Reg)));
}
break;
case InlineAsm::Kind_RegDefEarlyClobber:
case InlineAsm::Kind_Clobber:
for (unsigned j = 0; j != NumVals; ++j, ++i) {
unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
MIB.addReg(Reg, RegState::Define | RegState::EarlyClobber |
getImplRegState(TargetRegisterInfo::isPhysicalRegister(Reg)));
ECRegs.push_back(Reg);
}
break;
case InlineAsm::Kind_RegUse: // Use of register.
case InlineAsm::Kind_Imm: // Immediate.
case InlineAsm::Kind_Mem: // Addressing mode.
// The addressing mode has been selected, just add all of the
// operands to the machine instruction.
for (unsigned j = 0; j != NumVals; ++j, ++i)
AddOperand(MIB, Node->getOperand(i), 0, nullptr, VRBaseMap,
/*IsDebug=*/false, IsClone, IsCloned);
// Manually set isTied bits.
if (InlineAsm::getKind(Flags) == InlineAsm::Kind_RegUse) {
unsigned DefGroup = 0;
if (InlineAsm::isUseOperandTiedToDef(Flags, DefGroup)) {
unsigned DefIdx = GroupIdx[DefGroup] + 1;
unsigned UseIdx = GroupIdx.back() + 1;
for (unsigned j = 0; j != NumVals; ++j)
MIB->tieOperands(DefIdx + j, UseIdx + j);
}
}
break;
}
}
// GCC inline assembly allows input operands to also be early-clobber
// output operands (so long as the operand is written only after it's
// used), but this does not match the semantics of our early-clobber flag.
// If an early-clobber operand register is also an input operand register,
// then remove the early-clobber flag.
for (unsigned Reg : ECRegs) {
if (MIB->readsRegister(Reg, TRI)) {
MachineOperand *MO = MIB->findRegisterDefOperand(Reg, false, TRI);
assert(MO && "No def operand for clobbered register?");
MO->setIsEarlyClobber(false);
}
}
// Get the mdnode from the asm if it exists and add it to the instruction.
SDValue MDV = Node->getOperand(InlineAsm::Op_MDNode);
const MDNode *MD = cast<MDNodeSDNode>(MDV)->getMD();
if (MD)
MIB.addMetadata(MD);
MBB->insert(InsertPos, MIB);
break;
}
}
}
/// InstrEmitter - Construct an InstrEmitter and set it to start inserting
/// at the given position in the given block.
InstrEmitter::InstrEmitter(MachineBasicBlock *mbb,
MachineBasicBlock::iterator insertpos)
: MF(mbb->getParent()), MRI(&MF->getRegInfo()),
TII(MF->getSubtarget().getInstrInfo()),
TRI(MF->getSubtarget().getRegisterInfo()),
TLI(MF->getSubtarget().getTargetLowering()), MBB(mbb),
InsertPos(insertpos) {}
| 42,436
| 13,993
|
#include <cstdint>
#include <cstring>
#include <vector>
#include <benchmark/benchmark.h>
#include <unet/detail/arp_cache.hpp>
#include <unet/random.hpp>
namespace unet {
namespace detail {
constexpr auto kNumAddOps = 65'536;
static Ipv4Addr randomIpv4(std::uint32_t maxAddress) {
auto raw = randInt<std::uint32_t>(0, maxAddress);
Ipv4Addr addr;
std::memcpy(&addr, &raw, sizeof(raw));
return addr;
}
static std::vector<Ipv4Addr> randomIpv4s(std::uint32_t maxAddress) {
std::vector<Ipv4Addr> addresses;
while (addresses.size() < kNumAddOps) {
addresses.push_back(randomIpv4(maxAddress));
}
return addresses;
}
static void benchArpCacheAdd(benchmark::State& state) {
auto capacity = static_cast<std::size_t>(state.range(0));
ArpCache cache{capacity, std::chrono::seconds{60}};
auto maxAddress = static_cast<std::uint32_t>(state.range(1));
auto addresses = randomIpv4s(maxAddress);
for (auto _ : state) {
for (auto addr : addresses) {
cache.add(addr, EthernetAddr{});
}
}
}
static void benchArpCacheLookup(benchmark::State& state) {
auto capacity = static_cast<std::size_t>(state.range(0));
ArpCache cache{capacity, std::chrono::seconds{60}};
auto maxAddress = static_cast<std::uint32_t>(state.range(1));
auto addresses = randomIpv4s(maxAddress);
for (auto addr : addresses) {
cache.add(addr, EthernetAddr{});
}
for (auto _ : state) {
for (auto addr : addresses) {
benchmark::DoNotOptimize(cache.lookup(addr));
}
}
}
BENCHMARK(benchArpCacheAdd)
->RangeMultiplier(64)
->Ranges({{64, 4'096}, {64, 4'096}})
->Unit(benchmark::kMicrosecond);
BENCHMARK(benchArpCacheLookup)
->RangeMultiplier(64)
->Ranges({{64, 4'096}, {64, 4'096}})
->Unit(benchmark::kMicrosecond);
} // namespace detail
} // namespace unet
| 1,819
| 733
|
// This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (C) Microsoft Corporation
// All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
#include "stdafx.h"
#define new DEBUG_NEW
/////////////////////////////////////////////////////////////////////////////
// COleFrameHook Construction & Destruction
COleFrameHook::COleFrameHook(CFrameWnd* pFrameWnd, COleClientItem* pItem)
{
ASSERT_VALID(pItem);
ASSERT_VALID(pFrameWnd);
m_lpActiveObject = NULL;
m_pActiveItem = pItem;
m_pFrameWnd = pFrameWnd;
m_hWnd = pFrameWnd->m_hWnd;
m_bToolBarHidden = FALSE;
m_hAccelTable = NULL;
m_bInModalState = FALSE;
m_nModelessCount = 0;
pFrameWnd->m_pNotifyHook = this; // assume start out hooked
ASSERT_VALID(this);
}
COleFrameHook::~COleFrameHook()
{
if (m_pFrameWnd != NULL)
{
ASSERT_VALID(m_pFrameWnd);
if (m_pFrameWnd->m_pNotifyHook == this)
m_pFrameWnd->m_pNotifyHook = NULL;
}
ASSERT_VALID(this);
}
/////////////////////////////////////////////////////////////////////////////
// COleFrameHook overrides
void COleFrameHook::OnRecalcLayout()
{
ASSERT_VALID(this);
if (m_lpActiveObject == NULL)
return;
// get current border size (without current server control bars)
RECT rectBorder;
m_pFrameWnd->NegotiateBorderSpace(CFrameWnd::borderGet, &rectBorder);
// allow server to resize/move its control bars
m_lpActiveObject->ResizeBorder(&rectBorder, &m_xOleInPlaceFrame,
m_pActiveItem->m_pInPlaceFrame == this);
}
BOOL COleFrameHook::OnDocActivate(BOOL bActive)
{
ASSERT_VALID(this);
if (m_lpActiveObject == NULL)
return TRUE;
// allow server to do document activation related actions
m_lpActiveObject->OnDocWindowActivate(bActive);
// make sure window caption gets updated later
COleFrameHook* pNotifyHook = m_pActiveItem->m_pInPlaceFrame;
pNotifyHook->m_pFrameWnd->DelayUpdateFrameTitle();
if (!bActive)
{
// clear border space
pNotifyHook->m_xOleInPlaceFrame.SetBorderSpace(NULL);
if (m_pActiveItem->m_pInPlaceDoc != NULL)
m_pActiveItem->m_pInPlaceDoc->m_xOleInPlaceFrame.SetBorderSpace(NULL);
// remove the menu hook when the doc is not active
pNotifyHook->m_xOleInPlaceFrame.SetMenu(NULL, NULL, NULL);
// unhook top-level frame if not needed
if (pNotifyHook != this)
{
// shouldn't be removing some other hook
ASSERT(pNotifyHook->m_pFrameWnd->m_pNotifyHook == pNotifyHook);
pNotifyHook->m_pFrameWnd->m_pNotifyHook = NULL;
}
}
else
{
// rehook top-level frame if necessary (no effect if top-level == doc-level)
pNotifyHook->m_pFrameWnd->m_pNotifyHook = pNotifyHook;
}
// don't do default if activating
return bActive;
}
BOOL COleFrameHook::OnContextHelp(BOOL bEnter)
{
ASSERT_VALID(this);
if (m_lpActiveObject == NULL || m_pActiveItem->m_pInPlaceFrame != this)
return TRUE;
// allow all servers to enter/exit context sensitive help mode
return NotifyAllInPlace(bEnter, &COleFrameHook::DoContextSensitiveHelp);
}
/////////////////////////////////////////////////////////////////////////////
// COleFrameHook callbacks for the top-level frame
BOOL COleFrameHook::OnMenuSelect(UINT nItemID, UINT nFlags, HMENU hSysMenu)
{
UNUSED_ALWAYS(nFlags);
UNUSED_ALWAYS(nItemID);
// if we're over a docobject item, we need to reflect messages
COleDocObjectItem* pActiveDocObjectItem = DYNAMIC_DOWNCAST(COleDocObjectItem, m_pActiveItem);
if (pActiveDocObjectItem != NULL)
{
CWnd* pWnd = pActiveDocObjectItem->GetInPlaceWindow();
// if we're popping up a menu, figure out what menu is
// apparing; if it's in the help menu and it's not the
// first element, it's the object's menu.
if (nFlags & MF_POPUP)
{
if (pActiveDocObjectItem->m_pHelpPopupMenu->GetSafeHmenu() ==
hSysMenu)
{
pActiveDocObjectItem->m_bInHelpMenu = (nItemID != 0);
if (pActiveDocObjectItem->m_bInHelpMenu && pWnd != NULL)
{
pWnd->SendMessage(WM_MENUSELECT,
MAKEWPARAM(nItemID, nFlags), (LPARAM) hSysMenu);
return TRUE;
}
}
}
else
{
if (pActiveDocObjectItem->m_bInHelpMenu && pWnd != NULL)
{
pWnd->SendMessage(WM_MENUSELECT,
MAKEWPARAM(nItemID, nFlags), (LPARAM) hSysMenu);
return TRUE;
}
}
}
return FALSE;
}
void COleFrameHook::OnInitMenu(CMenu* pMenu)
{
UNUSED_ALWAYS(pMenu);
// reset the help menu flag when a new menu is opening
COleDocObjectItem* pActiveDocObjectItem = DYNAMIC_DOWNCAST(COleDocObjectItem, m_pActiveItem);
if (pActiveDocObjectItem != NULL)
pActiveDocObjectItem->m_bInHelpMenu = FALSE;
return;
}
BOOL COleFrameHook::OnInitMenuPopup(CMenu* pMenu, int nIndex, BOOL bSysMenu)
{
UNUSED_ALWAYS(nIndex);
if (bSysMenu)
return FALSE;
COleDocObjectItem* pActiveDocObjectItem = DYNAMIC_DOWNCAST(COleDocObjectItem, m_pActiveItem);
if (pActiveDocObjectItem == NULL)
return FALSE;
// if we're popping up a new menu, for the object,
// reflect the message and don't let MFC handle it
// with ON_COMMAND_UI stuff
if (pActiveDocObjectItem->m_bInHelpMenu)
{
CWnd* pWnd = pActiveDocObjectItem->GetInPlaceWindow();
if (pWnd != NULL)
{
pWnd->SendMessage(WM_INITMENUPOPUP, (WPARAM) pMenu->m_hMenu,
MAKELPARAM(nIndex, bSysMenu));
return TRUE;
}
}
return FALSE;
}
BOOL COleFrameHook::OnPreTranslateMessage(MSG* pMsg)
{
ASSERT_VALID(this);
if (m_lpActiveObject == NULL || m_pActiveItem->m_pInPlaceFrame != this)
return FALSE;
// allow server to translate accelerators
if (pMsg->message >= WM_KEYFIRST && pMsg->message <= WM_KEYLAST)
return m_lpActiveObject->TranslateAccelerator(pMsg) == S_OK;
// if we've finally gotten a WM_COMMAND message, make sure
// that it is appropriately reflected to the docobject
if (pMsg->message == WM_COMMAND)
{
COleDocObjectItem* pActiveDocObjectItem = DYNAMIC_DOWNCAST(COleDocObjectItem, m_pActiveItem);
if (pActiveDocObjectItem != NULL)
{
LRESULT lResult = 0;
if (pActiveDocObjectItem->m_bInHelpMenu)
{
CWnd* pWnd = pActiveDocObjectItem->GetInPlaceWindow();
if (pWnd != NULL)
lResult = pWnd->SendNotifyMessage(WM_COMMAND, pMsg->wParam, pMsg->lParam);
}
return (lResult != 0);
}
}
return FALSE;
}
void COleFrameHook::OnActivate(BOOL bActive)
{
ASSERT_VALID(this);
if (m_lpActiveObject == NULL || m_pActiveItem->m_pInPlaceFrame != this)
return;
if (m_pFrameWnd->IsWindowEnabled())
{
// allow active server to do frame level activation
m_lpActiveObject->OnFrameWindowActivate(bActive);
}
}
void COleFrameHook::OnEnableModeless(BOOL bEnable)
{
ASSERT_VALID(this);
if (m_lpActiveObject == NULL || m_pActiveItem->m_pInPlaceFrame != this)
return;
// allow server to disable/enable modeless dialogs
NotifyAllInPlace(bEnable, &COleFrameHook::DoEnableModeless);
}
BOOL COleFrameHook::OnUpdateFrameTitle()
{
ASSERT_VALID(this);
ASSERT_VALID(m_pActiveItem);
if (m_lpActiveObject == NULL || m_pActiveItem->m_pInPlaceFrame != this)
return FALSE;
return m_pActiveItem->OnUpdateFrameTitle();
}
void COleFrameHook::OnPaletteChanged(CWnd* pFocusWnd)
{
CWnd* pWnd = m_pActiveItem->GetInPlaceWindow();
if (pWnd != NULL)
pWnd->SendMessage(WM_PALETTECHANGED, (WPARAM)pFocusWnd->GetSafeHwnd());
}
BOOL COleFrameHook::OnQueryNewPalette()
{
CWnd* pWnd = m_pActiveItem->GetInPlaceWindow();
if (pWnd != NULL)
return (pWnd->SendMessage(WM_QUERYNEWPALETTE) != 0);
return FALSE;
}
/////////////////////////////////////////////////////////////////////////////
// Helpers for notifications that have to affect all in-place windows
BOOL COleFrameHook::NotifyAllInPlace(
BOOL bParam, BOOL (COleFrameHook::*pNotifyFunc)(BOOL bParam))
{
ASSERT_VALID(this);
HWND hWndFrame = m_hWnd;
CWinApp* pApp = AfxGetApp();
// no doc manager - no templates
if (pApp->m_pDocManager == NULL)
return TRUE;
// walk all templates in the application
CDocTemplate* pTemplate;
POSITION pos = pApp->m_pDocManager->GetFirstDocTemplatePosition();
while (pos != NULL)
{
pTemplate = pApp->m_pDocManager->GetNextDocTemplate(pos);
ASSERT_VALID(pTemplate);
ASSERT_KINDOF(CDocTemplate, pTemplate);
// walk all documents in the template
POSITION pos2 = pTemplate->GetFirstDocPosition();
while (pos2)
{
COleDocument* pDoc = (COleDocument*)pTemplate->GetNextDoc(pos2);
ASSERT_VALID(pDoc);
if (pDoc->IsKindOf(RUNTIME_CLASS(COleDocument)))
{
// walk all COleClientItem objects in the document
COleClientItem* pItem;
POSITION pos3 = pDoc->GetStartPosition();
while ((pItem = pDoc->GetNextClientItem(pos3)) != NULL)
{
if (pItem->m_pInPlaceFrame != NULL &&
pItem->m_pInPlaceFrame->m_lpActiveObject != NULL &&
pItem->m_pView != NULL &&
AfxIsDescendant(hWndFrame, pItem->m_pView->m_hWnd))
{
// Whew! Found an in-place active item that is
// part of this frame window hierarchy.
COleFrameHook* pNotifyHook = pItem->m_pInPlaceFrame;
if (!(pNotifyHook->*pNotifyFunc)(bParam))
return FALSE;
}
}
}
}
}
return TRUE;
}
BOOL COleFrameHook::DoContextSensitiveHelp(BOOL bEnter)
{
ASSERT_VALID(this);
ASSERT(m_lpActiveObject != NULL);
return !FAILED(m_lpActiveObject->ContextSensitiveHelp(bEnter));
}
BOOL COleFrameHook::DoEnableModeless(BOOL bEnable)
{
ASSERT_VALID(this);
ASSERT(m_lpActiveObject != NULL);
// allow server to enable/disable any modeless windows
if (!bEnable)
{
if (m_nModelessCount++ == 0)
m_lpActiveObject->EnableModeless(FALSE);
}
else
{
if (m_nModelessCount != 0 && --m_nModelessCount == 0)
m_lpActiveObject->EnableModeless(TRUE);
}
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// COleClientItem - default in-place activation implementation
BOOL COleClientItem::CanActivate()
{
// don't allow in-place activations with iconic aspect items
if (m_nDrawAspect == DVASPECT_ICON)
{
return FALSE;
}
// if no view has been set, attempt to find suitable one.
// (necessary to get links to embeddings to work correctly)
if (m_pView == NULL)
{
// only use pActivateView if this item is in same document
_AFX_OLE_STATE* pOleState = _afxOleState;
if (pOleState->m_pActivateView != NULL && pOleState->m_pActivateView->GetDocument() != GetDocument())
{
pOleState->m_pActivateView = NULL; // not in same document
}
CView* pView = pOleState->m_pActivateView;
if (pView == NULL)
{
// no routing view available - try to use the one with focus
CWnd* pWnd = CWnd::GetFocus();
while (pWnd != NULL && !pWnd->IsKindOf(RUNTIME_CLASS(CView)))
{
pWnd = pWnd->GetParent();
}
pView = STATIC_DOWNCAST(CView, pWnd);
if (pView == NULL)
{
// still no routing view available - just use first one
COleDocument* pDoc = GetDocument();
POSITION pos = pDoc->GetFirstViewPosition();
pView = pDoc->GetNextView(pos);
}
}
m_pView = pView;
}
return m_pView->GetSafeHwnd() != NULL;
}
void COleClientItem::OnActivate()
{
ASSERT_VALID(this);
// it is necessary to lock the object when it is in-place
// (without this, a link to an embedding may disconnect unexpectedly)
if (!m_bLocked)
{
OleLockRunning(m_lpObject, TRUE, FALSE);
m_bLocked = TRUE;
}
// notify the item of the state change
if (m_nItemState != activeState)
{
OnChange(OLE_CHANGED_STATE, (DWORD)activeState);
m_nItemState = activeState;
}
}
void COleClientItem::OnActivateUI()
{
ASSERT_VALID(this);
CFrameWnd* pMainFrame;
CFrameWnd* pDocFrame = NULL;
if (OnGetWindowContext(&pMainFrame, &pDocFrame, NULL))
{
m_dwFrameMenuBarVisibility = pMainFrame->GetMenuBarVisibility();
pMainFrame->SetMenuBarVisibility(AFX_MBV_KEEPVISIBLE);
}
// notify the item of the state change
if (m_nItemState != activeUIState)
{
OnChange(OLE_CHANGED_STATE, (DWORD)activeUIState);
m_nItemState = activeUIState;
}
// the container window must have WS_CLIPCHILDREN set
ASSERT_VALID(m_pView);
m_dwContainerStyle = m_pView->GetStyle();
m_pView->ModifyStyle(0, WS_CLIPCHILDREN);
// cache the server's HWND for later
LPOLEINPLACEOBJECT lpInPlaceObject = QUERYINTERFACE(m_lpObject, IOleInPlaceObject);
ASSERT(lpInPlaceObject != NULL);
// get the HWND for the in-place active object
HWND hWnd;
if (lpInPlaceObject->GetWindow(&hWnd) != S_OK)
{
hWnd = NULL;
}
lpInPlaceObject->Release();
m_hWndServer = hWnd;
// make sure top-level frame is hooked
if (m_pInPlaceFrame != NULL)
{
ASSERT_VALID(m_pInPlaceFrame->m_pFrameWnd);
m_pInPlaceFrame->m_pFrameWnd->m_pNotifyHook = m_pInPlaceFrame;
}
// make sure doc-level frame is hooked
if (m_pInPlaceDoc != NULL)
{
ASSERT_VALID(m_pInPlaceDoc->m_pFrameWnd);
m_pInPlaceDoc->m_pFrameWnd->m_pNotifyHook = m_pInPlaceDoc;
}
}
BOOL COleClientItem::OnShowControlBars(CFrameWnd* pFrameWnd, BOOL bShow)
{
ASSERT_VALID(pFrameWnd);
ASSERT_VALID(this);
// show/hide all bars marked with CBRS_HIDE_INPLACE style
BOOL bResult = FALSE;
if (bShow)
{
POSITION pos = pFrameWnd->m_listControlBars.GetHeadPosition();
while (pos)
{
CControlBar* pBar =
(CControlBar*)pFrameWnd->m_listControlBars.GetNext(pos);
ASSERT_VALID(pBar);
if ((pBar->GetBarStyle() & CBRS_HIDE_INPLACE) &&
(pBar->m_nStateFlags & CControlBar::tempHide))
{
pBar->m_nStateFlags &= ~CControlBar::tempHide;
pFrameWnd->ShowControlBar(pBar, TRUE, TRUE);
bResult = TRUE;
}
}
}
else
{
POSITION pos = pFrameWnd->m_listControlBars.GetHeadPosition();
while (pos)
{
CControlBar* pBar =
(CControlBar*)pFrameWnd->m_listControlBars.GetNext(pos);
ASSERT_VALID(pBar);
if (pBar->IsVisible() && (pBar->GetBarStyle() & CBRS_HIDE_INPLACE))
{
pBar->m_nStateFlags |= CControlBar::tempHide;
pFrameWnd->ShowControlBar(pBar, FALSE, TRUE);
bResult = TRUE;
}
}
}
return bResult;
}
BOOL COleClientItem::OnGetWindowContext(CFrameWnd** ppMainFrame, CFrameWnd** ppDocFrame, LPOLEINPLACEFRAMEINFO pFrameInfo)
{
ASSERT(AfxIsValidAddress(ppMainFrame, sizeof(CFrameWnd*)));
ASSERT(AfxIsValidAddress(ppDocFrame, sizeof(CFrameWnd*)));
ASSERT(pFrameInfo == NULL || AfxIsValidAddress(pFrameInfo, sizeof(OLEINPLACEFRAMEINFO)));
ASSERT_VALID(this);
ASSERT_VALID(m_pView);
if ((ppMainFrame == NULL) || (ppDocFrame == NULL))
{
return E_POINTER;
}
// get main window of application
*ppMainFrame = m_pView->GetTopLevelFrame();
ENSURE_VALID(*ppMainFrame);
ASSERT_KINDOF(CFrameWnd, *ppMainFrame);
// get document window (if there is one)
CFrameWnd* pDocFrame = m_pView->GetParentFrame();
if (pDocFrame != *ppMainFrame)
{
*ppDocFrame = pDocFrame;
ASSERT_VALID(*ppDocFrame);
ASSERT_KINDOF(CFrameWnd, *ppDocFrame);
}
if (pFrameInfo != NULL)
{
// get accelerator table
CDocTemplate* pTemplate = GetDocument()->GetDocTemplate();
HACCEL hAccel = pTemplate != NULL ? pTemplate->m_hAccelInPlace : NULL;
pFrameInfo->cAccelEntries =
hAccel != NULL ? CopyAcceleratorTable(hAccel, NULL, 0) : 0;
pFrameInfo->haccel = pFrameInfo->cAccelEntries != 0 ? hAccel : NULL;
pFrameInfo->hwndFrame = (*ppMainFrame)->m_hWnd;
pFrameInfo->fMDIApp = *ppDocFrame != NULL;
}
return TRUE;
}
BOOL COleClientItem::OnScrollBy(CSize sizeExtent)
{
ASSERT_VALID(this);
ASSERT_VALID(m_pView);
// scroll through splitter or view
CSplitterWnd* pSplitter = CView::GetParentSplitter(m_pView, FALSE);
BOOL bResult;
if (pSplitter != NULL)
bResult = pSplitter->DoScrollBy(m_pView, sizeExtent);
else
bResult = m_pView->OnScrollBy(sizeExtent);
return bResult;
}
void COleClientItem::OnDeactivateUI(BOOL /*bUndoable*/)
{
ASSERT_VALID(this);
// notify the item of the state change
if (m_nItemState != activeState)
{
OnChange(OLE_CHANGED_STATE, (DWORD)activeState);
m_nItemState = activeState;
}
if (m_pView != NULL && m_pDocument->GetFirstViewPosition())
{
// restore container window's WS_CLIPCHILDREN bit...
ASSERT_VALID(m_pView);
m_pView->ModifyStyle(WS_CLIPCHILDREN, m_dwContainerStyle & WS_CLIPCHILDREN);
}
// restore original user interface on the frame window
CFrameWnd* pMainFrame;
CFrameWnd* pDocFrame = NULL;
if (OnGetWindowContext(&pMainFrame, &pDocFrame, NULL))
{
ENSURE(pMainFrame->GetMenuBarVisibility() == AFX_MBV_KEEPVISIBLE);
pMainFrame->SetMenuBarVisibility(m_dwFrameMenuBarVisibility);
ASSERT_VALID(pMainFrame);
pMainFrame->DelayUpdateFrameTitle();
if (pMainFrame->NegotiateBorderSpace(CFrameWnd::borderSet, NULL))
pMainFrame->DelayRecalcLayout();
// restore original user interface on the document window
if (pDocFrame != NULL)
{
pDocFrame->DelayUpdateFrameTitle();
if (pDocFrame->NegotiateBorderSpace(CFrameWnd::borderSet, NULL))
pDocFrame->DelayRecalcLayout();
}
}
// cleanup frame interfaces allocated in GetWindowContext
if (m_pInPlaceFrame != NULL)
{
OnShowControlBars(m_pInPlaceFrame->m_pFrameWnd, TRUE);
// release OLE frame window hooks and allow menu update
::OleSetMenuDescriptor(NULL, m_pInPlaceFrame->m_pFrameWnd->m_hWnd,
NULL, NULL, NULL);
if (m_pInPlaceDoc != NULL)
{
::OleSetMenuDescriptor(NULL, m_pInPlaceDoc->m_pFrameWnd->m_hWnd,
NULL, NULL, NULL);
}
m_pInPlaceFrame->m_pFrameWnd->DelayUpdateFrameMenu(NULL);
// unhook from frame window
if (m_pInPlaceFrame->m_pFrameWnd->m_pNotifyHook == m_pInPlaceFrame)
m_pInPlaceFrame->m_pFrameWnd->m_pNotifyHook = NULL;
// cleanup document interfaces allocated in GetWindowContext
if (m_pInPlaceDoc != NULL)
{
OnShowControlBars(m_pInPlaceDoc->m_pFrameWnd, TRUE);
// unhook from frame window
if (m_pInPlaceDoc->m_pFrameWnd->m_pNotifyHook == m_pInPlaceDoc)
m_pInPlaceDoc->m_pFrameWnd->m_pNotifyHook = NULL;
}
}
// reset server HWND -- no longer necessary
m_hWndServer = NULL;
CWnd* pWnd = AfxGetMainWnd();
if (pWnd != NULL)
{
// set focus back to the container
pWnd = pWnd->EnsureTopLevelParent();
if (::GetActiveWindow() == pWnd->m_hWnd)
{
pWnd->SetFocus();
}
}
}
void COleClientItem::OnDeactivate()
{
ASSERT_VALID(this);
// notify the item of the state change
if (m_nItemState != loadedState)
{
OnChange(OLE_CHANGED_STATE, (DWORD)loadedState);
m_nItemState = loadedState;
}
// cleanup frame interfaces allocated in GetWindowContext
if (m_pInPlaceFrame != NULL)
{
// release in place frame
if (m_pInPlaceFrame->m_pFrameWnd->m_pNotifyHook == m_pInPlaceFrame)
{
m_pInPlaceFrame->m_pFrameWnd->m_pNotifyHook = NULL;
m_pInPlaceFrame->m_pFrameWnd = NULL;
}
m_pInPlaceFrame->InternalRelease();
m_pInPlaceFrame = NULL;
// cleanup document interfaces allocated in GetWindowContext
if (m_pInPlaceDoc != NULL)
{
// release in place document
if (m_pInPlaceDoc->m_pFrameWnd->m_pNotifyHook == m_pInPlaceDoc)
{
m_pInPlaceDoc->m_pFrameWnd->m_pNotifyHook = NULL;
m_pInPlaceDoc->m_pFrameWnd = NULL;
}
m_pInPlaceDoc->InternalRelease();
m_pInPlaceDoc = NULL;
}
}
// both frame-level and doc-level interfaces should be cleaned up
ASSERT(m_pInPlaceFrame == NULL);
ASSERT(m_pInPlaceDoc == NULL);
// no longer need the container window
m_pView = NULL;
}
void COleClientItem::OnDiscardUndoState()
{
ASSERT_VALID(this);
// default does nothing
}
void COleClientItem::OnDeactivateAndUndo()
{
ASSERT_VALID(this);
DeactivateUI(); // default is to UI deactivate
}
BOOL COleClientItem::OnChangeItemPosition(const CRect& rectPos)
{
if (!IsInPlaceActive())
return FALSE;
ASSERT_VALID(this);
ASSERT(AfxIsValidAddress(&rectPos, sizeof(CRect), FALSE));
ASSERT_VALID(m_pView);
// determine the visible rect based on intersection between client rect
CRect clipRect;
OnGetClipRect(clipRect);
CRect visRect;
visRect.IntersectRect(clipRect, rectPos);
// advise the server of the new visible rectangle
if (!visRect.IsRectEmpty())
return SetItemRects(&rectPos, &clipRect);
return FALSE;
}
/////////////////////////////////////////////////////////////////////////////
// IOleInPlaceFrame notifications (default implementation)
void COleClientItem::OnInsertMenus(CMenu* pMenuShared,
LPOLEMENUGROUPWIDTHS lpMenuWidths)
{
ASSERT_VALID(this);
ASSERT_VALID(pMenuShared);
ASSERT(AfxIsValidAddress(lpMenuWidths, sizeof(OLEMENUGROUPWIDTHS)));
// initialize the group widths array
lpMenuWidths->width[0] = 0;
lpMenuWidths->width[2] = 0;
lpMenuWidths->width[4] = 0;
// get menu from document template
CDocTemplate* pTemplate = GetDocument()->GetDocTemplate();
HMENU hMenuOLE = pTemplate->m_hMenuInPlace;
// only copy the popups if there is a menu loaded
if (hMenuOLE == NULL)
return;
// insert our menu items and adjust group widths array
AfxMergeMenus(pMenuShared->GetSafeHmenu(), hMenuOLE, &lpMenuWidths->width[0], 0);
}
void COleClientItem::OnSetMenu(CMenu* pMenuShared, HOLEMENU holemenu,
HWND hwndActiveObject)
{
ASSERT_VALID(this);
ASSERT(m_pInPlaceFrame != NULL);
ASSERT(m_pInPlaceFrame->m_pFrameWnd != NULL);
// don't set the doc is active
CFrameWnd* pFrameWnd = m_pInPlaceFrame->m_pFrameWnd;
ASSERT_VALID(pFrameWnd);
if (m_pInPlaceDoc != NULL &&
m_pInPlaceDoc->m_pFrameWnd != pFrameWnd->GetActiveFrame())
{
return;
}
// update the menu
pFrameWnd->DelayUpdateFrameMenu(pMenuShared->GetSafeHmenu());
// enable/disable the OLE command routing hook
::OleSetMenuDescriptor(holemenu, pFrameWnd->m_hWnd,
hwndActiveObject, NULL, NULL);
if (m_pInPlaceDoc != NULL)
{
pFrameWnd = m_pInPlaceDoc->m_pFrameWnd;
ASSERT_VALID(pFrameWnd);
::OleSetMenuDescriptor(holemenu, pFrameWnd->m_hWnd,
hwndActiveObject, NULL, NULL);
}
}
void COleClientItem::OnRemoveMenus(CMenu* pMenuShared)
{
ASSERT_VALID(this);
ASSERT_VALID(pMenuShared);
// get menu from document template
CDocTemplate* pTemplate = GetDocument()->GetDocTemplate();
HMENU hMenuOLE = pTemplate->m_hMenuInPlace;
if (hMenuOLE == NULL)
return;
// remove any menu popups originally added in OnInsertMenus
AfxUnmergeMenus(pMenuShared->GetSafeHmenu(), hMenuOLE);
}
BOOL COleClientItem::OnUpdateFrameTitle()
{
ASSERT_VALID(this);
return FALSE;
}
/////////////////////////////////////////////////////////////////////////////
// In-place Activation operations
void COleClientItem::Deactivate()
{
ASSERT_VALID(this);
ASSERT(m_lpObject != NULL);
ASSERT(IsInPlaceActive());
// get IOleInPlaceObject interface
LPOLEINPLACEOBJECT lpInPlaceObject =
QUERYINTERFACE(m_lpObject, IOleInPlaceObject);
if (lpInPlaceObject == NULL)
{
Close(); // handle rare failure cases by calling Close
return;
}
// call IOleInPlaceObject::InPlaceDeactivate
m_scLast = lpInPlaceObject->InPlaceDeactivate();
lpInPlaceObject->Release();
if (FAILED(m_scLast))
{
Close(); // handle rare failure cases by calling Close
return;
}
m_nItemState = loadedState; // just in case server has crashed
}
void COleClientItem::DeactivateUI()
{
ASSERT_VALID(this);
ASSERT(m_lpObject != NULL);
ASSERT(GetItemState() == activeUIState);
// get IOleInPlaceObject interface
LPOLEINPLACEOBJECT lpInPlaceObject =
QUERYINTERFACE(m_lpObject, IOleInPlaceObject);
if (lpInPlaceObject == NULL)
{
Close(); // handle rare failure cases by calling Close
return;
}
// call IOleInPlaceObject::UIDeactivate
m_scLast = lpInPlaceObject->UIDeactivate();
lpInPlaceObject->Release();
if (FAILED(m_scLast))
{
Close(); // handle rare failure cases by calling Close
return;
}
if (m_nItemState == activeUIState)
m_nItemState = activeState; // just in case server has crashed
}
BOOL COleClientItem::SetItemRects(LPCRECT lpPosRect, LPCRECT lpClipRect)
{
ASSERT_VALID(this);
ASSERT(m_lpObject != NULL);
ASSERT(IsInPlaceActive());
ASSERT(lpPosRect == NULL ||
AfxIsValidAddress(lpPosRect, sizeof(RECT), FALSE));
ASSERT(lpClipRect == NULL ||
AfxIsValidAddress(lpClipRect, sizeof(RECT), FALSE));
// get IOleInPlaceObject interface
LPOLEINPLACEOBJECT lpInPlaceObject =
QUERYINTERFACE(m_lpObject, IOleInPlaceObject);
if (lpInPlaceObject == NULL)
return FALSE; // perhaps server crashed?
// use OnGetPosRect if rectangle not specified
CRect rectPos;
if (lpPosRect == NULL)
{
ASSERT(lpClipRect == NULL);
OnGetItemPosition(rectPos);
lpPosRect = &rectPos;
}
// use OnGetClipRect if clipping rectangle not specified
CRect rectClip;
if (lpClipRect == NULL)
{
OnGetClipRect(rectClip);
lpClipRect = &rectClip;
}
ASSERT(lpPosRect != NULL);
ASSERT(lpClipRect != NULL);
// notify the server of the new item rectangles
m_scLast = lpInPlaceObject->SetObjectRects(lpPosRect, lpClipRect);
lpInPlaceObject->Release();
// remember position rectangle as cached position
return !FAILED(m_scLast);
}
BOOL COleClientItem::ReactivateAndUndo()
{
ASSERT_VALID(this);
ASSERT(m_lpObject != NULL);
ASSERT(IsInPlaceActive());
// get IOleInPlaceObject interface
LPOLEINPLACEOBJECT lpInPlaceObject =
QUERYINTERFACE(m_lpObject, IOleInPlaceObject);
if (lpInPlaceObject == NULL)
{
Close(); // handle rare failure cases by calling Close
return FALSE;
}
// call IOleInPlaceObject::ReactivateAndUndo
m_scLast = lpInPlaceObject->ReactivateAndUndo();
lpInPlaceObject->Release();
if (FAILED(m_scLast))
{
Close(); // handle rare failure cases by calling Close
return FALSE;
}
return TRUE;
}
CWnd* COleClientItem::GetInPlaceWindow()
{
ASSERT_VALID(this);
ASSERT(m_lpObject != NULL);
// only inplace active items should be asking for the window handle
if (GetItemState() != activeUIState)
return NULL;
// handle case of server that just disappears
if (m_hWndServer != NULL && !::IsWindow(m_hWndServer))
{
Close();
return NULL;
}
ASSERT(m_hWndServer == NULL || ::IsWindow(m_hWndServer));
return CWnd::FromHandle(m_hWndServer);
}
/////////////////////////////////////////////////////////////////////////////
// COleFrameHook OLE interface implementation
BEGIN_INTERFACE_MAP(COleFrameHook, CCmdTarget)
INTERFACE_PART(COleFrameHook, IID_IOleWindow, OleInPlaceFrame)
INTERFACE_PART(COleFrameHook, IID_IOleInPlaceUIWindow, OleInPlaceFrame)
INTERFACE_PART(COleFrameHook, IID_IOleInPlaceFrame, OleInPlaceFrame)
INTERFACE_PART(COleFrameHook, IID_IOleCommandTarget, OleCommandTarget)
END_INTERFACE_MAP()
/////////////////////////////////////////////////////////////////////////////
// COleFrameHook::XOleCommandTarget implementation
STDMETHODIMP_(ULONG) COleFrameHook::XOleCommandTarget::AddRef()
{
METHOD_PROLOGUE_EX_(COleFrameHook, OleCommandTarget)
return pThis->ExternalAddRef();
}
STDMETHODIMP_(ULONG) COleFrameHook::XOleCommandTarget::Release()
{
METHOD_PROLOGUE_EX_(COleFrameHook, OleCommandTarget)
return pThis->ExternalRelease();
}
STDMETHODIMP COleFrameHook::XOleCommandTarget::QueryInterface(
REFIID iid, LPVOID* ppvObj)
{
METHOD_PROLOGUE_EX_(COleFrameHook, OleCommandTarget)
return pThis->ExternalQueryInterface(&iid, ppvObj);
}
STDMETHODIMP COleFrameHook::XOleCommandTarget::Exec(
const GUID* pguidCmdGroup, DWORD nCmdID, DWORD nCmdExecOpt,
VARIANTARG* pvarargIn, VARIANTARG* pvarargOut)
{
HRESULT hResult = OLECMDERR_E_UNKNOWNGROUP;
METHOD_PROLOGUE_EX_(COleFrameHook, OleCommandTarget)
COleDocObjectItem* pActiveDocObjectItem =
DYNAMIC_DOWNCAST(COleDocObjectItem, pThis->m_pActiveItem);
if (pActiveDocObjectItem != NULL)
{
hResult = _AfxExecOleCommandHelper(pActiveDocObjectItem,
pguidCmdGroup, nCmdID, nCmdExecOpt, pvarargIn, pvarargOut);
}
return hResult;
}
STDMETHODIMP COleFrameHook::XOleCommandTarget::QueryStatus(
const GUID* pguidCmdGroup, ULONG cCmds, OLECMD rgCmds[],
OLECMDTEXT* pcmdtext)
{
HRESULT hResult = OLECMDERR_E_UNKNOWNGROUP;
METHOD_PROLOGUE_EX_(COleFrameHook, OleCommandTarget)
COleDocObjectItem* pActiveDocObjectItem =
DYNAMIC_DOWNCAST(COleDocObjectItem, pThis->m_pActiveItem);
if (pActiveDocObjectItem != NULL)
{
hResult = _AfxQueryStatusOleCommandHelper(pActiveDocObjectItem,
pguidCmdGroup, cCmds, rgCmds, pcmdtext);
}
return hResult;
}
/////////////////////////////////////////////////////////////////////////////
// COleFrameHook::XOleInPlaceFrame implementation
STDMETHODIMP_(ULONG) COleFrameHook::XOleInPlaceFrame::AddRef()
{
METHOD_PROLOGUE_EX_(COleFrameHook, OleInPlaceFrame)
return pThis->ExternalAddRef();
}
STDMETHODIMP_(ULONG) COleFrameHook::XOleInPlaceFrame::Release()
{
METHOD_PROLOGUE_EX_(COleFrameHook, OleInPlaceFrame)
return pThis->ExternalRelease();
}
STDMETHODIMP COleFrameHook::XOleInPlaceFrame::QueryInterface(
REFIID iid, LPVOID* ppvObj)
{
METHOD_PROLOGUE_EX_(COleFrameHook, OleInPlaceFrame)
return pThis->ExternalQueryInterface(&iid, ppvObj);
}
STDMETHODIMP COleFrameHook::XOleInPlaceFrame::GetWindow(HWND* lphwnd)
{
METHOD_PROLOGUE_EX_(COleFrameHook, OleInPlaceFrame)
if (lphwnd == NULL)
{
return E_POINTER;
}
*lphwnd = pThis->m_hWnd;
return *lphwnd != NULL ? S_OK : E_FAIL;
}
STDMETHODIMP COleFrameHook::XOleInPlaceFrame::ContextSensitiveHelp(
BOOL fEnterMode)
{
METHOD_PROLOGUE_EX(COleFrameHook, OleInPlaceFrame)
ASSERT_VALID(pThis);
// document frame windows should not be put in help mode, so we get the
// top-level frame window and check it first
CFrameWnd* pFrameWnd = pThis->m_pFrameWnd->GetTopLevelFrame();
ENSURE_VALID(pFrameWnd);
if (fEnterMode)
{
if (!pFrameWnd->m_bHelpMode)
{
// check if help mode probable
if (!pFrameWnd->CanEnterHelpMode())
return E_UNEXPECTED;
// attempt to enter context help
if (!pThis->OnContextHelp(TRUE) ||
!pFrameWnd->PostMessage(WM_COMMAND, ID_CONTEXT_HELP))
{
return E_UNEXPECTED;
}
}
}
else
{
// just exit help mode
pFrameWnd->ExitHelpMode();
}
return S_OK;
}
STDMETHODIMP COleFrameHook::XOleInPlaceFrame::GetBorder(LPRECT lpRectBorder)
{
METHOD_PROLOGUE_EX(COleFrameHook, OleInPlaceFrame)
ASSERT_VALID(pThis);
COleClientItem* pItem = pThis->m_pActiveItem;
ASSERT_VALID(pItem);
CFrameWnd* pFrameWnd = pThis->m_pFrameWnd;
ASSERT_VALID(pFrameWnd);
// hide the control bars temporarily
BOOL bHidden = pItem->OnShowControlBars(pFrameWnd, FALSE);
// determine border space assuming that we'll remove our control bars
CRect rectSave = pFrameWnd->m_rectBorder;
pFrameWnd->NegotiateBorderSpace(CFrameWnd::borderSet, NULL);
pFrameWnd->NegotiateBorderSpace(CFrameWnd::borderGet, lpRectBorder);
pFrameWnd->NegotiateBorderSpace(CFrameWnd::borderSet, &rectSave);
// restore control bars
if (bHidden)
pItem->OnShowControlBars(pFrameWnd, TRUE);
return S_OK;
}
STDMETHODIMP COleFrameHook::XOleInPlaceFrame::RequestBorderSpace(
LPCRECT lpRectWidths)
{
METHOD_PROLOGUE_EX(COleFrameHook, OleInPlaceFrame)
ASSERT_VALID(pThis);
CFrameWnd* pFrameWnd = pThis->m_pFrameWnd;
ASSERT_VALID(pFrameWnd);
if (!pFrameWnd->NegotiateBorderSpace(
CFrameWnd::borderRequest, (LPRECT)lpRectWidths))
{
return INPLACE_E_NOTOOLSPACE;
}
return S_OK;
}
STDMETHODIMP COleFrameHook::XOleInPlaceFrame::SetBorderSpace(
LPCRECT lpRectWidths)
{
METHOD_PROLOGUE_EX(COleFrameHook, OleInPlaceFrame)
ASSERT_VALID(pThis);
CFrameWnd* pFrameWnd = pThis->m_pFrameWnd;
if (pFrameWnd->NegotiateBorderSpace(
CFrameWnd::borderSet, (LPRECT)lpRectWidths))
{
// We have to turn off the notify and idlelayout flags so RecalcLayout
// doesn't call back into the object and tell it to resize it's borders
// while we are in the middle of setting the border space.
pFrameWnd->m_nIdleFlags &= ~(CFrameWnd::idleLayout|CFrameWnd::idleNotify);
// synchronously re-layout borders.
pFrameWnd->RecalcLayout(FALSE);
}
pThis->m_pActiveItem->OnShowControlBars(pFrameWnd, lpRectWidths == NULL);
return S_OK;
}
STDMETHODIMP COleFrameHook::XOleInPlaceFrame::SetActiveObject(
LPOLEINPLACEACTIVEOBJECT lpActiveObject, LPCOLESTR lpszObjName)
{
METHOD_PROLOGUE_EX(COleFrameHook, OleInPlaceFrame)
ASSERT_VALID(pThis);
SCODE sc = E_UNEXPECTED;
TRY
{
// release the old active object
RELEASE(pThis->m_lpActiveObject);
// set the new active object
pThis->m_lpActiveObject = lpActiveObject;
if (lpActiveObject != NULL)
lpActiveObject->AddRef();
// update caption if necessary
pThis->m_strObjName.Empty();
if (lpszObjName != NULL && lpActiveObject != NULL)
{
pThis->m_strObjName = lpszObjName;
pThis->m_pActiveItem->OnUpdateFrameTitle();
}
sc = S_OK;
}
END_TRY
return sc;
}
STDMETHODIMP COleFrameHook::XOleInPlaceFrame::InsertMenus(
HMENU hmenuShared, LPOLEMENUGROUPWIDTHS lpMenuWidths)
{
METHOD_PROLOGUE_EX(COleFrameHook, OleInPlaceFrame)
ASSERT_VALID(pThis);
// get the associated COleClientItem object
COleClientItem* pItem = pThis->m_pActiveItem;
ASSERT_VALID(pItem);
SCODE sc = E_UNEXPECTED;
TRY
{
pItem->OnInsertMenus(CMenu::FromHandle(hmenuShared), lpMenuWidths);
sc = S_OK;
}
END_TRY
return sc;
}
STDMETHODIMP COleFrameHook::XOleInPlaceFrame::SetMenu(
HMENU hmenuShared, HOLEMENU holemenu, HWND hwndActiveObject)
{
METHOD_PROLOGUE_EX(COleFrameHook, OleInPlaceFrame)
ASSERT_VALID(pThis);
// get the associated COleClientItem object
COleClientItem* pItem = pThis->m_pActiveItem;
ASSERT_VALID(pItem);
SCODE sc = E_UNEXPECTED;
TRY
{
pItem->OnSetMenu(CMenu::FromHandle(hmenuShared), holemenu,
hwndActiveObject);
sc = S_OK;
}
END_TRY
return sc;
}
STDMETHODIMP COleFrameHook::XOleInPlaceFrame::RemoveMenus(
HMENU hmenuShared)
{
METHOD_PROLOGUE_EX(COleFrameHook, OleInPlaceFrame)
ASSERT_VALID(pThis);
// get the associated COleClientItem object
COleClientItem* pItem = pThis->m_pActiveItem;
ASSERT_VALID(pItem);
SCODE sc = E_UNEXPECTED;
TRY
{
pItem->OnRemoveMenus(CMenu::FromHandle(hmenuShared));
sc = S_OK;
}
END_TRY
return sc;
}
STDMETHODIMP COleFrameHook::XOleInPlaceFrame::SetStatusText(
LPCOLESTR lpszStatusText)
{
METHOD_PROLOGUE_EX_(COleFrameHook, OleInPlaceFrame)
LPARAM lParam;
CString strText;
if (lpszStatusText)
{
strText = lpszStatusText;
lParam = reinterpret_cast<LPARAM>(strText.GetString());
}
else
{
lParam = 0;
}
pThis->m_pFrameWnd->SendMessage(WM_SETMESSAGESTRING, 0, lParam);
return S_OK;
}
STDMETHODIMP COleFrameHook::XOleInPlaceFrame::EnableModeless(BOOL fEnable)
{
METHOD_PROLOGUE_EX(COleFrameHook, OleInPlaceFrame)
ASSERT_VALID(pThis);
ASSERT_VALID(pThis->m_pFrameWnd);
SCODE sc = E_UNEXPECTED;
TRY
{
if (!fEnable)
pThis->m_pFrameWnd->BeginModalState();
else
pThis->m_pFrameWnd->EndModalState();
sc = S_OK;
}
END_TRY
return sc;
}
STDMETHODIMP COleFrameHook::XOleInPlaceFrame::TranslateAccelerator(
LPMSG lpmsg, WORD /*wID*/)
{
METHOD_PROLOGUE_EX(COleFrameHook, OleInPlaceFrame)
ASSERT_VALID(pThis);
SCODE sc = E_UNEXPECTED;
TRY
{
// swap accel tables and call PreTranslateMessage
CFrameWnd* pFrameWnd = pThis->m_pFrameWnd;
HACCEL hAccelSave = pFrameWnd->m_hAccelTable;
pFrameWnd->m_hAccelTable = pThis->m_hAccelTable;
ASSERT(lpmsg != NULL);
MSG msg = *lpmsg;
sc = pFrameWnd->PreTranslateMessage(&msg) ? S_OK : S_FALSE;
*lpmsg = msg;
pFrameWnd->m_hAccelTable = hAccelSave;
}
END_TRY
return sc;
}
/////////////////////////////////////////////////////////////////////////////
// COleClientItem::XOleIPSite implementation
STDMETHODIMP_(ULONG) COleClientItem::XOleIPSite::AddRef()
{
METHOD_PROLOGUE_EX_(COleClientItem, OleIPSite)
return pThis->ExternalAddRef();
}
STDMETHODIMP_(ULONG) COleClientItem::XOleIPSite::Release()
{
METHOD_PROLOGUE_EX_(COleClientItem, OleIPSite)
return pThis->ExternalRelease();
}
STDMETHODIMP COleClientItem::XOleIPSite::QueryInterface(REFIID iid, LPVOID* ppvObj)
{
METHOD_PROLOGUE_EX_(COleClientItem, OleIPSite)
return pThis->ExternalQueryInterface(&iid, ppvObj);
}
STDMETHODIMP COleClientItem::XOleIPSite::GetWindow(HWND* lphwnd)
{
METHOD_PROLOGUE_EX_(COleClientItem, OleIPSite)
if (lphwnd == NULL)
{
return E_POINTER;
}
*lphwnd = pThis->m_pView->GetSafeHwnd();
return *lphwnd != NULL ? S_OK : E_FAIL;
}
STDMETHODIMP COleClientItem::XOleIPSite::ContextSensitiveHelp(
BOOL fEnterMode)
{
METHOD_PROLOGUE_EX_(COleClientItem, OleIPSite)
if (pThis->m_pInPlaceFrame == NULL)
return E_UNEXPECTED;
// simply delegate to frame window implementation
return pThis->m_pInPlaceFrame->
m_xOleInPlaceFrame.ContextSensitiveHelp(fEnterMode);
}
STDMETHODIMP COleClientItem::XOleIPSite::CanInPlaceActivate()
{
METHOD_PROLOGUE_EX(COleClientItem, OleIPSite)
return pThis->CanActivate() ? S_OK : S_FALSE;
}
STDMETHODIMP COleClientItem::XOleIPSite::OnInPlaceActivate()
{
METHOD_PROLOGUE_EX(COleClientItem, OleIPSite)
ASSERT_VALID(pThis);
SCODE sc = E_UNEXPECTED;
TRY
{
pThis->OnActivate();
sc = S_OK;
}
END_TRY
return sc;
}
STDMETHODIMP COleClientItem::XOleIPSite::OnUIActivate()
{
METHOD_PROLOGUE_EX(COleClientItem, OleIPSite)
ASSERT_VALID(pThis);
SCODE sc = E_UNEXPECTED;
TRY
{
pThis->OnActivateUI();
sc = S_OK;
}
END_TRY
return sc;
}
STDMETHODIMP COleClientItem::XOleIPSite::GetWindowContext(LPOLEINPLACEFRAME* lplpFrame,
LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT lpPosRect, LPRECT lpClipRect, LPOLEINPLACEFRAMEINFO lpFrameInfo)
{
METHOD_PROLOGUE_EX(COleClientItem, OleIPSite)
ASSERT_VALID(pThis);
if ((lplpFrame == NULL) || (lplpDoc == NULL))
{
return E_POINTER;
}
*lplpFrame = NULL; // init these in-case of mem-alloc failure
*lplpDoc = NULL;
CFrameWnd* pMainFrame = NULL;
CFrameWnd* pDocFrame = NULL;
SCODE sc = E_UNEXPECTED;
TRY
{
// get position of the item relative to activation view
CRect rect;
pThis->OnGetItemPosition(rect);
::CopyRect(lpPosRect, &rect);
pThis->OnGetClipRect(rect);
::CopyRect(lpClipRect, &rect);
// get the window context information
if (pThis->OnGetWindowContext(&pMainFrame, &pDocFrame, lpFrameInfo))
{
// hook IOleInPlaceFrame interface to pMainFrame
if (pThis->m_pInPlaceFrame == NULL)
pThis->m_pInPlaceFrame = new COleFrameHook(pMainFrame, pThis);
pThis->m_pInPlaceFrame->InternalAddRef();
*lplpFrame = (LPOLEINPLACEFRAME)pThis->m_pInPlaceFrame->
GetInterface(&IID_IOleInPlaceFrame);
// save accel table for IOleInPlaceFrame::TranslateAccelerators
pThis->m_pInPlaceFrame->m_hAccelTable = lpFrameInfo->haccel;
// hook IOleInPlaceUIWindow to pDocFrame
if (pDocFrame != NULL)
{
if (pThis->m_pInPlaceDoc == NULL)
pThis->m_pInPlaceDoc = new COleFrameHook(pDocFrame, pThis);
pThis->m_pInPlaceDoc->InternalAddRef();
*lplpDoc = (LPOLEINPLACEUIWINDOW)pThis->m_pInPlaceDoc->
GetInterface(&IID_IOleInPlaceUIWindow);
}
sc = S_OK;
}
}
CATCH_ALL(e)
{
// cleanup memory that may be partially allocated
delete *lplpFrame;
ASSERT(*lplpDoc == NULL);
DELETE_EXCEPTION(e);
}
END_CATCH_ALL
return sc;
}
STDMETHODIMP COleClientItem::XOleIPSite::Scroll(SIZE scrollExtent)
{
METHOD_PROLOGUE_EX(COleClientItem, OleIPSite)
ASSERT_VALID(pThis);
SCODE sc = E_UNEXPECTED;
TRY
{
if (!pThis->OnScrollBy(CSize(scrollExtent)))
sc = S_FALSE;
else
sc = S_OK;
}
END_TRY
return sc;
}
STDMETHODIMP COleClientItem::XOleIPSite::OnUIDeactivate(BOOL fUndoable)
{
METHOD_PROLOGUE_EX(COleClientItem, OleIPSite)
ASSERT_VALID(pThis);
SCODE sc = E_UNEXPECTED;
TRY
{
pThis->OnDeactivateUI(fUndoable);
sc = S_OK;
}
END_TRY
return sc;
}
STDMETHODIMP COleClientItem::XOleIPSite::OnInPlaceDeactivate()
{
METHOD_PROLOGUE_EX(COleClientItem, OleIPSite)
ASSERT_VALID(pThis);
SCODE sc = E_UNEXPECTED;
TRY
{
pThis->OnDeactivate();
sc = S_OK;
}
END_TRY
return sc;
}
STDMETHODIMP COleClientItem::XOleIPSite::DiscardUndoState()
{
METHOD_PROLOGUE_EX(COleClientItem, OleIPSite)
ASSERT_VALID(pThis);
SCODE sc = E_UNEXPECTED;
TRY
{
pThis->OnDiscardUndoState();
sc = S_OK;
}
END_TRY
return sc;
}
STDMETHODIMP COleClientItem::XOleIPSite::DeactivateAndUndo()
{
METHOD_PROLOGUE_EX(COleClientItem, OleIPSite)
ASSERT_VALID(pThis);
SCODE sc = E_UNEXPECTED;
TRY
{
pThis->OnDeactivateAndUndo();
sc = S_OK;
}
END_TRY
return sc;
}
STDMETHODIMP COleClientItem::XOleIPSite::OnPosRectChange(
LPCRECT lpPosRect)
{
METHOD_PROLOGUE_EX(COleClientItem, OleIPSite)
ASSERT_VALID(pThis);
SCODE sc = E_UNEXPECTED;
TRY
{
CRect rect;
rect.CopyRect(lpPosRect);
pThis->OnChangeItemPosition(rect);
sc = S_OK;
}
END_TRY
return sc;
}
/////////////////////////////////////////////////////////////////////////////
| 40,167
| 16,459
|
/*
* PROJECT: Universal C++ RunTime (UCXXRT)
* FILE: message.cpp
* DATA: 2022/05/22
*
* PURPOSE: Universal C++ RunTime
*
* LICENSE: Relicensed under The MIT License from The CC BY 4.0 License
*
* DEVELOPER: MiroKaku (miro.kaku AT Outlook.com)
*/
EXTERN_C NTSTATUS NTAPI RtlFindAndFormatMessage(
_In_ UINT32 Flags,
_In_opt_ LPCVOID Source,
_In_ UINT32 MessageId,
_In_ UINT32 LanguageId,
_Out_ LPWSTR Buffer,
_Inout_ UINT32* Size,
_In_opt_ va_list* Arguments
)
{
NTSTATUS Status = STATUS_SUCCESS;
PVOID AllocatedBuffer = nullptr;
ANSI_STRING AnsiMessage{};
UNICODE_STRING UnicodeMessage{};
do
{
/* If this is a Win32 error wrapped as an OLE HRESULT then unwrap it */
if (((MessageId & 0xffff0000) == 0x80070000) &&
BooleanFlagOn(Flags, FORMAT_MESSAGE_FROM_SYSTEM) &&
!BooleanFlagOn(Flags, FORMAT_MESSAGE_FROM_HMODULE) &&
!BooleanFlagOn(Flags, FORMAT_MESSAGE_FROM_STRING))
{
MessageId &= 0x0000ffff;
}
if (Buffer == nullptr)
{
Status = STATUS_INVALID_PARAMETER;
break;
}
if (Flags & FORMAT_MESSAGE_ALLOCATE_BUFFER)
{
*(PVOID*)Buffer = nullptr;
}
PVOID DllHandle = nullptr;
ULONG MaximumWidth = 0ul;
PWSTR MessageFormat = nullptr;
PMESSAGE_RESOURCE_ENTRY MessageEntry = nullptr;
__try
{
PVOID BaseDllHandle = ucxxrt::PsSystemDllBase;
MaximumWidth = Flags & FORMAT_MESSAGE_MAX_WIDTH_MASK;
if (MaximumWidth == FORMAT_MESSAGE_MAX_WIDTH_MASK)
{
MaximumWidth = ULONG_MAX;
}
if (BooleanFlagOn(Flags, FORMAT_MESSAGE_FROM_STRING))
{
MessageFormat = (PWSTR)Source;
}
else
{
if (BooleanFlagOn(Flags, FORMAT_MESSAGE_FROM_HMODULE))
{
if (Source == nullptr)
{
DllHandle = BaseDllHandle;
}
else
{
DllHandle = (LPVOID)Source;
}
}
else if (BooleanFlagOn(Flags, FORMAT_MESSAGE_FROM_SYSTEM))
{
DllHandle = BaseDllHandle;
}
else
{
Status = STATUS_INVALID_PARAMETER;
break;
}
Status = RtlFindMessage(
DllHandle,
PtrToUlong(RT_MESSAGETABLE),
LanguageId,
MessageId,
&MessageEntry);
if (Status == STATUS_MESSAGE_NOT_FOUND)
{
if (BooleanFlagOn(Flags, FORMAT_MESSAGE_FROM_HMODULE) &&
BooleanFlagOn(Flags, FORMAT_MESSAGE_FROM_SYSTEM))
{
DllHandle = BaseDllHandle;
ClearFlag(Flags, FORMAT_MESSAGE_FROM_HMODULE);
Status = RtlFindMessage(
DllHandle,
PtrToUlong(RT_MESSAGETABLE),
LanguageId,
MessageId,
&MessageEntry);
}
}
if (!NT_SUCCESS(Status))
{
break;
}
if (!BooleanFlagOn(MessageEntry->Flags, MESSAGE_RESOURCE_UNICODE))
{
RtlInitAnsiString(&AnsiMessage, (PCSZ)MessageEntry->Text);
Status = RtlAnsiStringToUnicodeString(&UnicodeMessage, &AnsiMessage, TRUE);
if (!NT_SUCCESS(Status))
{
break;
}
MessageFormat = UnicodeMessage.Buffer;
}
else
{
MessageFormat = (PWSTR)MessageEntry->Text;
}
}
auto WrittenSize = 256ul;
bool IgnoreInserts = BooleanFlagOn(Flags, FORMAT_MESSAGE_IGNORE_INSERTS);
bool ArgumentsAreAnAnsi = BooleanFlagOn(Flags, FORMAT_MESSAGE_ARGUMENT_ANSI);
bool ArgumentsAreAnArray = BooleanFlagOn(Flags, FORMAT_MESSAGE_ARGUMENT_ARRAY);
do
{
if (AllocatedBuffer)
{
free(AllocatedBuffer);
}
AllocatedBuffer = malloc(WrittenSize);
if (AllocatedBuffer == nullptr)
{
Status = STATUS_INSUFFICIENT_RESOURCES;
break;
}
Status = RtlFormatMessage(
MessageFormat,
MaximumWidth,
IgnoreInserts,
ArgumentsAreAnAnsi,
ArgumentsAreAnArray,
Arguments,
(PWSTR)AllocatedBuffer,
WrittenSize,
&WrittenSize);
if (NT_SUCCESS(Status))
{
break;
}
if (Status != STATUS_BUFFER_OVERFLOW)
{
break;
}
WrittenSize += 256;
} while (true);
if (!NT_SUCCESS(Status))
{
break;
}
if (BooleanFlagOn(Flags, FORMAT_MESSAGE_ALLOCATE_BUFFER))
{
*(PVOID*)Buffer = AllocatedBuffer;
AllocatedBuffer = nullptr;
}
else if ((WrittenSize / sizeof(WCHAR)) > *Size)
{
Status = STATUS_BUFFER_TOO_SMALL;
break;
}
else
{
RtlMoveMemory(Buffer, AllocatedBuffer, WrittenSize);
}
*Size = (WrittenSize - sizeof(WCHAR)) / sizeof(WCHAR);
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
Status = GetExceptionCode();
break;
}
} while (false);
free(AllocatedBuffer);
RtlFreeUnicodeString(&UnicodeMessage);
return Status;
}
| 6,505
| 1,876
|
//
// Created by xiang on 2019/9/24.
//
// Description:
// 有n(n<=100)个整数,已经按照从小到大顺序排列好,现在另外给一个整数x,请将该数插入到序列中,并使新的序列仍然有序。
//
// Input:
// 输入数据包含多个测试实例,每组数据由两行组成,第一行是n和m,第二行是已经有序的n个数的数列。n和m同时为0标示输入数据的结束,本行不做处理。
//
// Output:
// 对于每个测试实例,输出插入新的元素后的数列。
//
// Sample:
//
// 3 3
// 1 2 4 -> 1 2 3 4
// 0 0
//
//
#include <cstdio>
int main() {
int n, m;
while (scanf("%d %d", &n, &m) != EOF) {
if (n == 0 && m == 0) {
continue;
}
int a[n + 1];
for (int i = 0; i < n; i++) {
scanf("%d", a + i);
}
int j;
for (j = n - 1; j >= 0; j--) {
if (a[j] <= m) {
break;
}
}
j++;
for (int k = n; k > j; k--) {
a[k] = a[k - 1];
}
a[j] = m;
for (int i = 0; i < n + 1; i++) {
printf("%d", a[i]);
if (i != n) {
printf(" ");
}
}
printf("\n");
}
return 0;
}
| 1,032
| 537
|
#pragma once
#include <mbgl/storage/file_source.hpp>
#include <mbgl/storage/online_file_source.hpp>
#include <mbgl/storage/resource.hpp>
#include <mbgl/storage/resource_options.hpp>
#include <mbgl/util/timer.hpp>
#include <map>
#include <unordered_map>
namespace mbgl {
class StubFileSource : public FileSource {
public:
enum class ResponseType {
Asynchronous = 0,
Synchronous
};
StubFileSource(const ResourceOptions&, ResponseType = ResponseType::Asynchronous);
StubFileSource(ResponseType = ResponseType::Asynchronous);
~StubFileSource() override;
std::unique_ptr<AsyncRequest> request(const Resource&, Callback) override;
bool canRequest(const Resource&) const override { return true; }
void remove(AsyncRequest*);
void setProperty(const std::string&, const mapbox::base::Value&) override;
mapbox::base::Value getProperty(const std::string&) const override;
using ResponseFunction = std::function<optional<Response> (const Resource&)>;
// You can set the response callback on a global level by assigning this callback:
ResponseFunction response = [this] (const Resource& resource) {
return defaultResponse(resource);
};
// Or set per-kind responses by setting these callbacks:
ResponseFunction styleResponse;
ResponseFunction sourceResponse;
ResponseFunction tileResponse;
ResponseFunction glyphsResponse;
ResponseFunction spriteJSONResponse;
ResponseFunction spriteImageResponse;
ResponseFunction imageResponse;
void setResourceOptions(ResourceOptions options) override;
ResourceOptions getResourceOptions() override;
private:
friend class StubOnlineFileSource;
// The default behavior is to throw if no per-kind callback has been set.
optional<Response> defaultResponse(const Resource&);
std::unordered_map<AsyncRequest*, std::tuple<Resource, ResponseFunction, Callback>> pending;
ResponseType type;
util::Timer timer;
std::map<std::string, mapbox::base::Value> properties;
ResourceOptions resourceOptions;
};
} // namespace mbgl
| 2,102
| 564
|
// Copyright 2008 Christophe Henry
// henry UNDERSCORE christophe AT hotmail DOT com
// This is an extended version of the state machine available in the boost::mpl library
// Distributed under the same license as the original.
// Copyright for the original version:
// Copyright 2005 David Abrahams and Aleksey Gurtovoy. 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)
#ifndef BOOST_MSM_FRONT_EUML_GUARD_GRAMMAR_H
#define BOOST_MSM_FRONT_EUML_GUARD_GRAMMAR_H
#include <boost/msm/front/euml/common.hpp>
#include <boost/msm/front/euml/operator.hpp>
#include <boost/msm/front/euml/state_grammar.hpp>
namespace boost { namespace msm { namespace front { namespace euml
{
struct BuildGuards;
struct BuildActions;
struct BuildGuardsCases
{
// The primary template matches nothing:
template<typename Tag>
struct case_
: proto::not_<proto::_>
{};
};
template<>
struct BuildGuardsCases::case_<proto::tag::logical_or>
: proto::when<
proto::logical_or<BuildGuards,BuildGuards >,
Or_<BuildGuards(proto::_left),BuildGuards(proto::_right)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::logical_and>
: proto::when<
proto::logical_and<BuildGuards,BuildGuards >,
And_<BuildGuards(proto::_left),BuildGuards(proto::_right)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::logical_not>
: proto::when<
proto::logical_not<BuildGuards >,
Not_<BuildGuards(proto::_child)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::less>
: proto::when<
proto::less<BuildGuards, BuildGuards >,
Less_<BuildGuards(proto::_left),BuildGuards(proto::_right)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::less_equal>
: proto::when<
proto::less_equal<BuildGuards, BuildGuards >,
LessEqual_<BuildGuards(proto::_left),BuildGuards(proto::_right)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::greater>
: proto::when<
proto::greater<BuildGuards, BuildGuards >,
Greater_<BuildGuards(proto::_left),BuildGuards(proto::_right)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::greater_equal>
: proto::when<
proto::greater_equal<BuildGuards, BuildGuards >,
GreaterEqual_<BuildGuards(proto::_left),BuildGuards(proto::_right)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::equal_to>
: proto::when<
proto::equal_to<BuildGuards, BuildGuards >,
EqualTo_<BuildGuards(proto::_left),BuildGuards(proto::_right)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::not_equal_to>
: proto::when<
proto::not_equal_to<BuildGuards, BuildGuards >,
NotEqualTo_<BuildGuards(proto::_left),BuildGuards(proto::_right)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::pre_inc>
: proto::when<
proto::pre_inc<BuildGuards >,
Pre_inc_<BuildGuards(proto::_child)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::dereference>
: proto::when<
proto::dereference<BuildGuards >,
Deref_<BuildGuards(proto::_child)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::pre_dec>
: proto::when<
proto::pre_dec<BuildGuards >,
Pre_dec_<BuildGuards(proto::_child)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::post_inc>
: proto::when<
proto::post_inc<BuildGuards >,
Post_inc_<BuildGuards(proto::_child)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::post_dec>
: proto::when<
proto::post_dec<BuildGuards >,
Post_dec_<BuildGuards(proto::_child)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::plus>
: proto::when<
proto::plus<BuildGuards,BuildGuards >,
Plus_<BuildGuards(proto::_left),BuildGuards(proto::_right)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::minus>
: proto::when<
proto::minus<BuildGuards,BuildGuards >,
Minus_<BuildGuards(proto::_left),BuildGuards(proto::_right)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::multiplies>
: proto::when<
proto::multiplies<BuildGuards,BuildGuards >,
Multiplies_<BuildGuards(proto::_left),BuildGuards(proto::_right)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::divides>
: proto::when<
proto::divides<BuildGuards,BuildGuards >,
Divides_<BuildGuards(proto::_left),BuildGuards(proto::_right)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::modulus>
: proto::when<
proto::modulus<BuildGuards,BuildGuards >,
Modulus_<BuildGuards(proto::_left),BuildGuards(proto::_right)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::bitwise_and>
: proto::when<
proto::bitwise_and<BuildGuards,BuildGuards >,
Bitwise_And_<BuildGuards(proto::_left),BuildGuards(proto::_right)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::bitwise_or>
: proto::when<
proto::bitwise_or<BuildGuards,BuildGuards >,
Bitwise_Or_<BuildGuards(proto::_left),BuildGuards(proto::_right)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::subscript>
: proto::when<
proto::subscript<BuildGuards,BuildGuards >,
Subscript_<BuildGuards(proto::_left),BuildGuards(proto::_right)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::plus_assign>
: proto::when<
proto::plus_assign<BuildGuards,BuildGuards >,
Plus_Assign_<BuildGuards(proto::_left),BuildGuards(proto::_right)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::minus_assign>
: proto::when<
proto::minus_assign<BuildGuards,BuildGuards >,
Minus_Assign_<BuildGuards(proto::_left),BuildGuards(proto::_right)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::multiplies_assign>
: proto::when<
proto::multiplies_assign<BuildGuards,BuildGuards >,
Multiplies_Assign_<BuildGuards(proto::_left),BuildGuards(proto::_right)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::divides_assign>
: proto::when<
proto::divides_assign<BuildGuards,BuildGuards >,
Divides_Assign_<BuildGuards(proto::_left),BuildGuards(proto::_right)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::modulus_assign>
: proto::when<
proto::modulus_assign<BuildGuards,BuildGuards >,
Modulus_Assign_<BuildGuards(proto::_left),BuildGuards(proto::_right)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::shift_left_assign>
: proto::when<
proto::shift_left_assign<BuildGuards,BuildGuards >,
ShiftLeft_Assign_<BuildGuards(proto::_left),BuildGuards(proto::_right)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::shift_right_assign>
: proto::when<
proto::shift_right_assign<BuildGuards,BuildGuards >,
ShiftRight_Assign_<BuildGuards(proto::_left),BuildGuards(proto::_right)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::shift_left>
: proto::when<
proto::shift_left<BuildGuards,BuildGuards >,
ShiftLeft_<BuildGuards(proto::_left),BuildGuards(proto::_right)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::shift_right>
: proto::when<
proto::shift_right<BuildGuards,BuildGuards >,
ShiftRight_<BuildGuards(proto::_left),BuildGuards(proto::_right)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::assign>
: proto::when<
proto::assign<BuildGuards,BuildGuards >,
Assign_<BuildGuards(proto::_left),BuildGuards(proto::_right)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::bitwise_xor>
: proto::when<
proto::bitwise_xor<BuildGuards,BuildGuards >,
Bitwise_Xor_<BuildGuards(proto::_left),BuildGuards(proto::_right)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::negate>
: proto::when<
proto::negate<BuildGuards >,
Unary_Minus_<BuildGuards(proto::_child)>()
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::function>
: proto::or_<
proto::when<
proto::function<proto::terminal<if_tag>,BuildGuards,BuildGuards,BuildGuards >,
If_Else_<BuildGuards(proto::_child_c<1>),
BuildGuards(proto::_child_c<2>),
BuildGuards(proto::_child_c<3>) >()
>,
proto::when<
proto::function<proto::terminal<proto::_> >,
get_fct<proto::_child_c<0> >()
>,
proto::when<
proto::function<proto::terminal<proto::_>,BuildActions >,
get_fct<proto::_child_c<0>,BuildActions(proto::_child_c<1>) >()
>,
proto::when<
proto::function<proto::terminal<proto::_>,BuildActions,BuildActions >,
get_fct<proto::_child_c<0>,BuildActions(proto::_child_c<1>),BuildActions(proto::_child_c<2>) >()
>,
proto::when<
proto::function<proto::terminal<proto::_>,BuildActions,BuildActions,BuildActions >,
get_fct<proto::_child_c<0>,BuildActions(proto::_child_c<1>)
,BuildActions(proto::_child_c<2>),BuildActions(proto::_child_c<3>) >()
>,
proto::when<
proto::function<proto::terminal<proto::_>,BuildActions,BuildActions,BuildActions,BuildActions >,
get_fct<proto::_child_c<0>
,BuildActions(proto::_child_c<1>),BuildActions(proto::_child_c<2>)
,BuildActions(proto::_child_c<3>),BuildActions(proto::_child_c<4>) >()
>,
proto::when<
proto::function<proto::terminal<proto::_>,BuildActions,BuildActions,BuildActions,BuildActions,BuildActions >,
get_fct<proto::_child_c<0>
,BuildActions(proto::_child_c<1>),BuildActions(proto::_child_c<2>)
,BuildActions(proto::_child_c<3>),BuildActions(proto::_child_c<4>),BuildActions(proto::_child_c<5>) >()
>
#ifdef BOOST_MSVC
,proto::when<
proto::function<proto::terminal<proto::_>,BuildActions,BuildActions,BuildActions,BuildActions,BuildActions,BuildActions >,
get_fct<proto::_child_c<0>
,BuildActions(proto::_child_c<1>),BuildActions(proto::_child_c<2>)
,BuildActions(proto::_child_c<3>),BuildActions(proto::_child_c<4>)
,BuildActions(proto::_child_c<5>),BuildActions(proto::_child_c<6>) >()
>
#endif
>
{};
template<>
struct BuildGuardsCases::case_<proto::tag::terminal>
: proto::or_<
proto::when <
proto::terminal<action_tag>,
get_action_name<proto::_ >()
>,
proto::when<
proto::terminal<state_tag>,
get_state_name<proto::_>()
>,
proto::when<
proto::terminal<flag_tag>,
proto::_
>,
proto::when<
proto::terminal<event_tag>,
proto::_
>,
proto::when<
proto::terminal<fsm_artefact_tag>,
get_fct<proto::_ >()
>,
proto::when<
proto::terminal<proto::_>,
proto::_value
>
>
{};
struct BuildGuards
: proto::switch_<BuildGuardsCases>
{};
}}}}
#endif //BOOST_MSM_FRONT_EUML_GUARD_GRAMMAR_H
| 13,201
| 4,091
|
#include "cbase.h"
#include "tf_gamerules.h"
#include "tf_shareddefs.h"
#include "ammodef.h"
#include "basetfcombatweapon_shared.h"
#ifdef CLIENT_DLL
#include "c_shield.h"
#include "c_te_effect_dispatch.h"
#define CShield C_Shield
#else
#include "tf_shield.h"
#include "te_effect_dispatch.h"
#include "player.h"
#include "tf_player.h"
#include "game.h"
#include "gamerules.h"
#include "teamplay_gamerules.h"
#include "menu_base.h"
#include "ammodef.h"
#include "techtree.h"
#include "tf_team.h"
#include "tf_shield.h"
#include "mathlib/mathlib.h"
#include "entitylist.h"
#include "basecombatweapon.h"
#include "voice_gamemgr.h"
#include "tf_class_infiltrator.h"
#include "team_messages.h"
#include "ndebugoverlay.h"
#include "bot_base.h"
#include "vstdlib/random.h"
#include "info_act.h"
#include "igamesystem.h"
#include "filesystem.h"
#include "info_vehicle_bay.h"
#include "IserverVehicle.h"
#include "weapon_builder.h"
#include "weapon_objectselection.h"
#endif
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
REGISTER_GAMERULES_CLASS(CTeamFortress);
//IMPLEMENT_NETWORKCLASS_ALIASED( TeamFortress, DT_TeamFortress )
BEGIN_NETWORK_TABLE_NOBASE( CTeamFortress, DT_TeamFortress )
END_NETWORK_TABLE()
#ifndef CLIENT_DLL
#define MAX_OBJECT_COMMAND_DISTANCE 120.0f
class CVoiceGameMgrHelper : public IVoiceGameMgrHelper
{
public:
virtual bool CanPlayerHearPlayer( CBasePlayer *pListener, CBasePlayer *pTalker, bool &bProximity )
{
// Gagged players can't talk at all
if ( ((CBaseTFPlayer*)pTalker)->CanSpeak() == false )
return false;
// Dead players can only be heard by other dead team mates
if ( pTalker->IsAlive() == false )
{
if ( pListener->IsAlive() == false )
return ( pListener->InSameTeam( pTalker ) );
return false;
}
return ( pListener->InSameTeam( pTalker ) );
}
};
CVoiceGameMgrHelper g_VoiceGameMgrHelper;
IVoiceGameMgrHelper *g_pVoiceGameMgrHelper = &g_VoiceGameMgrHelper;
// Load the objects.txt file.
class CObjectsFileLoad : public CAutoGameSystem
{
public:
virtual bool Init()
{
LoadObjectInfos( filesystem );
return true;
}
} g_ObjectsFileLoad;
extern bool g_fGameOver;
float g_flNextReinforcementTime = 0.0f;
extern ConVar tf_knockdowntime;
// Time between reinforcements
#define REINFORCEMENT_TIME 15.0
ConVar sk_plr_dmg_grenade ( "sk_plr_dmg_grenade","0");
char *sTeamNames[] =
{
"Unassigned",
"Spectator",
"Human",
"Alien",
};
// Handle the "PossessBot" command.
CON_COMMAND_F(PossessBot, "Toggle. Possess a bot.\n\tArguments: <bot client number>", FCVAR_CHEAT)
{
CBaseTFPlayer *pPlayer = CBaseTFPlayer::Instance( UTIL_GetCommandClientIndex() );
if ( !pPlayer )
return;
// Put the local player in control of this bot.
if ( args.ArgC() != 2 )
{
Warning( "PossessBot <client index>\n" );
return;
}
int iBotClient = atoi( args[1] );
int iBotEnt = iBotClient + 1;
if ( iBotClient < 0 ||
iBotClient >= gpGlobals->maxClients ||
pPlayer->entindex() == iBotEnt )
Warning( "PossessBot <client index>\n" );
else
{
edict_t *pPlayerData = pPlayer->edict();
edict_t *pBotData = engine->PEntityOfEntIndex( iBotEnt );
if ( pBotData && pBotData->GetUnknown() )
{
// SWAP EDICTS
// Backup things we don't want to swap.
edict_t oldPlayerData = *pPlayerData;
edict_t oldBotData = *pBotData;
// Swap edicts.
edict_t tmp = *pPlayerData;
*pPlayerData = *pBotData;
*pBotData = tmp;
// Restore things we didn't want to swap.
//pPlayerData->m_EntitiesTouched = oldPlayerData.m_EntitiesTouched;
//pBotData->m_EntitiesTouched = oldBotData.m_EntitiesTouched;
CBaseEntity *pPlayerBaseEnt = CBaseEntity::Instance( pPlayerData );
CBaseEntity *pBotBaseEnt = CBaseEntity::Instance( pBotData );
// Make the other a bot and make the player not a bot.
pPlayerBaseEnt->RemoveFlag( FL_FAKECLIENT );
pBotBaseEnt->AddFlag( FL_FAKECLIENT );
// Point the CBaseEntities at the right players.
pPlayerBaseEnt->NetworkProp()->SetEdict( pPlayerData );
pBotBaseEnt->NetworkProp()->SetEdict( pBotData );
// Freeze the bot.
pBotBaseEnt->AddEFlags( EFL_BOT_FROZEN );
// Remove orders to both of them..
CTFTeam *pTeam = pPlayer->GetTFTeam();
if ( pTeam )
{
pTeam->RemoveOrdersToPlayer( (CBaseTFPlayer*)pPlayerBaseEnt );
pTeam->RemoveOrdersToPlayer( (CBaseTFPlayer*)pBotBaseEnt );
}
}
}
}
// Handler for the "bot" command.
CON_COMMAND_F(bot, "Add a bot.", FCVAR_CHEAT)
{
CBaseTFPlayer *pPlayer = CBaseTFPlayer::Instance( UTIL_GetCommandClientIndex() );
// The bot command uses switches like command-line switches.
// -count <count> tells how many bots to spawn.
// -team <index> selects the bot's team. Default is -1 which chooses randomly.
// Note: if you do -team !, then it
// -class <index> selects the bot's class. Default is -1 which chooses randomly.
// -frozen prevents the bots from running around when they spawn in.
// Look at -count.
int count = args.FindArgInt( "-count", 1 );
count = clamp( count, 1, 16 );
int iTeam = -1;
const char *pVal = args.FindArg( "-team" );
if ( pVal )
{
if ( pVal[0] == '!' )
iTeam = pPlayer->GetTFTeam()->GetEnemyTeam()->GetTeamNumber();
else
{
iTeam = atoi( pVal );
iTeam = clamp( iTeam, 0, GetNumberOfTeams() );
}
}
int iClass = args.FindArgInt( "-class", -1 );
iClass = clamp( iClass, -1, TFCLASS_CLASS_COUNT );
if ( iClass == TFCLASS_UNDECIDED )
iClass = TFCLASS_RECON;
// Look at -frozen.
bool bFrozen = !!args.FindArg( "-frozen" );
// Ok, spawn all the bots.
while ( --count >= 0 )
BotPutInServer( bFrozen, iTeam, iClass );
}
bool IsSpaceEmpty( CBaseEntity *pMainEnt, const Vector &vMin, const Vector &vMax )
{
Vector vHalfDims = ( vMax - vMin ) * 0.5f;
Vector vCenter = vMin + vHalfDims;
trace_t trace;
UTIL_TraceHull( vCenter, vCenter, -vHalfDims, vHalfDims, MASK_SOLID, pMainEnt, COLLISION_GROUP_NONE, &trace );
bool bClear = ( trace.fraction == 1 && trace.allsolid != 1 && (trace.startsolid != 1) );
return bClear;
}
Vector MaybeDropToGround(
CBaseEntity *pMainEnt,
bool bDropToGround,
const Vector &vPos,
const Vector &vMins,
const Vector &vMaxs )
{
if ( bDropToGround )
{
trace_t trace;
UTIL_TraceHull( vPos, vPos + Vector( 0, 0, -500 ), vMins, vMaxs, MASK_SOLID, pMainEnt, COLLISION_GROUP_NONE, &trace );
return trace.endpos;
}
else
{
return vPos;
}
}
//-----------------------------------------------------------------------------
// Purpose: This function can be used to find a valid placement location for an entity.
// Given an origin to start looking from and a minimum radius to place the entity at,
// it will sweep out a circle around vOrigin and try to find a valid spot (on the ground)
// where mins and maxs will fit.
// Input : *pMainEnt - Entity to place
// &vOrigin - Point to search around
// fRadius - Radius to search within
// nTries - Number of tries to attempt
// &mins - mins of the Entity
// &maxs - maxs of the Entity
// &outPos - Return point
// Output : Returns true and fills in outPos if it found a spot.
//-----------------------------------------------------------------------------
bool EntityPlacementTest( CBaseEntity *pMainEnt, const Vector &vOrigin, Vector &outPos, bool bDropToGround )
{
// This function moves the box out in each dimension in each step trying to find empty space like this:
//
// X
// X X
// Step 1: X Step 2: XXX Step 3: XXXXX
// X X
// X
//
Vector mins, maxs;
pMainEnt->CollisionProp()->WorldSpaceAABB( &mins, &maxs );
mins -= pMainEnt->GetAbsOrigin();
maxs -= pMainEnt->GetAbsOrigin();
// Put some padding on their bbox.
float flPadSize = 5;
Vector vTestMins = mins - Vector( flPadSize, flPadSize, flPadSize );
Vector vTestMaxs = maxs + Vector( flPadSize, flPadSize, flPadSize );
// First test the starting origin.
if ( IsSpaceEmpty( pMainEnt, vOrigin + vTestMins, vOrigin + vTestMaxs ) )
{
outPos = MaybeDropToGround( pMainEnt, bDropToGround, vOrigin, vTestMins, vTestMaxs );
return true;
}
Vector vDims = vTestMaxs - vTestMins;
// Keep branching out until we get too far.
int iCurIteration = 0;
int nMaxIterations = 15;
int offset = 0;
do
{
for ( int iDim=0; iDim < 3; iDim++ )
{
float flCurOffset = offset * vDims[iDim];
for ( int iSign=0; iSign < 2; iSign++ )
{
Vector vBase = vOrigin;
vBase[iDim] += (iSign*2-1) * flCurOffset;
if ( IsSpaceEmpty( pMainEnt, vBase + vTestMins, vBase + vTestMaxs ) )
{
// Ensure that there is a clear line of sight from the spawnpoint entity to the actual spawn point.
// (Useful for keeping things from spawning behind walls near a spawn point)
trace_t tr;
UTIL_TraceLine( vOrigin, vBase, MASK_SOLID, pMainEnt, COLLISION_GROUP_NONE, &tr );
if ( tr.fraction != 1.0 )
{
continue;
}
outPos = MaybeDropToGround( pMainEnt, bDropToGround, vBase, vTestMins, vTestMaxs );
return true;
}
}
}
++offset;
} while ( iCurIteration++ < nMaxIterations );
// Warning( "EntityPlacementTest for ent %d:%s failed!\n", pMainEnt->entindex(), pMainEnt->GetClassname() );
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CBaseEntity *CTeamFortress::GetPlayerSpawnSpot( CBasePlayer *pPlayer )
{
CBaseEntity *pSpawnSpot = pPlayer->EntSelectSpawnPoint();
#if 0
// Make sure the spawn spot isn't blocked...
Vector vecTestOrg = pSpawnSpot->GetAbsOrigin();
vecTestOrg.z += pPlayer->WorldAlignSize().z * 0.5;
Vector origin;
EntityPlacementTest( pPlayer, vecTestOrg, origin, true );
// Move the player to the place it said.
pPlayer->Teleport( &origin, NULL, NULL );
#else
pPlayer->SetLocalOrigin(MaybeDropToGround(pPlayer,true,pSpawnSpot->GetAbsOrigin(),VEC_HULL_MIN,VEC_HULL_MAX));
#endif
pPlayer->SetAbsVelocity( vec3_origin );
pPlayer->SetLocalAngles( pSpawnSpot->GetLocalAngles() );
pPlayer->m_Local.m_vecPunchAngle = vec3_angle;
pPlayer->SnapEyeAngles( pSpawnSpot->GetLocalAngles() );
return pSpawnSpot;
}
CTeamFortress::CTeamFortress()
{
m_bAllowWeaponSwitch = true;
// Create the team managers
for ( int i = 0; i < MAX_TF_TEAMS; i++ )
{
CTFTeam *pTeam = (CTFTeam*)CreateEntityByName( "tf_team_manager" );
pTeam->Init( sTeamNames[i], i );
g_Teams.AddToTail( pTeam );
}
// Create the hint manager
CBaseEntity::Create( "tf_hintmanager", vec3_origin, vec3_angle );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CTeamFortress::~CTeamFortress()
{
// Note, don't delete each team since they are in the gEntList and will
// automatically be deleted from there, instead.
g_Teams.Purge();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTeamFortress::UpdateClientData( CBasePlayer *player )
{
}
//-----------------------------------------------------------------------------
// Purpose: Called after every level and load change
//-----------------------------------------------------------------------------
void CTeamFortress::LevelInitPostEntity()
{
g_flNextReinforcementTime = gpGlobals->curtime + REINFORCEMENT_TIME;
BaseClass::LevelInitPostEntity();
}
//-----------------------------------------------------------------------------
// Purpose: The gamerules think function
//-----------------------------------------------------------------------------
void CTeamFortress::Think( void )
{
BaseClass::Think();
// Check the reinforcement time
if ( g_flNextReinforcementTime <= gpGlobals->curtime )
{
//Msg( "Reinforcement Tick\n" );
// Reinforce any dead players
for ( int i = 1; i <= gpGlobals->maxClients; i++ )
{
CBaseTFPlayer *pPlayer = ToBaseTFPlayer( UTIL_PlayerByIndex(i) );
if ( pPlayer )
{
// Ready to respawn?
if ( pPlayer->IsReadyToReinforce() )
{
pPlayer->Reinforce();
//pPlayer->GetTFTeam()->PostMessage( TEAMMSG_REINFORCEMENTS_ARRIVED );
}
}
}
g_flNextReinforcementTime += REINFORCEMENT_TIME;
}
// Tell each Team to think
for ( int i = 0; i < GetNumberOfTeams(); i++ )
GetGlobalTeam( i )->Think();
}
//-----------------------------------------------------------------------------
// Purpose: Player has just left the game
//-----------------------------------------------------------------------------
void CTeamFortress::ClientDisconnected( edict_t *pClient )
{
CBaseTFPlayer *pPlayer = (CBaseTFPlayer *)CBaseEntity::Instance( pClient );
if ( pPlayer )
{
// Tell all orders that this player's left
COrderEvent_PlayerDisconnected order( pPlayer );
GlobalOrderEvent( &order );
// Delete this player's playerclass
pPlayer->ClearPlayerClass();
}
BaseClass::ClientDisconnected( pClient );
}
//-----------------------------------------------------------------------------
// Purpose: TF2 Specific Client Commands
// Input :
// Output :
//-----------------------------------------------------------------------------
bool CTeamFortress::ClientCommand(CBaseEntity *pEdict, const CCommand &args)
{
CBaseTFPlayer *pPlayer = (CBaseTFPlayer *)pEdict;
const char *pcmd = args[0];
if ( FStrEq( pcmd, "objcmd" ) )
{
if ( args.ArgC() < 3 )
return true;
int entindex = atoi( args[1] );
edict_t* pEdict = INDEXENT(entindex);
if (pEdict)
{
CBaseEntity* pBaseEntity = GetContainingEntity(pEdict);
CBaseObject* pObject = dynamic_cast<CBaseObject*>(pBaseEntity);
if (pObject && pObject->InSameTeam(pPlayer))
{
// We have to be relatively close to the object too...
// FIXME: When I put in a better dismantle solution (namely send the dismantle
// command along with a cancledismantle command), re-enable this.
// Also, need to solve the problem of control panels on large objects
// For the battering ram, for instance, this distance is too far.
// float flDistSq = pObject->GetAbsOrigin().DistToSqr( pPlayer->GetAbsOrigin() );
// if (flDistSq <= (MAX_OBJECT_COMMAND_DISTANCE * MAX_OBJECT_COMMAND_DISTANCE))
{
CCommand objectArgs( args.ArgC() - 2, &args.ArgV()[2]);
pObject->ClientCommand(pPlayer, objectArgs);
}
}
}
return true;
}
if ( FStrEq( pcmd, "buildvehicle" ) )
{
if ( args.ArgC() < 3 )
return true;
int entindex = atoi( args[1] );
int ivehicle = atoi( args[2] );
edict_t *pEdict = INDEXENT(entindex);
if (pEdict)
{
CBaseEntity *pBaseEntity = GetContainingEntity(pEdict);
CVGuiScreenVehicleBay *pBayScreen = dynamic_cast<CVGuiScreenVehicleBay*>(pBaseEntity);
if ( pBayScreen && pBayScreen->InSameTeam(pPlayer) )
{
// Need the same logic as objcmd above to ensure the player's near the vehicle bay vgui screen
pBayScreen->BuildVehicle( pPlayer, ivehicle );
}
}
return true;
}
// TF Commands
if ( FStrEq( pcmd, "menuselect" ) )
{
if ( pPlayer->m_pCurrentMenu == NULL )
return true;
if ( args.ArgC() < 2 )
return true;
int slot = atoi( args[1] );
// select the item from the current menu
if ( pPlayer->m_pCurrentMenu->Input( pPlayer, slot ) == false )
{
// invalid selection, force menu refresh
pPlayer->m_MenuUpdateTime = gpGlobals->curtime;
pPlayer->m_MenuRefreshTime = gpGlobals->curtime;
}
return true;
}
else if ( FStrEq( pcmd, "changeclass" ) )
// Rewrote this... ~hogsy
{
if(args.ArgC() < 2)
return true;
int iClass = atoi(args.Arg(1)),
iOldClass = pPlayer->PlayerClass();
if(iClass == iOldClass)
return true;
// Random class selection.
if(iClass <= -1)
iClass = random->RandomInt(TFCLASS_RECON,TFCLASS_CLASS_COUNT-1);
pPlayer->ChangeClass((TFClass)iClass);
int iTeam = pPlayer->GetTeamNumber();
if( !pPlayer->IsDead() &&
((iTeam == TEAM_HUMANS || iTeam == TEAM_ALIENS) &&
((iOldClass > TFCLASS_UNDECIDED) && (iOldClass < TFCLASS_CLASS_COUNT))))
{
pPlayer->RemoveAllItems(false);
pPlayer->HideViewModels();
pPlayer->ClearPlayerClass();
pPlayer->CommitSuicide(false,true);
pPlayer->IncrementFragCount(1);
}
else
pPlayer->ForceRespawn();
return true;
}
else if ( FStrEq( pcmd, "changeteam" ) )
// Rewrote this... ~hogsy
{
if(args.ArgC() < 2)
return true;
int iTeam = atoi(args.Arg(1)),
iOldTeam = pPlayer->GetTeamNumber();
if(iTeam == iOldTeam)
return true;
// Automatic team selection.
if(iTeam <= -1)
pPlayer->PlacePlayerInTeam();
// Otherwise throw us into our selected team.
else
pPlayer->ChangeTeam(iTeam);
// Don't commit suicide unless we're already in a team.
if(!pPlayer->IsDead() && (iOldTeam == TEAM_HUMANS || iOldTeam == TEAM_ALIENS))
{
pPlayer->RemoveAllItems(false);
pPlayer->HideViewModels();
pPlayer->CommitSuicide(false,true);
pPlayer->IncrementFragCount(1);
}
else
pPlayer->ForceRespawn();
return true;
}
else if ( FStrEq( pcmd, "tactical" ) )
{
bool bTactical = args[1][0] == '!' ? !pPlayer->GetLocalData()->m_nInTacticalView : (atoi( args[1] ) ? true : false);
pPlayer->ShowTacticalView( bTactical );
return true;
}
else if ( FStrEq( pcmd, "tech" ) )
{
CTFTeam *pTFTeam = pPlayer->GetTFTeam();
if ( !pTFTeam )
return true;
if ( args.ArgC() == 2 )
{
const char *name = args[1];
CBaseTechnology *tech = pTFTeam->m_pTechnologyTree->GetTechnology( name );
if ( tech )
pTFTeam->EnableTechnology( tech );
}
else
Msg( "usage: tech <name>\n" );
return true;
}
else if ( FStrEq( pcmd, "techall" ) )
{
if ( pPlayer->GetTFTeam() )
pPlayer->GetTFTeam()->EnableAllTechnologies();
return true;
}
else if ( FStrEq( pcmd, "tank" ) )
CBaseEntity::Create( "tank", pPlayer->WorldSpaceCenter(), pPlayer->GetLocalAngles() );
else if ( FStrEq( pcmd, "addres" ) || FStrEq( pcmd, "ar" ) )
{
if ( args.ArgC() == 3 )
{
int team = atoi( args[1] );
float flResourceAmount = atof( args[2] );
if ( team > 0 && team <= GetNumberOfTeams() )
GetGlobalTFTeam( team )->AddTeamResources( flResourceAmount );
}
else
Msg( "usage: ar <team 1 : 2> <amount>\n" );
return true;
}
else if ( FStrEq( pcmd, "preftech" ) )
{
CTFTeam *pTFTeam = pPlayer->GetTFTeam();
if ( !pTFTeam )
return true;
if ( args.ArgC() == 2 )
{
int iPrefTechIndex = atoi( args[1] );
pPlayer->SetPreferredTechnology( pTFTeam->m_pTechnologyTree, iPrefTechIndex );
}
return true;
}
else if( FStrEq( pcmd, "decaltest" ) )
{
trace_t trace;
int entityIndex;
Vector vForward;
AngleVectors( pEdict->GetAbsAngles(), &vForward, NULL, NULL );
UTIL_TraceLine( pEdict->GetAbsOrigin(), pEdict->GetAbsOrigin() + vForward * 10000, MASK_SOLID_BRUSHONLY, pEdict, COLLISION_GROUP_NONE, &trace );
entityIndex = trace.GetEntityIndex();
int id = UTIL_PrecacheDecal( "decals/tscorch", true );
CBroadcastRecipientFilter filter;
te->BSPDecal( filter, 0.0,
&trace.endpos, entityIndex, id );
return true;
}
else if( FStrEq( pcmd, "killorder" ) )
{
if( pPlayer->GetTFTeam() )
pPlayer->GetTFTeam()->RemoveOrdersToPlayer( pPlayer );
return true;
}
else if( BaseClass::ClientCommand( pEdict, args ) )
return true;
else
return pPlayer->ClientCommand(args);
return false;
}
//-----------------------------------------------------------------------------
// Purpose: Player has just spawned. Equip them.
//-----------------------------------------------------------------------------
void CTeamFortress::PlayerSpawn( CBasePlayer *pPlayer )
{
pPlayer->EquipSuit();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CTeamFortress::PlayFootstepSounds( CBasePlayer *pl )
{
if ( footsteps.GetInt() == 0 )
return false;
CBaseTFPlayer *tfPlayer = static_cast< CBaseTFPlayer * >( pl );
if ( tfPlayer )
if ( tfPlayer->IsKnockedDown() )
return false;
// only make step sounds in multiplayer if the player is moving fast enough
if ( pl->IsOnLadder() || pl->GetAbsVelocity().Length2D() > 100 )
return true;
return false;
}
//-----------------------------------------------------------------------------
// Purpose: Remove falling damage for jetpacking recons
//-----------------------------------------------------------------------------
float CTeamFortress::FlPlayerFallDamage( CBasePlayer *pPlayer )
{
int iFallDamage = (int)falldamage.GetFloat();
CBaseTFPlayer *pTFPlayer = (CBaseTFPlayer *)pPlayer;
if ( pTFPlayer->IsClass( TFCLASS_RECON ) )
return 0;
switch ( iFallDamage )
{
case 1://progressive
pPlayer->m_Local.m_flFallVelocity -= PLAYER_MAX_SAFE_FALL_SPEED;
return pPlayer->m_Local.m_flFallVelocity * DAMAGE_FOR_FALL_SPEED;
break;
default:
case 0:// fixed
return 10;
break;
}
}
//-----------------------------------------------------------------------------
// Is the ray blocked by enemy shields?
//-----------------------------------------------------------------------------
bool CTeamFortress::IsBlockedByEnemyShields( const Vector& src, const Vector& end, int nFriendlyTeam )
{
// Iterate over all shields on the same team, disable them so
// we don't intersect with them...
CShield::ActivateShields( false, nFriendlyTeam );
bool bBlocked = CShield::IsBlockedByShields( src, end );
CShield::ActivateShields( true, nFriendlyTeam );
return bBlocked;
}
//-----------------------------------------------------------------------------
// Traces a line vs a shield, returns damage reduction
//-----------------------------------------------------------------------------
float CTeamFortress::WeaponTraceEntity( CBaseEntity *pEntity,
const Vector &src, const Vector &end, unsigned int mask, trace_t *pTrace )
{
int damageType = pEntity->GetDamageType();
// Iterate over all shields on the same team, disable them so
// we don't intersect with them...
CShield::ActivateShields( false, pEntity->GetTeamNumber() );
// Trace it baby...
float damage = 1.0f;
bool done;
do
{
// FIXME: Optimize so we don't test the same ray but start at the
// previous collision point
done = true;
UTIL_TraceEntity( pEntity, src, end, mask, pTrace );
// Shield check...
if (pTrace->fraction != 1.0)
{
CBaseEntity *pCollidedEntity = pTrace->m_pEnt;
// Did we hit a shield?
CShield* pShield = dynamic_cast<CShield*>(pCollidedEntity);
if (pShield)
{
Vector vecDir;
VectorSubtract( end, src, vecDir );
// Let's see if we let this damage type through...
if (pShield->ProtectionAmount( damageType ) == 1.0f)
{
// We deflected all of the damage
pShield->RegisterDeflection( vecDir, damageType, pTrace );
damage = 0.0f;
}
else
{
// We deflected part of the damage, but we need to trace again
// only this time we can't let the shield register a collision
damage *= 1.0f - pShield->ProtectionAmount( damageType );
// FIXME: DMG_BULLET should be something else
pShield->RegisterPassThru( vecDir, damageType, pTrace );
pShield->ActivateCollisions( false );
done = false;
}
}
}
}
while (!done);
// Reduce the damage dealt... but don't worry about if if the
// shield actually deflected it. In that case, we actually want
// explosive things to explode at full blast power. The shield will prevent
// the blast damage to things behind the shield
if (damage != 0.0)
pEntity->SetDamage(pEntity->GetDamage() * damage);
// Reactivate all shields
CShield::ActivateShields( true );
return damage;
}
//-----------------------------------------------------------------------------
// Purpose: Is trace blocked by a world or a shield?
//-----------------------------------------------------------------------------
bool CTeamFortress::IsTraceBlockedByWorldOrShield( const Vector& src, const Vector& end, CBaseEntity *pShooter, int damageType, trace_t* pTrace )
{
// Iterate over all shields on the same team, disable them so
// we don't intersect with them...
CShield::ActivateShields( false, pShooter->GetTeamNumber() );
//NDebugOverlay::Line( src, pTrace->endpos, 255,255,255, true, 5.0 );
//NDebugOverlay::Box( pTrace->endpos, Vector(-2,-2,-2), Vector(2,2,2), 255,255,255, true, 5.0 );
// Now make sure there isn't something other than team players in the way.
class CShieldWorldFilter : public CTraceFilterSimple
{
public:
CShieldWorldFilter( CBaseEntity *pShooter ) : CTraceFilterSimple( pShooter, TFCOLLISION_GROUP_WEAPON )
{
}
virtual bool ShouldHitEntity( IHandleEntity *pHandleEntity, int contentsMask )
{
CBaseEntity *pEnt = static_cast<CBaseEntity*>(pHandleEntity);
// Did we hit a brushmodel?
if ( pEnt->GetSolid() == SOLID_BSP )
return true;
// Ignore collisions with everything but shields
if ( pEnt->GetCollisionGroup() != TFCOLLISION_GROUP_SHIELD )
return false;
return CTraceFilterSimple::ShouldHitEntity( pHandleEntity, contentsMask );
}
};
trace_t tr;
CShieldWorldFilter shieldworldFilter( pShooter );
UTIL_TraceLine( src, end, MASK_SOLID, &shieldworldFilter, pTrace );
// Shield check...
if (pTrace->fraction != 1.0)
{
CBaseEntity *pEntity = pTrace->m_pEnt;
CShield* pShield = dynamic_cast<CShield*>(pEntity);
if (pShield)
{
Vector vecDir;
VectorSubtract( end, src, vecDir );
// We deflected all of the damage
pShield->RegisterDeflection( vecDir, damageType, pTrace );
}
}
// Reactivate all shields
CShield::ActivateShields( true );
return ( pTrace->fraction < 1.0 );
}
//-----------------------------------------------------------------------------
// Default implementation of radius damage
//-----------------------------------------------------------------------------
void CTeamFortress::RadiusDamage( const CTakeDamageInfo &info, const Vector &vecSrcIn, float flRadius, int iClassIgnore )
{
CBaseEntity *pEntity = NULL;
trace_t tr;
float flAdjustedDamage, falloff;
Vector vecSpot;
Vector vecSrc = vecSrcIn;
if ( flRadius )
falloff = info.GetDamage() / flRadius;
else
falloff = 1.0;
int bInWater = (UTIL_PointContents ( vecSrc ) & MASK_WATER) ? true : false;
// in case grenade is lying on the ground
// Is this even needed anymore? Grenades already jump up in their explode code...
vecSrc.z += 1;
// iterate on all entities in the vicinity.
for ( CEntitySphereQuery sphere( vecSrc, flRadius ); ; sphere.NextEntity() )
{
pEntity = sphere.GetCurrentEntity();
if (!pEntity)
break;
if ( pEntity->m_takedamage != DAMAGE_NO )
{
// UNDONE: this should check a damage mask, not an ignore
if ( iClassIgnore != CLASS_NONE && pEntity->Classify() == iClassIgnore )
continue;
// blast's don't tavel into or out of water
if (bInWater && pEntity->GetWaterLevel() == 0)
continue;
if (!bInWater && pEntity->GetWaterLevel() == 3)
continue;
// Copy initial values out of the info
CTakeDamageInfo subInfo = info;
if ( !subInfo.GetAttacker() )
subInfo.SetAttacker( subInfo.GetInflictor() );
// Don't bother with hitboxes on this test
vecSpot = pEntity->WorldSpaceCenter( );
WeaponTraceLine ( vecSrc, vecSpot, MASK_SHOT & (~CONTENTS_HITBOX), subInfo.GetInflictor(), subInfo.GetDamageType(), &tr );
if ( tr.fraction != 1.0 && tr.m_pEnt != pEntity )
continue;
// We're going to need to see if it actually hit a shield
// the explosion can 'see' this entity, so hurt them!
if (tr.startsolid)
{
// if we're stuck inside them, fixup the position and distance
tr.endpos = vecSrc;
tr.fraction = 0.0;
}
// decrease damage for an ent that's farther from the bomb.
flAdjustedDamage = ( vecSrc - tr.endpos ).Length() * falloff;
flAdjustedDamage = subInfo.GetDamage() - flAdjustedDamage;
if ( flAdjustedDamage > 0 )
{
// Knockdown
// For now, just use damage. Eventually we should do it on a per-weapon basis.
/*
if ( pEntity->IsPlayer() && flAdjustedDamage > 40 )
{
Vector vecForce = vecSpot - vecSrc;
// Reduce the Z component and increase the X,Y
vecForce.x *= 3.0;
vecForce.y *= 3.0;
vecForce.z *= 0.5;
VectorNormalize( vecForce );
((CBaseTFPlayer*)pEntity)->KnockDownPlayer( vecForce, flAdjustedDamage * 15.0f, tf_knockdowntime.GetFloat() );
}
*/
// Msg( "hit %s\n", pEntity->GetClassname() );
subInfo.SetDamage( flAdjustedDamage );
Vector dir = tr.endpos - vecSrc;
if ( VectorNormalize( dir ) == 0 )
{
dir = vecSpot - vecSrc;
VectorNormalize( dir );
}
// If we don't have a damage force, manufacture one
if ( subInfo.GetDamagePosition() == vec3_origin || subInfo.GetDamageForce() == vec3_origin )
CalculateExplosiveDamageForce( &subInfo, dir, vecSrc );
if (tr.fraction != 1.0)
{
ClearMultiDamage( );
pEntity->DispatchTraceAttack( subInfo, dir, &tr );
ApplyMultiDamage();
}
else
pEntity->TakeDamage( subInfo );
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Find out if this player had an assistant when he killed an enemy
//-----------------------------------------------------------------------------
CBasePlayer *CTeamFortress::GetDeathAssistant( CBaseEntity *pKiller, CBaseEntity *pInflictor )
{
if ( !pKiller || pKiller->Classify() != CLASS_PLAYER )
return NULL;
CBaseTFPlayer *pAssistant = NULL;
// Killing entity might be specifying a scorer player
IScorer *pScorerInterface = dynamic_cast<IScorer*>( pKiller );
if ( pScorerInterface )
{
pAssistant = (CBaseTFPlayer*)pScorerInterface->GetAssistant();
}
// Inflicting entity might be specifying a scoring player
if ( !pAssistant )
{
pScorerInterface = dynamic_cast<IScorer*>( pInflictor );
if ( pScorerInterface )
{
pAssistant = (CBaseTFPlayer*)pScorerInterface->GetAssistant();
}
}
// Don't allow self assistance
Assert( pAssistant != pKiller );
return pAssistant;
}
void CTeamFortress::DeathNotice( CBasePlayer *pVictim, const CTakeDamageInfo &info )
{
// Work out what killed the player, and send a message to all clients about it
const char *killer_weapon_name = "world"; // by default, the player is killed by the world
int killer_index = 0;
int assist_index = 0;
// Find the killer & the scorer
CBaseEntity *pInflictor = info.GetInflictor();
CBaseEntity *pKiller = info.GetAttacker();
CBasePlayer *pScorer = GetDeathScorer( pKiller, pInflictor );
CBasePlayer *pAssistant = GetDeathAssistant( pKiller, pInflictor );
if ( pAssistant )
assist_index = pAssistant->entindex();
// Custom kill type?
if ( info.GetDamageCustom() )
{
killer_weapon_name = GetDamageCustomString(info);
if ( pScorer )
killer_index = pScorer->entindex();
}
else
{
// Is the killer a client?
if ( pScorer )
{
killer_index = pScorer->entindex();
if ( pInflictor )
{
if ( pInflictor == pScorer )
{
// If the inflictor is the killer, then it must be their current weapon doing the damage
if ( pScorer->GetActiveWeapon() )
killer_weapon_name = pScorer->GetActiveWeapon()->GetDeathNoticeName();
}
else
killer_weapon_name = STRING( pInflictor->m_iClassname ); // it's just that easy
}
}
else
killer_weapon_name = STRING( pInflictor->m_iClassname );
// strip the NPC_* or weapon_* from the inflictor's classname
if ( strncmp( killer_weapon_name, "weapon_", 7 ) == 0 )
killer_weapon_name += 7;
else if ( strncmp( killer_weapon_name, "NPC_", 8 ) == 0 )
killer_weapon_name += 8;
else if ( strncmp( killer_weapon_name, "func_", 5 ) == 0 )
killer_weapon_name += 5;
}
#if 0
// Did he kill himself?
if ( pVictim == pScorer )
UTIL_LogPrintf( "\"%s<%i>\" killed self with %s\n", STRING( pVictim->PlayerData()->netname ), engine->GetPlayerUserId( pVictim->edict() ), killer_weapon_name );
else if ( pScorer )
{
UTIL_LogPrintf( "\"%s<%i>\" killed \"%s<%i>\" with %s\n", STRING( pScorer->pl.netname ),
engine->GetPlayerUserId( pScorer->edict() ),
STRING( pVictim->PlayerData()->netname ),
engine->GetPlayerUserId( pVictim->edict() ),
killer_weapon_name );
}
else
// killed by the world
UTIL_LogPrintf( "\"%s<%i>\" killed by world with %s\n", STRING( pVictim->PlayerData()->netname ), engine->GetPlayerUserId( pVictim->edict() ), killer_weapon_name );
#endif
IGameEvent * event = gameeventmanager->CreateEvent( "player_death" );
if(event)
{
event->SetInt("killer", pScorer ? pScorer->GetUserID() : 0 );
event->SetInt("victim", pVictim->GetUserID() );
event->SetString("weapon", killer_weapon_name );
gameeventmanager->FireEvent( event, false );
}
}
//-----------------------------------------------------------------------------
// Purpose: Custom kill types for TF
//-----------------------------------------------------------------------------
const char *CTeamFortress::GetDamageCustomString(const CTakeDamageInfo &info)
{
switch( info.GetDamageCustom() )
{
case DMG_KILL_BULLRUSH:
return "bullrush";
break;
default:
break;
};
return "INVALID CUSTOM KILL TYPE";
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pListener -
// *pSpeaker -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CTeamFortress::PlayerCanHearChat( CBasePlayer *pListener, CBasePlayer *pSpeaker )
{
if ( BaseClass::PlayerCanHearChat( pListener, pSpeaker ) )
return true;
CBaseTFPlayer *listener = static_cast< CBaseTFPlayer * >( pListener );
CBaseTFPlayer *speaker = static_cast< CBaseTFPlayer * >( pSpeaker );
if ( listener && speaker )
{
if ( listener->IsClass( TFCLASS_INFILTRATOR ) )
{
Vector delta;
delta = listener->EarPosition() - speaker->GetAbsOrigin();
if ( delta.Length() < INFILTRATOR_EAVESDROP_RADIUS )
return true;
}
}
return false;
}
void CTeamFortress::InitDefaultAIRelationships( void )
{
// Allocate memory for default relationships
CBaseCombatCharacter::AllocateDefaultRelationships();
// --------------------------------------------------------------
// First initialize table so we can report missing relationships
// --------------------------------------------------------------
int i, j;
for (i=0;i<NUM_AI_CLASSES;i++)
{
for (j=0;j<NUM_AI_CLASSES;j++)
{
// By default all relationships are neutral of priority zero
CBaseCombatCharacter::SetDefaultRelationship( (Class_T)i, (Class_T)j, D_NU, 0 );
}
}
// ------------------------------------------------------------
// > CLASS_NONE
// ------------------------------------------------------------
CBaseCombatCharacter::SetDefaultRelationship(CLASS_NONE, CLASS_NONE, D_NU, 0);
CBaseCombatCharacter::SetDefaultRelationship(CLASS_NONE, CLASS_PLAYER, D_NU, 0);
// ------------------------------------------------------------
// > CLASS_PLAYER
// ------------------------------------------------------------
CBaseCombatCharacter::SetDefaultRelationship(CLASS_PLAYER, CLASS_NONE, D_NU, 0);
CBaseCombatCharacter::SetDefaultRelationship(CLASS_PLAYER, CLASS_PLAYER, D_NU, 0);
}
//-----------------------------------------------------------------------------
// Purpose: Return a pointer to the opposing team
//-----------------------------------------------------------------------------
CTFTeam *GetOpposingTeam( CTeam *pTeam )
{
// Hacky!
if ( pTeam->GetTeamNumber() == 1 )
return GetGlobalTFTeam( 2 );
return GetGlobalTFTeam( 1 );
}
//------------------------------------------------------------------------------
// Purpose : Return classify text for classify type
//------------------------------------------------------------------------------
const char *CTeamFortress::AIClassText(int classType)
{
switch (classType)
{
case CLASS_NONE: return "CLASS_NONE";
case CLASS_PLAYER: return "CLASS_PLAYER";
default: return "MISSING CLASS in ClassifyText()";
}
}
//-----------------------------------------------------------------------------
// Purpose: When gaining new technologies in TF, prevent auto switching if we
// receive a weapon during the switch
// Input : *pPlayer -
// *pWeapon -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CTeamFortress::FShouldSwitchWeapon( CBasePlayer *pPlayer, CBaseCombatWeapon *pWeapon )
{
if ( !GetAllowWeaponSwitch() )
return false;
// Never auto switch to object placement
if ( dynamic_cast<CWeaponBuilder*>(pWeapon) )
return false;
if ( dynamic_cast<CWeaponObjectSelection*>(pWeapon) )
return false;
return BaseClass::FShouldSwitchWeapon( pPlayer, pWeapon );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : allow -
//-----------------------------------------------------------------------------
void CTeamFortress::SetAllowWeaponSwitch( bool allow )
{
m_bAllowWeaponSwitch = allow;
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CTeamFortress::GetAllowWeaponSwitch( void )
{
return m_bAllowWeaponSwitch;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pPlayer -
// Output : const char
//-----------------------------------------------------------------------------
const char *CTeamFortress::SetDefaultPlayerTeam( CBasePlayer *pPlayer )
{
Assert( pPlayer );
return BaseClass::SetDefaultPlayerTeam( pPlayer );
}
// Called when game rules are created by CWorld
void CTeamFortress::LevelInitPreEntity( void )
{
BaseClass::LevelInitPreEntity();
g_flNextReinforcementTime = 0.0f;
}
// Called when game rules are destroyed by CWorld
void CTeamFortress::LevelShutdown( void )
{
g_flNextReinforcementTime = 0.0f;
g_hCurrentAct = NULL;
BaseClass::LevelShutdown();
}
bool CTeamFortress::IsConnectedUserInfoChangeAllowed( CBasePlayer *pPlayer )
{
return true;
}
void InitBodyQue(void)
{
// FIXME: Make this work
}
#endif
// ----------------------------------------------------------------------------- //
// Shared CTeamFortress code.
// ----------------------------------------------------------------------------- //
//-----------------------------------------------------------------------------
// Purpose: Send the appropriate weapon impact
//-----------------------------------------------------------------------------
void WeaponImpact( trace_t *tr, Vector vecDir, bool bHurt, CBaseEntity *pEntity, int iDamageType )
{
// If we hit a combat shield, play the hit effect
if ( iDamageType & (DMG_PLASMA | DMG_ENERGYBEAM) )
{
if ( bHurt )
{
Assert( pEntity );
bool bHitHandheldShield = (pEntity->IsPlayer() && ((CBaseTFPlayer*)pEntity)->IsHittingShield( vecDir, NULL ));
if ( bHitHandheldShield )
UTIL_ImpactTrace( tr, iDamageType, "PlasmaShield" );
else
{
// Client waits for server version
#ifndef CLIENT_DLL
// Make sure the server sends to us, even though we're predicting
CDisablePredictionFiltering dpf;
UTIL_ImpactTrace( tr, iDamageType, "PlasmaHurt" );
#endif
}
}
else
UTIL_ImpactTrace( tr, iDamageType, "PlasmaUnhurt" );
}
else
{
if ( bHurt )
{
Assert( pEntity );
bool bHitHandheldShield = (pEntity->IsPlayer() && ((CBaseTFPlayer*)pEntity)->IsHittingShield( vecDir, NULL ));
if ( bHitHandheldShield )
{
UTIL_ImpactTrace( tr, iDamageType, "ImpactShield" );
}
else
{
// Client waits for server version
#ifndef CLIENT_DLL
// Make sure the server sends to us, even though we're predicting
CDisablePredictionFiltering dpf;
UTIL_ImpactTrace( tr, iDamageType, "Impact" );
#endif
}
}
else
UTIL_ImpactTrace( tr, iDamageType, "ImpactUnhurt" );
}
}
static bool CheckCollisionGroupPlayerMovement( int collisionGroup0, int collisionGroup1 )
{
if ( collisionGroup0 == COLLISION_GROUP_PLAYER )
{
// Players don't collide with objects or other players
if ( collisionGroup1 == COLLISION_GROUP_PLAYER || collisionGroup1 == TFCOLLISION_GROUP_OBJECT )
return false;
}
if ( collisionGroup1 == COLLISION_GROUP_PLAYER_MOVEMENT )
{
// This is only for probing, so it better not be on both sides!!!
Assert( collisionGroup0 != COLLISION_GROUP_PLAYER_MOVEMENT );
// No collide with players any more
// Nor with objects or grenades
switch ( collisionGroup0 )
{
default:
break;
case COLLISION_GROUP_PLAYER:
return false;
case TFCOLLISION_GROUP_OBJECT_SOLIDTOPLAYERMOVEMENT:
// Certain objects are still solid to player movement
return true;
case TFCOLLISION_GROUP_COMBATOBJECT:
case TFCOLLISION_GROUP_OBJECT:
return false;
case TFCOLLISION_GROUP_GRENADE:
case COLLISION_GROUP_DEBRIS:
return false;
}
}
return true;
}
void CTeamFortress::WeaponTraceLine( const Vector& src, const Vector& end, unsigned int mask, CBaseEntity *pShooter, int damageType, trace_t* pTrace )
{
// Iterate over all shields on the same team, disable them so
// we don't intersect with them...
CShield::ActivateShields( false, pShooter->GetTeamNumber() );
UTIL_TraceLine(src, end, mask, pShooter, TFCOLLISION_GROUP_WEAPON, pTrace);
// NDebugOverlay::Line( src, pTrace->endpos, 255,255,255, true, 5.0 );
// NDebugOverlay::Box( pTrace->endpos, Vector(-2,-2,-2), Vector(2,2,2), 255,255,255, true, 5.0 );
// Shield check...
if (pTrace->fraction != 1.0)
{
CBaseEntity *pEntity = pTrace->m_pEnt;
CShield* pShield = dynamic_cast<CShield*>(pEntity);
if (pShield)
{
Vector vecDir;
VectorSubtract( end, src, vecDir );
// We deflected all of the damage
pShield->RegisterDeflection( vecDir, damageType, pTrace );
}
}
// Reactivate all shields
CShield::ActivateShields( true );
}
bool CTeamFortress::ShouldCollide( int collisionGroup0, int collisionGroup1 )
{
if ( collisionGroup0 > collisionGroup1 )
// swap so that lowest is always first
V_swap(collisionGroup0,collisionGroup1);
// Ignore base class HL2 definition for COLLISION_GROUP_WEAPON, change to COLLISION_GROUP_NONE
if ( collisionGroup0 == COLLISION_GROUP_WEAPON )
collisionGroup0 = COLLISION_GROUP_NONE;
if ( collisionGroup1 == COLLISION_GROUP_WEAPON )
collisionGroup1 = COLLISION_GROUP_NONE;
// Shields collide with weapons + grenades only
if ( collisionGroup0 == TFCOLLISION_GROUP_SHIELD )
return ((collisionGroup1 == TFCOLLISION_GROUP_WEAPON) || (collisionGroup1 == TFCOLLISION_GROUP_GRENADE));
// Weapons can collide with things (players) in vehicles.
if( collisionGroup0 == COLLISION_GROUP_IN_VEHICLE && collisionGroup1 == TFCOLLISION_GROUP_WEAPON )
return true;
// COLLISION TEST:
// Players don't collide with other players or objects
if ( !CheckCollisionGroupPlayerMovement( collisionGroup0, collisionGroup1 ) )
return false;
// Reciprocal test
if ( !CheckCollisionGroupPlayerMovement( collisionGroup1, collisionGroup0 ) )
return false;
// Grenades don't collide with debris
if ( collisionGroup1 == TFCOLLISION_GROUP_GRENADE )
if ( collisionGroup0 == COLLISION_GROUP_DEBRIS )
return false;
// Combat objects don't collide with players
if ( collisionGroup1 == TFCOLLISION_GROUP_COMBATOBJECT )
if ( collisionGroup0 == COLLISION_GROUP_PLAYER )
return false;
// Resource chunks don't collide with each other or vehicles
if ( collisionGroup1 == TFCOLLISION_GROUP_RESOURCE_CHUNK )
{
if ( collisionGroup0 == TFCOLLISION_GROUP_RESOURCE_CHUNK )
return false;
// if ( collisionGroup0 == COLLISION_GROUP_VEHICLE )
// return false;
}
return BaseClass::ShouldCollide( collisionGroup0, collisionGroup1 );
}
//-----------------------------------------------------------------------------
// Purpose: Fire a generic bullet
//-----------------------------------------------------------------------------
void CTeamFortress::FireBullets( const CTakeDamageInfo &info, int cShots, const Vector &vecSrc, const Vector &vecDirShooting,
const Vector &vecSpread, float flDistance, int iAmmoType,
int iTracerFreq, int firingEntID, int attachmentID, const char *sCustomTracer )
{
static int tracerCount;
bool tracer;
trace_t tr;
CTakeDamageInfo subInfo = info;
CBaseTFCombatWeapon *pWeapon = dynamic_cast<CBaseTFCombatWeapon*>(info.GetInflictor());
Assert( subInfo.GetInflictor() );
// Default attacker is the inflictor
if ( subInfo.GetAttacker() == NULL )
subInfo.SetAttacker( subInfo.GetInflictor() );
// --------------------------------------------------
// Get direction vectors for spread
// --------------------------------------------------
Vector vecUp = Vector(0,0,1);
Vector vecRight;
CrossProduct ( vecDirShooting, vecUp, vecRight );
CrossProduct ( vecDirShooting, -vecRight, vecUp );
#ifndef CLIENT_DLL
ClearMultiDamage();
#endif
int seed = 0;
for (int iShot = 0; iShot < cShots; iShot++)
{
// get circular gaussian spread
float x, y, z;
do
{
float x1, x2, y1, y2;
// Note the additional seed because otherwise we get the same set of random #'s and will get stuck
// in an infinite loop here potentially
// FIXME: Can we use a gaussian random # function instead? ywb
if ( CBaseEntity::GetPredictionRandomSeed() != -1 )
{
x1 = SharedRandomFloat("randshot", -0.5f, 0.5f, ++seed );
x2 = SharedRandomFloat("randshot", -0.5f, 0.5f, ++seed );
y1 = SharedRandomFloat("randshot", -0.5f, 0.5f, ++seed );
y2 = SharedRandomFloat("randshot", -0.5f, 0.5f, ++seed );
}
else
{
x1 = RandomFloat( -0.5, 0.5 );
x2 = RandomFloat( -0.5, 0.5 );
y1 = RandomFloat( -0.5, 0.5 );
y2 = RandomFloat( -0.5, 0.5 );
}
x = x1 + x2;
y = y1 + y2;
z = x*x+y*y;
} while (z > 1);
Vector vecDir = vecDirShooting + x * vecSpread.x * vecRight + y * vecSpread.y * vecUp;
Vector vecEnd = vecSrc + vecDir * flDistance;
// Try the trace
WeaponTraceLine( vecSrc, vecEnd, MASK_SHOT, subInfo.GetInflictor(), subInfo.GetDamageType(), &tr );
tracer = false;
if (iTracerFreq != 0 && (tracerCount++ % iTracerFreq) == 0)
{
Vector vecTracerSrc;
// adjust tracer position for player
if ( subInfo.GetInflictor()->IsPlayer() )
{
Vector forward, right;
CBasePlayer *pPlayer = ToBasePlayer( subInfo.GetInflictor() );
pPlayer->EyeVectors( &forward, &right, NULL );
vecTracerSrc = vecSrc + Vector ( 0 , 0 , -4 ) + right * 2 + forward * 16;
}
else
{
vecTracerSrc = vecSrc;
}
if ( iTracerFreq != 1 ) // guns that always trace also always decal
tracer = true;
if ( sCustomTracer )
UTIL_Tracer( vecTracerSrc, tr.endpos, subInfo.GetInflictor()->entindex(), TRACER_DONT_USE_ATTACHMENT, 0, false, (char*)sCustomTracer );
else
UTIL_Tracer( vecTracerSrc, tr.endpos, subInfo.GetInflictor()->entindex() );
}
// do damage, paint decals
if ( tr.fraction != 1.0 )
{
CBaseEntity *pEntity = tr.m_pEnt;
// NOTE: If we want to know more than whether or not the entity can actually be hurt
// for the purposes of impact effects, the client needs to know a lot more.
bool bTargetCouldBeHurt = false;
if ( pEntity->m_takedamage )
{
if ( !pEntity->InSameTeam( subInfo.GetInflictor() ) )
{
bTargetCouldBeHurt = true;
}
#ifndef CLIENT_DLL
subInfo.SetDamagePosition( vecSrc );
// Hit the target
pEntity->DispatchTraceAttack( subInfo, vecDir, &tr );
#endif
}
// No decal if we hit a shield
if ( pEntity->GetCollisionGroup() != TFCOLLISION_GROUP_SHIELD )
WeaponImpact( &tr, vecDir, bTargetCouldBeHurt, pEntity, subInfo.GetDamageType() );
}
if ( pWeapon )
pWeapon->BulletWasFired( vecSrc, tr.endpos );
}
// Apply any damage we've stacked up
#ifndef CLIENT_DLL
ApplyMultiDamage();
#endif
}
//-----------------------------------------------------------------------------
// Purpose: Init TF2 ammo definitions
//-----------------------------------------------------------------------------
CAmmoDef *GetAmmoDef()
{
static CAmmoDef def;
static bool bInitted = false;
if ( !bInitted )
{
bInitted = true;
// Added some basic physics force ~hogsy
def.AddAmmoType("Bullets", DMG_BULLET, TRACER_LINE, 0, 0, INFINITE_AMMO, 10, 0);
def.AddAmmoType("Rockets", DMG_BLAST, TRACER_LINE, 0, 0, 6, 50, 0);
def.AddAmmoType("Grenades", DMG_BLAST, TRACER_LINE, 0, 0, 3, 50, 0);
def.AddAmmoType("ShieldGrenades", DMG_ENERGYBEAM, TRACER_LINE, 0, 0, 5, 0, 0);
def.AddAmmoType("ShotgunEnergy", DMG_ENERGYBEAM, TRACER_LINE, 0, 0, INFINITE_AMMO, 0, 0);
def.AddAmmoType("PlasmaGrenade", DMG_ENERGYBEAM|DMG_BLAST, TRACER_LINE, 0, 0, 30, 0, 0);
def.AddAmmoType("ResourceChunks", DMG_GENERIC, TRACER_LINE, 0, 0, 4, 0, 0); // Resource chunks
def.AddAmmoType("Limpets", DMG_BLAST, TRACER_LINE, 0, 0, 40, 0, 0);
def.AddAmmoType("Gasoline", DMG_BURN, TRACER_LINE, 0, 0, 80, 0, 0);
// Combat Objects
def.AddAmmoType("RallyFlags", DMG_GENERIC, TRACER_NONE, 0, 0, 1, 0, 0);
def.AddAmmoType("EMPGenerators", DMG_GENERIC, TRACER_NONE, 0, 0, 1, 0, 0);
}
return &def;
}
| 50,637
| 20,378
|
// SPDX-License-Identifier: MIT
// Copyright contributors to the gecko project.
#include <base/ansi.h>
#include <base/contract.h>
#include <base/string_util.h>
#include <base/unit_test.h>
#include <base/uri.h>
#include <iostream>
#include <sstream>
namespace
{
void check(
base::unit_test & ut,
const std::string &test,
bool should = true,
bool except = false )
{
try
{
base::uri u( test );
std::string match = base::to_string( u );
if ( test == match )
ut.success( test );
else if ( !should )
ut.negative_success( test + " != " + match );
else
ut.failure( test + " != " + match );
}
catch ( const std::exception &e )
{
std::stringstream msg;
base::print_exception( msg, e );
if ( except )
ut.negative_success( test + " -> exception " + msg.str() );
else
ut.failure( test + " -> exception " + msg.str() );
}
}
int safemain( int argc, char *argv[] )
{
base::unit_test test( "uri" );
base::cmd_line options( argv[0] );
test.setup( options );
try
{
options.parse( argc, argv );
}
catch ( ... )
{
throw_add( "parsing command line arguments" );
}
test["basic_parsing"] = [&]( void ) {
check( test, "http", false, true );
check( test, "http:", false, true );
check( test, "file:/tmp" );
check( test, "file:///tmp", false );
check( test, "http://host.com" );
check( test, "http://user@host.com" );
check( test, "http://host.com:1234" );
check( test, "http://user@host.com:1234" );
check( test, "http://host.com/path1" );
check( test, "http://host.com/path1/path2" );
};
test["parse_query_frag"] = [&]( void ) {
check( test, "http://host.com?query" );
check( test, "http://host.com#frag" );
check( test, "http://host.com?query#frag" );
check( test, "http://host.com/path1?query#frag" );
};
test["parse_encoded"] = [&]( void ) {
check( test, "http://host.com/path1#frag%3Fmorefrag" );
check( test, "http://host%2ecom", false );
check( test, "http://host%2Ecom", false );
check( test, "http://host.com/%2fmore", false );
check( test, "http://host.com/%2Fmore" );
check( test, "http://host.com/with%20space", false );
check( test, "http://host.com/with space", true );
};
test["path_construction"] = [&]( void ) {
base::uri tf( "file", "" );
tf /= "file.txt";
if ( tf.pretty() == "file:///file.txt" )
test.success( "operator/=" );
else
test.failure( "operator/= -> {0}", tf );
tf = base::uri( "file", "" ) / "hello" / "world";
if ( tf.pretty() == "file:///hello/world" )
test.success( "operator/" );
else
test.failure( "operator/ -> {0}", tf );
};
// test.cleanup() = [&]( void ) {};
test.run( options );
test.clean();
return -static_cast<int>( test.failure_count() );
}
} // namespace
int main( int argc, char *argv[] )
{
try
{
return safemain( argc, argv );
}
catch ( const std::exception &e )
{
base::print_exception( std::cerr, e );
}
return -1;
}
| 3,375
| 1,155
|
/*
* FILE: debug.cpp
* PROGRAM: RAT
* AUTHORS: Isidor Kouvelas
* Colin Perkins
* Mark Handley
* Orion Hodson
* Jerry Isdale
*
* $Revision: 1.1 $
* $Date: 2007/11/08 09:48:59 $
*
* Copyright (c) 1995-2000 University College London
* Copyright (c) 2005-2021 CESNET, z. s. p. o.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, is 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. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the Computer Science
* Department at University College London
* 4. Neither the name of the University nor of the Department may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESSED 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 AUTHORS 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.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif // defined HAVE_CONFIG_H
#include "config_unix.h"
#include "config_win32.h"
#include <array>
#include <cstdint>
#include <string>
#include <unordered_map>
#include "compat/misc.h" // strdupa
#include "compat/platform_time.h"
#include "debug.h"
#include "host.h"
#include "rang.hpp"
#include "utils/color_out.h"
#include "utils/misc.h" // ug_strerror
using std::string;
using std::unordered_map;
volatile int log_level = LOG_LEVEL_INFO;
static void _dprintf(const char *format, ...)
{
if (log_level < LOG_LEVEL_DEBUG) {
return;
}
#ifdef WIN32
char msg[65535];
va_list ap;
va_start(ap, format);
_vsnprintf(msg, 65535, format, ap);
va_end(ap);
OutputDebugString(msg);
#else
va_list ap;
va_start(ap, format);
vfprintf(stderr, format, ap);
va_end(ap);
#endif /* WIN32 */
}
void log_msg(int level, const char *format, ...)
{
va_list ap;
if (log_level < level) {
return;
}
#if 0 // WIN32
if (log_level == LOG_LEVEL_DEBUG) {
char msg[65535];
va_list ap;
va_start(ap, format);
_vsnprintf(msg, 65535, format, ap);
va_end(ap);
OutputDebugString(msg);
return;
}
#endif /* WIN32 */
// get number of required bytes
va_start(ap, format);
int size = vsnprintf(NULL, 0, format, ap);
va_end(ap);
// format the string
char *buffer = (char *) alloca(size + 1);
va_start(ap, format);
if (vsprintf(buffer, format, ap) != size) {
va_end(ap);
return;
}
va_end(ap);
LOG(level) << buffer;
}
void log_msg_once(int level, uint32_t id, const char *msg) {
if (log_level < level) {
return;
}
Logger(level).once(id, msg);
}
/**
* This function is analogous to perror(). The message is printed using the logger.
*/
void log_perror(int level, const char *msg)
{
log_msg(level, "%s: %s\n", msg, ug_strerror(errno));
}
/**
* debug_dump:
* @lp: pointer to memory region.
* @len: length of memory region in bytes.
*
* Writes a dump of a memory region to stdout. The dump contains a
* hexadecimal and an ascii representation of the memory region.
*
**/
void debug_dump(void *lp, int len)
{
char *p;
int i, j, start;
char Buff[81];
char stuffBuff[10];
char tmpBuf[10];
_dprintf("Dump of %d=%x bytes\n", len, len);
start = 0L;
while (start < len) {
/* start line with pointer position key */
p = (char *)lp + start;
sprintf(Buff, "%p: ", p);
/* display each character as hex value */
for (i = start, j = 0; j < 16; p++, i++, j++) {
if (i < len) {
sprintf(tmpBuf, "%X", ((int)(*p) & 0xFF));
if (strlen((char *)tmpBuf) < 2) {
stuffBuff[0] = '0';
stuffBuff[1] = tmpBuf[0];
stuffBuff[2] = ' ';
stuffBuff[3] = '\0';
} else {
stuffBuff[0] = tmpBuf[0];
stuffBuff[1] = tmpBuf[1];
stuffBuff[2] = ' ';
stuffBuff[3] = '\0';
}
strcat(Buff, stuffBuff);
} else
strcat(Buff, " ");
if (j == 7) /* space between groups of 8 */
strcat(Buff, " ");
}
strcat(Buff, " ");
/* display each character as character value */
for (i = start, j = 0, p = (char *)lp + start;
(i < len && j < 16); p++, i++, j++) {
if (((*p) >= ' ') && ((*p) <= '~')) /* test displayable */
sprintf(tmpBuf, "%c", *p);
else
sprintf(tmpBuf, "%c", '.');
strcat(Buff, tmpBuf);
if (j == 7) /* space between groups of 8 */
strcat(Buff, " ");
}
_dprintf("%s\n", Buff);
start = i; /* next line starting byte */
}
}
bool set_log_level(const char *optarg, bool *logger_repeat_msgs, int *show_timestamps) {
assert(optarg != nullptr);
assert(logger_repeat_msgs != nullptr);
using namespace std::string_literals;
using std::clog;
using std::cout;
static const struct { const char *name; int level; } mapping[] = {
{ "quiet", LOG_LEVEL_QUIET },
{ "fatal", LOG_LEVEL_FATAL },
{ "error", LOG_LEVEL_ERROR },
{ "warning", LOG_LEVEL_WARNING},
{ "notice", LOG_LEVEL_NOTICE},
{ "info", LOG_LEVEL_INFO },
{ "verbose", LOG_LEVEL_VERBOSE},
{ "debug", LOG_LEVEL_DEBUG },
{ "debug2", LOG_LEVEL_DEBUG2 },
};
if ("help"s == optarg) {
cout << "log level: [0-" << LOG_LEVEL_MAX;
for (auto m : mapping) {
cout << "|" << m.name;
}
cout << "][+repeat][+/-timestamps]\n";
cout << BOLD("\trepeat") << " - print repeating log messages\n";
cout << BOLD("\ttimestamps") << " - enable/disable timestamps\n";
return false;
}
if (strstr(optarg, "+repeat") != nullptr) {
*logger_repeat_msgs = true;
}
if (const char *timestamps = strstr(optarg, "timestamps")) {
if (timestamps > optarg) {
*show_timestamps = timestamps[-1] == '+' ? 1 : 0;
}
}
if (getenv("ULTRAGRID_VERBOSE") != nullptr) {
log_level = LOG_LEVEL_VERBOSE;
}
if (optarg[0] == '+' || optarg[0] == '-') { // only flags, no log level
return true;
}
if (isdigit(optarg[0])) {
long val = strtol(optarg, nullptr, 0);
if (val < 0 || val > LOG_LEVEL_MAX) {
clog << "Log: wrong value: " << optarg << " (allowed range [0.." << LOG_LEVEL_MAX << "])\n";
return false;
}
log_level = val;
return true;
}
char *log_level_str = strdupa(optarg);
if (char *delim = strpbrk(log_level_str, "+-")) {
*delim = '\0';
}
for (auto m : mapping) {
if (strcmp(log_level_str, m.name) == 0) {
log_level = m.level;
return true;
}
}
LOG(LOG_LEVEL_ERROR) << "Wrong log level specification: " << optarg << "\n";
return false;
}
/**
* @param show_timestamps 0 - no; 1 - yes; -1 auto
*/
void Logger::preinit(bool skip_repeated, int show_timestamps)
{
Logger::skip_repeated = skip_repeated;
Logger::show_timestamps = show_timestamps;
if (rang::rang_implementation::supportsColor()
&& rang::rang_implementation::isTerminal(std::cout.rdbuf())
&& rang::rang_implementation::isTerminal(std::cerr.rdbuf())) {
// force ANSI sequences even when written to ostringstream
rang::setControlMode(rang::control::Force);
#ifdef _WIN32
// ANSI control sequences need to be explicitly set in Windows
if ((rang::rang_implementation::setWinTermAnsiColors(std::cout.rdbuf()) || rang::rang_implementation::isMsysPty(_fileno(stdout))) &&
(rang::rang_implementation::setWinTermAnsiColors(std::cerr.rdbuf()) || rang::rang_implementation::isMsysPty(_fileno(stderr)))) {
rang::setWinTermMode(rang::winTerm::Ansi);
}
#endif
}
}
#ifdef DEBUG
void debug_file_dump(const char *key, void (*serialize)(const void *data, FILE *), void *data) {
const char *dump_file_val = get_commandline_param("debug-dump");
static thread_local unordered_map<string, int> skip_map;
if (dump_file_val == nullptr) {
return;
}
// check if key is contained
string not_first = ",";
not_first + key;
int skip_n = 0;
if (strstr(dump_file_val, key) == dump_file_val) {
const char *val = dump_file_val + strlen(key);
if (val[0] == '=') {
skip_n = atoi(val + 1);
}
} else if (strstr(dump_file_val, not_first.c_str()) != NULL) {
const char *val = strstr(dump_file_val, not_first.c_str()) + strlen(key);
if (val[0] == '=') {
skip_n = atoi(val + 1);
}
} else {
return;
}
if (skip_map.find(key) == skip_map.end()) {
skip_map[key] = skip_n;
}
if (skip_map[key] == -1) { // already exported
return;
}
if (skip_map[key] > 0) {
skip_map[key]--;
return;
}
// export
string name = string(key) + ".dump";
FILE *out = fopen(name.c_str(), "wb");
if (out == nullptr) {
perror("debug_file_dump fopen");
return;
}
serialize(data, out);
fclose(out);
skip_map[key] = -1;
}
#endif
std::atomic<Logger::last_message *> Logger::last_msg{};
thread_local std::set<uint32_t> Logger::oneshot_messages;
std::atomic<bool> Logger::skip_repeated{true};
int Logger::show_timestamps = -1;
| 12,397
| 3,894
|
#include<stdio.h>
int main()
{
int a;
printf("enter the number");
scanf("%d",&a);
if(a%2==0)
{printf("The number is even");
}
else
{printf("The number is odd");
}
return 0;
}
| 201
| 88
|
//
// main.cpp
// D - Cryptography
//
// Created by Kieran Will on 10/14/15.
// Copyright © 2015 Kieran Will. All rights reserved.
//
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
const int MSIZE = 15002;
bool isPrime(int n) {
for(int i = 2; i <= sqrt(n); ++ i) {
if(n % i == 0)return false;
}
return true;
}
int N, tmp;
int main(int argc, const char * argv[]) {
int _C = 4, bss = 7; vector<int> _V; _V.push_back(2); _V.push_back(3); _V.push_back(5);
while (_C < MSIZE) {
tmp = bss;
if (isPrime(tmp)) {
_V.push_back(bss); _C ++;
}
bss ++;
}
while (cin >> N) {
for (int i = 0; i < N; ++ i) {
cin >> tmp; cout << _V[tmp-1] << "\n";
}
}
//std::cout << "Hello, World!\n";
return 0;
}
/*
4
3
2
5
7
*/
| 865
| 380
|
/////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2006-2013
//
// 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)
//
// See http://www.boost.org/libs/intrusive for documentation.
//
/////////////////////////////////////////////////////////////////////////////
//[doc_set_code
#include <boost/intrusive/set.hpp>
#include <vector>
#include <functional>
#include <cassert>
using namespace boost::intrusive;
//This is a base hook optimized for size
class MyClass : public set_base_hook<optimize_size<true> >
{
int int_;
public:
//This is a member hook
set_member_hook<> member_hook_;
MyClass(int i)
: int_(i)
{}
friend bool operator< (const MyClass &a, const MyClass &b)
{ return a.int_ < b.int_; }
friend bool operator> (const MyClass &a, const MyClass &b)
{ return a.int_ > b.int_; }
friend bool operator== (const MyClass &a, const MyClass &b)
{ return a.int_ == b.int_; }
};
//Define a set using the base hook that will store values in reverse order
typedef set< MyClass, compare<std::greater<MyClass> > > BaseSet;
//Define an multiset using the member hook
typedef member_hook<MyClass, set_member_hook<>, &MyClass::member_hook_> MemberOption;
typedef multiset< MyClass, MemberOption> MemberMultiset;
int main()
{
typedef std::vector<MyClass>::iterator VectIt;
//Create several MyClass objects, each one with a different value
std::vector<MyClass> values;
for(int i = 0; i < 100; ++i) values.push_back(MyClass(i));
BaseSet baseset;
MemberMultiset membermultiset;
//Check that size optimization is activated in the base hook
assert(sizeof(set_base_hook<optimize_size<true> >) == 3*sizeof(void*));
//Check that size optimization is deactivated in the member hook
assert(sizeof(set_member_hook<>) > 3*sizeof(void*));
//Now insert them in the reverse order in the base hook set
for(VectIt it(values.begin()), itend(values.end()); it != itend; ++it){
baseset.insert(*it);
membermultiset.insert(*it);
}
//Now test sets
{
BaseSet::reverse_iterator rbit(baseset.rbegin());
MemberMultiset::iterator mit(membermultiset.begin());
VectIt it(values.begin()), itend(values.end());
//Test the objects inserted in the base hook set
for(; it != itend; ++it, ++rbit)
if(&*rbit != &*it) return 1;
//Test the objects inserted in the member hook set
for(it = values.begin(); it != itend; ++it, ++mit)
if(&*mit != &*it) return 1;
}
return 0;
}
//]
| 2,815
| 938
|
// 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
#include "Base.h"
Base::Base(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
//=menu_action_edit
QAction* a1 = menu.addAction(trUtf8("Редактировать"));
if (a1 != nullptr)
{
a1->setParent(this);
connect(a1, &QAction::triggered, this, &Base::menuEdit);
}
//=menu_action_remove
QAction* a2 = menu.addAction(trUtf8("Удалить"));
if (a2 != nullptr)
{
a2->setParent(this);
connect(a2, &QAction::triggered, this, &Base::menuDelete);
}
clearAllButton = ui.clearAllButton;
addButton = ui.addButton;
exportButton = ui.exportButton;
nameEdit = ui.name;
surNameEdit = ui.surName;
tel1Edit = ui.tel0;
tel2Edit = ui.tel1;
tel3Edit = ui.tel2;
birthEdit = ui.birth;
tw = ui.tableWidget;
if (tw != nullptr)
{
tw->setSelectionBehavior(QAbstractItemView::SelectRows);
tw->setSelectionMode(QAbstractItemView::SingleSelection);
tw->setEditTriggers(QAbstractItemView::NoEditTriggers);
tw->setEnabled(false);
}
if (clearAllButton != nullptr)
{
clearAllButton->setEnabled(false);
connect(clearAllButton, &QPushButton::pressed, this, &Base::clearButtonPressed);
}
if (addButton != nullptr)
{
addButton->setEnabled(false);
connect(addButton, &QPushButton::pressed, this, &Base::addButtonPressed);
}
if (exportButton != nullptr)
{
exportButton->setEnabled(false);
connect(exportButton, &QPushButton::pressed, this, &Base::exportButtonPressed);
}
if (nameEdit != nullptr)
nameEdit->setEnabled(false);
if (surNameEdit != nullptr)
surNameEdit->setEnabled(false);
if (tel1Edit != nullptr)
tel1Edit->setEnabled(false);
if (tel2Edit != nullptr)
tel2Edit->setEnabled(false);
if (tel3Edit != nullptr)
tel3Edit->setEnabled(false);
if (birthEdit != nullptr)
birthEdit->setEnabled(false);
}
void Base::showMessage(QString text)
{
QMessageBox ms;
ms.setWindowIcon(QIcon(":/Resources/icon.ico"));
ms.setText(text);
ms.exec();
//this->close();
}
void Base::allLoaded()
{
if (tw != nullptr)
{
tw->setEnabled(true);
if (tw->columnCount() > 0)
{
quint64 width = tw->size().width()*1.0 / (tw->columnCount()*1.0);
for (quint64 i=0; i<tw->columnCount(); i++)
tw->horizontalHeader()->resizeSection(i, width);
tw->update();
}
}
if (clearAllButton != nullptr)
clearAllButton->setEnabled(true);
if (addButton != nullptr)
addButton->setEnabled(true);
if (exportButton != nullptr)
exportButton->setEnabled(true);
if (nameEdit != nullptr)
nameEdit->setEnabled(true);
if (surNameEdit != nullptr)
surNameEdit->setEnabled(true);
if (tel1Edit != nullptr)
tel1Edit->setEnabled(true);
if (tel2Edit != nullptr)
tel2Edit->setEnabled(true);
if (tel3Edit != nullptr)
tel3Edit->setEnabled(true);
if (birthEdit != nullptr)
birthEdit->setEnabled(true);
}
void Base::newRecord(QStringList val, quint64 id)
{
if (tw != nullptr && val.size() > Settings::inst()->datePosInTable)
{
if (id > lastId)
lastId = id;
ids.append(id);
quint64 s=0;
QDate cd = QDate::fromString(val.at(Settings::inst()->datePosInTable), Settings::inst()->dateFormat);
QDate date = QDate::currentDate();
// Lets find some position to insert with sorting by birth date. Birthdate should be last!
if (tw->rowCount() > 0)
{
bool found = false;
for (quint64 i = 0; i < tw->rowCount(); i++)
if (tw->item(i, Settings::inst()->datePosInTable) != nullptr)
{
QDate d1 = QDate::fromString(tw->item(i, Settings::inst()->datePosInTable)->text(), Settings::inst()->dateFormat);
if (cd.dayOfYear() < d1.dayOfYear())
{
found = true;
if (i == 0)
s = 0;
else
{
s = i;
}
break;
}
}
if (!found)
s = tw->rowCount();
}
// Lets move all table down
tw->insertRow(s);
// Lets insert new record
for (quint64 i = 0; i < qMin(val.size(), tw->columnCount()); i++)
{
QTableWidgetItem* t = new QTableWidgetItem(val.at(i));
t->setTextAlignment(Qt::AlignHCenter);
if (cd.dayOfYear() == date.dayOfYear())
{
QFont ff = t->font();
ff.setBold(true);
t->setFont(ff);
}
tw->setItem(s, i, t);
}
tw->update();
}
}
void Base::clearButtonPressed()
{
if (nameEdit != nullptr)
nameEdit->clear();
if (surNameEdit != nullptr)
surNameEdit->clear();
if (tel1Edit != nullptr)
tel1Edit->clear();
if (tel2Edit != nullptr)
tel2Edit->clear();
if (tel3Edit != nullptr)
tel3Edit->clear();
if (birthEdit != nullptr)
birthEdit->clear();
}
void Base::addButtonPressed()
{
if (nameEdit != nullptr && surNameEdit != nullptr && tel1Edit != nullptr &&
tel2Edit != nullptr && tel3Edit != nullptr && birthEdit != nullptr)
{
if (nameEdit->text().length() > 0 && tel1Edit->text().length() > 0 && birthEdit->text().length() > 0)
{
if (checkDate())
{
QStringList sl;
sl.append(nameEdit->text());
sl.append(surNameEdit->text());
sl.append(tel1Edit->text());
sl.append(tel2Edit->text());
sl.append(tel3Edit->text());
sl.append(birthEdit->text());
clearButtonPressed();
if (!editMode)
{
lastId++;
newRecord(sl, lastId);
emit insertNewUser(sl, lastId);
}
else
{
//=add_button_add
addButton->setText(trUtf8("Add"));
if (editPos < ids.size())
{
editMode = false;
emit modifyUser(sl, ids.at(editPos));
modifyRecord(sl, editPos);
}
}
}
else
{
//=message_box_"Enter name and phone!"_about_date_text
showMessage(trUtf8("Not valid date!"));
}
}
else
{
//=message_box_"Enter name and phone!"_about_all_data
showMessage(trUtf8("Enter name and phone!"));
}
}
}
void Base::contextMenuEvent(QContextMenuEvent* e)
{
menu.exec(e->globalPos());
}
void Base::showCurButtonPressed()
{
if (tw != nullptr)
{
QDate cd = QDate::currentDate();
qint64 first = -1;
qint64 last = -1;
quint64 curPos = qAbs(tw->currentRow());
if (tw->rowCount() > 0)
{
bool found = false;
for (quint64 i = 0; i < tw->rowCount(); i++)
{
QTableWidgetItem* t = tw->item(i, Settings::inst()->datePosInTable);
if (t != nullptr)
{
QDate d = QDate::fromString(t->text(), Settings::inst()->dateFormat);
if (d.dayOfYear() == cd.dayOfYear())
{
if (first < 0)
first = i;
last = i;
found = true;
for (quint64 k = 0; k < tw->columnCount(); k++)
{
t = tw->item(i, k);
if (t != nullptr)
{
QFont ff = t->font();
ff.setBold(true);
t->setFont(ff);
}
}
}
else
{
for (quint64 k = 0; k < tw->columnCount(); k++)
{
t = tw->item(i, k);
if (t != nullptr)
{
QFont ff = t->font();
ff.setBold(false);
t->setFont(ff);
}
}
}
}
}
if (!found)
{
//=message_box_"Enter name and phone!"_about_no_cur_day_data
showMessage(trUtf8("Nothing found!"));
}
}
}
}
bool Base::checkDate()
{
if (birthEdit != nullptr)
{
QDate d = QDate::fromString(birthEdit->text(), Settings::inst()->dateFormat);
return d.isValid();
}
return false;
}
void Base::menuDelete()
{
if (tw != nullptr)
{
quint64 pos = tw->currentRow();
if (pos < ids.size())
{
emit removeUser(ids.takeAt(pos));
tw->removeRow(pos);
}
}
}
void Base::menuEdit()
{
if (tw != nullptr && nameEdit != nullptr && surNameEdit != nullptr && tel1Edit != nullptr &&
tel2Edit != nullptr && tel3Edit != nullptr && birthEdit != nullptr)
{
quint64 pos = tw->currentRow();
if (pos < ids.size())
{
//=add_button_"Save"
addButton->setText(trUtf8("Save"));
editMode = true;
editPos = pos;
if (tw->item(pos, 0) != nullptr)
{
nameEdit->setText(tw->item(pos, 0)->text());
}
if (tw->item(pos, 1) != nullptr)
{
surNameEdit->setText(tw->item(pos, 1)->text());
}
if (tw->item(pos, 2) != nullptr)
{
tel1Edit->setText(tw->item(pos, 2)->text());
}
if (tw->item(pos, 3) != nullptr)
{
tel2Edit->setText(tw->item(pos, 3)->text());
}
if (tw->item(pos, 4) != nullptr)
{
tel3Edit->setText(tw->item(pos, 4)->text());
}
if (tw->item(pos, 5) != nullptr)
{
birthEdit->setText(tw->item(pos, 5)->text());
}
}
}
}
void Base::modifyRecord(QStringList sl, quint64 pos)
{
if (tw != nullptr)
{
if (pos < tw->rowCount())
{
tw->removeRow(pos);
newRecord(sl, pos);
}
}
}
void Base::exportButtonPressed()
{
if (tw != nullptr)
{
Document file;
int x = tw->rowCount();
int y = tw->columnCount();
if (y > 0)
{
//=file_dialog_caption
QString fileName = QFileDialog::getSaveFileName(this, trUtf8("Choose File"), QDir::homePath());
if (fileName.size() > 0)
{
if (fileName.right(5).compare(".xlsx") != 0)
fileName.append(".xlsx");
for (int j = 0; j < y; j++)
{
QTableWidgetItem* t = tw->horizontalHeaderItem(j);
if (t != nullptr)
{
Format hFmt;
hFmt.setFontBold(true);
file.write(1, j + 1, t->text(), hFmt);
file.setColumnWidth(j + 1, 20);
}
}
for (int i = 0; i < x; i++)
for (int j = 0; j < y; j++)
{
QTableWidgetItem* t = tw->item(i, j);
if (t != nullptr)
{
file.write(i + 2, j + 1, t->text());
}
}
file.saveAs(fileName);
//=message_box_all_done
showMessage(trUtf8("Сохранено!"));
}
else
{
//=message_box_nothing_saved
showMessage(trUtf8("Ничего не было сохранено!"));
}
}
else
{
//=message_box_no_data_in_table
showMessage(trUtf8("Table is clear!"));
}
}
}
| 9,678
| 4,453
|
// Copyright (c) 2018 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Validates correctness of barrier SPIR-V instructions.
#include "source/val/validate.h"
#include <string>
#include "source/diagnostic.h"
#include "source/opcode.h"
#include "source/spirv_constant.h"
#include "source/spirv_target_env.h"
#include "source/util/bitutils.h"
#include "source/val/instruction.h"
#include "source/val/validation_state.h"
namespace spvtools {
namespace val {
namespace {
// Validates Execution Scope operand.
spv_result_t ValidateExecutionScope(ValidationState_t& _,
const Instruction* inst, uint32_t id) {
const SpvOp opcode = inst->opcode();
bool is_int32 = false, is_const_int32 = false;
uint32_t value = 0;
std::tie(is_int32, is_const_int32, value) = _.EvalInt32IfConst(id);
if (!is_int32) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< spvOpcodeString(opcode)
<< ": expected Execution Scope to be a 32-bit int";
}
if (!is_const_int32) {
return SPV_SUCCESS;
}
if (spvIsVulkanEnv(_.context()->target_env)) {
if (value != SpvScopeWorkgroup && value != SpvScopeSubgroup) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< spvOpcodeString(opcode)
<< ": in Vulkan environment Execution Scope is limited to "
"Workgroup and Subgroup";
}
if (_.context()->target_env != SPV_ENV_VULKAN_1_0 &&
value != SpvScopeSubgroup) {
_.function(inst->function()->id())
->RegisterExecutionModelLimitation([](SpvExecutionModel model,
std::string* message) {
if (model == SpvExecutionModelFragment ||
model == SpvExecutionModelVertex ||
model == SpvExecutionModelGeometry ||
model == SpvExecutionModelTessellationEvaluation) {
if (message) {
*message =
"in Vulkan evironment, OpControlBarrier execution scope "
"must be Subgroup for Fragment, Vertex, Geometry and "
"TessellationEvaluation execution models";
}
return false;
}
return true;
});
}
}
// TODO(atgoo@github.com) Add checks for OpenCL and OpenGL environments.
return SPV_SUCCESS;
}
// Validates Memory Scope operand.
spv_result_t ValidateMemoryScope(ValidationState_t& _, const Instruction* inst,
uint32_t id) {
const SpvOp opcode = inst->opcode();
bool is_int32 = false, is_const_int32 = false;
uint32_t value = 0;
std::tie(is_int32, is_const_int32, value) = _.EvalInt32IfConst(id);
if (!is_int32) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< spvOpcodeString(opcode)
<< ": expected Memory Scope to be a 32-bit int";
}
if (!is_const_int32) {
return SPV_SUCCESS;
}
if (spvIsVulkanEnv(_.context()->target_env)) {
if (value == SpvScopeCrossDevice) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< spvOpcodeString(opcode)
<< ": in Vulkan environment, Memory Scope cannot be CrossDevice";
}
if (_.context()->target_env == SPV_ENV_VULKAN_1_0 &&
value != SpvScopeDevice && value != SpvScopeWorkgroup &&
value != SpvScopeInvocation) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< spvOpcodeString(opcode)
<< ": in Vulkan 1.0 environment Memory Scope is limited to "
"Device, "
"Workgroup and Invocation";
}
}
// TODO(atgoo@github.com) Add checks for OpenCL and OpenGL environments.
return SPV_SUCCESS;
}
// Validates Memory Semantics operand.
spv_result_t ValidateMemorySemantics(ValidationState_t& _,
const Instruction* inst, uint32_t id) {
const SpvOp opcode = inst->opcode();
bool is_int32 = false, is_const_int32 = false;
uint32_t value = 0;
std::tie(is_int32, is_const_int32, value) = _.EvalInt32IfConst(id);
if (!is_int32) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< spvOpcodeString(opcode)
<< ": expected Memory Semantics to be a 32-bit int";
}
if (!is_const_int32) {
return SPV_SUCCESS;
}
const size_t num_memory_order_set_bits = spvtools::utils::CountSetBits(
value & (SpvMemorySemanticsAcquireMask | SpvMemorySemanticsReleaseMask |
SpvMemorySemanticsAcquireReleaseMask |
SpvMemorySemanticsSequentiallyConsistentMask));
if (num_memory_order_set_bits > 1) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< spvOpcodeString(opcode)
<< ": Memory Semantics can have at most one of the following bits "
"set: Acquire, Release, AcquireRelease or SequentiallyConsistent";
}
if (spvIsVulkanEnv(_.context()->target_env)) {
const bool includes_storage_class =
value & (SpvMemorySemanticsUniformMemoryMask |
SpvMemorySemanticsWorkgroupMemoryMask |
SpvMemorySemanticsImageMemoryMask);
if (opcode == SpvOpMemoryBarrier && !num_memory_order_set_bits) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< spvOpcodeString(opcode)
<< ": Vulkan specification requires Memory Semantics to have one "
"of the following bits set: Acquire, Release, AcquireRelease "
"or SequentiallyConsistent";
}
if (opcode == SpvOpMemoryBarrier && !includes_storage_class) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< spvOpcodeString(opcode)
<< ": expected Memory Semantics to include a Vulkan-supported "
"storage class";
}
#if 0
// TODO(atgoo@github.com): this check fails Vulkan CTS, reenable once fixed.
if (opcode == SpvOpControlBarrier && value && !includes_storage_class) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< spvOpcodeString(opcode)
<< ": expected Memory Semantics to include a Vulkan-supported "
"storage class if Memory Semantics is not None";
}
#endif
}
// TODO(atgoo@github.com) Add checks for OpenCL and OpenGL environments.
return SPV_SUCCESS;
}
} // namespace
// Validates correctness of barrier instructions.
spv_result_t BarriersPass(ValidationState_t& _, const Instruction* inst) {
const SpvOp opcode = inst->opcode();
const uint32_t result_type = inst->type_id();
switch (opcode) {
case SpvOpControlBarrier: {
if (spvVersionForTargetEnv(_.context()->target_env) <
SPV_SPIRV_VERSION_WORD(1, 3)) {
_.function(inst->function()->id())
->RegisterExecutionModelLimitation(
[](SpvExecutionModel model, std::string* message) {
if (model != SpvExecutionModelTessellationControl &&
model != SpvExecutionModelGLCompute &&
model != SpvExecutionModelKernel &&
model != SpvExecutionModelTaskNV &&
model != SpvExecutionModelMeshNV) {
if (message) {
*message =
"OpControlBarrier requires one of the following "
"Execution "
"Models: TessellationControl, GLCompute or Kernel";
}
return false;
}
return true;
});
}
const uint32_t execution_scope = inst->word(1);
const uint32_t memory_scope = inst->word(2);
const uint32_t memory_semantics = inst->word(3);
if (auto error = ValidateExecutionScope(_, inst, execution_scope)) {
return error;
}
if (auto error = ValidateMemoryScope(_, inst, memory_scope)) {
return error;
}
if (auto error = ValidateMemorySemantics(_, inst, memory_semantics)) {
return error;
}
break;
}
case SpvOpMemoryBarrier: {
const uint32_t memory_scope = inst->word(1);
const uint32_t memory_semantics = inst->word(2);
if (auto error = ValidateMemoryScope(_, inst, memory_scope)) {
return error;
}
if (auto error = ValidateMemorySemantics(_, inst, memory_semantics)) {
return error;
}
break;
}
case SpvOpNamedBarrierInitialize: {
if (_.GetIdOpcode(result_type) != SpvOpTypeNamedBarrier) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< spvOpcodeString(opcode)
<< ": expected Result Type to be OpTypeNamedBarrier";
}
const uint32_t subgroup_count_type = _.GetOperandTypeId(inst, 2);
if (!_.IsIntScalarType(subgroup_count_type) ||
_.GetBitWidth(subgroup_count_type) != 32) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< spvOpcodeString(opcode)
<< ": expected Subgroup Count to be a 32-bit int";
}
break;
}
case SpvOpMemoryNamedBarrier: {
const uint32_t named_barrier_type = _.GetOperandTypeId(inst, 0);
if (_.GetIdOpcode(named_barrier_type) != SpvOpTypeNamedBarrier) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< spvOpcodeString(opcode)
<< ": expected Named Barrier to be of type OpTypeNamedBarrier";
}
const uint32_t memory_scope = inst->word(2);
const uint32_t memory_semantics = inst->word(3);
if (auto error = ValidateMemoryScope(_, inst, memory_scope)) {
return error;
}
if (auto error = ValidateMemorySemantics(_, inst, memory_semantics)) {
return error;
}
break;
}
default:
break;
}
return SPV_SUCCESS;
}
} // namespace val
} // namespace spvtools
| 10,338
| 3,237
|
/** @file
A brief file description
@section license License
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.
*/
/**************************************************************************
ink_hrtime.cc
This file contains code supporting the Inktomi high-resolution timer.
**************************************************************************/
#include "tscore/ink_hrtime.h"
#include "tscore/ink_assert.h"
#include "tscore/ink_defs.h"
#if defined(freebsd)
#include <sys/types.h>
#include <sys/param.h>
#ifdef HAVE_SYS_SYSCTL_H
#include <sys/sysctl.h>
#endif
#endif
#include <cstring>
#include <sys/time.h>
char *
int64_to_str(char *buf, unsigned int buf_size, int64_t val, unsigned int *total_chars, unsigned int req_width, char pad_char)
{
const unsigned int local_buf_size = 32;
char local_buf[local_buf_size];
bool using_local_buffer = false;
bool negative = false;
char *out_buf;
if (buf_size < 22) {
// int64_t may not fit in provided buffer, use the local one
out_buf = &local_buf[local_buf_size - 1];
using_local_buffer = true;
} else {
out_buf = &buf[buf_size - 1];
}
unsigned int num_chars = 1; // includes eos
*out_buf-- = 0;
if (val < 0) {
val = -val;
negative = true;
}
if (val < 10) {
*out_buf-- = '0' + static_cast<char>(val);
++num_chars;
} else {
do {
*out_buf-- = static_cast<char>(val % 10) + '0';
val /= 10;
++num_chars;
} while (val);
}
// pad with pad_char if needed
//
if (req_width) {
// add minus sign if padding character is not 0
if (negative && pad_char != '0') {
*out_buf = '-';
++num_chars;
} else {
out_buf++;
}
if (req_width > buf_size) {
req_width = buf_size;
}
unsigned int num_padding = 0;
if (req_width > num_chars) {
num_padding = req_width - num_chars;
switch (num_padding) {
case 3:
*--out_buf = pad_char;
// fallthrough
case 2:
*--out_buf = pad_char;
// fallthrough
case 1:
*--out_buf = pad_char;
break;
default:
for (unsigned int i = 0; i < num_padding; ++i, *--out_buf = pad_char) {
;
}
}
num_chars += num_padding;
}
// add minus sign if padding character is 0
if (negative && pad_char == '0') {
if (num_padding) {
*out_buf = '-'; // overwrite padding
} else {
*--out_buf = '-';
++num_chars;
}
}
} else if (negative) {
*out_buf = '-';
++num_chars;
} else {
out_buf++;
}
if (using_local_buffer) {
if (num_chars <= buf_size) {
memcpy(buf, out_buf, num_chars);
out_buf = buf;
} else {
// data does not fit return nullptr
out_buf = nullptr;
}
}
if (total_chars) {
*total_chars = num_chars;
}
return out_buf;
}
int
squid_timestamp_to_buf(char *buf, unsigned int buf_size, long timestamp_sec, long timestamp_usec)
{
int res;
const unsigned int tmp_buf_size = 32;
char tmp_buf[tmp_buf_size];
unsigned int num_chars_s;
char *ts_s = int64_to_str(tmp_buf, tmp_buf_size - 4, timestamp_sec, &num_chars_s, 0, '0');
ink_assert(ts_s);
// convert milliseconds
//
tmp_buf[tmp_buf_size - 5] = '.';
int ms = timestamp_usec / 1000;
unsigned int num_chars_ms;
char ATS_UNUSED *ts_ms = int64_to_str(&tmp_buf[tmp_buf_size - 4], 4, ms, &num_chars_ms, 4, '0');
ink_assert(ts_ms && num_chars_ms == 4);
unsigned int chars_to_write = num_chars_s + 3; // no eos
if (buf_size >= chars_to_write) {
memcpy(buf, ts_s, chars_to_write);
res = chars_to_write;
} else {
res = -(static_cast<int>(chars_to_write));
}
return res;
}
#ifdef USE_TIME_STAMP_COUNTER_HRTIME
uint32_t
init_hrtime_TCS()
{
int freqlen = sizeof(hrtime_freq);
if (sysctlbyname("machdep.tsc_freq", &hrtime_freq, (size_t *)&freqlen, nullptr, 0) < 0) {
perror("sysctl: machdep.tsc_freq");
exit(1);
}
hrtime_freq_float = (double)1000000000 / (double)hrtime_freq;
return hrtime_freq;
}
double hrtime_freq_float = 0.5; // 500 Mhz
uint32_t hrtime_freq = init_hrtime_TCS();
#endif
#ifdef NEED_HRTIME_BASIS
timespec timespec_basis;
ink_hrtime hrtime_offset;
ink_hrtime hrtime_basis = init_hrtime_basis();
ink_hrtime
init_hrtime_basis()
{
ink_hrtime t1, t2, b, now;
timespec ts;
#ifdef USE_TIME_STAMP_COUNTER_HRTIME
init_hrtime_TCS();
#endif
do {
t1 = ink_get_hrtime_internal();
#if HAVE_CLOCK_GETTIME
ink_assert(!clock_gettime(CLOCK_REALTIME, ×pec_basis));
#else
{
struct timeval tnow;
ink_assert(!gettimeofday(&tnow, nullptr));
timespec_basis.tv_sec = tnow.tv_sec;
timespec_basis.tv_nsec = tnow.tv_usec * 1000;
}
#endif
t2 = ink_get_hrtime_internal();
// accuracy must be at least 100 microseconds
} while (t2 - t1 > HRTIME_USECONDS(100));
b = (t2 + t1) / 2;
now = ink_hrtime_from_timespec(×pec_basis);
ts = ink_hrtime_to_timespec(now);
ink_assert(ts.tv_sec == timespec_basis.tv_sec && ts.tv_nsec == timespec_basis.tv_nsec);
hrtime_offset = now - b;
hrtime_basis = b;
return b;
}
#endif
| 5,940
| 2,302
|
// Distributed under the MIT License.
// See LICENSE.txt for details.
#pragma once
#include <algorithm> // IWYU pragma: keep // for std::fill
#include <array>
#include <cstddef>
#include <cstdlib>
#include <cstring>
#include <functional> // IWYU pragma: keep // for std::plus, etc.
#include <initializer_list>
#include <limits>
#include <memory>
#include <ostream>
#include <pup.h>
#include <type_traits>
#include "ErrorHandling/Assert.hpp"
#include "Utilities/ForceInline.hpp"
#include "Utilities/Gsl.hpp"
#include "Utilities/MakeWithValue.hpp" // IWYU pragma: keep
#include "Utilities/PointerVector.hpp" // IWYU pragma: keep
#include "Utilities/PrintHelpers.hpp"
#include "Utilities/Requires.hpp"
#include "Utilities/StdArrayHelpers.hpp"
#include "Utilities/TypeTraits/IsComplexOfFundamental.hpp"
/*!
* \ingroup DataStructuresGroup
* \brief Base class template for various DataVector and related types
*
* \details The `VectorImpl` class is the generic parent class for vectors
* representing collections of related function values, such as `DataVector`s
* for contiguous data over a computational domain.
*
* The `VectorImpl` does not itself define any particular mathematical
* operations on the contained values. The `VectorImpl` template class and the
* macros defined in `VectorImpl.hpp` assist in the construction of various
* derived classes supporting a chosen set of mathematical operations.
*
* In addition, the equivalence operator `==` is inherited from the underlying
* `PointerVector` type, and returns true if and only if the size and contents
* of the two compared vectors are equivalent.
*
* Template parameters:
* - `T` is the underlying stored type, e.g. `double`, `std::complex<double>`,
* `float`, etc.
* - `VectorType` is the type that should be associated with the VectorImpl
* during mathematical computations. In most cases, inherited types should
* have themselves as the second template argument, e.g.
* ```
* class DataVector : VectorImpl<double, DataVector> {
* ```
* The second template parameter communicates arithmetic type restrictions to
* the underlying Blaze framework. For example, if `VectorType` is
* `DataVector`, then the underlying architecture will prevent addition with a
* vector type whose `ResultType` (which is aliased to its `VectorType`) is
* `ModalVector`. Since `DataVector`s and `ModalVector`s represent data in
* different spaces, we wish to forbid several operations between them. This
* vector-type-tracking through an expression prevents accidental mixing of
* vector types in math expressions.
*
* \note
* - If created with size 0, then `data()` will return `nullptr`
* - If either `SPECTRE_DEBUG` or `SPECTRE_NAN_INIT` are defined, then the
* `VectorImpl` is default initialized to `signaling_NaN()`. Otherwise, the
* vector is filled with uninitialized memory for performance.
*/
template <typename T, typename VectorType>
class VectorImpl
: public PointerVector<T, blaze_unaligned, blaze_unpadded,
blaze::defaultTransposeFlag, VectorType> {
public:
using value_type = T;
using size_type = size_t;
using difference_type = std::ptrdiff_t;
using BaseType = PointerVector<T, blaze::unaligned, blaze::unpadded,
blaze::defaultTransposeFlag, VectorType>;
static constexpr bool transpose_flag = blaze::defaultTransposeFlag;
using ElementType = T;
using TransposeType = VectorImpl<T, VectorType>;
using CompositeType = const VectorImpl<T, VectorType>&;
using iterator = typename BaseType::Iterator;
using const_iterator = typename BaseType::ConstIterator;
using BaseType::operator[];
using BaseType::begin;
using BaseType::cbegin;
using BaseType::cend;
using BaseType::data;
using BaseType::end;
using BaseType::size;
// @{
/// Upcast to `BaseType`
/// \attention
/// upcast should only be used when implementing a derived vector type, not in
/// calling code
const BaseType& operator~() const noexcept {
return static_cast<const BaseType&>(*this);
}
BaseType& operator~() noexcept { return static_cast<BaseType&>(*this); }
// @}
/// Create with the given size. In debug mode, the vector is initialized to
/// 'NaN' by default. If not initialized to 'NaN', the memory is allocated but
/// not initialized.
///
/// - `set_size` number of values
explicit VectorImpl(size_t set_size) noexcept
: owned_data_(set_size > 0 ? static_cast<value_type*>(
malloc(set_size * sizeof(value_type)))
: nullptr,
&free) {
#if defined(SPECTRE_DEBUG) || defined(SPECTRE_NAN_INIT)
std::fill(owned_data_.get(), owned_data_.get() + set_size,
std::numeric_limits<value_type>::signaling_NaN());
#endif // SPECTRE_DEBUG
reset_pointer_vector(set_size);
}
/// Create with the given size and value.
///
/// - `set_size` number of values
/// - `value` the value to initialize each element
VectorImpl(size_t set_size, T value) noexcept
: owned_data_(set_size > 0 ? static_cast<value_type*>(
malloc(set_size * sizeof(value_type)))
: nullptr,
&free) {
std::fill(owned_data_.get(), owned_data_.get() + set_size, value);
reset_pointer_vector(set_size);
}
/// Create a non-owning VectorImpl that points to `start`
VectorImpl(T* start, size_t set_size) noexcept
: BaseType(start, set_size), owning_(false) {}
/// Create from an initializer list of `T`.
template <class U, Requires<std::is_same_v<U, T>> = nullptr>
VectorImpl(std::initializer_list<U> list) noexcept
: owned_data_(list.size() > 0 ? static_cast<value_type*>(malloc(
list.size() * sizeof(value_type)))
: nullptr,
&free) {
// Note: can't use memcpy with an initializer list.
std::copy(list.begin(), list.end(), owned_data_.get());
reset_pointer_vector(list.size());
}
/// Empty VectorImpl
VectorImpl() = default;
/// \cond HIDDEN_SYMBOLS
~VectorImpl() = default;
VectorImpl(const VectorImpl<T, VectorType>& rhs) noexcept;
VectorImpl& operator=(const VectorImpl<T, VectorType>& rhs) noexcept;
VectorImpl(VectorImpl<T, VectorType>&& rhs) noexcept;
VectorImpl& operator=(VectorImpl<T, VectorType>&& rhs) noexcept;
// This is a converting constructor. clang-tidy complains that it's not
// explicit, but we want it to allow conversion.
// clang-tidy: mark as explicit (we want conversion to VectorImpl type)
template <
typename VT, bool VF,
Requires<std::is_same_v<typename VT::ResultType, VectorType>> = nullptr>
VectorImpl(const blaze::DenseVector<VT, VF>& expression) noexcept; // NOLINT
template <typename VT, bool VF>
VectorImpl& operator=(const blaze::DenseVector<VT, VF>& expression) noexcept;
/// \endcond
VectorImpl& operator=(const T& rhs) noexcept;
// @{
/// Set the VectorImpl to be a reference to another VectorImpl object
void set_data_ref(gsl::not_null<VectorType*> rhs) noexcept {
set_data_ref(rhs->data(), rhs->size());
}
void set_data_ref(T* const start, const size_t set_size) noexcept {
owned_data_.reset();
(~*this).reset(start, set_size);
owning_ = false;
}
// @}
/*!
* \brief A common operation for checking the size and resizing a memory
* buffer if needed to ensure that it has the desired size. This operation is
* not permitted on a non-owning vector.
*
* \note This utility should NOT be used when it is anticipated that the
* supplied buffer will typically be the wrong size (in that case, suggest
* either manual checking or restructuring so that resizing is less common).
* This uses `UNLIKELY` to perform the check most quickly when the buffer
* needs no resizing, but will be slower when resizing is common.
*/
void SPECTRE_ALWAYS_INLINE
destructive_resize(const size_t new_size) noexcept {
if (UNLIKELY(size() != new_size)) {
if (owning_) {
// NOLINTNEXTLINE(modernize-avoid-c-arrays)
owned_data_ = std::unique_ptr<value_type[], decltype(&free)>{
new_size > 0 ? static_cast<value_type*>(
malloc(new_size * sizeof(value_type)))
: nullptr,
&free};
reset_pointer_vector(new_size);
} else {
ERROR("may not destructively resize a non-owning vector");
}
}
}
/// Returns true if the class owns the data
bool is_owning() const noexcept { return owning_; }
/// Serialization for Charm++
// clang-tidy: google-runtime-references
void pup(PUP::er& p) noexcept; // NOLINT
protected:
// NOLINTNEXTLINE(modernize-avoid-c-arrays)
std::unique_ptr<value_type[], decltype(&free)> owned_data_{nullptr, &free};
bool owning_{true};
SPECTRE_ALWAYS_INLINE void reset_pointer_vector(
const size_t set_size) noexcept {
this->reset(owned_data_.get(), set_size);
}
};
template <typename T, typename VectorType>
VectorImpl<T, VectorType>::VectorImpl(
const VectorImpl<T, VectorType>& rhs) noexcept
: BaseType{rhs},
owned_data_(rhs.size() > 0 ? static_cast<value_type*>(
malloc(rhs.size() * sizeof(value_type)))
: nullptr,
&free) {
reset_pointer_vector(rhs.size());
std::memcpy(data(), rhs.data(), size() * sizeof(value_type));
}
template <typename T, typename VectorType>
VectorImpl<T, VectorType>& VectorImpl<T, VectorType>::operator=(
const VectorImpl<T, VectorType>& rhs) noexcept {
if (this != &rhs) {
if (owning_) {
if (size() != rhs.size()) {
owned_data_.reset(rhs.size() > 0 ? static_cast<value_type*>(malloc(
rhs.size() * sizeof(value_type)))
: nullptr);
}
reset_pointer_vector(rhs.size());
} else {
ASSERT(rhs.size() == size(), "Must copy into same size, not "
<< rhs.size() << " into " << size());
}
std::memcpy(data(), rhs.data(), size() * sizeof(value_type));
}
return *this;
}
template <typename T, typename VectorType>
VectorImpl<T, VectorType>::VectorImpl(
VectorImpl<T, VectorType>&& rhs) noexcept {
owned_data_ = std::move(rhs.owned_data_);
~*this = ~rhs; // PointerVector is trivially copyable
owning_ = rhs.owning_;
rhs.owning_ = true;
rhs.reset();
}
template <typename T, typename VectorType>
VectorImpl<T, VectorType>& VectorImpl<T, VectorType>::operator=(
VectorImpl<T, VectorType>&& rhs) noexcept {
if (this != &rhs) {
if (owning_) {
owned_data_ = std::move(rhs.owned_data_);
~*this = ~rhs; /* PointerVector is trivially copyable */
owning_ = rhs.owning_;
} else {
ASSERT(rhs.size() == size(), "Must copy into same size, not "
<< rhs.size() << " into " << size());
std::memcpy(data(), rhs.data(), size() * sizeof(value_type));
}
rhs.owning_ = true;
rhs.reset();
}
return *this;
}
/// \cond HIDDEN_SYMBOLS
// This is a converting constructor. clang-tidy complains that it's not
// explicit, but we want it to allow conversion.
// clang-tidy: mark as explicit (we want conversion to VectorImpl)
template <typename T, typename VectorType>
template <typename VT, bool VF,
Requires<std::is_same_v<typename VT::ResultType, VectorType>>>
VectorImpl<T, VectorType>::VectorImpl(
const blaze::DenseVector<VT, VF>& expression) // NOLINT
noexcept
: owned_data_(static_cast<value_type*>(
malloc((~expression).size() * sizeof(value_type))),
&free) {
static_assert(std::is_same_v<typename VT::ResultType, VectorType>,
"You are attempting to assign the result of an expression "
"that is not consistent with the VectorImpl type you are "
"assigning to.");
reset_pointer_vector((~expression).size());
~*this = expression;
}
template <typename T, typename VectorType>
template <typename VT, bool VF>
VectorImpl<T, VectorType>& VectorImpl<T, VectorType>::operator=(
const blaze::DenseVector<VT, VF>& expression) noexcept {
static_assert(std::is_same_v<typename VT::ResultType, VectorType>,
"You are attempting to assign the result of an expression "
"that is not consistent with the VectorImpl type you are "
"assigning to.");
if (owning_ and (~expression).size() != size()) {
owned_data_.reset(static_cast<value_type*>(
// NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
malloc((~expression).size() * sizeof(value_type))));
reset_pointer_vector((~expression).size());
} else if (not owning_) {
ASSERT((~expression).size() == size(), "Must copy into same size, not "
<< (~expression).size()
<< " into " << size());
}
~*this = expression;
return *this;
}
/// \endcond
// The case of assigning a type apart from the same VectorImpl or a
// `blaze::DenseVector` forwards the assignment to the `PointerVector` base
// type. In the case of a single compatible value, this fills the vector with
// that value.
template <typename T, typename VectorType>
VectorImpl<T, VectorType>& VectorImpl<T, VectorType>::operator=(
const T& rhs) noexcept {
~*this = rhs;
return *this;
}
template <typename T, typename VectorType>
void VectorImpl<T, VectorType>::pup(PUP::er& p) noexcept { // NOLINT
auto my_size = size();
p | my_size;
if (my_size > 0) {
if (p.isUnpacking()) {
owning_ = true;
owned_data_.reset(my_size > 0 ? static_cast<value_type*>(
malloc(my_size * sizeof(value_type)))
: nullptr);
reset_pointer_vector(my_size);
}
PUParray(p, data(), size());
}
}
/// Output operator for VectorImpl
template <typename T, typename VectorType>
std::ostream& operator<<(std::ostream& os,
const VectorImpl<T, VectorType>& d) noexcept {
sequence_print_helper(os, d.begin(), d.end());
return os;
}
/*!
* \ingroup DataStructuresGroup
* \brief Instructs Blaze to provide the appropriate vector result type after
* math operations. This is accomplished by specializing Blaze's type traits
* that are used for handling return type deduction and specifying the `using
* Type =` nested type alias in the traits.
*
* \param VECTOR_TYPE The vector type, which matches the type of the operation
* result (e.g. `DataVector`)
*
* \param BLAZE_MATH_TRAIT The blaze trait/expression for which you want to
* specify the return type (e.g. `AddTrait`).
*/
#define BLAZE_TRAIT_SPECIALIZE_BINARY_TRAIT(VECTOR_TYPE, BLAZE_MATH_TRAIT) \
template <> \
struct BLAZE_MATH_TRAIT<VECTOR_TYPE, VECTOR_TYPE> { \
using Type = VECTOR_TYPE; \
}; \
template <> \
struct BLAZE_MATH_TRAIT<VECTOR_TYPE, VECTOR_TYPE::value_type> { \
using Type = VECTOR_TYPE; \
}; \
template <> \
struct BLAZE_MATH_TRAIT<VECTOR_TYPE::value_type, VECTOR_TYPE> { \
using Type = VECTOR_TYPE; \
}
/*!
* \ingroup DataStructuresGroup
* \brief Instructs Blaze to provide the appropriate vector result type of an
* operator between `VECTOR_TYPE` and `COMPATIBLE`, where the operation is
* represented by `BLAZE_MATH_TRAIT`
*
* \param VECTOR_TYPE The vector type, which matches the type of the operation
* result (e.g. `ComplexDataVector`)
*
* \param COMPATIBLE the type for which you want math operations to work with
* `VECTOR_TYPE` smoothly (e.g. `DataVector`)
*
* \param BLAZE_MATH_TRAIT The blaze trait for which you want declare the Type
* field (e.g. `AddTrait`)
*
* \param RESULT_TYPE The type which should be used as the 'return' type for the
* binary operation
*/
#define BLAZE_TRAIT_SPECIALIZE_COMPATIBLE_BINARY_TRAIT( \
VECTOR_TYPE, COMPATIBLE, BLAZE_MATH_TRAIT, RESULT_TYPE) \
template <> \
struct BLAZE_MATH_TRAIT<VECTOR_TYPE, COMPATIBLE> { \
using Type = RESULT_TYPE; \
}; \
template <> \
struct BLAZE_MATH_TRAIT<COMPATIBLE, VECTOR_TYPE> { \
using Type = RESULT_TYPE; \
}
/*!
* \ingroup DataStructuresGroup
* \brief Instructs Blaze to provide the appropriate vector result type of
* arithmetic operations for `VECTOR_TYPE`. This is accomplished by specializing
* Blaze's type traits that are used for handling return type deduction.
*
* \details Type definitions here are suitable for contiguous data
* (e.g. `DataVector`), but this macro might need to be tweaked for other types
* of data, for instance Fourier coefficients.
*
* \param VECTOR_TYPE The vector type, which for the arithmetic operations is
* the type of the operation result (e.g. `DataVector`)
*/
#define VECTOR_BLAZE_TRAIT_SPECIALIZE_ARITHMETIC_TRAITS(VECTOR_TYPE) \
template <> \
struct IsVector<VECTOR_TYPE> : std::true_type {}; \
template <> \
struct TransposeFlag<VECTOR_TYPE> \
: BoolConstant<VECTOR_TYPE::transpose_flag> {}; \
BLAZE_TRAIT_SPECIALIZE_BINARY_TRAIT(VECTOR_TYPE, AddTrait); \
BLAZE_TRAIT_SPECIALIZE_BINARY_TRAIT(VECTOR_TYPE, SubTrait); \
BLAZE_TRAIT_SPECIALIZE_BINARY_TRAIT(VECTOR_TYPE, MultTrait); \
BLAZE_TRAIT_SPECIALIZE_BINARY_TRAIT(VECTOR_TYPE, DivTrait)
/*!
* \ingroup DataStructuresGroup
* \brief Instructs Blaze to provide the appropriate vector result type of `Map`
* operations (unary and binary) acting on `VECTOR_TYPE`. This is accomplished
* by specializing Blaze's type traits that are used for handling return type
* deduction.
*
* \details Type declarations here are suitable for contiguous data (e.g.
* `DataVector`), but this macro might need to be tweaked for other types of
* data, for instance Fourier coefficients.
*
* \param VECTOR_TYPE The vector type, which for the `Map` operations is
* the type of the operation result (e.g. `DataVector`)
*/
#define VECTOR_BLAZE_TRAIT_SPECIALIZE_ALL_MAP_TRAITS(VECTOR_TYPE) \
template <typename Operator> \
struct MapTrait<VECTOR_TYPE, Operator> { \
using Type = VECTOR_TYPE; \
}; \
template <typename Operator> \
struct MapTrait<VECTOR_TYPE, VECTOR_TYPE, Operator> { \
using Type = VECTOR_TYPE; \
}
/*!
* \ingroup DataStructuresGroup
* \brief Defines the set of binary operations often supported for
* `std::array<VECTOR_TYPE, size>`, for arbitrary `size`.
*
* \param VECTOR_TYPE The vector type (e.g. `DataVector`)
*/
#define MAKE_STD_ARRAY_VECTOR_BINOPS(VECTOR_TYPE) \
DEFINE_STD_ARRAY_BINOP(VECTOR_TYPE, VECTOR_TYPE::value_type, \
VECTOR_TYPE, operator+, std::plus<>()) \
DEFINE_STD_ARRAY_BINOP(VECTOR_TYPE, VECTOR_TYPE, \
VECTOR_TYPE::value_type, operator+, std::plus<>()) \
DEFINE_STD_ARRAY_BINOP(VECTOR_TYPE, VECTOR_TYPE, VECTOR_TYPE, operator+, \
std::plus<>()) \
\
DEFINE_STD_ARRAY_BINOP(VECTOR_TYPE, VECTOR_TYPE::value_type, \
VECTOR_TYPE, operator-, std::minus<>()) \
DEFINE_STD_ARRAY_BINOP(VECTOR_TYPE, VECTOR_TYPE, \
VECTOR_TYPE::value_type, operator-, std::minus<>()) \
DEFINE_STD_ARRAY_BINOP(VECTOR_TYPE, VECTOR_TYPE, VECTOR_TYPE, operator-, \
std::minus<>()) \
\
DEFINE_STD_ARRAY_INPLACE_BINOP(VECTOR_TYPE, VECTOR_TYPE, operator-=, \
std::minus<>()) \
DEFINE_STD_ARRAY_INPLACE_BINOP( \
VECTOR_TYPE, VECTOR_TYPE::value_type, operator-=, std::minus<>()) \
DEFINE_STD_ARRAY_INPLACE_BINOP(VECTOR_TYPE, VECTOR_TYPE, operator+=, \
std::plus<>()) \
DEFINE_STD_ARRAY_INPLACE_BINOP( \
VECTOR_TYPE, VECTOR_TYPE::value_type, operator+=, std::plus<>())
/*!
* \ingroup DataStructuresGroup
* \brief Defines `MAKE_MATH_ASSIGN_EXPRESSION_POINTERVECTOR` with all
* assignment arithmetic operations
*
* \param VECTOR_TYPE The vector type (e.g. `DataVector`)
*/
#define MAKE_MATH_ASSIGN_EXPRESSION_ARITHMETIC(VECTOR_TYPE) \
MAKE_MATH_ASSIGN_EXPRESSION_POINTERVECTOR(+=, VECTOR_TYPE) \
MAKE_MATH_ASSIGN_EXPRESSION_POINTERVECTOR(-=, VECTOR_TYPE) \
MAKE_MATH_ASSIGN_EXPRESSION_POINTERVECTOR(*=, VECTOR_TYPE) \
MAKE_MATH_ASSIGN_EXPRESSION_POINTERVECTOR(/=, VECTOR_TYPE)
/*!
* \ingroup DataStructuresGroup
* \brief Defines the `MakeWithValueImpl` `apply` specialization
*
* \details The `MakeWithValueImpl<VECTOR_TYPE, VECTOR_TYPE>` member
* `apply(VECTOR_TYPE, VECTOR_TYPE::value_type)` specialization defined by this
* macro produces an object with the same size as the `input` argument,
* initialized with the `value` argument in every entry.
*
* \param VECTOR_TYPE The vector type (e.g. `DataVector`)
*/
#define MAKE_WITH_VALUE_IMPL_DEFINITION_FOR(VECTOR_TYPE) \
namespace MakeWithValueImpls { \
template <> \
struct MakeWithValueImpl<VECTOR_TYPE, VECTOR_TYPE> { \
static SPECTRE_ALWAYS_INLINE VECTOR_TYPE \
apply(const VECTOR_TYPE& input, \
const VECTOR_TYPE::value_type value) noexcept { \
return VECTOR_TYPE(input.size(), value); \
} \
}; \
template <> \
struct MakeWithValueImpl<VECTOR_TYPE, size_t> { \
static SPECTRE_ALWAYS_INLINE VECTOR_TYPE \
apply(const size_t size, const VECTOR_TYPE::value_type value) noexcept { \
return VECTOR_TYPE(size, value); \
} \
}; \
} // namespace MakeWithValueImpls
// {@
/*!
* \ingroup DataStructuresGroup
* \ingroup TypeTraitsGroup
* \brief Helper struct to determine the element type of a VectorImpl or
* container of VectorImpl
*
* \details Extracts the element type of a `VectorImpl`, a std::array of
* `VectorImpl`, or a reference or pointer to a `VectorImpl`. In any of these
* cases, the `type` member is defined as the `ElementType` of the `VectorImpl`
* in question. If, instead, `get_vector_element_type` is passed an arithmetic
* or complex arithemetic type, the `type` member is defined as the passed type.
*
* \snippet DataStructures/Test_VectorImpl.cpp get_vector_element_type_example
*/
// cast to bool needed to avoid the compiler mistaking the type to be determined
// by T
template <typename T,
bool = static_cast<bool>(tt::is_complex_of_fundamental_v<T> or
std::is_fundamental_v<T>)>
struct get_vector_element_type;
template <typename T>
struct get_vector_element_type<T, true> {
using type = T;
};
template <typename T>
struct get_vector_element_type<const T, false> {
using type = typename get_vector_element_type<T>::type;
};
template <typename T>
struct get_vector_element_type<T, false> {
using type = typename get_vector_element_type<
typename T::ResultType::ElementType>::type;
};
template <typename T>
struct get_vector_element_type<T*, false> {
using type = typename get_vector_element_type<T>::type;
};
template <typename T>
struct get_vector_element_type<T&, false> {
using type = typename get_vector_element_type<T>::type;
};
template <typename T, size_t S>
struct get_vector_element_type<std::array<T, S>, false> {
using type = typename get_vector_element_type<T>::type;
};
// @}
template <typename T>
using get_vector_element_type_t = typename get_vector_element_type<T>::type;
namespace detail {
template <typename... VectorImplTemplateArgs>
std::true_type is_derived_of_vector_impl_impl(
const VectorImpl<VectorImplTemplateArgs...>*);
std::false_type is_derived_of_vector_impl_impl(...);
} // namespace detail
/// \ingroup TypeTraitsGroup
/// This is `std::true_type` if the provided type possesses an implicit
/// conversion to any `VectorImpl`, which is the primary feature of SpECTRE
/// vectors generally. Otherwise, it is `std::false_type`.
template <typename T>
using is_derived_of_vector_impl =
decltype(detail::is_derived_of_vector_impl_impl(std::declval<T*>()));
template <typename T>
constexpr bool is_derived_of_vector_impl_v =
is_derived_of_vector_impl<T>::value;
/// \ingroup DataStructuresGroup
/// Make the input `view` a `const` view of the const data `vector`, at
/// offset `offset` and length `extent`.
///
/// \warning This DOES modify the (const) input `view`. The reason `view` is
/// taken by const pointer is to try to insist that the object to be a `const`
/// view is actually const. Of course, there are ways of subverting this
/// intended functionality and editing the data pointed into by `view` after
/// this function is called; doing so is highly discouraged and results in
/// undefined behavior.
template <typename VectorType,
Requires<is_derived_of_vector_impl_v<VectorType>> = nullptr>
void make_const_view(const gsl::not_null<const VectorType*> view,
const VectorType& vector, const size_t offset,
const size_t extent) noexcept {
const_cast<VectorType*>(view.get()) // NOLINT
->set_data_ref(
const_cast<typename VectorType::value_type*>(vector.data()) // NOLINT
+ offset, // NOLINT
extent);
}
| 27,665
| 8,311
|
/*
* Copyright 2016 The Cartographer Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 "cartographer/mapping/internal/2d/scan_matching/real_time_correlative_scan_matcher_2d.h"
#include <cmath>
#include <memory>
#include "Eigen/Geometry"
#include "absl/memory/memory.h"
#include "cartographer/common/internal/testing/lua_parameter_dictionary_test_helpers.h"
#include "cartographer/mapping/2d/probability_grid.h"
#include "cartographer/mapping/2d/probability_grid_range_data_inserter_2d.h"
#include "cartographer/mapping/internal/2d/tsdf_2d.h"
#include "cartographer/mapping/internal/2d/tsdf_range_data_inserter_2d.h"
#include "cartographer/mapping/internal/scan_matching/real_time_correlative_scan_matcher.h"
#include "cartographer/sensor/point_cloud.h"
#include "cartographer/transform/transform.h"
#include "gtest/gtest.h"
namespace cartographer {
namespace mapping {
namespace scan_matching {
namespace {
proto::RealTimeCorrelativeScanMatcherOptions
CreateRealTimeCorrelativeScanMatcherTestOptions2D() {
auto parameter_dictionary = common::MakeDictionary(
"return {"
"linear_search_window = 0.6, "
"angular_search_window = 0.16, "
"translation_delta_cost_weight = 0., "
"rotation_delta_cost_weight = 0., "
"}");
return CreateRealTimeCorrelativeScanMatcherOptions(
parameter_dictionary.get());
}
class RealTimeCorrelativeScanMatcherTest : public ::testing::Test {
protected:
RealTimeCorrelativeScanMatcherTest() {
Eigen::Vector3f origin(0.5f, -0.5f, 0.f);
point_cloud_.push_back({Eigen::Vector3f{0.025f, 0.175f, 0.f}, origin});
point_cloud_.push_back({Eigen::Vector3f{-0.025f, 0.175f, 0.f}, origin});
point_cloud_.push_back({Eigen::Vector3f{-0.075f, 0.175f, 0.f}, origin});
point_cloud_.push_back({Eigen::Vector3f{-0.125f, 0.175f, 0.f}, origin});
point_cloud_.push_back({Eigen::Vector3f{-0.125f, 0.125f, 0.f}, origin});
point_cloud_.push_back({Eigen::Vector3f{-0.125f, 0.075f, 0.f}, origin});
point_cloud_.push_back({Eigen::Vector3f{-0.125f, 0.025f, 0.f}, origin});
real_time_correlative_scan_matcher_ =
absl::make_unique<RealTimeCorrelativeScanMatcher2D>(
CreateRealTimeCorrelativeScanMatcherTestOptions2D());
}
void SetUpTSDF() {
grid_ = absl::make_unique<TSDF2D>(
MapLimits(0.05, Eigen::Vector2d(0.3, 0.5), CellLimits(20, 20)), 0.3,
1.0, &conversion_tables_);
{
auto parameter_dictionary = common::MakeDictionary(R"text(
return {
truncation_distance = 0.3,
maximum_weight = 10.,
update_free_space = false,
normal_estimation_options = {
num_normal_samples = 4,
sample_radius = 0.5,
},
project_sdf_distance_to_scan_normal = true,
update_weight_range_exponent = 0,
update_weight_angle_scan_normal_to_ray_kernel_bandwidth = 0.5,
update_weight_distance_cell_to_hit_kernel_bandwidth = 0.5,
})text");
range_data_inserter_ = absl::make_unique<TSDFRangeDataInserter2D>(
CreateTSDFRangeDataInserterOptions2D(parameter_dictionary.get()));
}
range_data_inserter_->Insert(
sensor::RangeData{point_cloud_.begin()->origin, point_cloud_, {}},
grid_.get());
grid_->FinishUpdate();
}
void SetUpProbabilityGrid() {
grid_ = absl::make_unique<ProbabilityGrid>(
MapLimits(0.05, Eigen::Vector2d(0.05, 0.25), CellLimits(6, 6)),
&conversion_tables_);
{
auto parameter_dictionary = common::MakeDictionary(
"return { "
"insert_free_space = true, "
"hit_probability = 0.7, "
"miss_probability = 0.4, "
"}");
range_data_inserter_ =
absl::make_unique<ProbabilityGridRangeDataInserter2D>(
CreateProbabilityGridRangeDataInserterOptions2D(
parameter_dictionary.get()));
}
range_data_inserter_->Insert(
sensor::RangeData{point_cloud_.begin()->origin, point_cloud_, {}},
grid_.get());
grid_->FinishUpdate();
}
ValueConversionTables conversion_tables_;
std::unique_ptr<Grid2D> grid_;
std::unique_ptr<RangeDataInserterInterface> range_data_inserter_;
sensor::PointCloud point_cloud_;
std::unique_ptr<RealTimeCorrelativeScanMatcher2D>
real_time_correlative_scan_matcher_;
};
TEST_F(RealTimeCorrelativeScanMatcherTest,
ScorePerfectHighResolutionCandidateProbabilityGrid) {
SetUpProbabilityGrid();
const std::vector<sensor::PointCloud> scans =
GenerateRotatedScans(point_cloud_, SearchParameters(0, 0, 0., 0.));
const std::vector<DiscreteScan2D> discrete_scans =
DiscretizeScans(grid_->limits(), scans, Eigen::Translation2f::Identity());
std::vector<Candidate2D> candidates;
candidates.emplace_back(0, 0, 0, SearchParameters(0, 0, 0., 0.));
real_time_correlative_scan_matcher_->ScoreCandidates(
*grid_, discrete_scans, SearchParameters(0, 0, 0., 0.), &candidates);
EXPECT_EQ(0, candidates[0].scan_index);
EXPECT_EQ(0, candidates[0].x_index_offset);
EXPECT_EQ(0, candidates[0].y_index_offset);
// Every point should align perfectly.
EXPECT_NEAR(0.7, candidates[0].score, 1e-2);
}
TEST_F(RealTimeCorrelativeScanMatcherTest,
ScorePerfectHighResolutionCandidateTSDF) {
SetUpTSDF();
const std::vector<sensor::PointCloud> scans =
GenerateRotatedScans(point_cloud_, SearchParameters(0, 0, 0., 0.));
const std::vector<DiscreteScan2D> discrete_scans =
DiscretizeScans(grid_->limits(), scans, Eigen::Translation2f::Identity());
std::vector<Candidate2D> candidates;
candidates.emplace_back(0, 0, 0, SearchParameters(0, 0, 0., 0.));
real_time_correlative_scan_matcher_->ScoreCandidates(
*grid_, discrete_scans, SearchParameters(0, 0, 0., 0.), &candidates);
EXPECT_EQ(0, candidates[0].scan_index);
EXPECT_EQ(0, candidates[0].x_index_offset);
EXPECT_EQ(0, candidates[0].y_index_offset);
// Every point should align perfectly.
EXPECT_NEAR(1.0, candidates[0].score, 1e-1);
EXPECT_LT(0.95, candidates[0].score);
}
TEST_F(RealTimeCorrelativeScanMatcherTest,
ScorePartiallyCorrectHighResolutionCandidateProbabilityGrid) {
SetUpProbabilityGrid();
const std::vector<sensor::PointCloud> scans =
GenerateRotatedScans(point_cloud_, SearchParameters(0, 0, 0., 0.));
const std::vector<DiscreteScan2D> discrete_scans =
DiscretizeScans(grid_->limits(), scans, Eigen::Translation2f::Identity());
std::vector<Candidate2D> candidates;
candidates.emplace_back(0, 0, 1, SearchParameters(0, 0, 0., 0.));
real_time_correlative_scan_matcher_->ScoreCandidates(
*grid_, discrete_scans, SearchParameters(0, 0, 0., 0.), &candidates);
EXPECT_EQ(0, candidates[0].scan_index);
EXPECT_EQ(0, candidates[0].x_index_offset);
EXPECT_EQ(1, candidates[0].y_index_offset);
// 3 points should align perfectly.
EXPECT_LT(0.7 * 3. / 7., candidates[0].score);
EXPECT_GT(0.7, candidates[0].score);
}
TEST_F(RealTimeCorrelativeScanMatcherTest,
ScorePartiallyCorrectHighResolutionCandidateTSDF) {
SetUpTSDF();
const std::vector<sensor::PointCloud> scans =
GenerateRotatedScans(point_cloud_, SearchParameters(0, 0, 0., 0.));
const std::vector<DiscreteScan2D> discrete_scans =
DiscretizeScans(grid_->limits(), scans, Eigen::Translation2f::Identity());
std::vector<Candidate2D> candidates;
candidates.emplace_back(0, 0, 1, SearchParameters(0, 0, 0., 0.));
real_time_correlative_scan_matcher_->ScoreCandidates(
*grid_, discrete_scans, SearchParameters(0, 0, 0., 0.), &candidates);
EXPECT_EQ(0, candidates[0].scan_index);
EXPECT_EQ(0, candidates[0].x_index_offset);
EXPECT_EQ(1, candidates[0].y_index_offset);
// 3 points should align perfectly.
EXPECT_LT(1.0 - 4. / (7. * 6.), candidates[0].score);
EXPECT_GT(1.0, candidates[0].score);
}
} // namespace
} // namespace scan_matching
} // namespace mapping
} // namespace cartographer
| 8,443
| 3,073
|
//
// Copyright (c) Bryan Berns. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
//
#define UMDF_USING_NTSTATUS
#include <ntstatus.h>
#include <windows.h>
#include <winternl.h>
#include <iostream>
#include <map>
#include <string>
#include <regex>
#include <ntlsa.h>
#include "WinPrivShared.h"
std::map<std::wstring, std::wstring> GetPrivilegeList()
{
// list of privileges to return
std::map<std::wstring, std::wstring> tPrivilegeList;
// object attributes are reserved, so initialize to zeros.
LSA_OBJECT_ATTRIBUTES ObjectAttributes;
ZeroMemory(&ObjectAttributes, sizeof(ObjectAttributes));
// get a handle to the policy object.
NTSTATUS iResult = 0;
LSA_HANDLE policyHandle;
if ((iResult = LsaOpenPolicy(NULL, &ObjectAttributes,
POLICY_VIEW_LOCAL_INFORMATION, &policyHandle)) != STATUS_SUCCESS)
{
// return on error - priv list will be empty
return tPrivilegeList;
}
// enumerate the privileges that are settable
PPOLICY_PRIVILEGE_DEFINITION buffer;
LSA_ENUMERATION_HANDLE enumerationContext = 0;
ULONG countReturned = 0;
while (LsaEnumeratePrivileges(policyHandle, &enumerationContext,
(PVOID *)&buffer, INFINITE, &countReturned) == STATUS_SUCCESS)
{
for (ULONG iPrivIndex = 0; iPrivIndex < countReturned; iPrivIndex++)
{
LPWSTR sDisplayName = nullptr;
DWORD iSize = 0;
DWORD iIden = 0;
// return privilege display name -- call lookup once to get string size
// and then alloc the string on the next call to get the string
if (LookupPrivilegeDisplayName(NULL, (LPWSTR)buffer[iPrivIndex].Name.Buffer, NULL, &iSize, &iIden) == 0 &&
LookupPrivilegeDisplayName(NULL, (LPWSTR)buffer[iPrivIndex].Name.Buffer,
sDisplayName = (LPWSTR)malloc(sizeof(WCHAR) * (++iSize)), &iSize, &iIden) != 0)
{
tPrivilegeList[buffer[iPrivIndex].Name.Buffer] = sDisplayName;
}
// cleanup
if (sDisplayName == nullptr) free(sDisplayName);
}
// cleanup
LsaFreeMemory(buffer);
}
// rights are not available from any enumerated functions so these are manually added
// temporarily disabled since they cannot be managed the same way as privileges
if (false)
{
tPrivilegeList[SE_BATCH_LOGON_NAME] = L"Log on as a batch job";
tPrivilegeList[SE_DENY_BATCH_LOGON_NAME] = L"Deny log on as a batch job";
tPrivilegeList[SE_DENY_INTERACTIVE_LOGON_NAME] = L"Deny log on locally";
tPrivilegeList[SE_DENY_NETWORK_LOGON_NAME] = L"Deny access to this computer from the network";
tPrivilegeList[SE_DENY_REMOTE_INTERACTIVE_LOGON_NAME] = L"Deny log on through Remote Desktop Services";
tPrivilegeList[SE_DENY_SERVICE_LOGON_NAME] = L"Deny log on as a service";
tPrivilegeList[SE_INTERACTIVE_LOGON_NAME] = L"Allow log on locally";
tPrivilegeList[SE_NETWORK_LOGON_NAME] = L"Access this computer from the network";
tPrivilegeList[SE_REMOTE_INTERACTIVE_LOGON_NAME] = L"Allow log on through Remote Desktop Services";
tPrivilegeList[SE_SERVICE_LOGON_NAME] = L"Log on as a service";
}
// cleanup
LsaClose(policyHandle);
return tPrivilegeList;
}
std::wstring GetWinPrivHelp()
{
// a messagebox will garble this help information so simply the help
// for the non-commandline version and defer to commandline for help
if (GetConsoleWindow() == NULL)
{
return std::wstring(PROJECT_NAME) +
L".exe [optional switches] <Command To Execute> \n" +
L"\n" +
L"See WinPrivCmd /Help to view optional switch information.";
}
// command line help
return std::wstring(PROJECT_NAME) +
LR"(.exe [optional switches] <Command To Execute>
WinPriv is system administration utility that alters the runtime behavior of
the specified process and its child processes. It does this by loading a
supplemental library into memory to intercept and alter the behavior of
common low-level functions such as registry and file system operations.
WinPriv can be used for a variety of purposes including testing security
settings without altering system-wide policy, implementing security-related
workarounds on a per-process basis instead of altering system-wide policy, and
taking advantageous of system privileges to perform file system auditing and
reconfiguration.
WinPriv comes in normal version (WinPriv) and a console version (WinPrivCmd).
The behavior of the subprocess is the same regardless of which version is used.
These versions are provided in case the target program is a console program
in which case you will only be able to get its screen output if you use
WinPrivCmd. Similarly, you may not wish to see the console windows when
targeting a non-console program in which case it may be advantageous to use
WinPriv.
Optional Switches
=================
/RegOverride <Registry Key Path> <Value Name> <Data Type> <Data Value>
Specifies a registry value to override. Instead of returning the true
registry value for the specified key path and value name, the value
the value specified in this switch is returned.
Examples:
/RegOverride HKCU\Software\Demo Enabled REG_DWORD 1
/RegOverride HKLM\Software\Demo UserName REG_SZ "James Bond"
/RegBlock <Registry Key Path>
Specified a registry key under which all values will be reported as
non-existent. When the application requests a particular value in the
specified key or one of its subkeys, it will be reported as not found
regardless as to whether it actually exists in the registry.
Examples:
/RegBlock HKCU\Software\Demo
/MacOverride <MAC Address>
Specifies a physical network address that will be returned when the target
application makes a query to the system to provide its MAC addresses. Any
call to GetAdaptersAddresses, GetAdaptersInfo, and NetWkstaTransportEnum
is handled. The hex octets can be delimited by dashes, colons, or nothing.
Examples:
/MacOverride 00-11-22-33-44-66
/HostOverride <Target HostName> <Replacement HostName>
Specifies that any request to obtain the IP address for the specified target
will instead receive the specified replacement IP address. This is done by
intercepting calls to WSALookupServiceNext() which nearly all address
lookups ultimately occur. Be aware due to special security protections,
this will not work for Internet Explorer and programs that use Internet
Explorer libraries but should work for most other processes.
Examples:
/HostOverride google.com yahoo.com
/HostOverride google.com 127.0.0.1
/FipsOn & /FipsOff
This option will turn cause the system to report that Federal Information
Processing System enforcement is turned on or off, regardless of its current
setting on the system. This operation is a convenience option that actually
uses the /RegOverride functionality on the FIPS-related registry key.
/PolicyBlock
This option will cause all registry queries to HKCU\Software\Policies and
HKCU\Software\Policies. This option is convenience option that actually uses
the /RegBlock functionality.
/BypassFileSecurity
This option causes the target process to enable the backup and restore
privileges and alters the way the program access files to take advantage of
this extra privileges. When these privileges are enabled, all access
control lists on the file system are ignored. This allows an administrator
to inspect and alter files without changing permissions or taking ownership.
Effective uses of this option include using command line utilities like
icacls.exe to inspect/alter permissions. Using this with cmd.exe or
powershell.exe also provide a mean to interact with secured areas.
Examples:
Access detailed permissions under 'C:\System Volume Information':
WinPrivCmd.exe /BypassFileSecurity icacls.exe
"C:\System Volume Information" /T
/BreakRemoteLocks
This option attempts to break remote file locks if a file cannot be accessed
because it is opened by another program remotely. For example, this can be
used to allow programs like robocopy to mirror an area where the destination
system has an in-use file. This option will have no effect if the file is
in-use by a program on the same system where WinPriv is executed.
/AdminImpersonate
This option causes any local administrator check using IsUserAnAdmin() or
CheckTokenMembership() to unconditionally succeed regardless if the user is
actually a member of the local administrator group.
/ServerEdition
This option causes the most common operating system version information
functions to indicate the that the system is running a server edition of
the operating system.
/RecordCrypto <Directory>
This option records the data being inputted to common Windows encryption
functions and the data being outputted from common Windows decryption
functions. A separate file will be created for each operation in the
specified directory. If 'SHOW' is specified instead of a directory path,
information is outputted to the console and message boxes, depending of the
type of application.
/SqlConnectShow
This option will display the ODBC connection parameters immediately before
a connection operation occurs.
/SqlConnectSearchReplace <SearchString> <ReplaceString>
This option performs a search / replace on an ODBC connection string prior
to passing it to the connection Open() function. The search string is
parsed as a regular expression.
Examples:
WinPrivCmd.exe /SqlConnectSearchReplace
Provider=SQLOLEDB Provider=SQLNCLI11 LegacyApplication.exe
/MeasureTime
This option measures the execution time of the target process and displays
it to the user.
/ListPrivileges
This option displays of list of available privileges and permissions.
Other Notes & Limitations
=========================
- Multiple switches can be specified in a single command. For example, one
can use multiple /RegBlock and /RegOverride commands to block and override
the specified set of registry key and values on a specified target program.
)";
}
| 10,030
| 2,950
|