hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a39af4e716ccffa5926250b8b89c5aff06e4948f | 27,416 | cc | C++ | storage/browser/blob/blob_builder_from_stream.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | storage/browser/blob/blob_builder_from_stream.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | storage/browser/blob/blob_builder_from_stream.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "storage/browser/blob/blob_builder_from_stream.h"
#include "base/bind.h"
#include "base/containers/span.h"
#include "base/guid.h"
#include "base/metrics/histogram_macros.h"
#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
#include "mojo/public/c/system/types.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
#include "storage/browser/blob/blob_data_item.h"
#include "storage/browser/blob/blob_storage_context.h"
#include "storage/browser/blob/shareable_file_reference.h"
namespace storage {
namespace {
// Size of individual type kBytes items the blob will be build from. The real
// limit is the min of this and limits_.max_bytes_data_item_size.
constexpr size_t kMaxMemoryChunkSize = 512 * 1024;
// Helper for RunCallbackWhenDataPipeReady, called when the watcher signals us.
void OnPipeReady(
mojo::ScopedDataPipeConsumerHandle pipe,
base::OnceCallback<void(mojo::ScopedDataPipeConsumerHandle)> callback,
std::unique_ptr<mojo::SimpleWatcher> watcher,
MojoResult result,
const mojo::HandleSignalsState& state) {
// If no more data can be read we must be done, so invalidate the pipe.
if (!state.readable())
pipe.reset();
std::move(callback).Run(std::move(pipe));
}
// Method that calls a callback when the provided data pipe becomes readable, or
// is closed.
void RunCallbackWhenDataPipeReady(
mojo::ScopedDataPipeConsumerHandle pipe,
base::OnceCallback<void(mojo::ScopedDataPipeConsumerHandle)> callback) {
auto watcher = std::make_unique<mojo::SimpleWatcher>(
FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::AUTOMATIC,
base::SequencedTaskRunnerHandle::Get());
auto* watcher_ptr = watcher.get();
auto raw_pipe = pipe.get();
watcher_ptr->Watch(
raw_pipe, MOJO_HANDLE_SIGNAL_READABLE, MOJO_WATCH_CONDITION_SATISFIED,
base::BindRepeating(&OnPipeReady, base::Passed(std::move(pipe)),
base::Passed(std::move(callback)),
base::Passed(std::move(watcher))));
}
// Helper base-class that reads upto a certain number of bytes from a data pipe.
// Deletes itself when done.
class DataPipeConsumerHelper {
protected:
DataPipeConsumerHelper(
mojo::ScopedDataPipeConsumerHandle pipe,
mojo::PendingAssociatedRemote<blink::mojom::ProgressClient>
progress_client,
uint64_t max_bytes_to_read)
: pipe_(std::move(pipe)),
progress_client_(std::move(progress_client)),
watcher_(FROM_HERE,
mojo::SimpleWatcher::ArmingPolicy::MANUAL,
base::SequencedTaskRunnerHandle::Get()),
max_bytes_to_read_(max_bytes_to_read) {
watcher_.Watch(pipe_.get(), MOJO_HANDLE_SIGNAL_READABLE,
MOJO_WATCH_CONDITION_SATISFIED,
base::BindRepeating(&DataPipeConsumerHelper::DataPipeReady,
base::Unretained(this)));
watcher_.ArmOrNotify();
}
virtual ~DataPipeConsumerHelper() = default;
// Return false if population fails.
virtual bool Populate(base::span<const char> data,
uint64_t bytes_previously_written) = 0;
virtual void InvokeDone(
mojo::ScopedDataPipeConsumerHandle pipe,
mojo::PendingAssociatedRemote<blink::mojom::ProgressClient>
progress_client,
bool success,
uint64_t bytes_written) = 0;
private:
void DataPipeReady(MojoResult result, const mojo::HandleSignalsState& state) {
if (result != MOJO_RESULT_OK) {
// We requested a trap on a condition that can never occur. The state of
// `pipe_` likely changed.
DCHECK_EQ(result, MOJO_RESULT_FAILED_PRECONDITION);
InvokeDone(mojo::ScopedDataPipeConsumerHandle(), PassProgressClient(),
/*success=*/true, current_offset_);
delete this;
return;
}
while (current_offset_ < max_bytes_to_read_) {
const void* data;
uint32_t size;
result = pipe_->BeginReadData(&data, &size, MOJO_READ_DATA_FLAG_NONE);
if (result == MOJO_RESULT_INVALID_ARGUMENT) {
// `pipe_` is not actually a ScopedDataPipeConsumerHandle.
InvokeDone(mojo::ScopedDataPipeConsumerHandle(), PassProgressClient(),
/*success=*/false, /*bytes_written=*/0);
delete this;
return;
}
if (result == MOJO_RESULT_SHOULD_WAIT) {
watcher_.ArmOrNotify();
return;
}
if (result == MOJO_RESULT_FAILED_PRECONDITION) {
// Pipe has closed, so we must be done.
pipe_.reset();
break;
}
DCHECK_EQ(MOJO_RESULT_OK, result);
size = std::min<uint64_t>(size, max_bytes_to_read_ - current_offset_);
if (!Populate(base::make_span(static_cast<const char*>(data), size),
current_offset_)) {
InvokeDone(mojo::ScopedDataPipeConsumerHandle(), PassProgressClient(),
false, current_offset_);
delete this;
return;
}
if (progress_client_)
progress_client_->OnProgress(size);
current_offset_ += size;
result = pipe_->EndReadData(size);
DCHECK_EQ(MOJO_RESULT_OK, result);
}
// Either the pipe closed, or we filled the entire item.
InvokeDone(std::move(pipe_), PassProgressClient(), true, current_offset_);
delete this;
}
mojo::PendingAssociatedRemote<blink::mojom::ProgressClient>
PassProgressClient() {
if (!progress_client_)
return mojo::NullAssociatedRemote();
return progress_client_.Unbind();
}
mojo::ScopedDataPipeConsumerHandle pipe_;
mojo::AssociatedRemote<blink::mojom::ProgressClient> progress_client_;
mojo::SimpleWatcher watcher_;
const uint64_t max_bytes_to_read_;
uint64_t current_offset_ = 0;
};
} // namespace
// Helper class that reads upto a certain number of bytes from a datapipe and
// writes those bytes to a file. When done, or if the pipe is closed, calls its
// callback.
class BlobBuilderFromStream::WritePipeToFileHelper
: public DataPipeConsumerHelper {
public:
using DoneCallback =
base::OnceCallback<void(bool success,
uint64_t bytes_written,
mojo::ScopedDataPipeConsumerHandle pipe,
mojo::PendingAssociatedRemote<
blink::mojom::ProgressClient> progress_client,
const base::Time& modification_time)>;
static void CreateAndAppend(
mojo::ScopedDataPipeConsumerHandle pipe,
mojo::PendingAssociatedRemote<blink::mojom::ProgressClient>
progress_client,
base::FilePath file_path,
uint64_t max_file_size,
DoneCallback callback) {
base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})
->PostTask(
FROM_HERE,
base::BindOnce(
&WritePipeToFileHelper::CreateAndAppendOnFileSequence,
std::move(pipe), std::move(progress_client),
std::move(file_path), max_file_size,
base::SequencedTaskRunnerHandle::Get(), std::move(callback)));
}
static void CreateAndStart(
mojo::ScopedDataPipeConsumerHandle pipe,
mojo::PendingAssociatedRemote<blink::mojom::ProgressClient>
progress_client,
base::File file,
uint64_t max_file_size,
DoneCallback callback) {
base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})
->PostTask(
FROM_HERE,
base::BindOnce(&WritePipeToFileHelper::CreateAndStartOnFileSequence,
std::move(pipe), std::move(progress_client),
std::move(file), max_file_size,
base::SequencedTaskRunnerHandle::Get(),
std::move(callback)));
}
private:
static void CreateAndAppendOnFileSequence(
mojo::ScopedDataPipeConsumerHandle pipe,
mojo::PendingAssociatedRemote<blink::mojom::ProgressClient>
progress_client,
base::FilePath file_path,
uint64_t max_file_size,
scoped_refptr<base::TaskRunner> reply_runner,
DoneCallback callback) {
base::File file(file_path, base::File::FLAG_OPEN | base::File::FLAG_APPEND);
new WritePipeToFileHelper(std::move(pipe), std::move(progress_client),
std::move(file), max_file_size,
std::move(reply_runner), std::move(callback));
}
static void CreateAndStartOnFileSequence(
mojo::ScopedDataPipeConsumerHandle pipe,
mojo::PendingAssociatedRemote<blink::mojom::ProgressClient>
progress_client,
base::File file,
uint64_t max_file_size,
scoped_refptr<base::TaskRunner> reply_runner,
DoneCallback callback) {
new WritePipeToFileHelper(std::move(pipe), std::move(progress_client),
std::move(file), max_file_size,
std::move(reply_runner), std::move(callback));
}
WritePipeToFileHelper(
mojo::ScopedDataPipeConsumerHandle pipe,
mojo::PendingAssociatedRemote<blink::mojom::ProgressClient>
progress_client,
base::File file,
uint64_t max_file_size,
scoped_refptr<base::TaskRunner> reply_runner,
DoneCallback callback)
: DataPipeConsumerHelper(std::move(pipe),
std::move(progress_client),
max_file_size),
file_(std::move(file)),
reply_runner_(std::move(reply_runner)),
callback_(std::move(callback)) {}
bool Populate(base::span<const char> data,
uint64_t bytes_previously_written) override {
return file_.WriteAtCurrentPos(data.data(), data.size()) >= 0;
}
void InvokeDone(mojo::ScopedDataPipeConsumerHandle pipe,
mojo::PendingAssociatedRemote<blink::mojom::ProgressClient>
progress_client,
bool success,
uint64_t bytes_written) override {
base::Time last_modified;
if (success) {
base::File::Info info;
if (file_.Flush() && file_.GetInfo(&info))
last_modified = info.last_modified;
}
reply_runner_->PostTask(
FROM_HERE, base::BindOnce(std::move(callback_), success, bytes_written,
std::move(pipe), std::move(progress_client),
last_modified));
}
base::File file_;
scoped_refptr<base::TaskRunner> reply_runner_;
DoneCallback callback_;
};
// Similar helper class that writes upto a certain number of bytes from a data
// pipe into a FutureData element.
class BlobBuilderFromStream::WritePipeToFutureDataHelper
: public DataPipeConsumerHelper {
public:
using DoneCallback = base::OnceCallback<void(
uint64_t bytes_written,
mojo::ScopedDataPipeConsumerHandle pipe,
mojo::PendingAssociatedRemote<blink::mojom::ProgressClient>
progress_client)>;
static void CreateAndStart(
mojo::ScopedDataPipeConsumerHandle pipe,
mojo::PendingAssociatedRemote<blink::mojom::ProgressClient>
progress_client,
scoped_refptr<BlobDataItem> item,
DoneCallback callback) {
new WritePipeToFutureDataHelper(std::move(pipe), std::move(progress_client),
std::move(item), std::move(callback));
}
private:
WritePipeToFutureDataHelper(
mojo::ScopedDataPipeConsumerHandle pipe,
mojo::PendingAssociatedRemote<blink::mojom::ProgressClient>
progress_client,
scoped_refptr<BlobDataItem> item,
DoneCallback callback)
: DataPipeConsumerHelper(std::move(pipe),
std::move(progress_client),
item->length()),
item_(std::move(item)),
callback_(std::move(callback)) {}
bool Populate(base::span<const char> data,
uint64_t bytes_previously_written) override {
if (item_->type() == BlobDataItem::Type::kBytesDescription)
item_->AllocateBytes();
std::memcpy(item_->mutable_bytes()
.subspan(bytes_previously_written, data.size())
.data(),
data.data(), data.size());
return true;
}
void InvokeDone(mojo::ScopedDataPipeConsumerHandle pipe,
mojo::PendingAssociatedRemote<blink::mojom::ProgressClient>
progress_client,
bool success,
uint64_t bytes_written) override {
DCHECK(success);
std::move(callback_).Run(bytes_written, std::move(pipe),
std::move(progress_client));
}
scoped_refptr<BlobDataItem> item_;
DoneCallback callback_;
};
BlobBuilderFromStream::BlobBuilderFromStream(
base::WeakPtr<BlobStorageContext> context,
std::string content_type,
std::string content_disposition,
ResultCallback callback)
: kMemoryBlockSize(std::min(
kMaxMemoryChunkSize,
context->memory_controller().limits().max_bytes_data_item_size)),
kMaxBytesInMemory(
context->memory_controller().limits().min_page_file_size),
kFileBlockSize(context->memory_controller().limits().min_page_file_size),
kMaxFileSize(context->memory_controller().limits().max_file_size),
context_(std::move(context)),
callback_(std::move(callback)),
content_type_(std::move(content_type)),
content_disposition_(std::move(content_disposition)) {
DCHECK(context_);
}
BlobBuilderFromStream::~BlobBuilderFromStream() {
DCHECK(!callback_) << "BlobBuilderFromStream was destroyed before finishing";
}
void BlobBuilderFromStream::Start(
uint64_t length_hint,
mojo::ScopedDataPipeConsumerHandle data,
mojo::PendingAssociatedRemote<blink::mojom::ProgressClient>
progress_client) {
context_->mutable_memory_controller()->CallWhenStorageLimitsAreKnown(
base::BindOnce(&BlobBuilderFromStream::AllocateMoreMemorySpace,
weak_factory_.GetWeakPtr(), length_hint,
std::move(progress_client), std::move(data)));
}
void BlobBuilderFromStream::Abort() {
OnError(Result::kAborted);
}
void BlobBuilderFromStream::AllocateMoreMemorySpace(
uint64_t length_hint,
mojo::PendingAssociatedRemote<blink::mojom::ProgressClient> progress_client,
mojo::ScopedDataPipeConsumerHandle pipe) {
if (!context_ || !callback_) {
OnError(Result::kAborted);
return;
}
if (!pipe.is_valid()) {
OnSuccess();
return;
}
// If too much data has already been saved in memory, switch to using disk
// backed data.
if (ShouldStoreNextBlockOnDisk(length_hint)) {
AllocateMoreFileSpace(length_hint, std::move(progress_client),
std::move(pipe));
return;
}
if (!length_hint)
length_hint = kMemoryBlockSize;
if (context_->memory_controller().GetAvailableMemoryForBlobs() <
length_hint) {
OnError(Result::kMemoryAllocationFailed);
return;
}
std::vector<scoped_refptr<ShareableBlobDataItem>> chunk_items;
while (length_hint > 0) {
const auto block_size = std::min<uint64_t>(kMemoryBlockSize, length_hint);
chunk_items.push_back(base::MakeRefCounted<ShareableBlobDataItem>(
BlobDataItem::CreateBytesDescription(block_size),
ShareableBlobDataItem::QUOTA_NEEDED));
length_hint -= block_size;
}
auto items_copy = chunk_items;
pending_quota_task_ =
context_->mutable_memory_controller()->ReserveMemoryQuota(
std::move(chunk_items),
base::BindOnce(&BlobBuilderFromStream::MemoryQuotaAllocated,
base::Unretained(this), std::move(pipe),
std::move(progress_client), std::move(items_copy), 0));
}
void BlobBuilderFromStream::MemoryQuotaAllocated(
mojo::ScopedDataPipeConsumerHandle pipe,
mojo::PendingAssociatedRemote<blink::mojom::ProgressClient> progress_client,
std::vector<scoped_refptr<ShareableBlobDataItem>> chunk_items,
size_t item_to_populate,
bool success) {
if (!success || !context_ || !callback_) {
OnError(success ? Result::kAborted : Result::kMemoryAllocationFailed);
return;
}
DCHECK_LT(item_to_populate, chunk_items.size());
auto item = chunk_items[item_to_populate];
WritePipeToFutureDataHelper::CreateAndStart(
std::move(pipe), std::move(progress_client), item->item(),
base::BindOnce(&BlobBuilderFromStream::DidWriteToMemory,
weak_factory_.GetWeakPtr(), std::move(chunk_items),
item_to_populate));
}
void BlobBuilderFromStream::DidWriteToMemory(
std::vector<scoped_refptr<ShareableBlobDataItem>> chunk_items,
size_t populated_item_index,
uint64_t bytes_written,
mojo::ScopedDataPipeConsumerHandle pipe,
mojo::PendingAssociatedRemote<blink::mojom::ProgressClient>
progress_client) {
if (!context_ || !callback_) {
OnError(Result::kAborted);
return;
}
DCHECK_LE(populated_item_index, chunk_items.size());
auto item = chunk_items[populated_item_index];
item->set_state(ShareableBlobDataItem::POPULATED_WITH_QUOTA);
current_total_size_ += bytes_written;
if (pipe.is_valid()) {
DCHECK_EQ(item->item()->length(), bytes_written);
items_.push_back(std::move(item));
// If we still have allocated items for this chunk, just keep going with
// those items.
if (populated_item_index + 1 < chunk_items.size()) {
MemoryQuotaAllocated(std::move(pipe), std::move(progress_client),
std::move(chunk_items), populated_item_index + 1,
true);
} else {
RunCallbackWhenDataPipeReady(
std::move(pipe),
base::BindOnce(&BlobBuilderFromStream::AllocateMoreMemorySpace,
weak_factory_.GetWeakPtr(), 0,
std::move(progress_client)));
}
} else {
// Pipe has closed, so we must be done. If we allocated more items than we
// ended up filling, those remaining items in |chunk_items| will just go out
// of scope, resulting in them being destroyed and their allocations to be
// freed.
DCHECK_LE(bytes_written, item->item()->length());
if (bytes_written > 0) {
item->item()->ShrinkBytes(bytes_written);
context_->mutable_memory_controller()->ShrinkMemoryAllocation(item.get());
items_.push_back(std::move(item));
}
OnSuccess();
}
}
void BlobBuilderFromStream::AllocateMoreFileSpace(
uint64_t length_hint,
mojo::PendingAssociatedRemote<blink::mojom::ProgressClient> progress_client,
mojo::ScopedDataPipeConsumerHandle pipe) {
if (!context_ || !callback_) {
OnError(Result::kAborted);
return;
}
if (!pipe.is_valid()) {
OnSuccess();
return;
}
if (!length_hint)
length_hint = kFileBlockSize;
if (context_->memory_controller().GetAvailableFileSpaceForBlobs() <
length_hint) {
OnError(Result::kFileAllocationFailed);
return;
}
// If the previous item was also a file, and the file isn't at its maximum
// size yet, extend the previous file rather than creating a new one.
if (!items_.empty() &&
items_.back()->item()->type() == BlobDataItem::Type::kFile &&
items_.back()->item()->length() < kMaxFileSize) {
auto item = items_.back()->item();
uint64_t old_file_size = item->length();
scoped_refptr<ShareableFileReference> file_reference = item->file_ref_;
DCHECK(file_reference);
auto file_size_delta = std::min(kMaxFileSize - old_file_size, length_hint);
context_->mutable_memory_controller()->GrowFileAllocation(
file_reference.get(), file_size_delta);
item->GrowFile(old_file_size + file_size_delta);
base::FilePath path = file_reference->path();
WritePipeToFileHelper::CreateAndAppend(
std::move(pipe), std::move(progress_client), path, file_size_delta,
base::BindOnce(&BlobBuilderFromStream::DidWriteToExtendedFile,
weak_factory_.GetWeakPtr(), std::move(file_reference),
old_file_size));
return;
}
std::vector<scoped_refptr<ShareableBlobDataItem>> chunk_items;
while (length_hint > 0) {
const auto file_size = std::min(kMaxFileSize, length_hint);
chunk_items.push_back(base::MakeRefCounted<ShareableBlobDataItem>(
BlobDataItem::CreateFutureFile(0, file_size, chunk_items.size()),
ShareableBlobDataItem::QUOTA_NEEDED));
length_hint -= file_size;
}
auto items_copy = chunk_items;
pending_quota_task_ = context_->mutable_memory_controller()->ReserveFileQuota(
std::move(chunk_items),
base::BindOnce(&BlobBuilderFromStream::FileQuotaAllocated,
base::Unretained(this), std::move(pipe),
std::move(progress_client), std::move(items_copy), 0));
}
void BlobBuilderFromStream::FileQuotaAllocated(
mojo::ScopedDataPipeConsumerHandle pipe,
mojo::PendingAssociatedRemote<blink::mojom::ProgressClient> progress_client,
std::vector<scoped_refptr<ShareableBlobDataItem>> chunk_items,
size_t item_to_populate,
std::vector<BlobMemoryController::FileCreationInfo> info,
bool success) {
if (!success || !context_ || !callback_) {
OnError(success ? Result::kAborted : Result::kFileAllocationFailed);
return;
}
DCHECK_EQ(chunk_items.size(), info.size());
DCHECK_LT(item_to_populate, chunk_items.size());
auto item = chunk_items[item_to_populate];
base::File file = std::move(info[item_to_populate].file);
WritePipeToFileHelper::CreateAndStart(
std::move(pipe), std::move(progress_client), std::move(file),
item->item()->length(),
base::BindOnce(&BlobBuilderFromStream::DidWriteToFile,
weak_factory_.GetWeakPtr(), std::move(chunk_items),
std::move(info), item_to_populate));
}
void BlobBuilderFromStream::DidWriteToFile(
std::vector<scoped_refptr<ShareableBlobDataItem>> chunk_items,
std::vector<BlobMemoryController::FileCreationInfo> info,
size_t populated_item_index,
bool success,
uint64_t bytes_written,
mojo::ScopedDataPipeConsumerHandle pipe,
mojo::PendingAssociatedRemote<blink::mojom::ProgressClient> progress_client,
const base::Time& modification_time) {
if (!success || !context_ || !callback_) {
OnError(success ? Result::kAborted : Result::kFileWriteFailed);
return;
}
DCHECK_EQ(chunk_items.size(), info.size());
DCHECK_LE(populated_item_index, chunk_items.size());
auto item = chunk_items[populated_item_index];
auto file = info[populated_item_index].file_reference;
item->item()->PopulateFile(file->path(), modification_time, file);
item->set_state(ShareableBlobDataItem::POPULATED_WITH_QUOTA);
current_total_size_ += bytes_written;
if (pipe.is_valid()) {
DCHECK_EQ(item->item()->length(), bytes_written);
items_.push_back(std::move(item));
// If we still have allocated items for this chunk, just keep going with
// those items.
if (populated_item_index + 1 < chunk_items.size()) {
FileQuotaAllocated(std::move(pipe), std::move(progress_client),
std::move(chunk_items), populated_item_index + 1,
std::move(info), true);
} else {
// Once we start writing to file, we keep writing to file.
RunCallbackWhenDataPipeReady(
std::move(pipe),
base::BindOnce(&BlobBuilderFromStream::AllocateMoreFileSpace,
weak_factory_.GetWeakPtr(), 0,
std::move(progress_client)));
}
} else {
// Pipe has closed, so we must be done. If we allocated more items than we
// ended up filling, those remaining items in |chunk_items| will just go out
// of scope, resulting in them being destroyed and their allocations to be
// freed.
DCHECK_LE(bytes_written, item->item()->length());
if (bytes_written > 0) {
context_->mutable_memory_controller()->ShrinkFileAllocation(
file.get(), item->item()->length(), bytes_written);
item->item()->ShrinkFile(bytes_written);
items_.push_back(std::move(item));
}
OnSuccess();
}
}
void BlobBuilderFromStream::DidWriteToExtendedFile(
scoped_refptr<ShareableFileReference> file_reference,
uint64_t old_file_size,
bool success,
uint64_t bytes_written,
mojo::ScopedDataPipeConsumerHandle pipe,
mojo::PendingAssociatedRemote<blink::mojom::ProgressClient> progress_client,
const base::Time& modification_time) {
if (!success || !context_ || !callback_) {
OnError(success ? Result::kAborted : Result::kFileWriteFailed);
return;
}
DCHECK(!items_.empty());
auto item = items_.back()->item();
DCHECK_EQ(item->type(), BlobDataItem::Type::kFile);
DCHECK_EQ(item->file_ref_, file_reference.get());
item->SetFileModificationTime(modification_time);
current_total_size_ += bytes_written;
if (pipe.is_valid()) {
DCHECK_EQ(item->length(), old_file_size + bytes_written);
// Once we start writing to file, we keep writing to file.
RunCallbackWhenDataPipeReady(
std::move(pipe),
base::BindOnce(&BlobBuilderFromStream::AllocateMoreFileSpace,
weak_factory_.GetWeakPtr(), 0,
std::move(progress_client)));
} else {
// Pipe has closed, so we must be done.
DCHECK_LE(old_file_size + bytes_written, item->length());
context_->mutable_memory_controller()->ShrinkFileAllocation(
file_reference.get(), item->length(), old_file_size + bytes_written);
item->ShrinkFile(old_file_size + bytes_written);
OnSuccess();
}
}
void BlobBuilderFromStream::OnError(Result result) {
if (pending_quota_task_)
pending_quota_task_->Cancel();
// Clear |items_| to avoid holding on to ShareableDataItems.
items_.clear();
if (!callback_)
return;
RecordResult(result);
std::move(callback_).Run(this, nullptr);
}
void BlobBuilderFromStream::OnSuccess() {
DCHECK(context_);
DCHECK(callback_);
RecordResult(Result::kSuccess);
std::move(callback_).Run(
this, context_->AddFinishedBlob(base::GenerateGUID(), content_type_,
content_disposition_, std::move(items_)));
}
void BlobBuilderFromStream::RecordResult(Result result) {
UMA_HISTOGRAM_ENUMERATION("Storage.Blob.BuildFromStreamResult", result);
}
bool BlobBuilderFromStream::ShouldStoreNextBlockOnDisk(uint64_t length_hint) {
DCHECK(context_);
const BlobMemoryController& controller = context_->memory_controller();
// Can't write to disk if paging isn't enabled.
if (!controller.file_paging_enabled())
return false;
// If we need more space than we want to fit in memory, immediately
// start writing to disk.
if (length_hint > kMaxBytesInMemory)
return true;
// If the next memory block would cause us to use more memory than we'd like,
// switch to disk.
if (current_total_size_ + kMemoryBlockSize > kMaxBytesInMemory &&
controller.GetAvailableFileSpaceForBlobs() >= kFileBlockSize) {
return true;
}
// Switch to disk if otherwise we'd need to page out some other blob.
return controller.GetAvailableMemoryForBlobs() < kMemoryBlockSize;
}
} // namespace storage
| 38.451613 | 80 | 0.676758 | [
"vector"
] |
a39b1da32b63bceede3dbee20a9d6380172ca3e2 | 310 | cpp | C++ | src/transforms/timestring.cpp | David-Jackson/SensESP | 903bad80472dafca9ce461865d681cae8e37964d | [
"Apache-2.0"
] | 86 | 2019-06-15T13:30:18.000Z | 2022-03-27T15:45:54.000Z | src/transforms/timestring.cpp | David-Jackson/SensESP | 903bad80472dafca9ce461865d681cae8e37964d | [
"Apache-2.0"
] | 369 | 2019-05-27T21:09:39.000Z | 2022-03-23T14:59:21.000Z | src/transforms/timestring.cpp | David-Jackson/SensESP | 903bad80472dafca9ce461865d681cae8e37964d | [
"Apache-2.0"
] | 83 | 2019-05-27T21:06:10.000Z | 2022-03-10T21:13:16.000Z |
#include "timestring.h"
TimeString::TimeString(String config_path)
: Transform<time_t, String>(config_path) {}
void TimeString::set_input(time_t input, uint8_t inputChannel) {
char buf[sizeof "2011-10-08T07:07:09Z"];
strftime(buf, sizeof buf, "%FT%TZ", gmtime(&input));
this->emit(String(buf));
}
| 25.833333 | 64 | 0.712903 | [
"transform"
] |
a39f580c1ff8a17cd4edaf79f73e4ec5f19666c5 | 7,887 | cpp | C++ | ros/src/computing/planning/mission/packages/lane_planner/nodes/lane_navi/lane_navi.cpp | sibojia/Autoware | 95a370c0c0afd1cfee20870c4be48456c962eb40 | [
"BSD-3-Clause"
] | 7 | 2016-11-24T06:48:50.000Z | 2022-02-18T20:41:47.000Z | ros/src/computing/planning/mission/packages/lane_planner/nodes/lane_navi/lane_navi.cpp | sibojia/Autoware | 95a370c0c0afd1cfee20870c4be48456c962eb40 | [
"BSD-3-Clause"
] | 1 | 2017-12-06T11:35:14.000Z | 2017-12-06T11:35:14.000Z | ros/src/computing/planning/mission/packages/lane_planner/nodes/lane_navi/lane_navi.cpp | sibojia/Autoware | 95a370c0c0afd1cfee20870c4be48456c962eb40 | [
"BSD-3-Clause"
] | 5 | 2016-12-19T16:09:09.000Z | 2019-11-05T04:53:54.000Z | /*
* Copyright (c) 2015, Nagoya University
* 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 Autoware nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <sstream>
#include <ros/console.h>
#include <tf/transform_datatypes.h>
#include <map_file/PointClassArray.h>
#include <map_file/LaneArray.h>
#include <map_file/NodeArray.h>
#include <waypoint_follower/LaneArray.h>
#include <lane_planner/vmap.hpp>
namespace {
int waypoint_max;
double search_radius; // meter
double velocity; // km/h
std::string frame_id;
std::string output_file;
ros::Publisher waypoint_pub;
lane_planner::vmap::VectorMap all_vmap;
lane_planner::vmap::VectorMap lane_vmap;
tablet_socket::route_cmd cached_route;
std::vector<std::string> split(const std::string& str, char delim)
{
std::stringstream ss(str);
std::string s;
std::vector<std::string> vec;
while (std::getline(ss, s, delim))
vec.push_back(s);
if (!str.empty() && str.back() == delim)
vec.push_back(std::string());
return vec;
}
std::string join(const std::vector<std::string>& vec, char delim)
{
std::string str;
for (size_t i = 0; i < vec.size(); ++i) {
str += vec[i];
if (i != (vec.size() - 1))
str += delim;
}
return str;
}
int count_lane(const lane_planner::vmap::VectorMap& vmap)
{
int lcnt = -1;
for (const map_file::Lane& l : vmap.lanes) {
if (l.lcnt > lcnt)
lcnt = l.lcnt;
}
return lcnt;
}
void create_waypoint(const tablet_socket::route_cmd& msg)
{
std_msgs::Header header;
header.stamp = ros::Time::now();
header.frame_id = frame_id;
if (all_vmap.points.empty() || all_vmap.lanes.empty() || all_vmap.nodes.empty()) {
cached_route.header = header;
cached_route.point = msg.point;
return;
}
lane_planner::vmap::VectorMap coarse_vmap = lane_planner::vmap::create_coarse_vmap_from_route(msg);
if (coarse_vmap.points.size() < 2)
return;
std::vector<lane_planner::vmap::VectorMap> fine_vmaps;
lane_planner::vmap::VectorMap fine_mostleft_vmap =
lane_planner::vmap::create_fine_vmap(lane_vmap, lane_planner::vmap::LNO_MOSTLEFT, coarse_vmap,
search_radius, waypoint_max);
if (fine_mostleft_vmap.points.size() < 2)
return;
fine_vmaps.push_back(fine_mostleft_vmap);
int lcnt = count_lane(fine_mostleft_vmap);
for (int i = lane_planner::vmap::LNO_MOSTLEFT + 1; i <= lcnt; ++i) {
lane_planner::vmap::VectorMap v =
lane_planner::vmap::create_fine_vmap(lane_vmap, i, coarse_vmap, search_radius, waypoint_max);
if (v.points.size() < 2)
continue;
fine_vmaps.push_back(v);
}
waypoint_follower::LaneArray lane_waypoint;
for (const lane_planner::vmap::VectorMap& v : fine_vmaps) {
waypoint_follower::lane l;
l.header = header;
l.increment = 1;
size_t last_index = v.points.size() - 1;
for (size_t i = 0; i < v.points.size(); ++i) {
double yaw;
if (i == last_index) {
geometry_msgs::Point p1 =
lane_planner::vmap::create_geometry_msgs_point(v.points[i]);
geometry_msgs::Point p2 =
lane_planner::vmap::create_geometry_msgs_point(v.points[i - 1]);
yaw = atan2(p2.y - p1.y, p2.x - p1.x);
yaw -= M_PI;
} else {
geometry_msgs::Point p1 =
lane_planner::vmap::create_geometry_msgs_point(v.points[i]);
geometry_msgs::Point p2 =
lane_planner::vmap::create_geometry_msgs_point(v.points[i + 1]);
yaw = atan2(p2.y - p1.y, p2.x - p1.x);
}
waypoint_follower::waypoint w;
w.pose.header = header;
w.pose.pose.position = lane_planner::vmap::create_geometry_msgs_point(v.points[i]);
w.pose.pose.orientation = tf::createQuaternionMsgFromYaw(yaw);
w.twist.header = header;
w.twist.twist.linear.x = velocity / 3.6; // to m/s
l.waypoints.push_back(w);
}
lane_waypoint.lanes.push_back(l);
}
waypoint_pub.publish(lane_waypoint);
for (size_t i = 0; i < fine_vmaps.size(); ++i) {
std::stringstream ss;
ss << "_" << i;
std::vector<std::string> v1 = split(output_file, '/');
std::vector<std::string> v2 = split(v1.back(), '.');
v2[0] = v2.front() + ss.str();
v1[v1.size() - 1] = join(v2, '.');
std::string path = join(v1, '/');
lane_planner::vmap::write_waypoints(fine_vmaps[i].points, velocity, path);
}
}
void update_values()
{
if (all_vmap.points.empty() || all_vmap.lanes.empty() || all_vmap.nodes.empty())
return;
lane_vmap = lane_planner::vmap::create_lane_vmap(all_vmap, lane_planner::vmap::LNO_ALL);
if (!cached_route.point.empty()) {
create_waypoint(cached_route);
cached_route.point.clear();
cached_route.point.shrink_to_fit();
}
}
void cache_point(const map_file::PointClassArray& msg)
{
all_vmap.points = msg.point_classes;
update_values();
}
void cache_lane(const map_file::LaneArray& msg)
{
all_vmap.lanes = msg.lanes;
update_values();
}
void cache_node(const map_file::NodeArray& msg)
{
all_vmap.nodes = msg.nodes;
update_values();
}
} // namespace
int main(int argc, char **argv)
{
ros::init(argc, argv, "lane_navi");
ros::NodeHandle n;
int sub_vmap_queue_size;
n.param<int>("/lane_navi/sub_vmap_queue_size", sub_vmap_queue_size, 1);
int sub_route_queue_size;
n.param<int>("/lane_navi/sub_route_queue_size", sub_route_queue_size, 1);
int pub_waypoint_queue_size;
n.param<int>("/lane_navi/pub_waypoint_queue_size", pub_waypoint_queue_size, 1);
bool pub_waypoint_latch;
n.param<bool>("/lane_navi/pub_waypoint_latch", pub_waypoint_latch, true);
n.param<int>("/lane_navi/waypoint_max", waypoint_max, 10000);
n.param<double>("/lane_navi/search_radius", search_radius, 10);
n.param<double>("/lane_navi/velocity", velocity, 40);
n.param<std::string>("/lane_navi/frame_id", frame_id, "map");
n.param<std::string>("/lane_navi/output_file", output_file, "/tmp/lane_waypoint.csv");
if (output_file.empty()) {
ROS_ERROR_STREAM("output filename is empty");
return EXIT_FAILURE;
}
if (output_file.back() == '/') {
ROS_ERROR_STREAM(output_file << " is directory");
return EXIT_FAILURE;
}
waypoint_pub = n.advertise<waypoint_follower::LaneArray>("/lane_waypoints_array", pub_waypoint_queue_size,
pub_waypoint_latch);
ros::Subscriber route_sub = n.subscribe("/route_cmd", sub_route_queue_size, create_waypoint);
ros::Subscriber point_sub = n.subscribe("/vector_map_info/point_class", sub_vmap_queue_size, cache_point);
ros::Subscriber lane_sub = n.subscribe("/vector_map_info/lane", sub_vmap_queue_size, cache_lane);
ros::Subscriber node_sub = n.subscribe("/vector_map_info/node", sub_vmap_queue_size, cache_node);
ros::spin();
return EXIT_SUCCESS;
}
| 31.051181 | 107 | 0.718397 | [
"vector"
] |
a39fc690dab3bf5412d12742148c8d84558fb4cc | 24,606 | cpp | C++ | src/governance.cpp | CryptoMonzt0r/NeoDash | 79a105a31c28890be56916c3a058f90cb0506740 | [
"MIT"
] | 2 | 2018-01-22T02:59:08.000Z | 2018-02-11T19:29:25.000Z | src/governance.cpp | CryptoMonzt0r/NeoDash | 79a105a31c28890be56916c3a058f90cb0506740 | [
"MIT"
] | 12 | 2018-01-18T23:28:27.000Z | 2018-04-05T13:32:48.000Z | src/governance.cpp | CryptoMonzt0r/NeoDash | 79a105a31c28890be56916c3a058f90cb0506740 | [
"MIT"
] | 3 | 2018-01-22T02:57:39.000Z | 2020-03-12T11:26:42.000Z | // Copyright (c) 2014-2016 The Neodash Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "core_io.h"
#include "main.h"
#include "init.h"
#include "flat-database.h"
#include "governance.h"
#include "governance-vote.h"
#include "masternode.h"
#include "governance.h"
#include "darksend.h"
#include "masternodeman.h"
#include "masternode-sync.h"
#include "util.h"
#include "addrman.h"
#include <boost/lexical_cast.hpp>
class CNode;
CGovernanceManager governance;
CCriticalSection cs_budget;
std::map<uint256, int64_t> mapAskedForGovernanceObject;
std::vector<CGovernanceObject> vecImmatureGovernanceObjects;
int nSubmittedFinalBudget;
bool IsCollateralValid(uint256 nTxCollateralHash, uint256 nExpectedHash, std::string& strError, int& nConf, CAmount minFee)
{
CTransaction txCollateral;
uint256 nBlockHash;
// RETRIEVE TRANSACTION IN QUESTION
if(!GetTransaction(nTxCollateralHash, txCollateral, Params().GetConsensus(), nBlockHash, true)){
strError = strprintf("Can't find collateral tx %s", txCollateral.ToString());
LogPrintf ("CGovernanceObject::IsCollateralValid - %s\n", strError);
return false;
}
if(txCollateral.vout.size() < 1) {
strError = strprintf("tx vout size less than 1 | %d", txCollateral.vout.size());
LogPrintf ("CGovernanceObject::IsCollateralValid - %s\n", strError);
return false;
}
// LOOK FOR SPECIALIZED GOVERNANCE SCRIPT (PROOF OF BURN)
CScript findScript;
findScript << OP_RETURN << ToByteVector(nExpectedHash);
bool foundOpReturn = false;
BOOST_FOREACH(const CTxOut o, txCollateral.vout){
if(!o.scriptPubKey.IsNormalPaymentScript() && !o.scriptPubKey.IsUnspendable()){
strError = strprintf("Invalid Script %s", txCollateral.ToString());
LogPrintf ("CGovernanceObject::IsCollateralValid - %s\n", strError);
return false;
}
if(o.scriptPubKey == findScript && o.nValue >= minFee) foundOpReturn = true;
}
if(!foundOpReturn){
strError = strprintf("Couldn't find opReturn %s in %s", nExpectedHash.ToString(), txCollateral.ToString());
LogPrintf ("CGovernanceObject::IsCollateralValid - %s\n", strError);
return false;
}
// GET CONFIRMATIONS FOR TRANSACTION
LOCK(cs_main);
int nConfirmationsIn = GetIXConfirmations(nTxCollateralHash);
if (nBlockHash != uint256()) {
BlockMap::iterator mi = mapBlockIndex.find(nBlockHash);
if (mi != mapBlockIndex.end() && (*mi).second) {
CBlockIndex* pindex = (*mi).second;
if (chainActive.Contains(pindex)) {
nConfirmationsIn += chainActive.Height() - pindex->nHeight + 1;
}
}
}
nConf = nConfirmationsIn;
//if we're syncing we won't have instantX information, so accept 1 confirmation
if(nConfirmationsIn >= GOVERNANCE_FEE_CONFIRMATIONS){
strError = "valid";
} else {
strError = strprintf("Collateral requires at least %d confirmations - %d confirmations", GOVERNANCE_FEE_CONFIRMATIONS, nConfirmationsIn);
LogPrintf ("CGovernanceObject::IsCollateralValid - %s - %d confirmations\n", strError, nConfirmationsIn);
return false;
}
return true;
}
void CGovernanceManager::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)
{
// lite mode is not supported
if(fLiteMode) return;
if(!masternodeSync.IsBlockchainSynced()) return;
LOCK(cs_budget);
// GOVERANCE SYNCING FUNCTIONALITY
if (strCommand == NetMsgType::MNGOVERNANCESYNC)
{
uint256 nProp;
vRecv >> nProp;
if(Params().NetworkIDString() == CBaseChainParams::MAIN){
if(nProp == uint256()) {
if(pfrom->HasFulfilledRequest(NetMsgType::MNGOVERNANCESYNC)) {
LogPrint("mngovernance", "peer already asked me for the list\n");
Misbehaving(pfrom->GetId(), 20);
return;
}
pfrom->FulfilledRequest(NetMsgType::MNGOVERNANCESYNC);
}
}
// ask for a specific proposal and it's votes
Sync(pfrom, nProp);
LogPrint("mngovernance", "syncing governance objects to our peer at %s\n", pfrom->addr.ToString());
}
// NEW GOVERNANCE OBJECT
else if (strCommand == NetMsgType::MNGOVERNANCEOBJECT)
{
// MAKE SURE WE HAVE A VALID REFERENCE TO THE TIP BEFORE CONTINUING
if(!pCurrentBlockIndex) return;
CGovernanceObject govobj;
vRecv >> govobj;
if(mapSeenGovernanceObjects.count(govobj.GetHash())){
// TODO - print error code? what if it's GOVOBJ_ERROR_IMMATURE?
masternodeSync.AddedBudgetItem(govobj.GetHash());
return;
}
std::string strError = "";
int nConf = 0;
if(!IsCollateralValid(govobj.nFeeTXHash, govobj.GetHash(), strError, nConf, GOVERNANCE_FEE_TX)){
LogPrintf("Governance object collateral tx is not valid - %s - %s\n", govobj.nFeeTXHash.ToString(), strError);
//todo 12.1
//if(nConf >= 1) vecImmatureGovernanceObjects.push_back(govobj);
return;
}
if(!govobj.IsValid(pCurrentBlockIndex, strError)) {
mapSeenGovernanceObjects.insert(make_pair(govobj.GetHash(), SEEN_OBJECT_ERROR_INVALID));
LogPrintf("Governance object is invalid - %s\n", strError);
return;
}
// UPDATE CACHED VARIABLES FOR THIS OBJECT AND ADD IT TO OUR MANANGED DATA
govobj.UpdateSentinelVariables(pCurrentBlockIndex);
if(AddGovernanceObject(govobj)) govobj.Relay();
mapSeenGovernanceObjects.insert(make_pair(govobj.GetHash(), SEEN_OBJECT_IS_VALID));
masternodeSync.AddedBudgetItem(govobj.GetHash());
LogPrintf("Governance object - new! - %s\n", govobj.GetHash().ToString());
//We might have active votes for this proposal that are valid now
CheckOrphanVotes();
}
// NEW GOVERNANCE OBJECT VOTE
else if (strCommand == NetMsgType::MNGOVERNANCEVOTE)
{
CGovernanceVote vote;
vRecv >> vote;
vote.fValid = true;
if(mapSeenVotes.count(vote.GetHash())){
masternodeSync.AddedBudgetItem(vote.GetHash());
return;
}
CMasternode* pmn = mnodeman.Find(vote.vinMasternode);
if(pmn == NULL) {
LogPrint("mngovernance", "mngovernance - unknown masternode - vin: %s\n", vote.vinMasternode.ToString());
mnodeman.AskForMN(pfrom, vote.vinMasternode);
return;
}
if(!vote.IsValid(true)){
LogPrintf("mngovernance - signature invalid\n");
if(masternodeSync.IsSynced()) Misbehaving(pfrom->GetId(), 20);
// it could just be a non-synced masternode
mnodeman.AskForMN(pfrom, vote.vinMasternode);
mapSeenVotes.insert(make_pair(vote.GetHash(), SEEN_OBJECT_ERROR_INVALID));
return;
} else {
mapSeenVotes.insert(make_pair(vote.GetHash(), SEEN_OBJECT_IS_VALID));
}
std::string strError = "";
if(UpdateGovernanceObject(vote, pfrom, strError)) {
vote.Relay();
masternodeSync.AddedBudgetItem(vote.GetHash());
}
LogPrint("mngovernance", "new vote - %s\n", vote.GetHash().ToString());
}
}
void CGovernanceManager::CheckOrphanVotes()
{
LOCK(cs);
std::string strError = "";
std::map<uint256, CGovernanceVote>::iterator it1 = mapOrphanVotes.begin();
while(it1 != mapOrphanVotes.end()){
if(UpdateGovernanceObject(((*it1).second), NULL, strError)){
LogPrintf("CGovernanceManager::CheckOrphanVotes - Governance object is known, activating and removing orphan vote\n");
mapOrphanVotes.erase(it1++);
} else {
++it1;
}
}
}
bool CGovernanceManager::AddGovernanceObject(CGovernanceObject& govobj)
{
LOCK(cs);
std::string strError = "";
if(!govobj.IsValid(pCurrentBlockIndex, strError)) {
LogPrintf("CGovernanceManager::AddGovernanceObject - invalid governance object - %s - (pCurrentBlockIndex nHeight %d) \n", strError, pCurrentBlockIndex->nHeight);
return false;
}
if(mapObjects.count(govobj.GetHash())) {
LogPrintf("CGovernanceManager::AddGovernanceObject - already have governance object - %s\n", strError);
return false;
}
mapObjects.insert(make_pair(govobj.GetHash(), govobj));
return true;
}
void CGovernanceManager::CheckAndRemove()
{
LogPrintf("CGovernanceManager::CheckAndRemove \n");
// DOUBLE CHECK THAT WE HAVE A VALID POINTER TO TIP
if(!pCurrentBlockIndex) return;
// DELETE OBJECTS WHICH MASTERNODE HAS FLAGGED DELETE=TRUE
std::map<uint256, CGovernanceObject>::iterator it = mapObjects.begin();
while(it != mapObjects.end())
{
CGovernanceObject* pObj = &((*it).second);
// UPDATE LOCAL VALIDITY AGAINST CRYPTO DATA
pObj->UpdateLocalValidity(pCurrentBlockIndex);
// UPDATE SENTINEL SIGNALING VARIABLES
pObj->UpdateSentinelVariables(pCurrentBlockIndex);
// SHOULD WE DELETE THIS OBJECT FROM MEMORY
/*
- delete objects from memory where fCachedDelete is true
- this should be robust enough that if someone sends us the proposal later, we should know it was deleted
*/
++it;
}
}
CGovernanceObject *CGovernanceManager::FindGovernanceObject(const std::string &strName)
{
// find the prop with the highest yes count
int nYesCount = -99999;
CGovernanceObject* pGovObj = NULL;
std::map<uint256, CGovernanceObject>::iterator it = mapObjects.begin();
while(it != mapObjects.end()){
pGovObj = &((*it).second);
int nGovObjYesCount = pGovObj->GetYesCount(VOTE_SIGNAL_FUNDING);
if((*it).second.strName == strName && nGovObjYesCount > nYesCount){
nYesCount = nGovObjYesCount;
}
++it;
}
if(nYesCount == -99999) return NULL;
return pGovObj;
}
CGovernanceObject *CGovernanceManager::FindGovernanceObject(const uint256& nHash)
{
LOCK(cs);
if(mapObjects.count(nHash))
return &mapObjects[nHash];
return NULL;
}
std::vector<CGovernanceObject*> CGovernanceManager::GetAllProposals(int64_t nMoreThanTime)
{
LOCK(cs);
std::vector<CGovernanceObject*> vGovObjs;
std::map<uint256, CGovernanceObject>::iterator it = mapObjects.begin();
while(it != mapObjects.end())
{
// if((*it).second.nTime < nMoreThanTime) {
// ++it;
// continue;
// }
// (*it).second.CleanAndRemove(false);
CGovernanceObject* pGovObj = &((*it).second);
vGovObjs.push_back(pGovObj);
++it;
}
return vGovObjs;
}
//
// Sort by votes, if there's a tie sort by their feeHash TX
//
struct sortProposalsByVotes {
bool operator()(const std::pair<CGovernanceObject*, int> &left, const std::pair<CGovernanceObject*, int> &right) {
if( left.second != right.second)
return (left.second > right.second);
return (UintToArith256(left.first->nFeeTXHash) > UintToArith256(right.first->nFeeTXHash));
}
};
void CGovernanceManager::NewBlock()
{
TRY_LOCK(cs, fBudgetNewBlock);
if(!fBudgetNewBlock) return;
if(!pCurrentBlockIndex) return;
// todo - 12.1 - add govobj sync
if (masternodeSync.RequestedMasternodeAssets <= MASTERNODE_SYNC_GOVERNANCE) return;
//this function should be called 1/6 blocks, allowing up to 100 votes per day on all proposals
if(pCurrentBlockIndex->nHeight % 6 != 0) return;
// description: incremental sync with our peers
// note: incremental syncing seems excessive, well just have clients ask for specific objects and their votes
// note: 12.1 - remove
// if(masternodeSync.IsSynced()){
// /*
// Needs comment below:
// - Why are we doing a partial sync with our peers on new blocks?
// - Why only partial? Why not partial when we recieve the request directly?
// - Can we simplify this somehow?
// - Why are we marking everything synced? Was this to correct a bug?
// */
// LogPrintf("CGovernanceManager::NewBlock - incremental sync started\n");
// if(pCurrentBlockIndex->nHeight % 600 == rand() % 600) {
// ClearSeen();
// ResetSync();
// }
// LOCK(cs_vNodes);
// BOOST_FOREACH(CNode* pnode, vNodes)
// if(pnode->nVersion >= MSG_GOVERNANCE_PEER_PROTO_VERSION)
// Sync(pnode, uint256());
// MarkSynced();
// }
CheckAndRemove();
//remove invalid votes once in a while (we have to check the signatures and validity of every vote, somewhat CPU intensive)
std::map<uint256, int64_t>::iterator it = mapAskedForGovernanceObject.begin();
while(it != mapAskedForGovernanceObject.end()){
if((*it).second > GetTime() - (60*60*24)){
++it;
} else {
mapAskedForGovernanceObject.erase(it++);
}
}
std::map<uint256, CGovernanceObject>::iterator it2 = mapObjects.begin();
while(it2 != mapObjects.end()){
(*it2).second.CleanAndRemove(false);
++it2;
}
std::vector<CGovernanceObject>::iterator it4 = vecImmatureGovernanceObjects.begin();
while(it4 != vecImmatureGovernanceObjects.end())
{
std::string strError = "";
int nConf = 0;
if(!IsCollateralValid((*it4).nFeeTXHash, (*it4).GetHash(), strError, nConf, GOVERNANCE_FEE_TX)){
++it4;
continue;
}
// 12.1 -- fix below
// if(!(*it4).IsValid(pCurrentBlockIndex, strError)) {
// LogPrintf("mprop (immature) - invalid budget proposal - %s\n", strError);
// it4 = vecImmatureGovernanceObjects.erase(it4);
// continue;
// }
// CGovernanceObject budgetProposal((*it4));
// if(AddGovernanceObject(budgetProposal)) {(*it4).Relay();}
// LogPrintf("mprop (immature) - new budget - %s\n", (*it4).GetHash().ToString());
// it4 = vecImmatureGovernanceObjects.erase(it4);
}
}
void CGovernanceManager::Sync(CNode* pfrom, uint256 nProp)
{
LOCK(cs);
/*
This code checks each of the hash maps for all known budget proposals and finalized budget proposals, then checks them against the
budget object to see if they're OK. If all checks pass, we'll send it to the peer.
*/
int nInvCount = 0;
// SYNC GOVERNANCE OBJECTS WITH OTHER CLIENT
std::map<uint256, CGovernanceObject>::iterator it1 = mapObjects.begin();
while(it1 != mapObjects.end()) {
uint256 h = (*it1).first;
if((*it1).second.fCachedValid && ((nProp == uint256() || (h == nProp)))){
// Push the inventory budget proposal message over to the other client
pfrom->PushInventory(CInv(MSG_GOVERNANCE_OBJECT, h));
nInvCount++;
}
++it1;
}
// SYNC OUR GOVERNANCE OBJECT VOTES WITH THEIR GOVERNANCE OBJECT VOTES
std::map<uint256, CGovernanceVote>::iterator it2 = mapVotesByHash.begin();
while(it2 != mapVotesByHash.end()) {
pfrom->PushInventory(CInv(MSG_GOVERNANCE_VOTE, (*it2).first));
nInvCount++;
++it2;
}
pfrom->PushMessage(NetMsgType::SYNCSTATUSCOUNT, MASTERNODE_SYNC_GOVOBJ, nInvCount);
LogPrintf("CGovernanceManager::Sync - sent %d items\n", nInvCount);
}
void CGovernanceManager::SyncParentObjectByVote(CNode* pfrom, const CGovernanceVote& vote)
{
if(!mapAskedForGovernanceObject.count(vote.nParentHash)){
pfrom->PushMessage(NetMsgType::MNGOVERNANCESYNC, vote.nParentHash);
mapAskedForGovernanceObject[vote.nParentHash] = GetTime();
}
}
bool CGovernanceManager::UpdateGovernanceObject(const CGovernanceVote& vote, CNode* pfrom, std::string& strError)
{
LOCK(cs);
if(!mapObjects.count(vote.nParentHash)){
if(pfrom){
// only ask for missing items after our syncing process is complete --
// otherwise we'll think a full sync succeeded when they return a result
if(!masternodeSync.IsSynced()) return false;
LogPrintf("CGovernanceManager::UpdateGovernanceObject - Unknown object %d, asking for source\n", vote.nParentHash.ToString());
mapOrphanVotes[vote.nParentHash] = vote;
SyncParentObjectByVote(pfrom, vote);
}
strError = "Governance object not found!";
return false;
}
return AddOrUpdateVote(vote, strError);
}
bool CGovernanceManager::AddOrUpdateVote(const CGovernanceVote& vote, std::string& strError)
{
LOCK(cs);
// GET DETERMINISTIC HASH WHICH COLLIDES ON MASTERNODE-VIN/GOVOBJ-HASH/VOTE-SIGNAL
uint256 nTypeHash = vote.GetTypeHash();
uint256 nHash = vote.GetHash();
// LOOK FOR PREVIOUS VOTES BY THIS SPECIFIC MASTERNODE FOR THIS SPECIFIC SIGNAL
if(mapVotesByType.count(nTypeHash)) {
if(mapVotesByType[nTypeHash].nTime > vote.nTime){
strError = strprintf("new vote older than existing vote - %s", nTypeHash.ToString());
LogPrint("mngovernance", "CGovernanceObject::AddOrUpdateVote - %s\n", strError);
return false;
}
if(vote.nTime - mapVotesByType[nTypeHash].nTime < GOVERNANCE_UPDATE_MIN){
strError = strprintf("time between votes is too soon - %s - %lli", nTypeHash.ToString(), vote.nTime - mapVotesByType[nTypeHash].nTime);
LogPrint("mngovernance", "CGovernanceObject::AddOrUpdateVote - %s\n", strError);
return false;
}
}
// UPDATE TO NEWEST VOTE
mapVotesByType[nTypeHash] = vote;
mapVotesByHash[nHash] = vote;
// // SET CACHE AS DIRTY / WILL BE UPDATED NEXT BLOCK
// CGovernanceObject* pGovObj = FindGovernanceObject(vote.GetParentHash());
// if(pGovObj) pGovObj->fDirtyCache = true;
return true;
}
CGovernanceObject::CGovernanceObject()
{
strName = "unknown";
nTime = 0;
nHashParent = uint256(); //parent object, 0 is root
nRevision = 0; //object revision in the system
nFeeTXHash = uint256(); //fee-tx
// caching
fCachedFunding = false;
fCachedValid = true;
fCachedDelete = false;
fCachedEndorsed = false;
//fDirtyCache = true;
}
CGovernanceObject::CGovernanceObject(uint256 nHashParentIn, int nRevisionIn, std::string strNameIn, int64_t nTimeIn, uint256 nFeeTXHashIn)
{
nHashParent = nHashParentIn; //parent object, 0 is root
nRevision = nRevisionIn; //object revision in the system
strName = strNameIn;
nTime = nTimeIn;
nFeeTXHash = nFeeTXHashIn; //fee-tx
// caching
fCachedFunding = false;
fCachedValid = true;
fCachedDelete = false;
fCachedEndorsed = false;
//fDirtyCache = true;
}
CGovernanceObject::CGovernanceObject(const CGovernanceObject& other)
{
// COPY OTHER OBJECT'S DATA INTO THIS OBJECT
nHashParent = other.nHashParent;
nRevision = other.nRevision;
strName = other.strName;
nTime = other.nTime;
nFeeTXHash = other.nFeeTXHash;
strData = other.strData;
// caching
fCachedFunding = other.fCachedFunding;
fCachedValid = other.fCachedValid;
fCachedDelete = other.fCachedDelete;
fCachedEndorsed = other.fCachedEndorsed;
//fDirtyCache = other.fDirtyCache;
}
bool CGovernanceObject::IsValid(const CBlockIndex* pindex, std::string& strError, bool fCheckCollateral)
{
if(GetNoCount(VOTE_SIGNAL_VALID) - GetYesCount(VOTE_SIGNAL_VALID) > mnodeman.CountEnabled(MSG_GOVERNANCE_PEER_PROTO_VERSION)/10){
strError = "Automated removal";
return false;
}
// if(nEndTime < GetTime()) {
// strError = "Expired Proposal";
// return false;
// }
if(!pindex) {
strError = "Tip is NULL";
return true;
}
// if(nAmount < 10000) {
// strError = "Invalid proposal amount (minimum 10000)";
// return false;
// }
if(strName.size() > 20) {
strError = "Invalid object name, limit of 20 characters.";
return false;
}
if(strName != SanitizeString(strName)) {
strError = "Invalid object name, unsafe characters found.";
return false;
}
if(fCheckCollateral){
int nConf = 0;
if(!IsCollateralValid(nFeeTXHash, GetHash(), strError, nConf, GOVERNANCE_FEE_TX)){
// strError set in IsCollateralValid
return false;
}
}
/*
TODO: There might be an issue with multisig in the coinbase on mainnet, we will add support for it in a future release.
*/
// if(address.IsPayToScriptHash()) {
// strError = "Multisig is not currently supported.";
// return false;
// }
// 12.1 move to pybrain
// //can only pay out 10% of the possible coins (min value of coins)
// if(nAmount > budget.GetTotalBudget(nBlockStart)) {
// strError = "Payment more than max";
// return false;
// }
return true;
}
void CGovernanceObject::CleanAndRemove(bool fSignatureCheck) {
// TODO: do smth here
}
void CGovernanceManager::CleanAndRemove(bool fSignatureCheck)
{
/*
*
* Loop through each item and delete the items that have become invalid
*
*/
// std::map<uint256, CGovernanceVote>::iterator it2 = mapVotesByHash.begin();
// while(it2 != mapVotesByHash.end()){
// if(!(*it2).second.IsValid(fSignatureCheck))
// {
// // 12.1 - log to specialized handle (govobj?)
// LogPrintf("CGovernanceManager::CleanAndRemove - Proposal/Budget is known, activating and removing orphan vote\n");
// mapVotesByHash.erase(it2++);
// } else {
// ++it2;
// }
// }
}
/**
* Get specific vote counts for each outcome (funding, validity, etc)
*/
int CGovernanceObject::GetAbsoluteYesCount(int nVoteSignalIn)
{
return governance.CountMatchingVotes((*this), nVoteSignalIn, VOTE_OUTCOME_YES) - governance.CountMatchingVotes((*this), nVoteSignalIn, VOTE_OUTCOME_NO);
}
int CGovernanceObject::GetAbsoluteNoCount(int nVoteSignalIn)
{
return governance.CountMatchingVotes((*this), nVoteSignalIn, VOTE_OUTCOME_NO) - governance.CountMatchingVotes((*this), nVoteSignalIn, VOTE_OUTCOME_YES);
}
int CGovernanceObject::GetYesCount(int nVoteSignalIn)
{
return governance.CountMatchingVotes((*this), nVoteSignalIn, VOTE_OUTCOME_YES);
}
int CGovernanceObject::GetNoCount(int nVoteSignalIn)
{
return governance.CountMatchingVotes((*this), nVoteSignalIn, VOTE_OUTCOME_NO);
}
int CGovernanceObject::GetAbstainCount(int nVoteSignalIn)
{
return governance.CountMatchingVotes((*this), nVoteSignalIn, VOTE_OUTCOME_ABSTAIN);
}
void CGovernanceObject::Relay()
{
CInv inv(MSG_GOVERNANCE_OBJECT, GetHash());
RelayInv(inv, MSG_GOVERNANCE_PEER_PROTO_VERSION);
}
std::string CGovernanceManager::ToString() const
{
std::ostringstream info;
info << "Governance Objects: " << (int)mapObjects.size() <<
", Seen Budgets: " << (int)mapSeenGovernanceObjects.size() <<
", Seen Budget Votes: " << (int)mapSeenVotes.size() <<
", VoteByHash Count: " << (int)mapVotesByHash.size() <<
", VoteByType Count: " << (int)mapVotesByType.size();
return info.str();
}
void CGovernanceManager::UpdatedBlockTip(const CBlockIndex *pindex)
{
pCurrentBlockIndex = pindex;
LogPrint("mngovernance", "pCurrentBlockIndex->nHeight: %d\n", pCurrentBlockIndex->nHeight);
if(!fLiteMode && masternodeSync.RequestedMasternodeAssets > MASTERNODE_SYNC_LIST)
NewBlock();
}
int CGovernanceManager::CountMatchingVotes(CGovernanceObject& govobj, int nVoteSignalIn, int nVoteOutcomeIn)
{
/*
*
* Count matching votes and return
*
*/
int nCount = 0;
std::map<uint256, CGovernanceVote>::iterator it2 = mapVotesByHash.begin();
while(it2 != mapVotesByHash.end()){
if((*it2).second.fValid && (*it2).second.nVoteSignal == nVoteSignalIn && (*it2).second.GetParentHash() == govobj.GetHash())
{
nCount += ((*it2).second.nVoteOutcome == nVoteOutcomeIn ? 1 : 0);
++it2;
} else {
++it2;
}
}
return nCount;
} | 32.333771 | 170 | 0.645656 | [
"object",
"vector"
] |
a3a6c0a29f921d387205cc28edf415e210a8f054 | 1,154 | cpp | C++ | leetcode/cpp/094.cpp | xpharry/leetcode_and_lintcode_battle | a06d966ad45bdbed6dda51cf0b480592fc4000d6 | [
"MIT"
] | null | null | null | leetcode/cpp/094.cpp | xpharry/leetcode_and_lintcode_battle | a06d966ad45bdbed6dda51cf0b480592fc4000d6 | [
"MIT"
] | null | null | null | leetcode/cpp/094.cpp | xpharry/leetcode_and_lintcode_battle | a06d966ad45bdbed6dda51cf0b480592fc4000d6 | [
"MIT"
] | 2 | 2020-09-29T21:59:43.000Z | 2021-06-22T13:24:04.000Z | /*
* Binary Tree, Recursion
*
*
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> sol;
inorder(root, sol);
return sol;
}
void inorder(TreeNode* root, vector<int>& sol) {
if(!root) return;
inorder(root->left, sol);
sol.push_back(root->val);
inorder(root->right, sol);
}
};
/*
* Binary Tree, Iteration
*
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
vector<int> res;
stack<TreeNode*> s;
TreeNode *p = root;
while (p || !s.empty()) {
while (p) {
s.push(p);
p = p->left;
}
p = s.top();
s.pop();
res.push_back(p->val);
p = p->right;
}
return res;
}
};
/*****
Idea:
1. 首先inorder的顺序是“左-根-右”,那么需要找到最左边的节点,再往上回溯,如果不用recursion的话,
那么久只能选择stack了;
2. 用p作为游历节点,从根节点或当前节点开始,逐个把左子节点压入stack中,到达最左节点后,需要考虑的
只有两种情况,(a)该节点是叶子节点,即没有左右子节点,(b)该节点存在右子节点;
3. 在处理这两种情况之前,一定是先把该节点的值推入结果res中,然后游历节点移到右子节点上,如果存在
右子节点,继续压入左子节点的操作,如果右子节点为空,则通过stack回溯到父节点或上一个左子节点。
*****/
| 20.245614 | 59 | 0.55026 | [
"vector"
] |
a3aa8d74ca1549b6fc56263a1686152b1a87a496 | 34,537 | cpp | C++ | DataProxy/src/DatabaseConnectionManager.cpp | aol/DataProxyLibrary | b1a16e6abadcf3e1cd07448086e2375511a337e6 | [
"BSD-3-Clause"
] | null | null | null | DataProxy/src/DatabaseConnectionManager.cpp | aol/DataProxyLibrary | b1a16e6abadcf3e1cd07448086e2375511a337e6 | [
"BSD-3-Clause"
] | null | null | null | DataProxy/src/DatabaseConnectionManager.cpp | aol/DataProxyLibrary | b1a16e6abadcf3e1cd07448086e2375511a337e6 | [
"BSD-3-Clause"
] | null | null | null | //
// FILE NAME: $HeadURL: svn+ssh://svn.cm.aol.com/advertising/adlearn/gen1/trunk/lib/cpp/DataProxy/private/DatabaseConnectionManager.cpp $
//
// REVISION: $Revision: 305781 $
//
// COPYRIGHT: (c) 2007 Advertising.com All Rights Reserved.
//
// LAST UPDATED: $Date: 2014-11-05 14:02:19 -0500 (Wed, 05 Nov 2014) $
// UPDATED BY: $Author: sstrick $
#include "DatabaseConnectionManager.hpp"
#include "DataProxyClient.hpp"
#include "DatabaseConnectionBinder.hpp"
#include "CSVReader.hpp"
#include "Database.hpp"
#include "Stopwatch.hpp"
#include "DPLCommon.hpp"
#include "XMLUtilities.hpp"
#include "MVLogger.hpp"
#include "LargeStringStream.hpp"
#include "ContainerToString.hpp"
#include <boost/lexical_cast.hpp>
namespace
{
const std::string DATA_DEFINITION_CONNECTION_PREFIX("__ddl_connection_");
const std::string CONNECTIONS_BY_TABLE_NODE("ConnectionsByTable");
const std::string CONNECTIONS_NODE_NAME_ATTRIBUTE( "connectionsNodeName" );
const std::string TABLES_NODE_NAME_ATTRIBUTE( "tablesNodeName" );
const std::string DATABASE_NODE("Database");
const std::string DATABASE_NAME_ATTRIBUTE("name");
const std::string DATABASE_SERVER_ATTRIBUTE("server");
const std::string DATABASE_USERNAME_ATTRIBUTE("user");
const std::string DATABASE_PASSWORD_ATTRIBUTE("password");
const std::string DATABASE_SCHEMA_ATTRIBUTE("schema");
const std::string DISABLE_CACHE_ATTRIBUTE("disableCache");
const std::string RECONNECT_TIMEOUT_ATTRIBUTE("reconnectTimeout");
const std::string MIN_POOL_SIZE_ATTRIBUTE("minPoolSize");
const std::string MAX_POOL_SIZE_ATTRIBUTE("maxPoolSize");
const std::string POOL_REFRESH_PERIOD_ATTRIBUTE("poolRefreshPeriod");
const std::string TXN_ISOLATION_LEVEL_ATTRIBUTE("txnIsolationLevel");
const std::string TXN_ISOLATION_LEVEL_READ_COMMITTED("readCommitted");
const std::string TXN_ISOLATION_LEVEL_SERIALIZABLE("serializable");
const std::string CONNECTION_NAME_ATTRIBUTE("connection");
const std::string DISABLE_CACHE_COLUMN( "disable_cache" );
const std::string DATABASE_TYPE_COLUMN( "type" );
const std::string TABLE_NAME_COLUMN( "table_id" );
const std::string NODE_COLUMN( "node_id" );
const std::string NODE_NAME_PREFIX( "__shard" );
Database::TransactionIsolationLevel GetTxnIsolationLevel( const std::string& i_rDesc )
{
if( i_rDesc == TXN_ISOLATION_LEVEL_READ_COMMITTED )
{
return Database::READ_COMMITTED;
}
if( i_rDesc == TXN_ISOLATION_LEVEL_SERIALIZABLE )
{
return Database::SERIALIZABLE;
}
MV_THROW( DatabaseConnectionManagerException, "Unknown transaction isolation level requested: " << i_rDesc );
}
std::string GetConnectionName( const std::string& i_rNodeId, const std::string& i_rShardNode )
{
return NODE_NAME_PREFIX + "_" + i_rShardNode + "_" + i_rNodeId;
}
size_t GetPoolSize( xercesc::DOMNode* i_pNode, const std::string& i_rName, size_t i_Default )
{
xercesc::DOMAttr* pAttribute = XMLUtilities::GetAttribute( i_pNode, i_rName );
if( pAttribute != NULL )
{
std::string poolSizeString = XMLUtilities::XMLChToString( pAttribute->getValue() );
try
{
int result = boost::lexical_cast< int >( poolSizeString );
if( result < 0 )
{
MV_THROW( DatabaseConnectionManagerException, "Illegal value provided: " << result << " for attribute: " << i_rName << "; must be non-negative" );
}
return size_t( result );
}
catch( const boost::bad_lexical_cast& i_rException )
{
MV_THROW( DatabaseConnectionManagerException, "Error parsing " << i_rName << " attribute: " << poolSizeString << " as int" );
}
}
return i_Default;
}
template< typename T_Data >
T_Data GetOptional( xercesc::DOMNode* i_pNode, const std::string& i_rName, T_Data i_Default, const std::string& i_rType )
{
xercesc::DOMAttr* pAttribute = XMLUtilities::GetAttribute( i_pNode, i_rName );
if( pAttribute != NULL )
{
std::string reconnectString = XMLUtilities::XMLChToString( pAttribute->getValue() );
try
{
return boost::lexical_cast< T_Data >( reconnectString );
}
catch( const boost::bad_lexical_cast& i_rException )
{
MV_THROW( DatabaseConnectionManagerException, "Error parsing " << i_rName << " attribute: " << reconnectString << " as " << i_rType );
}
}
return i_Default;
}
void ReconnectIfNecessary( const std::string& i_rConnectionName, const DatabaseConfigDatum& i_rConfig, DatabaseInstanceDatum& i_rInstance )
{
// if we need to reconnect based on time, do it
double secondsElapsed = i_rInstance.GetReference< ConnectionTimer >()->GetElapsedSeconds();
if( secondsElapsed > i_rConfig.GetValue< ConnectionReconnect >() )
{
if( !i_rInstance.GetValue< DatabaseHandle >().unique() )
{
MVLOGGER( "root.lib.DataProxy.DatabaseConnectionManager.CannotReconnect",
"Connection #" << i_rInstance.GetValue< ConnectionNumber >() << " for name: " << i_rConnectionName << " has been active for: "
<< secondsElapsed << " seconds. Reconnect timeout is set to: " << i_rConfig.GetValue< ConnectionReconnect >()
<< ", but there are active handles to it. Skipping reconnect." );
return;
}
MVLOGGER( "root.lib.DataProxy.DatabaseConnectionManager.Reconnecting",
"Connection #" << i_rInstance.GetValue< ConnectionNumber >() << " for name: " << i_rConnectionName << " has been active for: "
<< secondsElapsed << " seconds. Reconnect timeout is set to: " << i_rConfig.GetValue< ConnectionReconnect >() << ". Reconnecting." );
i_rInstance.GetReference< DatabaseHandle >().reset( new Database( *i_rInstance.GetReference< DatabaseHandle >() ) );
i_rInstance.GetReference< ConnectionTimer >()->Reset();
}
}
int TryReducePool( DatabaseConnectionDatum& i_rDatum )
{
int poolRefreshPeriod = 0;
int itemsToRemove = 0;
{
boost::shared_lock< boost::shared_mutex > lock( *i_rDatum.GetReference< Mutex >() );
poolRefreshPeriod = i_rDatum.GetValue< DatabaseConfig >().GetValue< PoolRefreshPeriod >();
Stopwatch& rStopwatch = *i_rDatum.GetReference< PoolRefreshTimer >();
int elapsedSeconds = rStopwatch.GetElapsedSeconds();
// if this connection doesn't have to refresh, return
if( poolRefreshPeriod < 0 )
{
return -1;
}
// if we don't have to refresh yet, return...
if( elapsedSeconds < poolRefreshPeriod )
{
return poolRefreshPeriod - elapsedSeconds;
}
rStopwatch.Reset();
itemsToRemove = i_rDatum.GetValue< DatabasePool >().size() - i_rDatum.GetValue< DatabaseConfig >().GetValue< MinPoolSize >();
if( itemsToRemove <= 0 )
{
return poolRefreshPeriod;
}
}
{
// if we get here, we have to obtain a lock and check again...
boost::unique_lock< boost::shared_mutex > lock( *i_rDatum.GetReference< Mutex >() );
itemsToRemove = i_rDatum.GetValue< DatabasePool >().size() - i_rDatum.GetValue< DatabaseConfig >().GetValue< MinPoolSize >();
// iterate and remove any unique connections, until we've removed enough
std::vector< int > closedConnections;
std::stringstream details;
int itemsRemoved( 0 );
std::vector< DatabaseInstanceDatum >::iterator iter = i_rDatum.GetReference< DatabasePool >().begin();
while( iter != i_rDatum.GetReference< DatabasePool >().end() )
{
if( itemsRemoved < itemsToRemove && iter->GetValue< DatabaseHandle >().unique() )
{
closedConnections.push_back( iter->GetValue< ConnectionNumber >() );
iter = i_rDatum.GetReference< DatabasePool >().erase( iter );
++itemsRemoved;
}
else
{
if( itemsRemoved > 0 )
{
if( details.tellp() > 0 )
{
details << "; ";
}
details << "connection #" << iter->GetValue< ConnectionNumber >() << " renumbered to ";
details << ( iter->GetReference< ConnectionNumber >() -= itemsRemoved );
}
++iter;
}
}
if( itemsRemoved > 0 )
{
MVLOGGER( "root.lib.DataProxy.DatabaseConnectionManager.ReducedPool",
"Connection pool under name: " << i_rDatum.GetValue< ConnectionName >()
<< " had " << itemsToRemove << " connections to reduce to get to minPoolSize,"
<< " and " << itemsRemoved << " connections were destroyed: numbers " << ContainerToString( closedConnections, "," )
<< "; " << details.str() );
}
}
return poolRefreshPeriod;
}
boost::shared_ptr< Database > CreateConnection( const std::string& i_rConnectionName, const DatabaseConfigDatum& i_rConfig )
{
std::string connectionType = i_rConfig.GetValue<DatabaseConnectionType>();
if (connectionType == ORACLE_DB_TYPE)
{
return boost::shared_ptr< Database >( new Database( Database::DBCONN_OCI_THREADSAFE_ORACLE,
"",
i_rConfig.GetValue<DatabaseName>(),
i_rConfig.GetValue<DatabaseUserName>(),
i_rConfig.GetValue<DatabasePassword>(),
false,
i_rConfig.GetValue<DatabaseSchema>(),
// the following cast is safe because the data was originally stored as a Database::TransactionIsolationLevel
Database::TransactionIsolationLevel( i_rConfig.GetValue<TransactionIsolationLevel>() ) ) );
}
else if (connectionType == MYSQL_DB_TYPE)
{
return boost::shared_ptr< Database >( new Database( Database::DBCONN_ODBC_MYSQL,
i_rConfig.GetValue<DatabaseServer>(),
"",
i_rConfig.GetValue<DatabaseUserName>(),
i_rConfig.GetValue<DatabasePassword>(),
i_rConfig.GetValue<DisableCache>(),
i_rConfig.GetValue<DatabaseName>(),
// the following cast is safe because the data was originally stored as a Database::TransactionIsolationLevel
Database::TransactionIsolationLevel( i_rConfig.GetValue<TransactionIsolationLevel>() ) ) );
}
else if (connectionType == VERTICA_DB_TYPE)
{
return boost::shared_ptr< Database >( new Database( Database::DBCONN_ODBC_VERTICA,
i_rConfig.GetValue<DatabaseServer>(),
"",
i_rConfig.GetValue<DatabaseUserName>(),
i_rConfig.GetValue<DatabasePassword>(),
false,
i_rConfig.GetValue<DatabaseName>(),
// the following cast is safe because the data was originally stored as a Database::TransactionIsolationLevel
Database::TransactionIsolationLevel( i_rConfig.GetValue<TransactionIsolationLevel>() ) ) );
}
else
{
MV_THROW(DatabaseConnectionManagerException, "Invalid Database type: " << connectionType);
}
}
size_t FindLowestUseCount( const std::vector< DatabaseInstanceDatum >& i_rInstances )
{
std::vector< DatabaseInstanceDatum >::const_iterator iter = i_rInstances.begin();
if( iter == i_rInstances.end() )
{
MV_THROW( DatabaseConnectionManagerException, "Tried to find the lowest use-count of an empty vector of instances" );
}
size_t i=1;
size_t lowestUseCountIndex=0;
long lowestUseCount = iter->GetValue< DatabaseHandle >().use_count();
++iter;
for( ; iter != i_rInstances.end(); ++i, ++iter )
{
long useCount = iter->GetValue< DatabaseHandle >().use_count();
if( useCount < lowestUseCount )
{
lowestUseCount = useCount;
lowestUseCountIndex = i;
}
}
return lowestUseCountIndex;
}
DatabaseInstanceDatum* GetDatabase( DatabaseConnectionDatum& i_rDatabaseConnectionDatum, bool i_InsideTransaction, bool i_CreateIfNeeded, bool* o_pCreated = NULL )
{
if( i_rDatabaseConnectionDatum.GetValue< DatabaseConfig >().GetValue< MaxPoolSize >() == 0 )
{
MV_THROW(DatabaseConnectionManagerException, "Connection: " << i_rDatabaseConnectionDatum.GetValue< ConnectionName >() << " has a max pool size of 0" );
}
DatabaseInstanceDatum* pResult = NULL;
std::vector< DatabaseInstanceDatum >::iterator iter = i_rDatabaseConnectionDatum.GetReference< DatabasePool >().begin();
for( int i=0; iter != i_rDatabaseConnectionDatum.GetReference< DatabasePool >().end(); ++i, ++iter )
{
// if no one has a handle on this db already, return it!
if( iter->GetValue< DatabaseHandle >().unique() )
{
if( o_pCreated != NULL )
{
*o_pCreated = false;
}
pResult = &*iter;
pResult->GetReference< DatabaseHandle >()->Ping( true );
return pResult;
}
}
// if we can create one, do it!
if( i_CreateIfNeeded )
{
if( i_rDatabaseConnectionDatum.GetValue< DatabasePool >().size() < i_rDatabaseConnectionDatum.GetValue< DatabaseConfig >().GetValue< MaxPoolSize >() )
{
boost::shared_ptr< Database > pNewDatabase = CreateConnection( i_rDatabaseConnectionDatum.GetValue< ConnectionName >(),
i_rDatabaseConnectionDatum.GetValue< DatabaseConfig >() );
DatabaseInstanceDatum instance;
instance.SetValue< ConnectionNumber >( i_rDatabaseConnectionDatum.GetReference< DatabasePool >().size() + 1 );
instance.SetValue< DatabaseHandle >( pNewDatabase );
instance.SetValue< ConnectionTimer >( boost::shared_ptr< Stopwatch >( new Stopwatch() ) );
i_rDatabaseConnectionDatum.GetReference< DatabasePool >().push_back( instance );
MVLOGGER("root.lib.DataProxy.DatabaseConnectionManager.Connect.CreatedDatabaseConnection",
"Created db connection #" << instance.GetValue< ConnectionNumber >()
<< " for name: " << i_rDatabaseConnectionDatum.GetValue< ConnectionName >() );
if( o_pCreated != NULL )
{
*o_pCreated = true;
}
pResult = &i_rDatabaseConnectionDatum.GetReference< DatabasePool >().back();
pResult->GetReference< DatabaseHandle >()->Ping( true );
return pResult;
}
// return the one with the least use_count
size_t lowestUseCountIndex = FindLowestUseCount( i_rDatabaseConnectionDatum.GetValue< DatabasePool >() );
if( o_pCreated != NULL )
{
*o_pCreated = false;
}
pResult = &i_rDatabaseConnectionDatum.GetReference< DatabasePool >()[lowestUseCountIndex];
// try to soft-ping the database...
// if we fail and we're inside a transaction, we have to throw so clients can do whatever rollbacks they need
// otherwise, we can assume that the pending data loss is not critical, so we log an error & force-ping
if( !pResult->GetReference< DatabaseHandle >()->Ping( false ) )
{
std::stringstream message;
message << "Connection #" << pResult->GetValue< ConnectionNumber >() << " for name: " << i_rDatabaseConnectionDatum.GetValue< ConnectionName >()
<< " failed ping operation, and there are active handles to it so a safe reconnect is impossible. Any pending data on this transaction has been lost.";
if( i_InsideTransaction )
{
MV_THROW( DatabaseConnectionManagerException, message.str() );
}
MVLOGGER( "root.lib.DataProxy.DatabaseConnectionManager.BusyConnectionLost", message.str() );
pResult->GetReference< DatabaseHandle >()->Ping( true );
}
return pResult;
}
// we're out of options...
return NULL;
}
void ResetTimerIfConnectionsPegged( Stopwatch& o_rTimer, boost::shared_mutex& i_rMutex, const std::vector< DatabaseInstanceDatum >& i_rPool )
{
{
boost::shared_lock< boost::shared_mutex > lock( i_rMutex );
std::vector< DatabaseInstanceDatum >::const_iterator iter = i_rPool.begin();
for( ; iter != i_rPool.end(); ++iter )
{
if( iter->GetValue< DatabaseHandle >().unique() )
{
return;
}
}
}
{
boost::unique_lock< boost::shared_mutex > lock( i_rMutex );
o_rTimer.Reset();
}
}
}
DatabaseConnectionManager::DatabaseConnectionManager( DataProxyClient& i_rDataProxyClient )
: m_DatabaseConnectionContainer(),
m_ShardDatabaseConnectionContainer(),
m_ShardCollections(),
m_ConnectionsByTableName(),
m_rDataProxyClient( i_rDataProxyClient ),
m_ConfigVersion(),
m_ShardVersion(),
m_pRefreshThread( NULL )
{
}
DatabaseConnectionManager::~DatabaseConnectionManager()
{
if( m_pRefreshThread )
{
m_pRefreshThread->interrupt();
m_pRefreshThread->join();
}
}
void DatabaseConnectionManager::ParseConnectionsByTable( const xercesc::DOMNode& i_rDatabaseConnectionNode )
{
boost::unique_lock< boost::shared_mutex > lock( m_ShardVersion );
std::vector<xercesc::DOMNode*> nodes;
XMLUtilities::GetChildrenByName( nodes, &i_rDatabaseConnectionNode, CONNECTIONS_BY_TABLE_NODE);
std::vector<xercesc::DOMNode*>::const_iterator iter = nodes.begin();
for ( ; iter != nodes.end(); ++iter )
{
std::set< std::string > allowedAttributes;
allowedAttributes.insert( NAME_ATTRIBUTE );
allowedAttributes.insert( CONNECTIONS_NODE_NAME_ATTRIBUTE );
allowedAttributes.insert( TABLES_NODE_NAME_ATTRIBUTE );
allowedAttributes.insert( RECONNECT_TIMEOUT_ATTRIBUTE );
XMLUtilities::ValidateAttributes( *iter, allowedAttributes );
XMLUtilities::ValidateNode( *iter, std::set< std::string >() );
ShardCollectionDatum datum;
datum.SetValue< ShardCollectionName >( XMLUtilities::GetAttributeValue(*iter, NAME_ATTRIBUTE) );
datum.SetValue< ConnectionNodeName >( XMLUtilities::GetAttributeValue(*iter, CONNECTIONS_NODE_NAME_ATTRIBUTE) );
datum.SetValue< TablesNodeName >( XMLUtilities::GetAttributeValue(*iter, TABLES_NODE_NAME_ATTRIBUTE) );
datum.SetValue< ConnectionReconnect >( GetOptional< double >( *iter, RECONNECT_TIMEOUT_ATTRIBUTE, 3600, "double" ) );
m_ShardCollections.InsertUpdate( datum );
}
}
void DatabaseConnectionManager::Parse( const xercesc::DOMNode& i_rDatabaseConnectionNode )
{
boost::unique_lock< boost::shared_mutex > lock( m_ConfigVersion );
std::set< std::string > allowedChildren;
allowedChildren.insert( DATABASE_NODE );
allowedChildren.insert( CONNECTIONS_BY_TABLE_NODE );
XMLUtilities::ValidateNode( &i_rDatabaseConnectionNode, allowedChildren );
XMLUtilities::ValidateAttributes( &i_rDatabaseConnectionNode, std::set< std::string >() );
std::vector<xercesc::DOMNode*> nodes;
XMLUtilities::GetChildrenByName( nodes, &i_rDatabaseConnectionNode, DATABASE_NODE);
std::vector<xercesc::DOMNode*>::const_iterator iter = nodes.begin();
for (; iter != nodes.end(); ++iter)
{
DatabaseConfigDatum databaseConfig;
DatabaseConnectionDatum datum;
std::string type = XMLUtilities::GetAttributeValue(*iter, TYPE_ATTRIBUTE);
std::string databaseUserName = XMLUtilities::GetAttributeValue( *iter, DATABASE_USERNAME_ATTRIBUTE );
std::string databasePassword = XMLUtilities::GetAttributeValue( *iter, DATABASE_PASSWORD_ATTRIBUTE );
std::string connectionName = XMLUtilities::GetAttributeValue( *iter, CONNECTION_NAME_ATTRIBUTE );
double reconnectTimeout = GetOptional< double >( *iter, RECONNECT_TIMEOUT_ATTRIBUTE, 3600, "double" ); // by default, reconnect every hour
size_t minPoolSize = GetPoolSize( *iter, MIN_POOL_SIZE_ATTRIBUTE, 1 );
size_t maxPoolSize = GetPoolSize( *iter, MAX_POOL_SIZE_ATTRIBUTE, minPoolSize );
int poolRefreshPeriod = GetOptional< int >( *iter, POOL_REFRESH_PERIOD_ATTRIBUTE, 60, "int" );
Database::TransactionIsolationLevel txnIsolation = GetTxnIsolationLevel( GetOptional< std::string >( *iter, TXN_ISOLATION_LEVEL_ATTRIBUTE, TXN_ISOLATION_LEVEL_READ_COMMITTED, "string" ) );
if( maxPoolSize < minPoolSize )
{
MV_THROW( DatabaseConnectionManagerException, "maxPoolSize: " << maxPoolSize << " must be greater than or equal to minPoolSize: " << minPoolSize );
}
else if( maxPoolSize == 0 )
{
MV_THROW( DatabaseConnectionManagerException, "maxPoolSize must be greater than 0" );
}
if( minPoolSize == maxPoolSize )
{
poolRefreshPeriod = -1;
}
databaseConfig.SetValue<DatabaseUserName>(databaseUserName);
databaseConfig.SetValue<DatabasePassword>(databasePassword);
databaseConfig.SetValue<DatabaseConnectionType>(type);
datum.SetValue<ConnectionName>(connectionName);
if (type == ORACLE_DB_TYPE)
{
std::string databaseName = XMLUtilities::GetAttributeValue( *iter, DATABASE_NAME_ATTRIBUTE );
std::string databaseSchema = XMLUtilities::GetAttributeValue( *iter, DATABASE_SCHEMA_ATTRIBUTE );
databaseConfig.SetValue<DatabaseSchema>(databaseSchema);
databaseConfig.SetValue<DatabaseName>(databaseName);
}
else if (type == MYSQL_DB_TYPE)
{
std::string databaseName = XMLUtilities::GetAttributeValue( *iter, DATABASE_NAME_ATTRIBUTE );
std::string databaseServer = XMLUtilities::GetAttributeValue( *iter, DATABASE_SERVER_ATTRIBUTE );
std::string disableCache = XMLUtilities::GetAttributeValue( *iter, DISABLE_CACHE_ATTRIBUTE );
bool bDisableCache = false;
if (disableCache == "true")
{
bDisableCache = true;
}
else if (disableCache == "false")
{
bDisableCache = false;
}
else
{
MV_THROW(DatabaseConnectionManagerException,
"MySQL db connection has invalid value for disableCache attribute: " << disableCache << ". Valid values are 'true' and 'false'");
}
databaseConfig.SetValue<DatabaseName>(databaseName);
databaseConfig.SetValue<DatabaseServer>(databaseServer);
databaseConfig.SetValue<DisableCache>(bDisableCache);
}
else if (type == VERTICA_DB_TYPE)
{
// vertica does not actually support multiple databases, so db name is not needed.
// however, it does use schemas, but in order to fit our current ODBCdb class, we will actually parse
// the schema attribute and set it as the database NAME, so that we switch over to the right schema
std::string databaseSchema = XMLUtilities::GetAttributeValue( *iter, DATABASE_SCHEMA_ATTRIBUTE );
std::string databaseServer = XMLUtilities::GetAttributeValue( *iter, DATABASE_SERVER_ATTRIBUTE );
databaseConfig.SetValue<DatabaseName>(databaseSchema);
databaseConfig.SetValue<DatabaseServer>(databaseServer);
}
else
{
MV_THROW(DatabaseConnectionManagerException,
"Unrecognized type in DatabaseNode: " << type );
}
if (m_DatabaseConnectionContainer.find(datum) != m_DatabaseConnectionContainer.end())
{
MV_THROW(DatabaseConnectionManagerException, "Duplicate Connections named '" << datum.GetValue<ConnectionName>() << "' in the DatabaseConnections node");
}
databaseConfig.SetValue< ConnectionReconnect >( reconnectTimeout );
databaseConfig.SetValue< MinPoolSize >( minPoolSize );
databaseConfig.SetValue< MaxPoolSize >( maxPoolSize );
databaseConfig.SetValue< PoolRefreshPeriod >( poolRefreshPeriod );
databaseConfig.SetValue< TransactionIsolationLevel >( txnIsolation );
datum.SetValue< DatabaseConfig >( databaseConfig );
datum.GetReference< DatabasePool >().reserve( maxPoolSize );
datum.GetReference< Mutex >().reset( new boost::shared_mutex() );
datum.GetReference< PoolRefreshTimer >().reset( new Stopwatch() );
m_DatabaseConnectionContainer.InsertUpdate(datum);
// also add a connection for ddl operations
datum.SetValue<ConnectionName>(DATA_DEFINITION_CONNECTION_PREFIX + datum.GetValue<ConnectionName>());
datum.GetReference< Mutex >().reset( new boost::shared_mutex() );
datum.GetReference< PoolRefreshTimer >().reset( new Stopwatch() );
m_DatabaseConnectionContainer.InsertUpdate(datum);
}
if( !m_pRefreshThread )
{
m_pRefreshThread.reset( new boost::thread( boost::bind( boost::mem_fn( &DatabaseConnectionManager::WatchPools ), this ) ) );
}
}
void DatabaseConnectionManager::FetchConnectionsByTable( const std::string& i_rName,
const std::string& i_rConnectionsNode,
const std::string& i_rTablesNode,
double i_ConnectionReconnect ) const
{
// first load connections
std::map< std::string, std::string > parameters;
boost::scoped_ptr< std::large_stringstream > pTempStream;
pTempStream.reset( new std::large_stringstream() );
m_rDataProxyClient.Load( i_rConnectionsNode, parameters, *pTempStream );
pTempStream->flush();
boost::scoped_ptr< CSVReader > pReader;
pReader.reset( new CSVReader( *pTempStream ) );
DatabaseConfigDatum configDatum;
Nullable< int > disableCache;
std::string type;
std::string node;
DatabaseConfigBinder::Bind( configDatum, *pReader );
pReader->BindCol( DATABASE_TYPE_COLUMN, type );
pReader->BindCol( DISABLE_CACHE_COLUMN, disableCache );
pReader->BindCol( NODE_COLUMN, node );
while( pReader->NextRow() )
{
if( type != MYSQL_DB_TYPE && type != ORACLE_DB_TYPE && type != VERTICA_DB_TYPE )
{
MV_THROW( DatabaseConnectionManagerException, "Unrecognized database type parsed from shard connections: " << type );
}
std::string connectionName = GetConnectionName( node, i_rName );
DatabaseConnectionDatum connectionDatum;
configDatum.SetValue< ConnectionReconnect >( i_ConnectionReconnect );
connectionDatum.SetValue< ConnectionName >( connectionName );
if( m_DatabaseConnectionContainer.find( connectionDatum ) != m_DatabaseConnectionContainer.end() )
{
MV_THROW( DatabaseConnectionManagerException, "Duplicate node id: " << node << " loaded from connections node: " << i_rConnectionsNode << " (conflicts with non-shard connection)" );
}
if( m_ShardDatabaseConnectionContainer.find( connectionDatum ) != m_ShardDatabaseConnectionContainer.end() )
{
MV_THROW( DatabaseConnectionManagerException, "Duplicate node id: " << node << " loaded from connections node: " << i_rConnectionsNode << " (conflicts with shard connection)" );
}
configDatum.SetValue< DatabaseConnectionType >( type );
configDatum.SetValue< DisableCache >( disableCache.IsNull() ? false : boost::lexical_cast< bool >( disableCache ) );
configDatum.SetValue< MinPoolSize >( 1 );
configDatum.SetValue< MaxPoolSize >( 1 );
configDatum.SetValue< PoolRefreshPeriod >( -1 );
connectionDatum.SetValue< DatabaseConfig >( configDatum );
connectionDatum.GetReference< Mutex >().reset( new boost::shared_mutex() );
connectionDatum.GetReference< PoolRefreshTimer >().reset( new Stopwatch() );
m_ShardDatabaseConnectionContainer.InsertUpdate( connectionDatum );
// also add a connection for ddl operations
connectionDatum.SetValue<ConnectionName>(DATA_DEFINITION_CONNECTION_PREFIX + connectionDatum.GetValue<ConnectionName>());
m_ShardDatabaseConnectionContainer.InsertUpdate(connectionDatum);
}
// now load the tables
pTempStream.reset( new std::large_stringstream() );
m_rDataProxyClient.Load( i_rTablesNode, parameters, *pTempStream );
pTempStream->flush();
pReader.reset( new CSVReader( *pTempStream ) );
std::string tableName;
pReader->BindCol( TABLE_NAME_COLUMN, tableName );
pReader->BindCol( NODE_COLUMN, node );
while( pReader->NextRow() )
{
std::string connectionName = GetConnectionName( node, i_rName );
DatabaseConnectionDatum connectionDatum;
connectionDatum.SetValue< ConnectionName >( connectionName );
if( m_ShardDatabaseConnectionContainer.find( connectionDatum ) == m_ShardDatabaseConnectionContainer.end() )
{
MV_THROW( DatabaseConnectionManagerException, "Table: " << tableName << " loaded from node: " << i_rTablesNode << " is reported to be located in unknown node id: " << node );
}
m_ConnectionsByTableName[ tableName ] = connectionName;
}
}
DatabaseConnectionDatum& DatabaseConnectionManager::PrivateGetConnection( const std::string& i_rConnectionName )
{
boost::shared_lock< boost::shared_mutex > lock( m_ConfigVersion );
DatabaseConnectionDatum datum;
datum.SetValue<ConnectionName>(i_rConnectionName);
DatabaseConnectionContainer::iterator iter = m_DatabaseConnectionContainer.find(datum);
if (iter == m_DatabaseConnectionContainer.end())
{
// if it's not a named connection, try a shard connection
iter = m_ShardDatabaseConnectionContainer.find( datum );
if (iter == m_ShardDatabaseConnectionContainer.end())
{
MV_THROW(DatabaseConnectionManagerException,
"DatabaseConnection '" << i_rConnectionName << "' was not found. Make sure the dpl config's 'DatabaseConnections' node is configured correctly.");
}
}
return iter->second;
}
const DatabaseConnectionDatum& DatabaseConnectionManager::PrivateGetConnection( const std::string& i_rConnectionName ) const
{
boost::shared_lock< boost::shared_mutex > lock( m_ConfigVersion );
DatabaseConnectionDatum datum;
datum.SetValue<ConnectionName>(i_rConnectionName);
DatabaseConnectionContainer::const_iterator iter = m_DatabaseConnectionContainer.find(datum);
if (iter == m_DatabaseConnectionContainer.end())
{
// if it's not a named connection, try a shard connection
iter = m_ShardDatabaseConnectionContainer.find( datum );
if (iter == m_ShardDatabaseConnectionContainer.end())
{
MV_THROW(DatabaseConnectionManagerException,
"DatabaseConnection '" << i_rConnectionName << "' was not found. Make sure the dpl config's 'DatabaseConnections' node is configured correctly.");
}
}
return iter->second;
}
void DatabaseConnectionManager::ValidateConnectionName(const std::string& i_ConnectionName ) const
{
PrivateGetConnection(i_ConnectionName);
}
void DatabaseConnectionManager::RefreshConnectionsByTable() const
{
m_ShardDatabaseConnectionContainer.clear();
m_ConnectionsByTableName.clear();
ShardCollectionContainer::const_iterator shardIter = m_ShardCollections.begin();
for( ; shardIter != m_ShardCollections.end(); ++shardIter )
{
FetchConnectionsByTable( shardIter->second.GetValue< ShardCollectionName >(),
shardIter->second.GetValue< ConnectionNodeName >(),
shardIter->second.GetValue< TablesNodeName >(),
shardIter->second.GetValue< ConnectionReconnect >() );
}
}
std::string DatabaseConnectionManager::PrivateGetConnectionNameByTable(const std::string& i_rTableName ) const
{
std_ext::unordered_map< std::string, std::string >::const_iterator iter;
{
boost::unique_lock< boost::shared_mutex > lock( m_ShardVersion );
iter = m_ConnectionsByTableName.find( i_rTableName );
if( iter == m_ConnectionsByTableName.end() )
{
MVLOGGER("root.lib.DataProxy.DatabaseConnectionManager.GetConnectionByTable.LoadingShardCollections",
"Unable to find table name: " << i_rTableName << " in existing shard collections. Reloading shard collections..." );
RefreshConnectionsByTable();
iter = m_ConnectionsByTableName.find( i_rTableName );
if( iter == m_ConnectionsByTableName.end() )
{
MV_THROW( DatabaseConnectionManagerException, "Unable to find a registered connection for table name: " << i_rTableName );
}
}
}
return iter->second;
}
boost::shared_ptr< Database > DatabaseConnectionManager::GetConnectionByTable( const std::string& i_rTableName )
{
std::string connectionName = PrivateGetConnectionNameByTable(i_rTableName);
return GetConnection(connectionName);
}
boost::shared_ptr< Database > DatabaseConnectionManager::GetDataDefinitionConnectionByTable( const std::string& i_rTableName )
{
std::string connectionName = PrivateGetConnectionNameByTable(i_rTableName);
return GetConnection(DATA_DEFINITION_CONNECTION_PREFIX + connectionName);
}
boost::shared_ptr< Database > DatabaseConnectionManager::GetDataDefinitionConnection(const std::string& i_ConnectionName)
{
return GetConnection(DATA_DEFINITION_CONNECTION_PREFIX + i_ConnectionName);
}
boost::shared_ptr< Database > DatabaseConnectionManager::GetConnection(const std::string& i_ConnectionName)
{
DatabaseConnectionDatum& rDatum = PrivateGetConnection(i_ConnectionName);
DatabaseInstanceDatum* pInstance = NULL;
boost::shared_ptr< Database > pResult;
// try to get one of the connections that has been established
{
boost::unique_lock< boost::shared_mutex > lock( *rDatum.GetValue< Mutex >() );
pInstance = GetDatabase( rDatum, m_rDataProxyClient.InsideTransaction(), false );
// if we were successful, we may have to reconnect
if( pInstance != NULL )
{
ReconnectIfNecessary( i_ConnectionName, rDatum.GetValue< DatabaseConfig >(), *pInstance );
pResult = pInstance->GetValue< DatabaseHandle >();
}
}
// otherwise, we have to create one
if( pInstance == NULL )
{
boost::unique_lock< boost::shared_mutex > lock( *rDatum.GetValue< Mutex >() );
// double-check getting one for free
pInstance = GetDatabase( rDatum, m_rDataProxyClient.InsideTransaction(), false );
if( pInstance != NULL )
{
ReconnectIfNecessary( i_ConnectionName, rDatum.GetValue< DatabaseConfig >(), *pInstance );
pResult = pInstance->GetValue< DatabaseHandle >();
}
else
{
pInstance = GetDatabase( rDatum, m_rDataProxyClient.InsideTransaction(), true );
// this should never happen
if( pInstance == NULL )
{
MV_THROW( DatabaseConnectionManagerException, "Unable to create a database for connection: " << i_ConnectionName );
}
pResult = pInstance->GetValue< DatabaseHandle >();
}
}
ResetTimerIfConnectionsPegged( *rDatum.GetReference< PoolRefreshTimer >(), *rDatum.GetReference< Mutex >(), rDatum.GetReference< DatabasePool >() );
return pResult;
}
std::string DatabaseConnectionManager::GetDatabaseType(const std::string& i_ConnectionName) const
{
boost::shared_lock< boost::shared_mutex > lock( m_ConfigVersion );
return PrivateGetConnection(i_ConnectionName).GetValue< DatabaseConfig >().GetValue< DatabaseConnectionType >();
}
std::string DatabaseConnectionManager::GetDatabaseTypeByTable( const std::string& i_rTableName ) const
{
std::string connectionName = PrivateGetConnectionNameByTable(i_rTableName);
return GetDatabaseType( connectionName );
}
void DatabaseConnectionManager::ClearConnections()
{
boost::unique_lock< boost::shared_mutex > lock( m_ConfigVersion );
boost::unique_lock< boost::shared_mutex > lock2( m_ShardVersion );
m_DatabaseConnectionContainer.clear();
m_ShardDatabaseConnectionContainer.clear();
m_ShardCollections.clear();
m_ConnectionsByTableName.clear();
}
void DatabaseConnectionManager::WatchPools()
{
try
{
Stopwatch stopwatch;
int sleepPeriod = 0;
while( true )
{
// check to see if we've been told to stop
boost::this_thread::interruption_point();
// sleep with interrupts
Stopwatch sleepStopwatch;
while( sleepStopwatch.GetElapsedSeconds() < sleepPeriod )
{
usleep( 100000 );
boost::this_thread::interruption_point();
}
int minSleepPeriod = 60; // sleep 60 seconds if nothing gives us anything to sleep for (also minimum)
// at this point, we have to refresh
{
// obtain a shared lock on the config because we are going to be reading the connection container
boost::shared_lock< boost::shared_mutex > lock( m_ConfigVersion );
DatabaseConnectionContainer::iterator iter = m_DatabaseConnectionContainer.begin();
for( ; iter != m_DatabaseConnectionContainer.end(); ++iter )
{
DatabaseConnectionDatum& rDatum = iter->second;
int sleepPeriod = TryReducePool( rDatum );
if( sleepPeriod > 0 )
{
minSleepPeriod = std::min( minSleepPeriod, sleepPeriod );
}
}
}
sleepPeriod = minSleepPeriod;
}
}
catch( const boost::thread_interrupted& i_rInterrupt )
{
// do nothing
}
}
| 41.610843 | 190 | 0.7311 | [
"vector"
] |
a3ab619da3147820096cb49f30e63899696d1272 | 7,573 | cpp | C++ | src/gdal_field_defn.cpp | fulcrumapp/node-gdal | 5c894cc6fda3f2c08fbe95fe2efc5e03d9bf6e46 | [
"Apache-2.0"
] | null | null | null | src/gdal_field_defn.cpp | fulcrumapp/node-gdal | 5c894cc6fda3f2c08fbe95fe2efc5e03d9bf6e46 | [
"Apache-2.0"
] | null | null | null | src/gdal_field_defn.cpp | fulcrumapp/node-gdal | 5c894cc6fda3f2c08fbe95fe2efc5e03d9bf6e46 | [
"Apache-2.0"
] | 1 | 2019-07-14T16:41:59.000Z | 2019-07-14T16:41:59.000Z |
#include "gdal_common.hpp"
#include "gdal_field_defn.hpp"
#include "utils/field_types.hpp"
namespace node_gdal {
Nan::Persistent<FunctionTemplate> FieldDefn::constructor;
void FieldDefn::Initialize(Local<Object> target)
{
Nan::HandleScope scope;
Local<FunctionTemplate> lcons = Nan::New<FunctionTemplate>(FieldDefn::New);
lcons->InstanceTemplate()->SetInternalFieldCount(1);
lcons->SetClassName(Nan::New("FieldDefn").ToLocalChecked());
ATTR(lcons, "name", nameGetter, nameSetter);
ATTR(lcons, "type", typeGetter, typeSetter);
ATTR(lcons, "justification", justificationGetter, justificationSetter);
ATTR(lcons, "width", widthGetter, widthSetter);
ATTR(lcons, "precision", precisionGetter, precisionSetter);
ATTR(lcons, "ignored", ignoredGetter, ignoredSetter);
target->Set(Nan::New("FieldDefn").ToLocalChecked(), lcons->GetFunction());
constructor.Reset(lcons);
}
FieldDefn::FieldDefn(OGRFieldDefn *def)
: Nan::ObjectWrap(),
this_(def),
owned_(false)
{
LOG("Created FieldDefn [%p]", def);
}
FieldDefn::FieldDefn()
: Nan::ObjectWrap(),
this_(0),
owned_(false)
{
}
FieldDefn::~FieldDefn()
{
if(this_){
LOG("Disposing FieldDefn [%p] (%s)", this_, owned_ ? "owned" : "unowned");
if(owned_) delete this_;
LOG("Disposed FieldDefn [%p]", this_);
this_ = NULL;
}
}
/**
* @constructor
* @class gdal.FieldDefn
* @param {String} name Field name
* @param {String} type Data type (see {{#crossLink "Constants (OFT)"}}OFT constants{{/crossLink}})
*/
NAN_METHOD(FieldDefn::New)
{
Nan::HandleScope scope;
if (!info.IsConstructCall()) {
Nan::ThrowError("Cannot call constructor as function, you need to use 'new' keyword");
return;
}
if (info[0]->IsExternal()) {
Local<External> ext = info[0].As<External>();
void* ptr = ext->Value();
FieldDefn *f = static_cast<FieldDefn *>(ptr);
f->Wrap(info.This());
info.GetReturnValue().Set(info.This());
return;
} else {
std::string field_name("");
std::string type_name("string");
NODE_ARG_STR(0, "field name", field_name);
NODE_ARG_STR(1, "field type", type_name);
int field_type = getFieldTypeByName(type_name);
if (field_type < 0) {
Nan::ThrowError("Unrecognized field type");
return;
}
FieldDefn* def = new FieldDefn(new OGRFieldDefn(field_name.c_str(), static_cast<OGRFieldType>(field_type)));
def->owned_ = true;
def->Wrap(info.This());
}
info.GetReturnValue().Set(info.This());
}
Local<Value> FieldDefn::New(OGRFieldDefn *def)
{
Nan::EscapableHandleScope scope;
return scope.Escape(FieldDefn::New(def, false));
}
Local<Value> FieldDefn::New(OGRFieldDefn *def, bool owned)
{
Nan::EscapableHandleScope scope;
if (!def) {
return scope.Escape(Nan::Null());
}
//make a copy of fielddefn owned by a featuredefn
// + no need to track when a featuredefn is destroyed
// + no need to throw errors when a method trys to modify an owned read-only fielddefn
// - is slower
if (!owned) {
def = new OGRFieldDefn(def);
}
FieldDefn *wrapped = new FieldDefn(def);
wrapped->owned_ = true;
v8::Local<v8::Value> ext = Nan::New<External>(wrapped);
v8::Local<v8::Object> obj = Nan::New(FieldDefn::constructor)->GetFunction()->NewInstance(1, &ext);
return scope.Escape(obj);
}
NAN_METHOD(FieldDefn::toString)
{
Nan::HandleScope scope;
info.GetReturnValue().Set(Nan::New("FieldDefn").ToLocalChecked());
}
/**
* @attribute name
* @type {String}
*/
NAN_GETTER(FieldDefn::nameGetter)
{
Nan::HandleScope scope;
FieldDefn *def = Nan::ObjectWrap::Unwrap<FieldDefn>(info.This());
info.GetReturnValue().Set(SafeString::New(def->this_->GetNameRef()));
}
/**
* Data type (see {{#crossLink "Constants (OFT)"}}OFT constants{{/crossLink}})
*
* @attribute type
* @type {String}
*/
NAN_GETTER(FieldDefn::typeGetter)
{
Nan::HandleScope scope;
FieldDefn *def = Nan::ObjectWrap::Unwrap<FieldDefn>(info.This());
info.GetReturnValue().Set(SafeString::New(getFieldTypeName(def->this_->GetType())));
}
/**
* @attribute ignored
* @type {Boolean}
*/
NAN_GETTER(FieldDefn::ignoredGetter)
{
Nan::HandleScope scope;
FieldDefn *def = Nan::ObjectWrap::Unwrap<FieldDefn>(info.This());
info.GetReturnValue().Set(Nan::New<Boolean>(def->this_->IsIgnored()));
}
/**
* Field justification (see {{#crossLink "Constants (OJ)"}}OJ constants{{/crossLink}})
*
* @attribute justification
* @type {String}
*/
NAN_GETTER(FieldDefn::justificationGetter)
{
Nan::HandleScope scope;
FieldDefn *def = Nan::ObjectWrap::Unwrap<FieldDefn>(info.This());
OGRJustification justification = def->this_->GetJustify();
if (justification == OJRight) {
info.GetReturnValue().Set(Nan::New("Right").ToLocalChecked());
return;
}
if (justification == OJLeft) {
info.GetReturnValue().Set(Nan::New("Left").ToLocalChecked());
return;
}
info.GetReturnValue().Set(Nan::Undefined());
}
/**
* @attribute width
* @type {Integer}
*/
NAN_GETTER(FieldDefn::widthGetter)
{
Nan::HandleScope scope;
FieldDefn *def = Nan::ObjectWrap::Unwrap<FieldDefn>(info.This());
info.GetReturnValue().Set(Nan::New<Integer>(def->this_->GetWidth()));
}
/**
* @attribute precision
* @type {Integer}
*/
NAN_GETTER(FieldDefn::precisionGetter)
{
Nan::HandleScope scope;
FieldDefn *def = Nan::ObjectWrap::Unwrap<FieldDefn>(info.This());
info.GetReturnValue().Set(Nan::New<Integer>(def->this_->GetPrecision()));
}
NAN_SETTER(FieldDefn::nameSetter)
{
Nan::HandleScope scope;
FieldDefn *def = Nan::ObjectWrap::Unwrap<FieldDefn>(info.This());
if(!value->IsString()){
Nan::ThrowError("Name must be string");
return;
}
std::string name = *Nan::Utf8String(value);
def->this_->SetName(name.c_str());
}
NAN_SETTER(FieldDefn::typeSetter)
{
Nan::HandleScope scope;
FieldDefn *def = Nan::ObjectWrap::Unwrap<FieldDefn>(info.This());
if(!value->IsString()){
Nan::ThrowError("type must be a string");
return;
}
std::string name = *Nan::Utf8String(value);
int type = getFieldTypeByName(name.c_str());
if(type < 0){
Nan::ThrowError("Unrecognized field type");
} else {
def->this_->SetType(OGRFieldType(type));
}
}
NAN_SETTER(FieldDefn::justificationSetter)
{
Nan::HandleScope scope;
FieldDefn *def = Nan::ObjectWrap::Unwrap<FieldDefn>(info.This());
OGRJustification justification;
std::string str = *Nan::Utf8String(value);
if(value->IsString()){
if(str == "Left") {
justification = OJLeft;
} else if (str == "Right") {
justification = OJRight;
} else if (str == "Undefined") {
justification = OJUndefined;
} else {
Nan::ThrowError("Unrecognized justification");
return;
}
} else if (value->IsNull() || value->IsUndefined()){
justification = OJUndefined;
} else {
Nan::ThrowError("justification must be a string or undefined");
return;
}
def->this_->SetJustify(justification);
}
NAN_SETTER(FieldDefn::widthSetter)
{
Nan::HandleScope scope;
FieldDefn *def = Nan::ObjectWrap::Unwrap<FieldDefn>(info.This());
if(!value->IsInt32()){
Nan::ThrowError("width must be an integer");
return;
}
def->this_->SetWidth(value->IntegerValue());
}
NAN_SETTER(FieldDefn::precisionSetter)
{
Nan::HandleScope scope;
FieldDefn *def = Nan::ObjectWrap::Unwrap<FieldDefn>(info.This());
if(!value->IsInt32()){
Nan::ThrowError("precision must be an integer");
return;
}
def->this_->SetPrecision(value->IntegerValue());
}
NAN_SETTER(FieldDefn::ignoredSetter)
{
Nan::HandleScope scope;
FieldDefn *def = Nan::ObjectWrap::Unwrap<FieldDefn>(info.This());
if(!value->IsBoolean()){
Nan::ThrowError("ignored must be a boolean");
return;
}
def->this_->SetIgnored(value->IntegerValue());
}
} // namespace node_gdal | 24.587662 | 110 | 0.694309 | [
"object"
] |
a3ac9a37e5ee066ac4ce19579eb6c40968e382b9 | 5,282 | cpp | C++ | GDP2019_20/main.cpp | RichyRich515/OpenGL | 6b2e21d6b78b5e04d3403440f7cf95dc739d58cf | [
"MIT"
] | null | null | null | GDP2019_20/main.cpp | RichyRich515/OpenGL | 6b2e21d6b78b5e04d3403440f7cf95dc739d58cf | [
"MIT"
] | null | null | null | GDP2019_20/main.cpp | RichyRich515/OpenGL | 6b2e21d6b78b5e04d3403440f7cf95dc739d58cf | [
"MIT"
] | null | null | null | // Main.cpp
// Entrypoint for program
// 2019-09-04
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <vector>
#include <glm/glm.hpp>
#include <glm/vec3.hpp> // glm::vec3
#include <glm/vec4.hpp> // glm::vec4
#include <glm/mat4x4.hpp> // glm::mat4
#include <glm/gtc/matrix_transform.hpp>
// glm::translate, glm::rotate, glm::scale, glm::perspective
#include <glm/gtc/type_ptr.hpp> // glm::value_ptr
static const struct Vertex
{
float x, y;
float r, g, b;
};
std::vector<Vertex> vertices;
static const char* vertex_shader_text =
"uniform mat4 MVP;\n"
"attribute vec3 vCol;\n"
"attribute vec2 vPos;\n"
"varying vec3 color;\n"
"void main()\n"
"{\n"
" gl_Position = MVP * vec4(vPos, 0.0, 1.0);\n"
" color = vCol;\n"
"}\n";
static const char* fragment_shader_text =
"varying vec3 color;\n"
"void main()\n"
"{\n"
" gl_FragColor = vec4(color, 1.0);\n"
"}\n";
static void error_callback(int error, const char* description)
{
fprintf(stderr, "Error: %s\n", description);
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GLFW_TRUE);
}
int main(void)
{
GLFWwindow* window;
GLuint vertex_buffer, vertex_shader, fragment_shader, program;
GLint mvp_location, vpos_location, vcol_location;
glfwSetErrorCallback(error_callback);
if (!glfwInit())
{
exit(EXIT_FAILURE);
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
window = glfwCreateWindow(640, 480, "Simple example", NULL, NULL);
if (!window)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwSetKeyCallback(window, key_callback);
glfwMakeContextCurrent(window);
gladLoadGLLoader((GLADloadproc)glfwGetProcAddress);
glfwSwapInterval(1);
float x1 = 60.0f;
float x2 = -60.0f;
float x3 = 0;
float y1 = -30.0f;
float y2 = 60.f;
vertices.push_back(Vertex{ x1, y1, 1.0f, 0.0f, 0.0f });
vertices.push_back(Vertex{ x2, y1, 0.0f, 1.0f, 0.0f });
vertices.push_back(Vertex{ x3, y2, 0.0f, 0.0f, 1.0f });
for (int i = 0; i < 11; i++)
{
x1 = x1 / -2;
x2 = x2 / -2;
x3 = x3 / -2;
y1 = y1 / -2;
y2 = y2 / -2;
vertices.push_back(Vertex{ x1, y1, 1.0f, 0.0f, 0.0f });
vertices.push_back(Vertex{ x2, y1, 0.0f, 1.0f, 0.0f });
vertices.push_back(Vertex{ x3, y2, 0.0f, 0.0f, 1.0f });
}
// NOTE: OpenGL error checks have been omitted for brevity
glGenBuffers(1, &vertex_buffer);
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * vertices.size(), vertices.data(), GL_STATIC_DRAW);
vertex_shader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex_shader, 1, &vertex_shader_text, NULL);
glCompileShader(vertex_shader);
fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment_shader, 1, &fragment_shader_text, NULL);
glCompileShader(fragment_shader);
program = glCreateProgram();
glAttachShader(program, vertex_shader);
glAttachShader(program, fragment_shader);
glLinkProgram(program);
mvp_location = glGetUniformLocation(program, "MVP");
vpos_location = glGetAttribLocation(program, "vPos");
vcol_location = glGetAttribLocation(program, "vCol");
glEnableVertexAttribArray(vpos_location);
glVertexAttribPointer(vpos_location, 2, GL_FLOAT, GL_FALSE, sizeof(vertices[0]), (void*)0);
glEnableVertexAttribArray(vcol_location);
glVertexAttribPointer(vcol_location, 3, GL_FLOAT, GL_FALSE, sizeof(vertices[0]), (void*)(sizeof(float) * 2));
glm::vec3 cameraEye = glm::vec3(0.0, 15.0, -150.0f);
glm::vec3 cameraTarget = glm::vec3(0.0f, 15.0f, 0.0f);
glm::vec3 upVector = glm::vec3(0.0f, 1.0f, 0.0f);
double startTime = glfwGetTime();
double lastTime = glfwGetTime();
double dt;
float cameraMovement = -10;
while (!glfwWindowShouldClose(window))
{
dt = lastTime - glfwGetTime();
lastTime = glfwGetTime();
float ratio;
int width, height;
glm::mat4 m, p, v, mvp;
glfwGetFramebufferSize(window, &width, &height);
ratio = width / (float)height;
glViewport(0, 0, width, height);
glClear(GL_COLOR_BUFFER_BIT);
// Wireframe
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
// Default
//glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
// Also see GL_POINT
m = glm::mat4(1.0f);
glm::mat4 rotateZ = glm::rotate(glm::mat4(1.0f), 0.0f, glm::vec3(0.0f, 0.0f, 1.0f));
m = m * rotateZ;
p = glm::perspective(0.6f, ratio, 0.1f, 1000.0f);
v = glm::mat4(1.0f);
// Move camera
if (cameraEye.z < 0)
{
cameraEye.y += dt * -cameraMovement / 10;
cameraTarget.y += dt * -cameraMovement / 10;
}
else
{
cameraEye.y -= dt * -cameraMovement / 10;
cameraTarget.y -= dt * -cameraMovement / 10;
}
if (cameraEye.z > 150)
cameraMovement = 10;
else if (cameraEye.z < -150)
cameraMovement = -10;
cameraEye.z += dt * cameraMovement;
std::cout << cameraEye.z << std::endl;
v = glm::lookAt(cameraEye, cameraTarget, upVector);
mvp = p * v * m;
glUseProgram(program);
glUniformMatrix4fv(mvp_location, 1, GL_FALSE, glm::value_ptr(mvp));
glDrawArrays(GL_TRIANGLES, 0, vertices.size());
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
exit(EXIT_SUCCESS);
}
| 25.765854 | 110 | 0.693677 | [
"vector"
] |
a3aebfae0220b74b7dd416de867f617ec0bc91e2 | 7,108 | cpp | C++ | 03_Tutorial/T06_XMGraphics/G11_AniTranslate/Source/main.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | 2 | 2017-08-03T07:15:00.000Z | 2018-06-18T10:32:53.000Z | 03_Tutorial/T06_XMGraphics/G11_AniTranslate/Source/main.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | null | null | null | 03_Tutorial/T06_XMGraphics/G11_AniTranslate/Source/main.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | 2 | 2019-03-04T22:57:42.000Z | 2020-03-06T01:32:26.000Z | /*
*
* File main.cpp
* Description XMGraphics : Translate animation demo
* Version 0.20.0801, 2011-08-01
* Author Y.H Mun
*
* --------------------------------------------------------------------------
*
* Copyright (C) 2010-2011 XMSoft. All rights reserved.
*
* Contact Email: chris@xmsoft.co.kr
* xmsoft77@gmail.com
*
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*
*/
#include "main.h"
#include "platform.h"
XM_APP_MAIN_BEGIN
XM_APP_WND_REALIZE(XM_SYS_DEFAULT)
XM_APP_MAIN_END
#define GRID_Y 9
#define INTERVAL 3000
static KDvoid SetAnimate ( KDvoid )
{
KD_GET_TLS ( KDTLS, tls );
GLfloat ani[ ] =
{
0.0f,
XMG_I2F ( tls->wnd_cx ), 0.0f, 0.0f, // position
1.0f, // alpha
0.0f,
0.0f, 0.0f, 0.0f,
0.0f,
};
GLfloat base = 500.0f;
GLfloat inc = 250.0f;
GLuint row;
for ( row = 0; row < GRID_Y; row++ )
{
switch ( row )
{
case 0 :
case GRID_Y - 1 : ani[ 5 ] = base; break;
default : ani[ 5 ] = base + inc; inc += 150.f; break;
}
tls->xmg_ani[ GRID_Y - row - 1 ]->SetKeyFrameByMask ( XMG_ANI_POSITION | XMG_ANI_ALPHA, 2, ani );
}
}
KDvoid SetQuad ( KDvoid )
{
KD_GET_TLS ( KDTLS, tls );
GLuint row;
XMGRectF v;
XMGRectF c;
GLfloat h_v;
GLfloat h_c;
GLfloat mul;
XMGVector3F pos;
XMGVector2F size;
v.m_w = XMG_I2F ( tls->wnd_cx );
v.m_h = XMG_I2F ( tls->wnd_cy );
tls->xmg_tex[ 0 ]->GetImageSize ( size );
c.m_w = size.m_x;
c.m_h = size.m_y;
h_v = v.m_h / GRID_SIZE;
h_c = c.m_h / GRID_SIZE;
for ( row = 0; row < GRID_Y; row++ )
{
switch ( row )
{
case 0 :
case GRID_Y - 1 : mul = 3.f; break;
default : mul = 2.f; break;
}
v.m_h = h_v * mul;
c.m_h = h_c * mul;
tls->xmg_quad[ 0 ]->SetVertexArray( &v, row );
tls->xmg_quad[ 1 ]->SetVertexArray( &v, row );
tls->xmg_quad[ 0 ]->SetPosition ( pos, row );
tls->xmg_quad[ 1 ]->SetPosition ( pos, row );
tls->xmg_quad[ 0 ]->SetTexture ( tls->xmg_tex[ 0 ], c, XMG_TEX_UNIT_0, row );
tls->xmg_quad[ 1 ]->SetTexture ( tls->xmg_tex[ 1 ], c, XMG_TEX_UNIT_0, row );
pos.m_y += v.m_h;
c.m_y += c.m_h;
}
}
KDvoid xmEventCreate ( KDvoid )
{
KD_SET_TLS ( KDTLS );
KD_GET_TLS ( KDTLS, tls );
GLuint idx;
tls->xmg_canvas = new XMGCanvas ( );
tls->xmg_font = new XMGFont ( "/res/font/COOPBL.TTF" );
tls->xmg_tex[0] = new XMGTexture ( "/res/image/menu.jpg" );
tls->xmg_tex[1] = new XMGTexture ( "/res/image/list.jpg" );
tls->xmg_text = new XMGText ( );
tls->xmg_quad[ 0 ] = new XMGQuad ( GRID_Y );
tls->xmg_quad[ 1 ] = new XMGQuad ( GRID_Y );
for ( idx = 0; idx < GRID_Y; idx++ )
{
tls->xmg_ani[ idx ] = new XMGAnimate ( );
}
tls->xmg_canvas->ClearColor ( XMGColorF ( 0, 0, 0, 1.0f ) );
tls->xmg_text->SetFont ( tls->xmg_font );
tls->xmg_text->SetText ( "XMGraphics : Translate" );
}
KDvoid xmEventDestroy ( KDvoid )
{
KD_GET_TLS ( KDTLS, tls );
for ( GLuint idx = 0; idx < GRID_Y; idx++ )
{
delete tls->xmg_ani[ idx ];
}
delete tls->xmg_quad[0];
delete tls->xmg_quad[1];
delete tls->xmg_text;
delete tls->xmg_tex[0];
delete tls->xmg_tex[1];
delete tls->xmg_font;
delete tls->xmg_canvas;
}
KDvoid xmEventRedraw ( KDvoid )
{
KD_GET_TLS ( KDTLS, tls );
tls->xmg_canvas->Clear ( );
tls->xmg_quad[ 0 ]->Render ( );
tls->xmg_quad[ 1 ]->Render ( );
tls->xmg_text->Render ( );
tls->xmg_canvas->Flush ( );
}
KDvoid xmEventUpdate ( KDuint msec )
{
KD_GET_TLS ( KDTLS, tls );
KDust t = msec - tls->app_msec;
GLuint row;
XMGMatrix4F mat;
XMGColorF col;
if ( t > INTERVAL )
{
t = 0;
tls->app_msec = msec;
}
for ( row = 0; row < GRID_Y; row++ )
{
tls->xmg_ani[ row ]->Update ( t, &mat, &col );
tls->xmg_quad[ 0 ]->SetColor ( col, row );
tls->xmg_quad[ 1 ]->SetMatrix ( mat, row );
}
}
KDvoid xmEventResize ( KDint width, KDint height )
{
KD_GET_TLS ( KDTLS, tls );
XMGRectF wnd = XMGRectF ( 0, 0, 0, XMG_I2F ( width ), XMG_I2F ( height ) );
tls->wnd_cx = width;
tls->wnd_cy = height;
tls->xmg_canvas->Viewport ( wnd );
tls->xmg_canvas->Perspective ( width, height );
tls->xmg_text->SetPosition ( XMGVector3F ( 5.0f, wnd.m_h - 20.0f ) );
tls->xmg_text->SetLineLength ( wnd.m_w - 5.0f );
SetQuad ( );
SetAnimate ( );
}
KD_API KDvoid KD_APIENTRY xmEventProc(const KDEvent* event)
{
switch (event->type)
{
case KD_EVENT_NATIVE:
{
//#if !defined ( SHP ) && defined ( _WIN32 )
//KDEventNativeWin32* proc = (KDEventNativeWin32*) event->data.native.p;
//KDEventNativeLinux* proc = (KDEventNativeLinux*) event->data.native.p;
//#endif
} break;
case KD_EVENT_CREATE:
{
// event->data.size.width;
// event->data.size.height;
xmEventCreate();
xmEventResize(event->data.size.width, event->data.size.height);
} break;
case KD_EVENT_DESTROY:
{
xmEventDestroy();
} break;
case KD_EVENT_RESIZE:
{
// event->data.size.width;
// event->data.size.height;
xmEventResize(event->data.size.width, event->data.size.height);
} break;
case KD_EVENT_FOCUS:
{
// event->data.value.i;
// 1 : focus
} break;
case KD_EVENT_VISIBLE:
{
// event->data.value.i;
// 1 : visible
} break;
case KD_EVENT_REDRAW:
{
xmEventRedraw();
} break;
case KD_EVENT_UPDATE:
{
// event->data.update.msec;
xmEventUpdate(event->data.update.msec);
} break;
case KD_EVENT_TOUCH_BEGAN:
{
// event->data.touch.touches;
// event->data.touch.count;
} break;
case KD_EVENT_TOUCH_MOVED:
{
} break;
case KD_EVENT_TOUCH_ENDED:
{
} break;
case KD_EVENT_TOUCH_CANCELLED:
{
} break;
case KD_EVENT_KEY_RELEASED:
{
// event->data.keypad.code;
} break;
case KD_EVENT_KEY_PRESSED:
{
} break;
case KD_EVENT_ACCELEROMETER:
{
// event->data.accelerometer.x;
// event->data.accelerometer.y;
// event->data.accelerometer.z;
} break;
case KD_EVENT_LOCATION:
{
// event->data.value.i;
// KD_NMEA_UPDATED_GPS, KD_NMEA_UPDATED_USER
} break;
case KD_EVENT_INSERT_TEXT:
{
// event->data.insert.utf8;
} break;
case KD_EVENT_SERIALIZE:
{
// event->data.serialize.type;
// event->data.serialize.data;
// event->data.serialize.size;
} break;
}
} | 20.723032 | 99 | 0.606922 | [
"render"
] |
a3b0bcf036afb16b3ee92ffef1546427ec13a38b | 11,369 | cc | C++ | apps/shell_window_geometry_cache.cc | nagineni/chromium-crosswalk | 5725642f1c67d0f97e8613ec1c3e8107ab53fdf8 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 4 | 2017-04-05T01:51:34.000Z | 2018-02-15T03:11:54.000Z | apps/shell_window_geometry_cache.cc | nagineni/chromium-crosswalk | 5725642f1c67d0f97e8613ec1c3e8107ab53fdf8 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-12-13T19:44:12.000Z | 2021-12-13T19:44:12.000Z | apps/shell_window_geometry_cache.cc | nagineni/chromium-crosswalk | 5725642f1c67d0f97e8613ec1c3e8107ab53fdf8 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 4 | 2017-04-05T01:52:03.000Z | 2022-02-13T17:58:45.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "apps/shell_window_geometry_cache.h"
#include "base/bind.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/extensions/extension_prefs.h"
#include "chrome/browser/extensions/extension_prefs_factory.h"
#include "chrome/browser/profiles/incognito_helpers.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/extensions/extension.h"
#include "components/browser_context_keyed_service/browser_context_dependency_manager.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_types.h"
namespace {
// The timeout in milliseconds before we'll persist window geometry to the
// StateStore.
const int kSyncTimeoutMilliseconds = 1000;
} // namespace
namespace apps {
ShellWindowGeometryCache::ShellWindowGeometryCache(
Profile* profile, extensions::ExtensionPrefs* prefs)
: prefs_(prefs),
sync_delay_(base::TimeDelta::FromMilliseconds(kSyncTimeoutMilliseconds)) {
registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_LOADED,
content::Source<Profile>(profile));
registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED,
content::Source<Profile>(profile));
}
ShellWindowGeometryCache::~ShellWindowGeometryCache() {
}
// static
ShellWindowGeometryCache* ShellWindowGeometryCache::Get(
content::BrowserContext* context) {
return Factory::GetForContext(context, true /* create */);
}
void ShellWindowGeometryCache::SaveGeometry(
const std::string& extension_id,
const std::string& window_id,
const gfx::Rect& bounds,
const gfx::Rect& screen_bounds,
ui::WindowShowState window_state) {
ExtensionData& extension_data = cache_[extension_id];
// If we don't have any unsynced changes and this is a duplicate of what's
// already in the cache, just ignore it.
if (extension_data[window_id].bounds == bounds &&
extension_data[window_id].window_state == window_state &&
extension_data[window_id].screen_bounds == screen_bounds &&
!ContainsKey(unsynced_extensions_, extension_id))
return;
base::Time now = base::Time::Now();
extension_data[window_id].bounds = bounds;
extension_data[window_id].screen_bounds = screen_bounds;
extension_data[window_id].window_state = window_state;
extension_data[window_id].last_change = now;
if (extension_data.size() > kMaxCachedWindows) {
ExtensionData::iterator oldest = extension_data.end();
// Too many windows in the cache, find the oldest one to remove.
for (ExtensionData::iterator it = extension_data.begin();
it != extension_data.end(); ++it) {
// Don't expunge the window that was just added.
if (it->first == window_id) continue;
// If time is in the future, reset it to now to minimize weirdness.
if (it->second.last_change > now)
it->second.last_change = now;
if (oldest == extension_data.end() ||
it->second.last_change < oldest->second.last_change)
oldest = it;
}
extension_data.erase(oldest);
}
unsynced_extensions_.insert(extension_id);
// We don't use Reset() because the timer may not yet be running.
// (In that case Stop() is a no-op.)
sync_timer_.Stop();
sync_timer_.Start(FROM_HERE, sync_delay_, this,
&ShellWindowGeometryCache::SyncToStorage);
}
void ShellWindowGeometryCache::SyncToStorage() {
std::set<std::string> tosync;
tosync.swap(unsynced_extensions_);
for (std::set<std::string>::const_iterator it = tosync.begin(),
eit = tosync.end(); it != eit; ++it) {
const std::string& extension_id = *it;
const ExtensionData& extension_data = cache_[extension_id];
scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue);
for (ExtensionData::const_iterator it = extension_data.begin(),
eit = extension_data.end(); it != eit; ++it) {
base::DictionaryValue* value = new base::DictionaryValue;
const gfx::Rect& bounds = it->second.bounds;
const gfx::Rect& screen_bounds = it->second.screen_bounds;
DCHECK(!bounds.IsEmpty());
DCHECK(!screen_bounds.IsEmpty());
DCHECK(it->second.window_state != ui::SHOW_STATE_DEFAULT);
value->SetInteger("x", bounds.x());
value->SetInteger("y", bounds.y());
value->SetInteger("w", bounds.width());
value->SetInteger("h", bounds.height());
value->SetInteger("screen_bounds_x", screen_bounds.x());
value->SetInteger("screen_bounds_y", screen_bounds.y());
value->SetInteger("screen_bounds_w", screen_bounds.width());
value->SetInteger("screen_bounds_h", screen_bounds.height());
value->SetInteger("state", it->second.window_state);
value->SetString(
"ts", base::Int64ToString(it->second.last_change.ToInternalValue()));
dict->SetWithoutPathExpansion(it->first, value);
}
prefs_->SetGeometryCache(extension_id, dict.Pass());
}
}
bool ShellWindowGeometryCache::GetGeometry(
const std::string& extension_id,
const std::string& window_id,
gfx::Rect* bounds,
gfx::Rect* screen_bounds,
ui::WindowShowState* window_state) {
std::map<std::string, ExtensionData>::const_iterator
extension_data_it = cache_.find(extension_id);
// Not in the map means loading data for the extension didn't finish yet or
// the cache was not constructed until after the extension was loaded.
// Attempt to load from sync to address the latter case.
if (extension_data_it == cache_.end()) {
LoadGeometryFromStorage(extension_id);
extension_data_it = cache_.find(extension_id);
DCHECK(extension_data_it != cache_.end());
}
ExtensionData::const_iterator window_data_it = extension_data_it->second.find(
window_id);
if (window_data_it == extension_data_it->second.end())
return false;
const WindowData& window_data = window_data_it->second;
// Check for and do not return corrupt data.
if ((bounds && window_data.bounds.IsEmpty()) ||
(screen_bounds && window_data.screen_bounds.IsEmpty()) ||
(window_state && window_data.window_state == ui::SHOW_STATE_DEFAULT))
return false;
if (bounds)
*bounds = window_data.bounds;
if (screen_bounds)
*screen_bounds = window_data.screen_bounds;
if (window_state)
*window_state = window_data.window_state;
return true;
}
void ShellWindowGeometryCache::Shutdown() {
SyncToStorage();
}
ShellWindowGeometryCache::WindowData::WindowData()
: window_state(ui::SHOW_STATE_DEFAULT) {
}
ShellWindowGeometryCache::WindowData::~WindowData() {
}
void ShellWindowGeometryCache::Observe(
int type, const content::NotificationSource& source,
const content::NotificationDetails& details) {
switch (type) {
case chrome::NOTIFICATION_EXTENSION_LOADED: {
std::string extension_id =
content::Details<const extensions::Extension>(details).ptr()->id();
LoadGeometryFromStorage(extension_id);
break;
}
case chrome::NOTIFICATION_EXTENSION_UNLOADED: {
std::string extension_id =
content::Details<const extensions::UnloadedExtensionInfo>(details).
ptr()->extension->id();
OnExtensionUnloaded(extension_id);
break;
}
default:
NOTREACHED();
return;
}
}
void ShellWindowGeometryCache::SetSyncDelayForTests(int timeout_ms) {
sync_delay_ = base::TimeDelta::FromMilliseconds(timeout_ms);
}
void ShellWindowGeometryCache::LoadGeometryFromStorage(
const std::string& extension_id) {
ExtensionData& extension_data = cache_[extension_id];
const base::DictionaryValue* stored_windows =
prefs_->GetGeometryCache(extension_id);
if (!stored_windows)
return;
for (base::DictionaryValue::Iterator it(*stored_windows); !it.IsAtEnd();
it.Advance()) {
// If the cache already contains geometry for this window, don't
// overwrite that information since it is probably the result of an
// application starting up very quickly.
const std::string& window_id = it.key();
ExtensionData::iterator cached_window = extension_data.find(window_id);
if (cached_window == extension_data.end()) {
const base::DictionaryValue* stored_window;
if (it.value().GetAsDictionary(&stored_window)) {
WindowData& window_data = extension_data[it.key()];
int i;
if (stored_window->GetInteger("x", &i))
window_data.bounds.set_x(i);
if (stored_window->GetInteger("y", &i))
window_data.bounds.set_y(i);
if (stored_window->GetInteger("w", &i))
window_data.bounds.set_width(i);
if (stored_window->GetInteger("h", &i))
window_data.bounds.set_height(i);
if (stored_window->GetInteger("screen_bounds_x", &i))
window_data.screen_bounds.set_x(i);
if (stored_window->GetInteger("screen_bounds_y", &i))
window_data.screen_bounds.set_y(i);
if (stored_window->GetInteger("screen_bounds_w", &i))
window_data.screen_bounds.set_width(i);
if (stored_window->GetInteger("screen_bounds_h", &i))
window_data.screen_bounds.set_height(i);
if (stored_window->GetInteger("state", &i)) {
window_data.window_state =
static_cast<ui::WindowShowState>(i);
}
std::string ts_as_string;
if (stored_window->GetString("ts", &ts_as_string)) {
int64 ts;
if (base::StringToInt64(ts_as_string, &ts)) {
window_data.last_change = base::Time::FromInternalValue(ts);
}
}
}
}
}
}
void ShellWindowGeometryCache::OnExtensionUnloaded(
const std::string& extension_id) {
SyncToStorage();
cache_.erase(extension_id);
}
///////////////////////////////////////////////////////////////////////////////
// Factory boilerplate
// static
ShellWindowGeometryCache* ShellWindowGeometryCache::Factory::GetForContext(
content::BrowserContext* context, bool create) {
return static_cast<ShellWindowGeometryCache*>(
GetInstance()->GetServiceForBrowserContext(context, create));
}
ShellWindowGeometryCache::Factory*
ShellWindowGeometryCache::Factory::GetInstance() {
return Singleton<ShellWindowGeometryCache::Factory>::get();
}
ShellWindowGeometryCache::Factory::Factory()
: BrowserContextKeyedServiceFactory(
"ShellWindowGeometryCache",
BrowserContextDependencyManager::GetInstance()) {
DependsOn(extensions::ExtensionPrefsFactory::GetInstance());
}
ShellWindowGeometryCache::Factory::~Factory() {
}
BrowserContextKeyedService*
ShellWindowGeometryCache::Factory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
Profile* profile = Profile::FromBrowserContext(context);
return new ShellWindowGeometryCache(
profile,
extensions::ExtensionPrefs::Get(profile));
}
bool ShellWindowGeometryCache::Factory::ServiceIsNULLWhileTesting() const {
return false;
}
content::BrowserContext*
ShellWindowGeometryCache::Factory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return chrome::GetBrowserContextRedirectedInIncognito(context);
}
} // namespace apps
| 35.528125 | 88 | 0.704723 | [
"geometry"
] |
a3c1fd7448ed922c587b5f159f1e0455eb75eac2 | 1,681 | cpp | C++ | CHAPTER 4/C4DRILL.cpp | lrpinnto/stroustrup-exercises | a471a0d7b49b51b7c26e005ff9e66f3f6db199dd | [
"MIT"
] | null | null | null | CHAPTER 4/C4DRILL.cpp | lrpinnto/stroustrup-exercises | a471a0d7b49b51b7c26e005ff9e66f3f6db199dd | [
"MIT"
] | null | null | null | CHAPTER 4/C4DRILL.cpp | lrpinnto/stroustrup-exercises | a471a0d7b49b51b7c26e005ff9e66f3f6db199dd | [
"MIT"
] | null | null | null | #include "../stroustrup/std_lib_facilities.h"
//CHAPTER 4 DRILL
char unit_conversion(string a) //unit converter
{
if (a=="cm")
{
return 'c';
}
else if (a=="m")
{
return 'm';
}
else if (a=="in")
{
return 'i';
}
else if (a=="ft")
{
return 'f';
}
else
{
return ' ';
}
}
int main()
{
double a = 0;
double smallest = 0;
double largest = 0;
bool first_pass = true;
string unit = " ";
double sum = 0;
int counter = 0;
vector<double>all_numbers;
while (cin>>a>>unit)
{
switch (unit_conversion(unit)) //defaults to meters
{
case 'c':
a*=0.01;
break;
case 'm':
break;
case 'i':
a*=2.54;
a*=0.01;
break;
case 'f':
a*=12; //feet to inches
a*=2.54; //inches to cm
a*=0.01; //cm to m
break;
default:
cout<<"Wrong Unit!\n";
continue;
break;
}
if (a>largest || first_pass==true)
{
largest=a;
}
if (a<smallest || first_pass==true)
{
smallest=a;
}
cout<<smallest<<"m the smallest so far\t"<<largest<<"m the largest so far\t\n";
sum+=a;
counter++;
all_numbers.push_back(a);
first_pass=false;
}
cout<<"Sum of "<<sum<<" with a total of "<<counter<<" values!!\n";
sort(all_numbers);
for (double i : all_numbers)
{
cout<<i<<"m ; \n";
}
}
| 16.81 | 87 | 0.416419 | [
"vector"
] |
a3c2d7aa9e9d09576f5ea5624369838aec88a1f9 | 19,215 | cpp | C++ | dbms/src/Server/StorageConfigParser.cpp | solotzg/tiflash | 66f45c76692e941bc845c01349ea89de0f2cc210 | [
"Apache-2.0"
] | 4 | 2022-03-25T21:34:15.000Z | 2022-03-25T21:35:12.000Z | dbms/src/Server/StorageConfigParser.cpp | solotzg/tiflash | 66f45c76692e941bc845c01349ea89de0f2cc210 | [
"Apache-2.0"
] | null | null | null | dbms/src/Server/StorageConfigParser.cpp | solotzg/tiflash | 66f45c76692e941bc845c01349ea89de0f2cc210 | [
"Apache-2.0"
] | 8 | 2022-03-25T10:20:08.000Z | 2022-03-31T10:17:25.000Z | // Copyright 2022 PingCAP, Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/// Suppress gcc warning: ‘*((void*)&<anonymous> +4)’ may be used uninitialized in this function
#if !__clang__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
#endif
#include <cpptoml.h>
#if !__clang__
#pragma GCC diagnostic pop
#endif
#include <Common/Exception.h>
#include <Common/formatReadable.h>
#include <IO/ReadHelpers.h>
#include <IO/WriteHelpers.h>
#include <Poco/Path.h>
#include <Poco/String.h>
#include <Poco/StringTokenizer.h>
#include <Poco/Util/LayeredConfiguration.h>
#include <Server/StorageConfigParser.h>
#include <common/logger_useful.h>
#include <fmt/core.h>
#include <set>
#include <sstream>
#include <tuple>
#include <vector>
namespace DB
{
namespace ErrorCodes
{
extern const int INVALID_CONFIG_PARAMETER;
} // namespace ErrorCodes
static std::string getCanonicalPath(std::string path)
{
Poco::trimInPlace(path);
if (path.empty())
throw Exception("path configuration parameter is empty");
if (path.back() != '/')
path += '/';
return path;
}
static String getNormalizedPath(const String & s)
{
return getCanonicalPath(Poco::Path{s}.toString());
}
void TiFlashStorageConfig::parseStoragePath(const String & storage, Poco::Logger * log)
{
std::istringstream ss(storage);
cpptoml::parser p(ss);
auto table = p.parse();
auto get_checked_qualified_array = [log](const std::shared_ptr<cpptoml::table> table, const char * key) -> cpptoml::option<Strings> {
auto throw_invalid_value = [log, key]() {
String error_msg = fmt::format("The configuration \"storage.{}\" should be an array of strings. Please check your configuration file.", key);
LOG_FMT_ERROR(log, "{}", error_msg);
throw Exception(error_msg, ErrorCodes::INVALID_CONFIG_PARAMETER);
};
// not exist key
if (!table->contains_qualified(key))
return cpptoml::option<Strings>();
// key exist, but not array
auto qualified_ptr = table->get_qualified(key);
if (!qualified_ptr->is_array())
{
throw_invalid_value();
}
// key exist, but can not convert to string array, maybe it is an int array
auto string_array = table->get_qualified_array_of<String>(key);
if (!string_array)
{
throw_invalid_value();
}
return string_array;
};
// main
if (auto main_paths = get_checked_qualified_array(table, "main.dir"); main_paths)
main_data_paths = *main_paths;
if (auto main_capacity = table->get_qualified_array_of<int64_t>("main.capacity"); main_capacity)
{
for (const auto & c : *main_capacity)
main_capacity_quota.emplace_back(static_cast<size_t>(c));
}
if (main_data_paths.empty())
{
String error_msg = "The configuration \"storage.main.dir\" is empty. Please check your configuration file.";
LOG_FMT_ERROR(log, "{}", error_msg);
throw Exception(error_msg, ErrorCodes::INVALID_CONFIG_PARAMETER);
}
if (!main_capacity_quota.empty() && main_capacity_quota.size() != main_data_paths.size())
{
String error_msg = fmt::format(
"The array size of \"storage.main.dir\"[size={}] "
"is not equal to \"storage.main.capacity\"[size={}]. "
"Please check your configuration file.",
main_data_paths.size(),
main_capacity_quota.size());
LOG_FMT_ERROR(log, "{}", error_msg);
throw Exception(error_msg, ErrorCodes::INVALID_CONFIG_PARAMETER);
}
for (size_t i = 0; i < main_data_paths.size(); ++i)
{
// normalized
main_data_paths[i] = getNormalizedPath(main_data_paths[i]);
if (main_capacity_quota.size() <= i)
main_capacity_quota.emplace_back(0);
LOG_FMT_INFO(log, "Main data candidate path: {}, capacity_quota: {}", main_data_paths[i], main_capacity_quota[i]);
}
// latest
if (auto latest_paths = get_checked_qualified_array(table, "latest.dir"); latest_paths)
latest_data_paths = *latest_paths;
if (auto latest_capacity = table->get_qualified_array_of<int64_t>("latest.capacity"); latest_capacity)
{
for (const auto & c : *latest_capacity)
latest_capacity_quota.emplace_back(static_cast<size_t>(c));
}
// If it is empty, use the same dir as "main.dir"
if (latest_data_paths.empty())
{
LOG_FMT_INFO(log, "The configuration \"storage.latest.dir\" is empty, use the same dir and capacity of \"storage.main.dir\"");
latest_data_paths = main_data_paths;
latest_capacity_quota = main_capacity_quota;
}
if (!latest_capacity_quota.empty() && latest_capacity_quota.size() != latest_data_paths.size())
{
String error_msg = fmt::format(
"The array size of \"storage.latest.dir\"[size={}] "
"is not equal to \"storage.latest.capacity\"[size={}]. "
"Please check your configuration file.",
latest_data_paths.size(),
latest_capacity_quota.size());
LOG_FMT_ERROR(log, "{}", error_msg);
throw Exception(error_msg, ErrorCodes::INVALID_CONFIG_PARAMETER);
}
for (size_t i = 0; i < latest_data_paths.size(); ++i)
{
// normalized
latest_data_paths[i] = getNormalizedPath(latest_data_paths[i]);
if (latest_capacity_quota.size() <= i)
latest_capacity_quota.emplace_back(0);
LOG_FMT_INFO(log, "Latest data candidate path: {}, capacity_quota: {}", latest_data_paths[i], latest_capacity_quota[i]);
}
// Raft
if (auto kvstore_paths = get_checked_qualified_array(table, "raft.dir"); kvstore_paths)
kvstore_data_path = *kvstore_paths;
if (kvstore_data_path.empty())
{
// generated from latest path
for (const auto & s : latest_data_paths)
{
String path = Poco::Path{s + "/kvstore"}.toString();
kvstore_data_path.emplace_back(std::move(path));
}
}
for (auto & path : kvstore_data_path)
{
// normalized
path = getNormalizedPath(path);
LOG_FMT_INFO(log, "Raft data candidate path: {}", path);
}
}
void TiFlashStorageConfig::parseMisc(const String & storage_section, Poco::Logger * log)
{
std::istringstream ss(storage_section);
cpptoml::parser p(ss);
auto table = p.parse();
if (table->contains("bg_task_io_rate_limit"))
{
LOG_FMT_WARNING(log, "The configuration \"bg_task_io_rate_limit\" is deprecated. Check [storage.io_rate_limit] section for new style.");
}
if (auto version = table->get_qualified_as<UInt64>("format_version"); version)
{
format_version = *version;
}
if (auto lazily_init = table->get_qualified_as<Int32>("lazily_init_store"); lazily_init)
{
lazily_init_store = (*lazily_init != 0);
}
// config for experimental feature, may remove later
if (auto enable_v3 = table->get_qualified_as<Int32>("enable_ps_v3"); enable_v3)
{
enable_ps_v3 = (*enable_v3 != 0);
}
LOG_FMT_INFO(log, "format_version {} lazily_init_store {} enable_ps_v3 {}", format_version, lazily_init_store, enable_ps_v3);
}
Strings TiFlashStorageConfig::getAllNormalPaths() const
{
Strings all_normal_path;
std::set<String> path_set;
for (const auto & s : main_data_paths)
path_set.insert(s);
for (const auto & s : latest_data_paths)
path_set.insert(s);
// keep the first path
all_normal_path.emplace_back(latest_data_paths[0]);
path_set.erase(latest_data_paths[0]);
for (const auto & s : path_set)
all_normal_path.emplace_back(s);
return all_normal_path;
}
bool TiFlashStorageConfig::parseFromDeprecatedConfiguration(Poco::Util::LayeredConfiguration & config, Poco::Logger * log)
{
if (!config.has("path"))
return false;
LOG_FMT_WARNING(log, "The configuration \"path\" is deprecated. Check [storage] section for new style.");
String paths = config.getString("path");
Poco::trimInPlace(paths);
if (paths.empty())
throw Exception(
fmt::format("The configuration \"path\" is empty! [path={}]", config.getString("path")),
ErrorCodes::INVALID_CONFIG_PARAMETER);
Strings all_normal_path;
Poco::StringTokenizer string_tokens(paths, ",");
for (const auto & string_token : string_tokens)
{
all_normal_path.emplace_back(getNormalizedPath(string_token));
}
// If you set `path_realtime_mode` to `true` and multiple directories are deployed in the path, the latest data is stored in the first directory and older data is stored in the rest directories.
bool path_realtime_mode = config.getBool("path_realtime_mode", false);
for (size_t i = 0; i < all_normal_path.size(); ++i)
{
const String p = Poco::Path{all_normal_path[i]}.toString();
// Only use the first path for storing latest data
if (i == 0)
latest_data_paths.emplace_back(p);
if (path_realtime_mode)
{
if (i != 0)
main_data_paths.emplace_back(p);
}
else
{
main_data_paths.emplace_back(p);
}
}
{
// kvstore_path
String str_kvstore_path;
if (config.has("raft.kvstore_path"))
{
LOG_FMT_WARNING(log, "The configuration \"raft.kvstore_path\" is deprecated. Check [storage.raft] section for new style.");
str_kvstore_path = config.getString("raft.kvstore_path");
}
if (str_kvstore_path.empty())
{
str_kvstore_path = all_normal_path[0] + "/kvstore";
}
str_kvstore_path = getNormalizedPath(str_kvstore_path);
kvstore_data_path.emplace_back(str_kvstore_path);
}
// Ensure these vars are clear
main_capacity_quota.clear();
latest_capacity_quota.clear();
// logging
for (const auto & s : main_data_paths)
LOG_FMT_INFO(log, "Main data candidate path: {}", s);
for (const auto & s : latest_data_paths)
LOG_FMT_INFO(log, "Latest data candidate path: {}", s);
for (const auto & s : kvstore_data_path)
LOG_FMT_INFO(log, "Raft data candidate path: {}", s);
return true;
}
std::tuple<size_t, TiFlashStorageConfig> TiFlashStorageConfig::parseSettings(Poco::Util::LayeredConfiguration & config, Poco::Logger * log)
{
size_t global_capacity_quota = 0; // "0" by default, means no quota, use the whole disk capacity.
TiFlashStorageConfig storage_config;
// Always try to parse storage miscellaneous configuration when [storage] section exist.
if (config.has("storage"))
{
storage_config.parseMisc(config.getString("storage"), log);
}
if (config.has("storage.main"))
{
if (config.has("path"))
LOG_FMT_WARNING(log, "The configuration \"path\" is ignored when \"storage\" is defined.");
if (config.has("capacity"))
LOG_FMT_WARNING(log, "The configuration \"capacity\" is ignored when \"storage\" is defined.");
storage_config.parseStoragePath(config.getString("storage"), log);
if (config.has("raft.kvstore_path"))
{
Strings & kvstore_paths = storage_config.kvstore_data_path;
String deprecated_kvstore_path = config.getString("raft.kvstore_path");
if (!deprecated_kvstore_path.empty())
{
LOG_FMT_WARNING(log, "The configuration \"raft.kvstore_path\" is deprecated. Check \"storage.raft.dir\" for new style.");
kvstore_paths.clear();
kvstore_paths.emplace_back(getNormalizedPath(deprecated_kvstore_path));
for (auto & kvstore_path : kvstore_paths)
{
LOG_FMT_WARNING(
log,
"Raft data candidate path: {}. "
"The path is overwritten by deprecated configuration for backward compatibility.",
kvstore_path);
}
}
}
}
else
{
// capacity
if (config.has("capacity"))
{
LOG_FMT_WARNING(log, "The configuration \"capacity\" is deprecated. Check [storage] section for new style.");
// TODO: support human readable format for capacity, mark_cache_size, minmax_index_cache_size
// eg. 100GiB, 10MiB
String capacities = config.getString("capacity");
Poco::trimInPlace(capacities);
Poco::StringTokenizer string_tokens(capacities, ",");
size_t num_token = 0;
for (const auto & string_token : string_tokens)
{
if (num_token == 0)
{
global_capacity_quota = DB::parse<size_t>(string_token.data(), string_token.size());
}
num_token++;
}
if (num_token != 1)
LOG_FMT_WARNING(log, "Only the first number in configuration \"capacity\" take effect");
LOG_FMT_INFO(log, "The capacity limit is: {}", formatReadableSizeWithBinarySuffix(global_capacity_quota));
}
if (!storage_config.parseFromDeprecatedConfiguration(config, log))
{
// Can not parse from the deprecated configuration "path".
String msg = "The configuration \"storage.main\" section is not defined. Please check your configuration file.";
LOG_FMT_ERROR(log, "{}", msg);
throw Exception(msg, ErrorCodes::INVALID_CONFIG_PARAMETER);
}
}
return std::make_tuple(global_capacity_quota, storage_config);
}
void StorageIORateLimitConfig::parse(const String & storage_io_rate_limit, Poco::Logger * log)
{
std::istringstream ss(storage_io_rate_limit);
cpptoml::parser p(ss);
auto config = p.parse();
auto read_config = [&](const std::string & name, auto & value) {
if (auto p = config->get_qualified_as<typename std::remove_reference<decltype(value)>::type>(name); p)
{
value = *p;
}
};
read_config("max_bytes_per_sec", max_bytes_per_sec);
read_config("max_read_bytes_per_sec", max_read_bytes_per_sec);
read_config("max_write_bytes_per_sec", max_write_bytes_per_sec);
read_config("foreground_write_weight", fg_write_weight);
read_config("background_write_weight", bg_write_weight);
read_config("foreground_read_weight", fg_read_weight);
read_config("background_read_weight", bg_read_weight);
read_config("emergency_pct", emergency_pct);
read_config("high_pct", high_pct);
read_config("medium_pct", medium_pct);
read_config("tune_base", tune_base);
read_config("min_bytes_per_sec", min_bytes_per_sec);
read_config("auto_tune_sec", auto_tune_sec);
use_max_bytes_per_sec = (max_read_bytes_per_sec == 0 && max_write_bytes_per_sec == 0);
LOG_FMT_DEBUG(log, "storage.io_rate_limit {}", toString());
}
std::string StorageIORateLimitConfig::toString() const
{
return fmt::format(
"max_bytes_per_sec {} max_read_bytes_per_sec {} max_write_bytes_per_sec {} use_max_bytes_per_sec {} "
"fg_write_weight {} bg_write_weight {} fg_read_weight {} bg_read_weight {} fg_write_max_bytes_per_sec {} "
"bg_write_max_bytes_per_sec {} fg_read_max_bytes_per_sec {} bg_read_max_bytes_per_sec {} emergency_pct {} high_pct {} "
"medium_pct {} tune_base {} min_bytes_per_sec {} auto_tune_sec {}",
max_bytes_per_sec,
max_read_bytes_per_sec,
max_write_bytes_per_sec,
use_max_bytes_per_sec,
fg_write_weight,
bg_write_weight,
fg_read_weight,
bg_read_weight,
getFgWriteMaxBytesPerSec(),
getBgWriteMaxBytesPerSec(),
getFgReadMaxBytesPerSec(),
getBgReadMaxBytesPerSec(),
emergency_pct,
high_pct,
medium_pct,
tune_base,
min_bytes_per_sec,
auto_tune_sec);
}
UInt64 StorageIORateLimitConfig::readWeight() const
{
return fg_read_weight + bg_read_weight;
}
UInt64 StorageIORateLimitConfig::writeWeight() const
{
return fg_write_weight + bg_write_weight;
}
UInt64 StorageIORateLimitConfig::totalWeight() const
{
return readWeight() + writeWeight();
}
UInt64 StorageIORateLimitConfig::getFgWriteMaxBytesPerSec() const
{
if (totalWeight() <= 0 || writeWeight() <= 0)
{
return 0;
}
return use_max_bytes_per_sec ? max_bytes_per_sec / totalWeight() * fg_write_weight
: max_write_bytes_per_sec / writeWeight() * fg_write_weight;
}
UInt64 StorageIORateLimitConfig::getBgWriteMaxBytesPerSec() const
{
if (totalWeight() <= 0 || writeWeight() <= 0)
{
return 0;
}
return use_max_bytes_per_sec ? max_bytes_per_sec / totalWeight() * bg_write_weight
: max_write_bytes_per_sec / writeWeight() * bg_write_weight;
}
UInt64 StorageIORateLimitConfig::getFgReadMaxBytesPerSec() const
{
if (totalWeight() <= 0 || readWeight() <= 0)
{
return 0;
}
return use_max_bytes_per_sec ? max_bytes_per_sec / totalWeight() * fg_read_weight
: max_read_bytes_per_sec / readWeight() * fg_read_weight;
}
UInt64 StorageIORateLimitConfig::getBgReadMaxBytesPerSec() const
{
if (totalWeight() <= 0 || readWeight() <= 0)
{
return 0;
}
return use_max_bytes_per_sec ? max_bytes_per_sec / totalWeight() * bg_read_weight
: max_read_bytes_per_sec / readWeight() * bg_read_weight;
}
UInt64 StorageIORateLimitConfig::getWriteMaxBytesPerSec() const
{
return getBgWriteMaxBytesPerSec() + getFgWriteMaxBytesPerSec();
}
UInt64 StorageIORateLimitConfig::getReadMaxBytesPerSec() const
{
return getBgReadMaxBytesPerSec() + getFgReadMaxBytesPerSec();
}
bool StorageIORateLimitConfig::operator==(const StorageIORateLimitConfig & config) const
{
return config.max_bytes_per_sec == max_bytes_per_sec && config.max_read_bytes_per_sec == max_read_bytes_per_sec
&& config.max_write_bytes_per_sec == max_write_bytes_per_sec && config.bg_write_weight == bg_write_weight
&& config.fg_write_weight == fg_write_weight && config.bg_read_weight == bg_read_weight && config.fg_read_weight == fg_read_weight
&& config.emergency_pct == emergency_pct && config.high_pct == high_pct && config.medium_pct == medium_pct
&& config.tune_base == tune_base && config.min_bytes_per_sec == min_bytes_per_sec && config.auto_tune_sec == auto_tune_sec;
}
} // namespace DB
| 37.750491 | 198 | 0.656154 | [
"vector"
] |
a3c4d666300679be1575133d55f4d6a32a3465cc | 11,569 | cpp | C++ | ModuleUserInterface.cpp | rogerta97/TryHard_Engine | 6dc6725264a2a1d86530aa3d8f00f260f8509883 | [
"MIT"
] | null | null | null | ModuleUserInterface.cpp | rogerta97/TryHard_Engine | 6dc6725264a2a1d86530aa3d8f00f260f8509883 | [
"MIT"
] | null | null | null | ModuleUserInterface.cpp | rogerta97/TryHard_Engine | 6dc6725264a2a1d86530aa3d8f00f260f8509883 | [
"MIT"
] | null | null | null | #include "ModuleUserInterface.h"
#include "UI_Image.h"
#include "ModuleInput.h"
#include "GameObject.h"
#include "ComponentRectTransform.h"
#include "ModuleImGui.h"
#include "UI_GamePanel.h"
#include "ComponentCamera.h"
#include "SDL\include\SDL_events.h"
#include "ComponentMesh.h"
#include "ComponentTransform.h"
#include "Application.h"
#include "OpenGL.h"
#include "DebugDraw.h"
#include "Font.h"
#include "ComponentCanvas.h"
#include "ComponentButton.h"
#include "UI_Canvas.h"
#include "UI_Button.h"
#include "mmgr\mmgr.h"
ModuleUserInterface::ModuleUserInterface()
{
name = "User_Interface";
}
ModuleUserInterface::~ModuleUserInterface()
{
}
bool ModuleUserInterface::Init(JSON_Object * config)
{
FT_Error error = FT_Init_FreeType(&ft_library);
if (error)
{
CONSOLE_ERROR("... an error occurred during FONT library initialization ...");
}
LoadAllFonts();
interpolating = false;
return true;
}
bool ModuleUserInterface::Start()
{
ui_render_box.minPoint = { -1, -1, -1 };
ui_render_box.maxPoint = { 1, 1, 1 };
return true;
}
update_status ModuleUserInterface::Update(float dt)
{
if (IsKeyPressed('\x2')) { //If f1 is pressed we enable UI
App->user_interface->EnableUI(true);
}
if (App->imgui->game_panel->is_mouse_in)
{
float2 norm_mouse_pos = App->imgui->game_panel->GetMousePosInDockZeroOne();
GameObject* canvas_go = GetLastCanvas();
if (canvas_go == nullptr)
return UPDATE_CONTINUE;
ComponentRectTransform* canvas_rect_trans = (ComponentRectTransform*)canvas_go->GetComponent(CMP_RECTTRANSFORM);
float2 mouse_pos_in_canvas = float2(canvas_rect_trans->GetPointFromPercentage(norm_mouse_pos).x, canvas_rect_trans->GetPointFromPercentage(norm_mouse_pos).y);
//CONSOLE_LOG("x:%f, y:%f", mouse_pos_in_canvas.x, mouse_pos_in_canvas.y);
ComponentCanvas* cmp_canvas = (ComponentCanvas*)canvas_go->GetComponent(CMP_CANVAS);
std::vector<GameObject*> intersected_elements = std::vector<GameObject*>();
UI_Canvas* ui_canvas = cmp_canvas->GetCanvas();
ui_canvas->elements_in_canvas;
for (auto ui_iterator = ui_canvas->elements_in_canvas.begin(); ui_iterator != ui_canvas->elements_in_canvas.end(); ui_iterator++)
{
ComponentRectTransform* elem_rect = (ComponentRectTransform*)(*ui_iterator)->GetComponent(CMP_RECTTRANSFORM);
bool inside = elem_rect->isMouseInsideRect(mouse_pos_in_canvas);
if (inside && (*ui_iterator)->GetComponent(CMP_BUTTON))
intersected_elements.push_back((*ui_iterator));
}
//auto last_list_item = intersected_elements.back();
GameObject* element_on_top = nullptr;
if (intersected_elements.size() > 0)
element_on_top = intersected_elements.back();
if (element_on_top)
{
//CONSOLE_LOG(element_on_top->name.c_str());
ComponentButton* cmp_button = (ComponentButton*)element_on_top->GetComponent(CMP_BUTTON);
UI_Button* button = cmp_button->GetButton();
if (element_on_top->GetComponent(CMP_BUTTON))
{
if (cmp_button->has_mouse_entered == false)
{
Event new_event;
new_event.type = UI_ELEMENT_ENTER;
new_event.button.but = button;
App->BroadCastEvent(new_event);
cmp_button->has_mouse_entered = true;
}
if (App->input->GetMouseButton(SDL_BUTTON_LEFT) == KEY_DOWN)
{
Event new_event;
new_event.type = UI_ELEMENT_DOWN;
new_event.button.but = button;
if(App->GetGameState() == RUNNING)
App->camera->SetLocked(true);
App->BroadCastEvent(new_event);
}
else if (App->input->GetMouseButton(SDL_BUTTON_LEFT) == KEY_UP)
{
Event new_event;
new_event.type = UI_ELEMENT_UP;
new_event.button.but = button;
App->BroadCastEvent(new_event);
}
}
}
if (intersected_elements.size() < last_intersected_elements.size() && !App->user_interface->IsInterpolating() && App->user_interface->HasInterpolationEnded()) //this mean some gameobject is not under the mouse any more
{
int max_size = last_intersected_elements.size();
for (int i = intersected_elements.size() <= 0 ? 0 : intersected_elements.size() - 1; i < last_intersected_elements.size(); i++)
{
if (last_intersected_elements[i])
{
ComponentButton* cmp_button = (ComponentButton*)last_intersected_elements[i]->GetComponent(CMP_BUTTON);
if (cmp_button)
{
Event new_event;
new_event.type = UI_ELEMENT_OUT;
new_event.button.but = cmp_button->GetButton();
cmp_button->has_mouse_entered = false;
App->BroadCastEvent(new_event);
}
}
}
}
last_intersected_elements = intersected_elements;
}
//Alpha interpolation
InterpolateAlpha();
return UPDATE_CONTINUE;
}
update_status ModuleUserInterface::PostUpdate(float dt)
{
buttons_pressed.clear();
return update_status::UPDATE_CONTINUE;
}
bool ModuleUserInterface::CleanUp()
{
go_with_canvas.clear();
return true;
}
void ModuleUserInterface::CleanCanvasList()
{
go_with_canvas.clear();
}
void ModuleUserInterface::EnableUI(bool new_value)
{
ComponentCanvas* cmp_canvas = (ComponentCanvas*)GetLastCanvas()->GetComponent(CMP_CANVAS);
cmp_canvas->SetRenderElements(new_value);
}
Font ModuleUserInterface::GetFont(std::string font_name) const
{
for (auto it = fonts_face_list.begin(); it != fonts_face_list.end(); it++)
{
if ((*it)->name == font_name)
{
return *(*it);
}
}
return Font();
}
Font* ModuleUserInterface::LoadNewFont(std::string font_name, int size)
{
Font* font_to_add = new Font();
font_to_add->name = font_name;
string path = App->file_system->GetFontsPath() + "\\" + font_name + ".ttf";
FT_Error error = FT_New_Face(ft_library, path.c_str(), 0, &font_to_add->text_font);
if (error)
return nullptr;
else
{
if (FT_HAS_VERTICAL(font_to_add->text_font))
{
CONSOLE_LOG("Vertical fonts not supported");
return nullptr;
}
FT_Set_Pixel_Sizes(font_to_add->text_font, 0, size);
font_to_add->GenerateCharacterList();
font_to_add->size = size;
fonts_face_list.push_back(font_to_add);
return font_to_add;
}
FT_Done_Face(font_to_add->text_font);
FT_Done_FreeType(ft_library);
}
void ModuleUserInterface::LoadAllFonts()
{
std::vector<std::string> font_files_name = std::vector<std::string>();
App->file_system->GetFilesInDirectory(App->file_system->GetFontsPath().c_str(), font_files_name, false, false);
for (auto it = font_files_name.begin(); it != font_files_name.end(); it++)
{
std::string name = App->file_system->DeleteFileExtension((*it).c_str());
name = App->file_system->GetLastPathItem(name.c_str());
LoadNewFont(name.c_str(), 25);
}
}
void ModuleUserInterface::DeleteFont(std::string name)
{
for (auto it = fonts_face_list.begin(); it != fonts_face_list.end(); it++)
{
if ((*it)->name == name)
{
(*it)->CleanCharacterList();
delete (*it);
fonts_face_list.erase(it);
return;
}
}
}
void ModuleUserInterface::RecieveEvent(const Event & new_event)
{
for (auto it = go_with_canvas.begin(); it != go_with_canvas.end(); it++)
{
(*it)->OnEvent(new_event);
}
}
bool ModuleUserInterface::IsKeyPressed(char key)
{
for (auto it = buttons_pressed.begin(); it != buttons_pressed.end(); it++)
{
if ((*it) == key)
return true;
}
return false;
}
void ModuleUserInterface::SendInput(SDL_Event * e)
{
if (e->type == SDL_KEYUP)
return;
if (e->type == SDL_TEXTINPUT && *e->text.text != '8')
{
buttons_pressed.push_back(*e->text.text);
return;
}
if (e->key.keysym.scancode == SDL_SCANCODE_BACKSPACE)
{
buttons_pressed.push_back('\x1');
return;
}
if (e->key.keysym.scancode == SDL_SCANCODE_F1)
{
buttons_pressed.push_back('\x2');
return;
}
}
std::list<char>& ModuleUserInterface::GetInputLastFrame()
{
return buttons_pressed;
}
void ModuleUserInterface::DrawSceneUI(GameObject* camera)
{
bool editor_cam = false;
ComponentCamera* cam = (ComponentCamera*)camera->GetComponent(CMP_CAMERA);
if (cam->is_editor)
editor_cam = true;
//Draw normal GameObjects
for (auto it = go_with_canvas.begin(); it != go_with_canvas.end(); it++)
{
if (!editor_cam)
{
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
ComponentRectTransform* rtransform = (ComponentRectTransform*)(*it)->GetComponent(CMP_RECTTRANSFORM);
Transform canvas_transform = rtransform->GetTransform()->transform;
// args: left, right, bottom, top, near, far
float left = canvas_transform.position.x - rtransform->width / 2;
float right = canvas_transform.position.x + rtransform->width / 2;
float bottom = canvas_transform.position.y - rtransform->height / 2;
float top = canvas_transform.position.y + rtransform->height / 2;
float near_plane = 1000.0f;
float far_plane = -1000.0f;
glOrtho(left, right, bottom, top, near_plane, far_plane);
float3 min = { left, bottom, near_plane };
float3 max = { right, top, far_plane };
ui_render_box.minPoint = min;
ui_render_box.maxPoint = max;
}
//App->renderer3D->UseDebugRenderSettings();
//{
// LineSegment curr_line;
// glBegin(GL_LINES);
// App->renderer3D->UseDebugRenderSettings();
// glColor3f(1.0f, 0.0f, 0.0f);
// for (int i = 0; i < 12; i++)
// {
// curr_line = ui_render_box.Edge(i);
// glVertex3f(curr_line.a.x, curr_line.a.y, curr_line.a.z);
// glVertex3f(curr_line.b.x, curr_line.b.y, curr_line.b.z);
// }
// glEnd();
//}
(*it)->Draw(editor_cam);
}
}
void ModuleUserInterface::AddCanvas(GameObject* canvas_go)
{
bool add = true;
for (auto it = go_with_canvas.begin(); it != go_with_canvas.end(); it++)
{
if (canvas_go == (*it))
{
add = false;
break;
}
}
if (add)
go_with_canvas.push_back(canvas_go);
}
void ModuleUserInterface::DeleteCanvas(GameObject * go)
{
for (auto it = go_with_canvas.begin(); it != go_with_canvas.end(); it++)
{
if ((*it) == go)
{
go_with_canvas.erase(it);
return;
}
}
}
void ModuleUserInterface::AddaptCanvasToScreen()
{
for (auto it = go_with_canvas.begin(); it != go_with_canvas.end(); it++)
{
ComponentRectTransform* r_transform = (ComponentRectTransform*)(*it)->GetComponent(CMP_RECTTRANSFORM);
if (r_transform != nullptr)
{
r_transform->AddaptRectToScreenSize();
ComponentMesh* mesh_cmp = r_transform->GetRectQuadComponent();
mesh_cmp->UpdateBoundingBox(r_transform->GetTransform());
}
}
}
GameObject* ModuleUserInterface::GetLastCanvas() const
{
int limit = go_with_canvas.size();
int count = 0;
for (auto it = go_with_canvas.begin(); it != go_with_canvas.end(); it++)
{
if (++count == limit)
return (*it);
}
return nullptr;
}
AABB ModuleUserInterface::GetRenderBox() const
{
return ui_render_box;
}
float3 ModuleUserInterface::GetMousePos() const
{
return mouse_game_pos;
}
void ModuleUserInterface::SetMousePos(const float3 & new_pos)
{
mouse_game_pos = new_pos;
}
void ModuleUserInterface::InterpolateAlpha()
{
if (interpolating)
{
float alpha_percentage = (interpolation_timer.Read() / (interpolate_in*1000));
if (alpha_percentage >= 1.0f)
{
finished_interpolation = true;
}
Event alpha_event;
alpha_event.type = INTERPOLATE_ALPHA;
alpha_event.alpha_lvl.percentage = (1 - alpha_percentage);
App->BroadCastEvent(alpha_event);
}
}
void ModuleUserInterface::SetInterpolation(bool value, float time)
{
interpolating = value;
interpolate_in = time;
finished_interpolation = false;
interpolation_timer.Start();
}
bool ModuleUserInterface::IsInterpolating()
{
return interpolating;
}
bool ModuleUserInterface::HasInterpolationEnded()
{
return finished_interpolation;
}
| 23.466531 | 221 | 0.707494 | [
"vector",
"transform"
] |
a3cae32aa28db68fad4ddc12c52a95644cfe42a4 | 11,233 | hpp | C++ | include/mypp/mypp.hpp | oschonrock/qa | f17c16a76ba5fc1ec11561d9e1be70c77380bda7 | [
"BSD-3-Clause"
] | null | null | null | include/mypp/mypp.hpp | oschonrock/qa | f17c16a76ba5fc1ec11561d9e1be70c77380bda7 | [
"BSD-3-Clause"
] | null | null | null | include/mypp/mypp.hpp | oschonrock/qa | f17c16a76ba5fc1ec11561d9e1be70c77380bda7 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include "date/date.h"
#include "fmt/core.h"
#include "mysql.h"
#include "os/str.hpp"
#include "os/tmp.hpp"
#include <cstddef>
#include <cstring>
#include <sstream>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <unordered_set>
#include <vector>
namespace mypp {
class mysql;
class result;
class row;
// the result set obtained from a query. Wrapper for MYSQL_RES.
class result {
public:
result(mysql* mysql_, MYSQL_RES* result) : mysql(mysql_), myr(result) {}
result(const result& m) = delete;
result& operator=(const result& other) = delete;
result(result&& other) noexcept = delete;
result& operator=(result&& other) noexcept = delete;
~result() { ::mysql_free_result(myr); }
row fetch_row();
unsigned num_fields() { return ::mysql_num_fields(myr); }
std::vector<std::string> fieldnames();
std::size_t* lengths() {
// is a direct return if we used mysql_use_result
// so no point caching it
return ::mysql_fetch_lengths(myr);
}
struct Iterator;
Iterator begin();
Iterator end();
private:
mysql* mysql;
MYSQL_RES* myr;
};
namespace impl {
// adapted from fmt::detail
template <typename ReturnType>
constexpr ReturnType parse_nonnegative_int(const char* begin, const char* end,
ReturnType error_value) noexcept {
assert(begin != end && '0' <= *begin && *begin <= '9');
std::uint64_t value = 0;
std::uint64_t prev = 0;
const char* p = begin;
do {
prev = value;
value = value * 10 + std::uint64_t(*p - '0');
++p;
} while (p != end && '0' <= *p && *p <= '9');
auto num_digits = p - begin;
if (num_digits <= std::numeric_limits<ReturnType>::digits10)
return static_cast<ReturnType>(value);
// Check for overflow. Will never happen here
const auto max = static_cast<std::uint64_t>(std::numeric_limits<ReturnType>::max());
return num_digits == std::numeric_limits<ReturnType>::digits10 + 1 &&
prev * 10ULL + std::uint64_t(p[-1] - '0') <= max
? static_cast<ReturnType>(value)
: error_value;
}
// high peformance mysql date format parsing
template <typename TimePointType>
TimePointType parse_date_time(const char* s, std::size_t len) {
static_assert(std::is_same_v<TimePointType, date::sys_days> ||
std::is_same_v<TimePointType, date::sys_seconds>,
"don't know how to parse this timepoint");
using date::year, date::month, date::day, std::chrono::hours, std::chrono::minutes,
std::chrono::seconds;
// fmt YYYY-MM-DD HH:MM:SS (time part only applies to date::sys_seconds)
// 0123456789012345678
if (len < 10) throw std::domain_error("not long enough to parse a date `" + std::string(s) + "`");
date::year_month_day ymd = {year(parse_nonnegative_int(&s[0], &s[4], -1)),
month(parse_nonnegative_int(&s[5], &s[7], ~0U)),
day(parse_nonnegative_int(&s[8], &s[10], ~0U))};
if (!ymd.ok()) throw std::domain_error("invalid date `" + std::string(s) + "`");
auto date_tp = date::sys_days{ymd};
if constexpr (std::is_same_v<TimePointType, date::sys_days>) {
return date_tp;
} else { // date::sys_seconds
if (len < 19)
throw std::domain_error("not long enough to parse a datetime `" + std::string(s) + "`");
auto hrs = hours(parse_nonnegative_int(&s[11], &s[13], ~0U));
auto mins = minutes(parse_nonnegative_int(&s[14], &s[16], ~0U));
auto secs = seconds(parse_nonnegative_int(&s[17], &s[19], ~0U));
if (hrs.count() > 23 || mins.count() > 59 || secs.count() > 59)
throw std::domain_error("invalid time in `" + std::string(s) + "`");
return date_tp + hrs + mins + secs;
}
}
// mysql/mariadb specific parsing
template <typename NumericType>
inline NumericType parse(const char* str, std::size_t len) {
if constexpr (os::tmp::is_optional<NumericType>::value) {
if (str == nullptr) return std::nullopt;
using InnerType = std::remove_reference_t<decltype(std::declval<NumericType>().value())>;
// special DATE and DATETIME null'ish values
if constexpr (std::is_same_v<InnerType, date::sys_seconds>) {
if (std::strcmp(str, "0000-00-00 00:00:00") == 0) return std::nullopt;
} else if constexpr (std::is_same_v<InnerType, date::sys_days>) {
if (std::strcmp(str, "0000-00-00") == 0) return std::nullopt;
}
return parse<InnerType>(str, len); // unwrap and recurse
} else {
if (str == nullptr)
throw std::domain_error("requested type was not std::optional, but db returned NULL");
if constexpr (std::is_same_v<NumericType, bool>) {
return os::str::parse<long>(str) != 0; // db uses int{0} and int{1} for bool
} else if constexpr (std::is_same_v<NumericType, date::sys_days> ||
std::is_same_v<NumericType, date::sys_seconds>) {
return parse_date_time<NumericType>(str, len);
} else {
// delegate to general numeric formats
return os::str::parse<NumericType>(str, len);
}
}
}
} // namespace impl
// representing one row of a resultset. Wrapper for MYSQL_ROW
class row {
public:
row(result& result_set, MYSQL_ROW row) : rs(&result_set), row_(row) {}
result* rs;
bool empty() { return row_ == nullptr; }
[[nodiscard]] std::vector<std::string> vector() const {
return std::vector<std::string>(row_, row_ + rs->num_fields());
}
[[nodiscard]] char* operator[](unsigned idx) const { return row_[idx]; }
[[nodiscard]] char* at(unsigned idx) const {
if (idx >= rs->num_fields()) throw std::logic_error("field idx out of bounds");
return row_[idx];
}
[[nodiscard]] std::size_t len(unsigned idx) const { return rs->lengths()[idx]; }
template <typename ValueType = std::string>
[[nodiscard]] ValueType get(unsigned idx) const {
// try numeric parsing by default
return impl::parse<ValueType>((*this)[idx], len(idx));
}
// takes a copy in a std::string
template <>
[[nodiscard]] std::string get<std::string>(unsigned idx) const {
return (*this)[idx]; // converting constructor
}
// access to the raw const char*, potentially for external parsing
// beware lifetimes!
template <>
[[nodiscard]] const char* get<const char*>(unsigned idx) const {
return (*this)[idx];
}
bool operator==(const row& rhs) const { return row_ == rhs.row_; }
bool operator!=(const row& rhs) const { return row_ != rhs.row_; }
private:
MYSQL_ROW row_;
};
// Iterates over a result set
struct result::Iterator {
using iterator_category = std::input_iterator_tag;
using difference_type = std::ptrdiff_t;
using value_type = const row;
using pointer = const row*;
using reference = const row&;
explicit Iterator(value_type row) : currow_(row) {}
reference operator*() const { return currow_; }
pointer operator->() const { return &currow_; }
Iterator& operator++() {
currow_ = currow_.rs->fetch_row();
return *this;
}
Iterator operator++(int) { // NOLINT const weirdness
Iterator tmp = *this;
++(*this);
return tmp;
}
bool operator==(const Iterator& rhs) const { return currow_ == rhs.currow_; }
bool operator!=(const Iterator& rhs) const { return currow_ != rhs.currow_; }
private:
row currow_; // atypically we store the value_type, because operator++ is a function
};
// representing a mysql/mariadb connection handle. Wrapper for MYSQL*
class mysql {
public:
mysql();
mysql(const mysql& m) = delete;
mysql& operator=(const mysql& other) = delete;
mysql(mysql&& other) noexcept = default; // needed to init static in con
mysql& operator=(mysql&& other) noexcept = delete;
~mysql() { ::mysql_close(mysql_); }
void connect(const std::string& host, const std::string& user, const std::string& password,
const std::string& db, unsigned port = 0, const std::string& socket = "",
std::uint64_t flags = 0UL);
void set_character_set(const std::string& charset);
std::string get_host_info();
result query(const std::string& sql, bool expect_result = true);
std::vector<std::string> single_row(const std::string& sql);
// throws if row not found
template <typename ValueType>
ValueType single_value(const std::string& sql, unsigned col = 0) {
static_assert(!std::is_same_v<ValueType, const char*>,
"single_value<const char*> will result in dangling pointers");
auto rs = query(sql);
auto row = rs.fetch_row();
if (row.empty()) throw std::logic_error("single row not found by: " + sql);
if (rs.num_fields() < col + 1)
throw std::logic_error("column " + std::to_string(col) + " not found");
return row.get<ValueType>(col); // take copy in appropriate type
}
template <typename ContainerType>
ContainerType single_column(const std::string& sql, unsigned col = 0) {
ContainerType values;
auto rs = query(sql);
using ValueType = typename ContainerType::value_type;
static_assert(!std::is_same_v<ValueType, const char*>,
"single_column<Container<const char*>> will result in dangling pointers");
for (auto&& row: rs) {
if constexpr (os::tmp::has_push_back<ContainerType>::value)
values.push_back(row.get<ValueType>(col));
else
values.insert(row.get<ValueType>(col));
}
return values;
}
int get_max_allowed_packet();
std::string quote(const char* in);
unsigned errnumber() { return ::mysql_errno(mysql_); }
std::string error() { return ::mysql_error(mysql_); }
void begin() { query("begin", false); }
void rollback() { query("rollback", false); }
private:
MYSQL* mysql_ = nullptr;
};
std::string quote_identifier(const std::string& identifier);
namespace impl {
// render integer value into buffer pre-filled with '0'
// doesn't work for negatives, but uses long for convenient interoperability
inline constexpr void stamp(char* s, long i) {
do {
*s-- = static_cast<char>(i % 10) + '0'; // NOLINT narrowing
i /= 10;
} while (i > 0);
}
} // namespace impl
// much faster date format function "YYYY-MM-DD HH:MM:SS" (credit Howard Hinnant)
template <typename TimePointType>
std::string format_time_point(TimePointType tp) {
static_assert(std::is_same_v<TimePointType, date::sys_days> ||
std::is_same_v<TimePointType, date::sys_seconds>,
"do not know how to format this TimePointType");
auto today = floor<date::days>(tp);
using impl::stamp;
// YYYY-MM-DD
std::string out = "0000-00-00";
// 0123456789
if constexpr (std::is_same_v<TimePointType, date::sys_seconds>) {
// YYYY-MM-DD hh:mm:ss
out = "0000-00-00 00:00:00";
// 0123456789012345678
date::hh_mm_ss hms{tp - today};
stamp(&out[12], hms.hours().count());
stamp(&out[15], hms.minutes().count());
stamp(&out[18], hms.seconds().count());
}
date::year_month_day ymd = today;
stamp(&out[3], int{ymd.year()});
stamp(&out[6], unsigned{ymd.month()});
stamp(&out[9], unsigned{ymd.day()});
return out;
}
} // namespace mypp
| 32.55942 | 100 | 0.640523 | [
"render",
"vector"
] |
a3cb4100584a40494ac1c4f4bf0b9315cba8f1e8 | 12,319 | cc | C++ | cfg/CFG.cc | franco-cacere/sorbet | 27b1f8a789ef8e54233db7852e02ae4932a3f0c0 | [
"Apache-2.0"
] | 1 | 2020-12-21T11:22:16.000Z | 2020-12-21T11:22:16.000Z | cfg/CFG.cc | franco-cacere/sorbet | 27b1f8a789ef8e54233db7852e02ae4932a3f0c0 | [
"Apache-2.0"
] | 5 | 2021-06-28T20:36:33.000Z | 2022-02-27T11:09:55.000Z | cfg/CFG.cc | franco-cacere/sorbet | 27b1f8a789ef8e54233db7852e02ae4932a3f0c0 | [
"Apache-2.0"
] | null | null | null | #include "cfg/CFG.h"
#include "absl/strings/escaping.h"
#include "absl/strings/str_split.h"
#include "common/Timer.h"
#include "common/UIntSetForEach.h"
#include "common/formatting.h"
#include "common/sort.h"
// helps debugging
template class std::unique_ptr<sorbet::cfg::CFG>;
template class std::unique_ptr<sorbet::cfg::BasicBlock>;
template class std::vector<sorbet::cfg::BasicBlock *>;
using namespace std;
namespace sorbet::cfg {
CFG::ReadsAndWrites::ReadsAndWrites(u4 maxBasicBlockId, u4 numLocalVariables)
: reads(maxBasicBlockId, UIntSet(numLocalVariables)), writes(maxBasicBlockId, UIntSet(numLocalVariables)),
dead(maxBasicBlockId, UIntSet(numLocalVariables)) {}
CFG::UnfreezeCFGLocalVariables::UnfreezeCFGLocalVariables(CFG &cfg) : cfg(cfg) {
this->cfg.localVariablesFrozen = false;
}
CFG::UnfreezeCFGLocalVariables::~UnfreezeCFGLocalVariables() {
this->cfg.localVariablesFrozen = true;
}
int CFG::numLocalVariables() const {
return this->localVariables.size();
}
BasicBlock *CFG::freshBlock(int outerLoops, int rubyBlockId) {
int id = this->maxBasicBlockId++;
auto &r = this->basicBlocks.emplace_back(make_unique<BasicBlock>());
r->id = id;
r->outerLoops = outerLoops;
r->rubyBlockId = rubyBlockId;
return r.get();
}
void CFG::enterLocalInternal(core::LocalVariable variable, LocalRef &ref) {
ENFORCE_NO_TIMER(!this->localVariablesFrozen);
int id = this->localVariables.size();
this->localVariables.emplace_back(variable);
// Default values
this->minLoops.emplace_back(INT_MAX);
this->maxLoopWrite.emplace_back(0);
ENFORCE(this->localVariables.size() == this->minLoops.size());
ENFORCE(this->localVariables.size() == this->maxLoopWrite.size());
ref = LocalRef(id);
}
LocalRef CFG::enterLocal(core::LocalVariable variable) {
auto &ref = localVariableToLocalRef[variable];
if (!ref.exists() && variable.exists()) {
// ref is an out parameter.
enterLocalInternal(variable, ref);
}
return ref;
}
CFG::CFG() {
freshBlock(0, 0); // entry;
freshBlock(0, 0); // dead code;
deadBlock()->bexit.elseb = deadBlock();
deadBlock()->bexit.thenb = deadBlock();
deadBlock()->bexit.cond.variable = LocalRef::unconditional();
UnfreezeCFGLocalVariables unfreezeVars(*this);
// Enter a few fixed local variables
// noVariable is special because it doesn't 'exist'.
this->enterLocalInternal(core::LocalVariable::noVariable(),
localVariableToLocalRef[core::LocalVariable::noVariable()]);
LocalRef blockCall = this->enterLocal(core::LocalVariable::blockCall());
ENFORCE(blockCall == LocalRef::blockCall());
LocalRef selfVariable = this->enterLocal(core::LocalVariable::selfVariable());
ENFORCE(selfVariable == LocalRef::selfVariable());
LocalRef unconditional = this->enterLocal(core::LocalVariable::unconditional());
ENFORCE(unconditional == LocalRef::unconditional());
LocalRef finalReturn = this->enterLocal(core::LocalVariable(core::Names::finalReturn(), 0));
ENFORCE(finalReturn == LocalRef::finalReturn());
}
CFG::ReadsAndWrites CFG::findAllReadsAndWrites(core::Context ctx) {
Timer timeit(ctx.state.tracer(), "findAllReadsAndWrites");
CFG::ReadsAndWrites target(maxBasicBlockId, numLocalVariables());
for (unique_ptr<BasicBlock> &bb : this->basicBlocks) {
auto &blockWrites = target.writes[bb->id];
auto &blockReads = target.reads[bb->id];
auto &blockDead = target.dead[bb->id];
for (Binding &bind : bb->exprs) {
blockWrites.add(bind.bind.variable.id());
/*
* When we write to an alias, we rely on the type information being
* propagated through block arguments from the point of
* assignment. Treating every write as also reading from the
* variable serves to represent this.
*/
if (bind.bind.variable.isAliasForGlobal(ctx, *this) &&
cast_instruction<Alias>(bind.value.get()) == nullptr) {
blockReads.add(bind.bind.variable.id());
}
if (auto *v = cast_instruction<Ident>(bind.value.get())) {
blockReads.add(v->what.id());
} else if (auto *v = cast_instruction<Send>(bind.value.get())) {
blockReads.add(v->recv.variable.id());
for (auto &arg : v->args) {
blockReads.add(arg.variable.id());
}
} else if (auto *v = cast_instruction<TAbsurd>(bind.value.get())) {
blockReads.add(v->what.variable.id());
} else if (auto *v = cast_instruction<Return>(bind.value.get())) {
blockReads.add(v->what.variable.id());
} else if (auto *v = cast_instruction<BlockReturn>(bind.value.get())) {
blockReads.add(v->what.variable.id());
} else if (auto *v = cast_instruction<Cast>(bind.value.get())) {
blockReads.add(v->value.variable.id());
} else if (auto *v = cast_instruction<LoadSelf>(bind.value.get())) {
blockReads.add(v->fallback.id());
} else if (auto *v = cast_instruction<SolveConstraint>(bind.value.get())) {
blockReads.add(v->send.id());
}
if (!blockReads.contains(bind.bind.variable.id())) {
blockDead.add(bind.bind.variable.id());
}
}
ENFORCE(bb->bexit.cond.variable.exists());
if (bb->bexit.cond.variable != LocalRef::unconditional()) {
blockReads.add(bb->bexit.cond.variable.id());
}
}
vector<pair<int, int>> usageCounts(this->numLocalVariables());
{
Timer timeit(ctx.state.tracer(), "privates1");
for (auto blockId = 0; blockId < maxBasicBlockId; blockId++) {
UIntSet blockReadsAndWrites = target.reads[blockId];
blockReadsAndWrites.add(target.writes[blockId]);
blockReadsAndWrites.forEach([&usageCounts, blockId](u4 local) -> void {
if (usageCounts[local].first == 0) {
usageCounts[local].second = blockId;
}
usageCounts[local].first += 1;
});
}
}
{
Timer timeit(ctx.state.tracer(), "privates2");
auto local = 0;
vector<UIntSet> writesToRemove(maxBasicBlockId, UIntSet(numLocalVariables()));
for (const auto &usages : usageCounts) {
if (usages.first == 1) {
writesToRemove[usages.second].add(local);
}
local++;
}
auto blockId = 0;
for (const auto &blockWritesToRemove : writesToRemove) {
target.writes[blockId].remove(blockWritesToRemove);
blockId++;
}
}
return target;
}
void CFG::sanityCheck(core::Context ctx) {
if (!debug_mode) {
return;
}
for (auto &bb : this->basicBlocks) {
ENFORCE(bb->bexit.isCondSet(), "Block exit condition left unset for block {}", bb->toString(ctx, *this));
if (bb.get() == deadBlock()) {
continue;
}
auto thenCount = absl::c_count(bb->bexit.thenb->backEdges, bb.get());
auto elseCount = absl::c_count(bb->bexit.elseb->backEdges, bb.get());
ENFORCE(thenCount == 1, "bb id={}; then has {} back edges", bb->id, thenCount);
ENFORCE(elseCount == 1, "bb id={}; else has {} back edges", bb->id, elseCount);
if (bb->bexit.thenb == bb->bexit.elseb) {
ENFORCE(bb->bexit.cond.variable == LocalRef::unconditional());
} else {
ENFORCE(bb->bexit.cond.variable.exists());
ENFORCE(bb->bexit.cond.variable != LocalRef::unconditional());
}
}
}
string CFG::toString(const core::GlobalState &gs) const {
fmt::memory_buffer buf;
string symbolName = this->symbol.data(gs)->showFullName(gs);
fmt::format_to(buf,
"subgraph \"cluster_{}\" {{\n"
" label = \"{}\";\n"
" color = blue;\n"
" \"bb{}_0\" [shape = invhouse];\n"
" \"bb{}_1\" [shape = parallelogram];\n\n",
symbolName, symbolName, symbolName, symbolName);
for (auto &basicBlock : this->basicBlocks) {
auto text = basicBlock->toString(gs, *this);
auto lines = absl::StrSplit(text, "\n");
fmt::format_to(
buf,
" \"bb{}_{}\" [\n"
" label = \"{}\\l\"\n"
" ];\n\n"
" \"bb{}_{}\" -> \"bb{}_{}\" [style=\"bold\"];\n",
symbolName, basicBlock->id,
fmt::map_join(lines.begin(), lines.end(), "\\l", [](auto line) -> string { return absl::CEscape(line); }),
symbolName, basicBlock->id, symbolName, basicBlock->bexit.thenb->id);
if (basicBlock->bexit.thenb != basicBlock->bexit.elseb) {
fmt::format_to(buf, " \"bb{}_{}\" -> \"bb{}_{}\" [style=\"tapered\"];\n\n", symbolName, basicBlock->id,
symbolName, basicBlock->bexit.elseb->id);
}
}
fmt::format_to(buf, "}}");
return to_string(buf);
}
string CFG::showRaw(core::Context ctx) const {
fmt::memory_buffer buf;
string symbolName = this->symbol.data(ctx)->showFullName(ctx);
fmt::format_to(buf,
"subgraph \"cluster_{}\" {{\n"
" label = \"{}\";\n"
" color = blue;\n"
" \"bb{}_0\" [shape = box];\n"
" \"bb{}_1\" [shape = parallelogram];\n\n",
symbolName, symbolName, symbolName, symbolName);
for (auto &basicBlock : this->basicBlocks) {
auto text = basicBlock->showRaw(ctx, *this);
auto lines = absl::StrSplit(text, "\n");
fmt::format_to(
buf,
" \"bb{}_{}\" [\n"
" label = \"{}\\l\"\n"
" ];\n\n"
" \"bb{}_{}\" -> \"bb{}_{}\" [style=\"bold\"];\n",
symbolName, basicBlock->id,
fmt::map_join(lines.begin(), lines.end(), "\\l", [](auto line) -> string { return absl::CEscape(line); }),
symbolName, basicBlock->id, symbolName, basicBlock->bexit.thenb->id);
if (basicBlock->bexit.thenb != basicBlock->bexit.elseb) {
fmt::format_to(buf, " \"bb{}_{}\" -> \"bb{}_{}\" [style=\"tapered\"];\n\n", symbolName, basicBlock->id,
symbolName, basicBlock->bexit.elseb->id);
}
}
fmt::format_to(buf, "}}");
return to_string(buf);
}
string BasicBlock::toString(const core::GlobalState &gs, const CFG &cfg) const {
fmt::memory_buffer buf;
fmt::format_to(buf, "block[id={}, rubyBlockId={}]({})\n", this->id, this->rubyBlockId,
fmt::map_join(
this->args.begin(), this->args.end(),
", ", [&](const auto &arg) -> auto { return arg.toString(gs, cfg); }));
if (this->outerLoops > 0) {
fmt::format_to(buf, "outerLoops: {}\n", this->outerLoops);
}
for (const Binding &exp : this->exprs) {
fmt::format_to(buf, "{} = {}\n", exp.bind.toString(gs, cfg), exp.value->toString(gs, cfg));
}
fmt::format_to(buf, "{}", this->bexit.cond.toString(gs, cfg));
return to_string(buf);
}
string BasicBlock::showRaw(const core::GlobalState &gs, const CFG &cfg) const {
fmt::memory_buffer buf;
fmt::format_to(
buf, "block[id={}]({})\n", this->id,
fmt::map_join(
this->args.begin(), this->args.end(), ", ", [&](const auto &arg) -> auto { return arg.showRaw(gs, cfg); }));
if (this->outerLoops > 0) {
fmt::format_to(buf, "outerLoops: {}\n", this->outerLoops);
}
for (const Binding &exp : this->exprs) {
fmt::format_to(buf, "Binding {{\n bind = {},\n value = {},\n}}\n", exp.bind.showRaw(gs, cfg, 1),
exp.value->showRaw(gs, cfg, 1));
}
fmt::format_to(buf, "{}", this->bexit.cond.showRaw(gs, cfg));
return to_string(buf);
}
Binding::Binding(LocalRef bind, core::LocOffsets loc, unique_ptr<Instruction> value)
: bind(bind), loc(loc), value(std::move(value)) {}
} // namespace sorbet::cfg
| 39.73871 | 120 | 0.57594 | [
"shape",
"vector"
] |
a3cb6028ed90ddfe44058bbd93273a28c62686f2 | 11,520 | cpp | C++ | src/CGameGraphics.cpp | Blokatt/fiTD | b909981103fddab32867f3860b01c3c79d8dc3ea | [
"MIT"
] | 3 | 2019-03-20T12:52:49.000Z | 2020-03-22T20:19:06.000Z | src/CGameGraphics.cpp | Blokatt/fiTD | b909981103fddab32867f3860b01c3c79d8dc3ea | [
"MIT"
] | 1 | 2019-03-20T10:23:33.000Z | 2019-03-20T12:04:26.000Z | src/CGameGraphics.cpp | Blokatt/fiTD | b909981103fddab32867f3860b01c3c79d8dc3ea | [
"MIT"
] | null | null | null | #include "CGameGraphics.h"
#include "CGfx.h"
#include <ncurses.h>
#include <iomanip>
#include <deque>
#include <sstream>
static const int SPEED_BASE = 30;
static const int SIDEBAR_WIDTH = 18;
static const int BOTTOM_BAR_HEIGHT = 10;
static const int MAX_LINE_LENGTH = 256;
WINDOW* CGameGraphics::winMainField;
WINDOW* CGameGraphics::winSidebar;
WINDOW* CGameGraphics::winBottomBar;
int CGameGraphics::cursorX, CGameGraphics::cursorY;
CGame* CGameGraphics::gamePtr;
bool CGameGraphics::messageDistinguish;
const unsigned int CGameGraphics::MESSAGE_LIMIT = 6; //Message limit
std::deque<std::string> CGameGraphics::messageLog;
void CGameGraphics::Setup(CGame* game) {
delwin(winMainField);
delwin(winSidebar);
delwin(winBottomBar);
gamePtr = game;
winMainField = newwin(LINES - BOTTOM_BAR_HEIGHT, COLS - SIDEBAR_WIDTH, 0, SIDEBAR_WIDTH);
winSidebar = newwin(LINES - BOTTOM_BAR_HEIGHT, SIDEBAR_WIDTH, 0, 0);
winBottomBar = newwin(BOTTOM_BAR_HEIGHT, COLS, LINES - BOTTOM_BAR_HEIGHT, 0);
cursorX = gamePtr->mMapWidth / 2;
cursorY = gamePtr->mMapHeight / 2;
messageDistinguish = false;
nodelay(stdscr, true);
nodelay(winMainField, true);
keypad(stdscr, true);
keypad(winMainField, true);
}
void CGameGraphics::ShowMessage(std::string str) {
std::replace(str.begin(), str.end(), '\n', ' '); //Get rid of newlines
messageDistinguish = !messageDistinguish; //Arrow boldness toggle
messageLog.emplace_front(str);
if (messageLog.size() > MESSAGE_LIMIT) {
messageLog.erase(messageLog.end());
}
}
void CGameGraphics::ThrowError(const std::string & str) {
delwin(CGameGraphics::winBottomBar);
delwin(CGameGraphics::winMainField);
delwin(CGameGraphics::winSidebar);
endwin();
erase();
attron(COLOR_PAIR(ECOLORS::RED) | A_BOLD);
mvwprintw(stdscr, 0, 0, ("ERROR: " + str).c_str());
attroff(A_BOLD);
mvwprintw(stdscr, 1, 0, "Press any key to quit.");
attroff(COLOR_PAIR(ECOLORS::RED));
refresh();
#ifndef NDEBUG
//Wait for any key
while (getch() == -1) {
}
#endif
}
void CGameGraphics::Maximise() {
wresize(winMainField, LINES - BOTTOM_BAR_HEIGHT, COLS - SIDEBAR_WIDTH);
wresize(winSidebar, LINES - BOTTOM_BAR_HEIGHT, SIDEBAR_WIDTH);
wresize(winBottomBar, BOTTOM_BAR_HEIGHT, COLS);
mvwin(winSidebar, 0, 0);
mvwin(winMainField, 0, SIDEBAR_WIDTH);
mvwin(winBottomBar, LINES - BOTTOM_BAR_HEIGHT, 0);
}
void CGameGraphics::DrawSideStat(int y, const std::string & str, int num) {
std::stringstream ss;
ss << str << std::setw(SIDEBAR_WIDTH - str.length() - 2) << num << std::flush;
mvwprintw(winSidebar, y, 1, ss.str().c_str());
short c = (short) ECOLORS::WHITE;
if (str == "$: ") {
if (num < 50) {
c = (short) ECOLORS::RED;
} else {
c = (short) ECOLORS::GREEN;
}
}
mvwchgat(winSidebar, y, 8, SIDEBAR_WIDTH - 9, A_BOLD, c, 0);
}
void CGameGraphics::DrawSideStat(int y, const std::string & str, const std::string & val) {
std::stringstream ss;
ss << str << std::setw(SIDEBAR_WIDTH - str.length() - 2) << val << std::flush;
mvwprintw(winSidebar, y, 1, ss.str().c_str());
short c = (short) ECOLORS::WHITE;
mvwchgat(winSidebar, y, 8, SIDEBAR_WIDTH - 9, A_BOLD, c, 0);
}
void CGameGraphics::Draw() {
//Erase
werase(winBottomBar);
werase(winSidebar);
werase(winMainField);
//Render tiles
for (unsigned int y = 0; y <= gamePtr->mMapHeight; ++y) {
for (unsigned int x = 0; x <= gamePtr->mMapWidth; ++x) {
mvwaddch(winMainField, 1 + y, 1 + x, (char) (gamePtr->mMapTiles[y][x].mSymbol) | gamePtr->mMapTiles[y][x].mColour);
}
}
//Render the spawn point
mvwaddch(winMainField, 1 + gamePtr->mSpawnY, 1 + gamePtr->mSpawnX, '<' | A_BOLD | COLOR_PAIR(ECOLORS::RED));
//Render all entities
for (auto e : gamePtr->mMapEntities) {
e->Draw(winMainField);
}
//Render main statistics
wattron(winSidebar, A_BOLD | A_UNDERLINE);
mvwprintw(winSidebar, 3, 1, "Enemies:");
wattroff(winSidebar, A_BOLD | A_UNDERLINE);
mvwprintw(winSidebar, 2, 1, "ENEMY:");
CGameGraphics::DrawSideStat(1, "$: ", (int) gamePtr->mMoney);
CGameGraphics::DrawSideStat(2, "Score: ", gamePtr->mScore);
CGameGraphics::DrawSideStat(4, "Target: ", gamePtr->mKillGoal);
CGameGraphics::DrawSideStat(5, "Killed: ", gamePtr->mEnemiesKilled);
CGameGraphics::DrawSideStat(6, "Waiting: ", gamePtr->mEnemySequence.size() - gamePtr->mEnemySequenceIndex);
mvwhline(winSidebar, 7, 1, 0, SIDEBAR_WIDTH - 2);
// Render bottom part of the side panel based on game state
switch (gamePtr->mGameState) {
case EGAME_STATE::IDLE: case EGAME_STATE::PAUSE:
{
// Draw sidebar stats when the cursor is hover on an entity
for (auto e : gamePtr->mMapEntities) {
if (typeid (*e) == typeid (CEnemy)) {
//Enemy
auto eP = std::dynamic_pointer_cast<CEnemy>(e);
if (eP->mX == cursorX && eP->mY == cursorY) {
wattron(winSidebar, A_BOLD | A_UNDERLINE);
mvwprintw(winSidebar, 8, 1, "Enemy:");
wattroff(winSidebar, A_BOLD | A_UNDERLINE);
mvwaddch(winSidebar, 8, SIDEBAR_WIDTH - 2, eP->GetSymbol());
if (eP->mResists != 0) {
auto t = CDefinitions::GetTowerDefinition(eP->mResists);
DrawSideStat(12, "Resists: ", "");
mvwaddch(winSidebar, 12, SIDEBAR_WIDTH - 2, t.mSymbol | COLOR_PAIR(t.mColour) | A_BOLD);
}
DrawSideStat(9, "HP: ", (int) eP->mHealth);
DrawSideStat(10, "Attack: ", (int) eP->mAttack);
DrawSideStat(11, "Speed: ", (int) SPEED_BASE - eP->mUpdateDelay);
}
} else if (typeid (*e) == typeid (CTower)) {
//Tower
auto eP = std::dynamic_pointer_cast<CTower>(e);
if (eP->OverlapPoint(cursorX, cursorY)) {
wattron(winSidebar, A_BOLD | A_UNDERLINE);
mvwprintw(winSidebar, 8, 1, "Tower:");
wattroff(winSidebar, A_BOLD | A_UNDERLINE);
mvwaddch(winSidebar, 8, SIDEBAR_WIDTH - 2, eP->GetSymbol());
DrawSideStat(9, "HP: ", (int) eP->mHealth);
DrawSideStat(10, "Attack: ", (int) eP->mDamage);
DrawSideStat(11, "Radius: ", (int) eP->mRadius);
DrawSideStat(12, "Speed: ", (int) SPEED_BASE - eP->mUpdateDelay);
if (gamePtr->mGameState == EGAME_STATE::IDLE) {
std::stringstream ss;
ss << "\\BS\\^B to sell (\\U$" << gamePtr->TowerSellingPrice(*eP) << "\\^U)" << std::flush;
CGfx::PrintFormattedHCentered(winSidebar, 19, ss.str());
}
}
}
}
if (gamePtr->mGameState == EGAME_STATE::IDLE) {
CGfx::PrintFormattedHCentered(winSidebar, 17, "\\BW\\^B to build");
CGfx::PrintFormattedHCentered(winSidebar, 18, "\\BSpace\\^B to pause");
} else if (gamePtr->mGameState == EGAME_STATE::PAUSE) {
CGfx::PrintFormattedHCentered(winSidebar, 17, "\\BGame paused.");
CGfx::PrintFormattedHCentered(winSidebar, 18, "\\BSpace\\^B to unpause");
}
break;
}
case EGAME_STATE::PLACING_TOWER:
{
//Render tower selection information
wattron(winSidebar, A_BOLD | A_UNDERLINE);
mvwprintw(winSidebar, 8, 1, "Available towers:");
wattroff(winSidebar, A_BOLD | A_UNDERLINE);
auto t = CDefinitions::GetTowerDefinitionByOrderIndex(gamePtr->mSelectedTower);
mvwaddch(winSidebar, 9, SIDEBAR_WIDTH / 2, t.mSymbol | COLOR_PAIR(t.mColour) | A_BOLD);
mvwaddch(winSidebar, 9, SIDEBAR_WIDTH / 2 - 2, '<' | COLOR_PAIR(ECOLORS::WHITE) | A_BOLD | A_BLINK);
mvwaddch(winSidebar, 9, SIDEBAR_WIDTH / 2 + 2, '>' | COLOR_PAIR(ECOLORS::WHITE) | A_BOLD | A_BLINK);
std::stringstream sstr;
sstr << "$" << t.mPrice << std::flush;
CGameGraphics::DrawSideStat(10, "Price: ", sstr.str());
sstr.str("");
sstr << t.mWidth << "x" << t.mHeight << std::flush;
CGameGraphics::DrawSideStat(11, "Size: ", sstr.str());
CGameGraphics::DrawSideStat(12, "HP: ", t.mHealth);
CGameGraphics::DrawSideStat(13, "Attack: ", t.mDamage);
CGameGraphics::DrawSideStat(14, "Radius: ", t.mRadius);
CGameGraphics::DrawSideStat(15, "Speed: ", SPEED_BASE - t.mFrequency);
CGfx::PrintFormattedHCentered(winSidebar, 17, "\\BQ\\^B/\\BE\\^B to navigate");
CGfx::PrintFormattedHCentered(winSidebar, 18, "\\BW\\^B to buy");
CGfx::PrintFormattedHCentered(winSidebar, 19, "\\BSpace\\^B to cancel");
//DRAW CURSOR
int xOffset = 0, yOffset = 0;
if (t.mWidth % 2 != 0) xOffset = t.mWidth / 2;
if (t.mHeight % 2 != 0) yOffset = t.mHeight / 2;
for (int y = 0; y < t.mHeight; ++y) {
for (int x = 0; x < t.mWidth; ++x) {
chtype c = mvwinch(winMainField, cursorY + 1 - yOffset + y, cursorX + 1 - xOffset + x) & A_CHARTEXT;
mvwaddch(winMainField, cursorY + 1 - yOffset + y, cursorX + 1 - xOffset + x, c | A_REVERSE);
}
}
break;
}
default: break;
}
//Bottom panel info
CGfx::PrintFormatted(winBottomBar, BOTTOM_BAR_HEIGHT - 2, 1, "\\BArrow Keys\\^B - Cursor movement | \\BEscape\\^B - Save and exit");
mvwhline(winBottomBar, BOTTOM_BAR_HEIGHT - 3, 1, 0, COLS - 2);
//Render the cursor
chtype c = mvwinch(winMainField, cursorY + 1, cursorX + 1) & A_CHARTEXT;
mvwaddch(winMainField, cursorY + 1, cursorX + 1, c | A_REVERSE | A_BOLD);
//Render messages
int offset = 0;
for (auto message : messageLog) {
chtype chars[MAX_LINE_LENGTH];
chtype* charPtr = &chars[0];
CGfx::FormatString(charPtr, message, MAX_LINE_LENGTH);
if ((offset + (int) messageDistinguish) % 2 == 0) wattron(winBottomBar, A_BOLD);
mvwaddstr(winBottomBar, BOTTOM_BAR_HEIGHT - 4 - offset, 1, "> ");
wattroff(winBottomBar, A_BOLD);
mvwaddchstr(winBottomBar, BOTTOM_BAR_HEIGHT - 4 - offset, 3, charPtr);
offset++;
}
//Render cursor position
std::stringstream ss;
ss << std::setw(4) << cursorX << std::setw(4) << cursorY << std::flush;
mvwprintw(winMainField, LINES - BOTTOM_BAR_HEIGHT - 2, COLS - SIDEBAR_WIDTH - 9, ss.str().c_str());
//Borders
wborder(winBottomBar, 0, 0, 0, 0, 0, 0, 0, 0);
wborder(winSidebar, 0, 0, 0, 0, 0, 0, 0, 0);
wborder(winMainField, 0, 0, 0, 0, ACS_DIAMOND, ACS_DIAMOND, ACS_DIAMOND, ACS_DIAMOND);
//Refresh
wrefresh(winBottomBar);
wrefresh(winSidebar);
wrefresh(winMainField);
}
| 40.706714 | 136 | 0.576649 | [
"render"
] |
a3cd415646c0d52162d36e3a2b49b51f094129eb | 4,503 | cpp | C++ | vcc/src/android_asset_istream.cpp | sjfricke/vulkan-cpp-library | 82314d765013ce96e23186594259eebaf3127072 | [
"Apache-2.0"
] | 276 | 2016-04-04T20:47:47.000Z | 2022-02-01T21:48:42.000Z | vcc/src/android_asset_istream.cpp | sjfricke/vulkan-cpp-library | 82314d765013ce96e23186594259eebaf3127072 | [
"Apache-2.0"
] | 2 | 2017-03-23T20:33:23.000Z | 2017-05-17T21:03:16.000Z | vcc/src/android_asset_istream.cpp | sjfricke/vulkan-cpp-library | 82314d765013ce96e23186594259eebaf3127072 | [
"Apache-2.0"
] | 42 | 2016-04-07T21:00:53.000Z | 2021-09-05T09:17:03.000Z | /*
* Copyright 2016 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cassert>
#include <vcc/android_asset_istream.h>
#include <vcc/util.h>
namespace android {
namespace internal {
typedef std::unique_ptr<AAsset, decltype(&AAsset_close)> asset_type;
struct stream_asset_istreambuf : public std::streambuf {
stream_asset_istreambuf(asset_type &&asset, size_t buff_sz = 256,
size_t put_back = 8)
: asset(std::forward<asset_type>(asset)),
put_back(std::max(put_back, size_t(1))),
buffer(std::max(buff_sz, put_back) + put_back) {
reset();
}
virtual ~stream_asset_istreambuf() {}
void reset() {
char *const end = buffer.data();
setg(end, end, end);
}
std::streambuf::int_type underflow() {
if (gptr() < egptr())
return traits_type::to_int_type(*gptr());
char *const base = buffer.data();
char *start = base;
if (eback() == base) {
std::memmove(base, egptr() - put_back, put_back);
start += put_back;
}
const int n(AAsset_read(asset.get(), start,
buffer.size() - (start - base)));
if (n == 0)
return traits_type::eof();
else if (n < 0) {
std::stringstream ss;
ss << "error while streaming: \"" << n << "\"";
throw std::runtime_error(ss.str());
}
setg(base, start, start + n);
return traits_type::to_int_type(*gptr());
}
std::streampos seekoff(std::streamoff off,
std::ios_base::seekdir way, std::ios_base::openmode which) {
assert(which == std::ios_base::in);
int whence;
switch (way) {
case std::ios_base::beg:
whence = SEEK_SET;
break;
case std::ios_base::cur:
whence = SEEK_CUR;
break;
case std::ios_base::end:
whence = SEEK_END;
break;
default:
assert(!"invalid seekdir");
break;
}
const int pos(AAsset_seek(asset.get(), off, whence));
assert(pos != -1);
reset();
return std::streampos(pos);
}
std::streampos seekpos(std::streampos sp, std::ios_base::openmode which) {
assert(which == std::ios_base::in);
const int pos(AAsset_seek(asset.get(), sp, SEEK_SET));
assert(pos != -1);
reset();
return std::streampos(pos);
}
private:
asset_type asset;
const size_t put_back;
std::vector<char> buffer;
};
struct map_asset_istreambuf : public std::streambuf {
map_asset_istreambuf(asset_type &&asset, const char *start, size_t size)
: asset(std::forward<asset_type>(asset)), start(start),
end(start + size), current(start) {}
virtual ~map_asset_istreambuf() {}
std::streambuf::int_type underflow() {
return current < end
? traits_type::to_int_type(*current) : traits_type::eof();
}
std::streambuf::int_type uflow() {
return current < end
? traits_type::to_int_type(*current++) : traits_type::eof();
}
std::streampos seekoff(std::streamoff off,
std::ios_base::seekdir way, std::ios_base::openmode which) {
assert(which == std::ios_base::in);
current = current + off;
return std::streampos(current - start);
}
std::streampos seekpos(std::streampos sp, std::ios_base::openmode which) {
assert(which == std::ios_base::in);
current = start + sp;
return std::streampos(sp);
}
private:
asset_type asset;
const char *const start, *const end;
const char *current;
};
std::unique_ptr<std::streambuf> make_asset_istreambuf(AAssetManager *mgr,
const char *filename) {
asset_type asset(
AAssetManager_open(mgr, filename, AASSET_MODE_STREAMING),
&AAsset_close);
if (!asset.get()) {
std::stringstream ss;
ss << "failed to open \"" << filename << "\" for streaming";
std::string string(ss.str());
VCC_PRINT("%s", string.c_str());
throw std::runtime_error(std::move(string));
}
const char *const buffer((const char *) AAsset_getBuffer(asset.get()));
return std::unique_ptr<std::streambuf>(buffer
? (std::streambuf *) new map_asset_istreambuf(std::move(asset), buffer,
AAsset_getLength(asset.get()))
: (std::streambuf *) new stream_asset_istreambuf(std::move(asset)));
}
} // namespace internal
} // namespace android
| 27.126506 | 75 | 0.678437 | [
"vector"
] |
a3cfb765bbb049f6f6ede2515144f7adf7d81388 | 10,138 | cpp | C++ | Tudat/Mathematics/Statistics/UnitTests/unitTestSimpleLinearRegression.cpp | JPelamatti/ThesisTUDAT | b94ce35fb7c8fa44ae83238e296a979dfa3adfe8 | [
"BSD-3-Clause"
] | null | null | null | Tudat/Mathematics/Statistics/UnitTests/unitTestSimpleLinearRegression.cpp | JPelamatti/ThesisTUDAT | b94ce35fb7c8fa44ae83238e296a979dfa3adfe8 | [
"BSD-3-Clause"
] | null | null | null | Tudat/Mathematics/Statistics/UnitTests/unitTestSimpleLinearRegression.cpp | JPelamatti/ThesisTUDAT | b94ce35fb7c8fa44ae83238e296a979dfa3adfe8 | [
"BSD-3-Clause"
] | 1 | 2019-05-30T03:42:22.000Z | 2019-05-30T03:42:22.000Z | /* Copyright (c) 2010-2015, Delft University of Technology
* 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 Delft University of Technology nor the names of its contributors
* may be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Changelog
* YYMMDD Author Comment
* 110702 K. Kumar File created.
* 110726 K. Kumar Changed filename and class name.
* 110802 K. Kumar Added standard deviation and chi-squared
* test; added note; renamed filename.
* 110905 S. Billemont Reorganized includes.
* Moved (con/de)structors and getter/setters to header.
* 120509 K. Kumar Boostified unit test.
* 120516 A. Ronse Updated namespaces and corrected reference. Added unit tests
* for horizontal and vertical cases. Adjusted precision.
*
* References
* Burden, R.L., Faires, J.D. Numerical Analysis, 7th Edition, Books/Cole, 2001.
*
* Notes
*
*/
#define BOOST_TEST_MAIN
#include <cmath>
#include <limits>
#include <map>
#include <boost/math/special_functions/fpclassify.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/unit_test.hpp>
#include "Tudat/Mathematics/Statistics/simpleLinearRegression.h"
namespace tudat
{
namespace unit_tests
{
BOOST_AUTO_TEST_SUITE( test_simple_linear_regression )
//! Test if simple linear regression method computes fit correctly.
BOOST_AUTO_TEST_CASE( testSimpleLinearRegressionBF )
{
// Test 1: Test implementation of simple linear regression method against benchmark data from
// pg. 487, example 1 of (Burden and Faires, 2001). Standard deviations were benchmarked
// using MATLAB's lscov() function.
// Benchmark data.
std::map< double, double > benchmarkInputData;
benchmarkInputData[ 1.0 ] = 1.3;
benchmarkInputData[ 2.0 ] = 3.5;
benchmarkInputData[ 3.0 ] = 4.2;
benchmarkInputData[ 4.0 ] = 5.0;
benchmarkInputData[ 5.0 ] = 7.0;
benchmarkInputData[ 6.0 ] = 8.8;
benchmarkInputData[ 7.0 ] = 10.1;
benchmarkInputData[ 8.0 ] = 12.5;
benchmarkInputData[ 9.0 ] = 13.0;
benchmarkInputData[ 10.0 ] = 15.6;
// Expected coefficients of linear fit.
const double expectedCoefficientOfConstantTerm = -0.359999999999999999;
const double expectedCoefficientOfLinearTerm = 1.5381818181818181818;
// Expected standard deviations of fit coefficients.
const double expectedStandardDeviationOfCoefficientOfConstantTerm = 0.369832066721825;
const double expectedStandardDeviationOfCoefficientOfLinearTerm = 0.059603834439483;
// Expected chi-squared value.
const double expectedChiSquared = 2.344727272727272;
// Declare simple linear regression object and set input data.
statistics::SimpleLinearRegression simpleLinearRegression( benchmarkInputData );
// Compute linear fit.
simpleLinearRegression.computeFit( );
// Check that computed coefficient of constant term matches expected value.
BOOST_CHECK_CLOSE_FRACTION( expectedCoefficientOfConstantTerm,
simpleLinearRegression.getCoefficientOfConstantTerm( ),
1.0e-14 );
// Check that computed coefficient of linear term matches expected value.
BOOST_CHECK_CLOSE_FRACTION( expectedCoefficientOfLinearTerm,
simpleLinearRegression.getCoefficientOfLinearTerm( ),
1.0e-15 );
// Compute linear fit errors.
simpleLinearRegression.computeFitErrors( );
// Check that computed standard deviation of coefficient of constant term matches expected
// value.
BOOST_CHECK_CLOSE_FRACTION( expectedStandardDeviationOfCoefficientOfConstantTerm,
simpleLinearRegression
.getStandardDeviationOfCoefficientOfConstantTerm( ),
1.0e-13 );
// Check that computed standard deviation of coefficient of linear term matches expected
// value.
BOOST_CHECK_CLOSE_FRACTION( expectedStandardDeviationOfCoefficientOfLinearTerm,
simpleLinearRegression
.getStandardDeviationOfCoefficientOfLinearTerm( ),
1.0e-13 );
// Check that computed chi-squared fit matches expected value.
BOOST_CHECK_CLOSE_FRACTION( expectedChiSquared,
simpleLinearRegression.getChiSquared( ),
1.0e-15 );
}
BOOST_AUTO_TEST_CASE( testSimpleLinearRegressionHorizontal )
{
// Test 2: Test implementation of simple linear regression method in case of sample points
// coinciding with the x-axis.
std::map< double, double > benchmarkInputData;
benchmarkInputData[ 1.0 ] = 0.0;
benchmarkInputData[ 2.0 ] = 0.0;
benchmarkInputData[ 3.0 ] = 0.0;
benchmarkInputData[ 4.0 ] = 0.0;
benchmarkInputData[ 5.0 ] = 0.0;
benchmarkInputData[ 6.0 ] = 0.0;
benchmarkInputData[ 7.0 ] = 0.0;
benchmarkInputData[ 8.0 ] = 0.0;
benchmarkInputData[ 9.0 ] = 0.0;
benchmarkInputData[ 10.0 ] = 0.0;
// Declare simple linear regression object and set input data.
statistics::SimpleLinearRegression simpleLinearRegression( benchmarkInputData );
// Compute linear fit.
simpleLinearRegression.computeFit( );
// Check that computed coefficient of constant term is zero.
BOOST_CHECK_SMALL( simpleLinearRegression.getCoefficientOfConstantTerm( ),
std::numeric_limits< double >::min( ) );
// Check that computed coefficient of linear term matches is zero.
BOOST_CHECK_SMALL( simpleLinearRegression.getCoefficientOfLinearTerm( ),
std::numeric_limits< double >::min( ) );
// Compute linear fit errors.
simpleLinearRegression.computeFitErrors( );
// Check that computed standard deviation of coefficient of constant term is zero.
BOOST_CHECK_SMALL( simpleLinearRegression.getStandardDeviationOfCoefficientOfConstantTerm( ),
std::numeric_limits< double >::min( ) );
// Check that computed standard deviation of coefficient of linear term is zero.
BOOST_CHECK_SMALL( simpleLinearRegression.getStandardDeviationOfCoefficientOfLinearTerm( ),
std::numeric_limits< double >::min( ) );
// Check that computed chi-squared fit is zero.
BOOST_CHECK_SMALL( simpleLinearRegression.getChiSquared( ),
std::numeric_limits< double >::min( ) );
}
BOOST_AUTO_TEST_CASE( testSimpleLinearRegressionVertical )
{
// Test 3: Test implementation of simple linear regression method in case of sample points
// coinciding with the y-axis.
std::map< double, double > benchmarkInputData;
benchmarkInputData[ 0.0 ] = 1.3;
benchmarkInputData[ 0.0 ] = 3.5;
benchmarkInputData[ 0.0 ] = 4.2;
benchmarkInputData[ 0.0 ] = 5.0;
benchmarkInputData[ 0.0 ] = 7.0;
benchmarkInputData[ 0.0 ] = 8.8;
benchmarkInputData[ 0.0 ] = 10.1;
benchmarkInputData[ 0.0 ] = 12.5;
benchmarkInputData[ 0.0 ] = 13.0;
benchmarkInputData[ 0.0 ] = 15.6;
// Declare simple linear regression object and set input data.
statistics::SimpleLinearRegression simpleLinearRegression( benchmarkInputData );
// Compute linear fit.
simpleLinearRegression.computeFit( );
// Check that computed coefficient of constant term matches expected value.
BOOST_CHECK( boost::math::isnan( simpleLinearRegression.getCoefficientOfConstantTerm( ) ) );
// Check that computed coefficient of linear term matches expected value.
BOOST_CHECK( boost::math::isnan( simpleLinearRegression.getCoefficientOfLinearTerm( ) ) );
// Compute linear fit errors.
simpleLinearRegression.computeFitErrors( );
// Check that computed standard deviation of coefficient of constant term matches expected
// value.
BOOST_CHECK( boost::math::isnan( simpleLinearRegression
.getStandardDeviationOfCoefficientOfConstantTerm( ) ) );
// Check that computed standard deviation of coefficient of linear term matches expected
// value.
BOOST_CHECK( boost::math::isnan(simpleLinearRegression
.getStandardDeviationOfCoefficientOfLinearTerm( ) ) );
// Check that computed chi-squared fit matches expected value.
BOOST_CHECK( boost::math::isnan(simpleLinearRegression.getChiSquared( ) ) );
}
BOOST_AUTO_TEST_SUITE_END( )
} // namespace unit_tests
} // namespace tudat
| 43.887446 | 100 | 0.686526 | [
"object"
] |
a3d057652132d15db4fdb366080461b5bbb4f7f3 | 1,560 | cpp | C++ | simulation/halsim_gazebo/src/main/native/cpp/main.cpp | shueja-personal/allwpilib | 4b2f6be29e21986703d9c3ddcd2fe07121b2ff6b | [
"BSD-3-Clause"
] | 707 | 2016-05-11T16:54:13.000Z | 2022-03-30T13:03:15.000Z | simulation/halsim_gazebo/src/main/native/cpp/main.cpp | shueja-personal/allwpilib | 4b2f6be29e21986703d9c3ddcd2fe07121b2ff6b | [
"BSD-3-Clause"
] | 2,308 | 2016-05-12T00:17:17.000Z | 2022-03-30T20:08:10.000Z | simulation/halsim_gazebo/src/main/native/cpp/main.cpp | shueja-personal/allwpilib | 4b2f6be29e21986703d9c3ddcd2fe07121b2ff6b | [
"BSD-3-Clause"
] | 539 | 2016-05-11T20:33:26.000Z | 2022-03-28T20:20:25.000Z | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include <fmt/core.h>
#include <hal/Ports.h>
#include "GazeboAnalogIn.h"
#include "GazeboDIO.h"
#include "GazeboEncoder.h"
#include "GazeboPCM.h"
#include "GazeboPWM.h"
#include "HALSimGazebo.h"
/* Currently, robots never terminate, so we keep a single static object
to access Gazebo with and it is never properly released or cleaned up. */
static HALSimGazebo halsim;
extern "C" {
int HALSIM_InitExtension(void) {
fmt::print("Gazebo Simulator Initializing.\n");
if (!halsim.node.Connect()) {
fmt::print(stderr,
"Error: unable to connect to Gazebo. Is it running?.\n");
return -1;
}
fmt::print("Gazebo Simulator Connected.\n");
for (int i = 0; i < HALSimGazebo::kPWMCount; i++)
halsim.pwms[i] = new GazeboPWM(i, &halsim);
for (int i = 0; i < HALSimGazebo::kPCMCount; i++)
halsim.pcms[i] = new GazeboPCM(0, i, &halsim);
GazeboPCM_SetPressureSwitch(0, true);
for (int i = 0; i < HALSimGazebo::kEncoderCount; i++)
halsim.encoders[i] = new GazeboEncoder(i, &halsim);
int analog_in_count = HAL_GetNumAnalogInputs();
for (int i = 0; i < analog_in_count; i++)
halsim.analog_inputs.push_back(new GazeboAnalogIn(i, &halsim));
int dio_count = HAL_GetNumDigitalChannels();
for (int i = 0; i < dio_count; i++)
halsim.dios.push_back(new GazeboDIO(i, &halsim));
return 0;
}
} // extern "C"
| 30.588235 | 76 | 0.685897 | [
"object"
] |
a3d10286777fe013c64a2f162115dabbd4c83139 | 5,135 | cc | C++ | chrome/browser/sharing/sms/sms_remote_fetcher_ui_controller.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | chrome/browser/sharing/sms/sms_remote_fetcher_ui_controller.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | chrome/browser/sharing/sms/sms_remote_fetcher_ui_controller.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sharing/sms/sms_remote_fetcher_ui_controller.h"
#include <utility>
#include "base/callback.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/app/vector_icons/vector_icons.h"
#include "chrome/browser/sharing/sharing_constants.h"
#include "chrome/browser/sharing/sharing_dialog.h"
#include "chrome/browser/shell_integration.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/grit/generated_resources.h"
#include "components/sync_device_info/device_info.h"
#include "components/vector_icons/vector_icons.h"
#include "content/public/browser/sms_fetcher.h"
#include "content/public/browser/web_contents.h"
#include "third_party/blink/public/common/sms/webotp_constants.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/paint_vector_icon.h"
#include "ui/strings/grit/ui_strings.h"
using SharingMessage = chrome_browser_sharing::SharingMessage;
// static
SmsRemoteFetcherUiController*
SmsRemoteFetcherUiController::GetOrCreateFromWebContents(
content::WebContents* web_contents) {
SmsRemoteFetcherUiController::CreateForWebContents(web_contents);
return SmsRemoteFetcherUiController::FromWebContents(web_contents);
}
SmsRemoteFetcherUiController::SmsRemoteFetcherUiController(
content::WebContents* web_contents)
: SharingUiController(web_contents) {}
SmsRemoteFetcherUiController::~SmsRemoteFetcherUiController() = default;
PageActionIconType SmsRemoteFetcherUiController::GetIconType() {
return PageActionIconType::kSmsRemoteFetcher;
}
sync_pb::SharingSpecificFields::EnabledFeatures
SmsRemoteFetcherUiController::GetRequiredFeature() const {
return sync_pb::SharingSpecificFields::SMS_FETCHER;
}
void SmsRemoteFetcherUiController::DoUpdateApps(UpdateAppsCallback callback) {
std::move(callback).Run(std::vector<SharingApp>());
}
void SmsRemoteFetcherUiController::OnDeviceChosen(
const syncer::DeviceInfo& device) {}
void SmsRemoteFetcherUiController::OnAppChosen(const SharingApp& app) {}
std::u16string SmsRemoteFetcherUiController::GetContentType() const {
return l10n_util::GetStringUTF16(IDS_BROWSER_SHARING_CONTENT_TYPE_TEXT);
}
const gfx::VectorIcon& SmsRemoteFetcherUiController::GetVectorIcon() const {
return kSmartphoneIcon;
}
std::u16string
SmsRemoteFetcherUiController::GetTextForTooltipAndAccessibleName() const {
return l10n_util::GetStringFUTF16(IDS_OMNIBOX_TOOLTIP_SMS_REMOTE_FETCHER,
base::UTF8ToUTF16(last_device_name_));
}
SharingFeatureName SmsRemoteFetcherUiController::GetFeatureMetricsPrefix()
const {
return SharingFeatureName::kSmsRemoteFetcher;
}
void SmsRemoteFetcherUiController::OnSmsRemoteFetchResponse(
OnRemoteCallback callback,
SharingSendMessageResult result,
std::unique_ptr<chrome_browser_sharing::ResponseMessage> response) {
if (result != SharingSendMessageResult::kSuccessful) {
// TODO(crbug.com/1015645): We should have a new category for remote
// failures.
std::move(callback).Run(base::nullopt, base::nullopt, base::nullopt);
return;
}
DCHECK(response);
DCHECK(response->has_sms_fetch_response());
if (response->sms_fetch_response().has_failure_type()) {
std::move(callback).Run(base::nullopt, base::nullopt,
static_cast<content::SmsFetchFailureType>(
response->sms_fetch_response().failure_type()));
return;
}
auto origin_strings = response->sms_fetch_response().origin();
std::vector<url::Origin> origin_list;
for (const std::string& origin_string : origin_strings)
origin_list.push_back(url::Origin::Create(GURL(origin_string)));
std::move(callback).Run(std::move(origin_list),
response->sms_fetch_response().one_time_code(),
base::nullopt);
}
base::OnceClosure SmsRemoteFetcherUiController::FetchRemoteSms(
const url::Origin& origin,
OnRemoteCallback callback) {
SharingService::SharingDeviceList devices = GetDevices();
if (devices.empty()) {
// No devices available to call.
// TODO(crbug.com/1015645): We should have a new category for remote
// failures.
std::move(callback).Run(base::nullopt, base::nullopt, base::nullopt);
return base::NullCallback();
}
// Sends to the first device that has the capability enabled. User cannot
// select device because the site sends out the SMS asynchronously.
const std::unique_ptr<syncer::DeviceInfo>& device = devices.front();
last_device_name_ = device->client_name();
chrome_browser_sharing::SharingMessage request;
request.mutable_sms_fetch_request()->set_origin(origin.Serialize());
return SendMessageToDevice(
*device.get(), blink::kWebOTPRequestTimeout, std::move(request),
base::BindOnce(&SmsRemoteFetcherUiController::OnSmsRemoteFetchResponse,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
WEB_CONTENTS_USER_DATA_KEY_IMPL(SmsRemoteFetcherUiController)
| 37.757353 | 80 | 0.763778 | [
"vector"
] |
a3d474126819da5051373726695b226ce883ca48 | 9,287 | hpp | C++ | include/simo/geom/detail/multilinestring.hpp | pavelsimo/Shapes | befdee7ec19dcc2d129b508f768b869976c09c09 | [
"MIT"
] | 5 | 2019-02-18T12:26:11.000Z | 2019-06-20T16:20:20.000Z | include/simo/geom/detail/multilinestring.hpp | pavelsimo/Shapes | befdee7ec19dcc2d129b508f768b869976c09c09 | [
"MIT"
] | 31 | 2019-01-18T23:16:03.000Z | 2019-06-10T22:09:10.000Z | include/simo/geom/detail/multilinestring.hpp | pavelsimo/Shapes | befdee7ec19dcc2d129b508f768b869976c09c09 | [
"MIT"
] | 1 | 2022-02-23T01:46:28.000Z | 2022-02-23T01:46:28.000Z | #pragma once
#include <ciso646>
#include <vector>
#include <set>
#include <sstream>
#include <iterator>
#include <iomanip>
#include <simo/geom/detail/geometry.hpp>
#include <simo/geom/detail/bounds.hpp>
namespace simo
{
namespace shapes
{
template <typename T, typename AllocatorType = std::allocator<T>>
class basic_multilinestring
: public std::vector<T, AllocatorType>,
public basic_geometry<basic_multilinestring<T>>
{
public:
using base_type = std::vector<T, AllocatorType>;
using point_type = typename T::point_type;
using point_iterator = typename std::vector<T>::iterator;
using point_const_iterator = typename std::vector<T>::const_iterator;
using coord_type = typename T::coord_type;
using coord_iterator = typename std::vector<coord_type>::iterator;
using coord_const_iterator = typename std::vector<coord_type>::const_iterator;
basic_multilinestring()
: base_type() {}
basic_multilinestring(point_iterator first, point_iterator last)
: base_type(first, last)
{
}
basic_multilinestring(point_const_iterator first, point_const_iterator last)
: base_type(first, last)
{
}
basic_multilinestring(std::initializer_list<T> init)
: base_type(init.begin(), init.end()) {}
template <typename CoordIterator, typename OffsetIterator>
basic_multilinestring(CoordIterator coord_first, CoordIterator coord_last, OffsetIterator offset_first, OffsetIterator offset_last)
{
if (std::distance(coord_first, coord_last) > 0)
{
auto n = this->ndim();
this->reserve((coord_last - coord_first) / n);
size_t lo = 0;
for (auto it = offset_first; it != offset_last; ++it)
{
size_t hi = *it;
this->emplace_back(coord_first + lo, coord_first + hi);
lo = hi;
}
}
}
// operators
friend bool operator==(const basic_multilinestring<T>& lhs, const basic_multilinestring<T>& rhs)
{
if (lhs.size() != rhs.size())
{
return false;
}
for (size_t i = 0; i < lhs.size(); ++i)
{
if (lhs[i] != rhs[i])
{
return false;
}
}
return true;
}
friend bool operator!=(const basic_multilinestring<T>& lhs, const basic_multilinestring<T>& rhs)
{
return not operator==(lhs, rhs);
}
std::vector<std::tuple<double, double>> xy() const
{
std::vector<std::tuple<double, double>> res;
res.reserve(this->size());
for (const auto& p : *this)
{
res.emplace_back(p.x, p.y);
}
return res;
}
private:
/// for allow basic_geometry to access basic_multipoint private members
friend class basic_geometry<basic_multilinestring<T>>;
/// @private
geometry_type geom_type_() const noexcept
{
if (is_basic_linestring_z<T>::value)
{
return geometry_type::MULTILINESTRINGZ;
}
if (is_basic_linestring_m<T>::value)
{
return geometry_type::MULTILINESTRINGM;
}
if (is_basic_linestring_zm<T>::value)
{
return geometry_type::MULTILINESTRINGZM;
}
return geometry_type::MULTILINESTRING;
}
/// @private
bool is_closed_() const noexcept
{
if (this->empty())
{
return true;
}
return *this[0] == *this[this->size() - 1];
}
/// @private
void throw_for_invalid_() const
{
for (const auto& ls : *this)
{
ls.throw_for_invalid();
}
}
/// @private
bounds_t bounds_() const
{
bounds_t res{};
for (const auto& p : *this)
{
res.extend(p.x, p.y);
}
return res;
}
// json
/// @private
static basic_multilinestring<T> from_json_(const std::string& json)
{
try
{
auto j = nlohmann::json::parse(json);
auto geom_type = j.at("type").get<std::string>();
if (geom_type != "MultiLineString")
{
throw exceptions::parse_error("invalid geometry type: " + std::string(geom_type));
}
const auto& linestrings = j.at("coordinates");
std::vector<T> res;
res.reserve(linestrings.size());
std::vector<point_type> points;
for (const auto& linestring : linestrings)
{
if (not linestring.empty())
{
const auto& coords = linestring.get<std::vector<std::vector<double>>>();
points.reserve(coords.size());
std::for_each(std::begin(coords), std::end(coords),
[&points](const std::vector<double>& coord) {
points.emplace_back(coord.begin(), coord.end());
});
res.emplace_back(points.begin(), points.end());
}
points.clear();
}
return basic_multilinestring<T>(res.begin(), res.end());
}
catch (const nlohmann::json::exception& e)
{
throw exceptions::parse_error("invalid json: " + std::string(e.what()));
}
catch (const exceptions::geometry_error& e)
{
throw exceptions::parse_error("invalid geometry: " + std::string(e.what()));
}
}
/// @private
std::string json_(std::int32_t precision = -1) const
{
std::stringstream ss;
if (precision >= 0)
{
ss << std::setprecision(precision);
}
ss << "{\"type\":\"MultiLineString\",\"coordinates\":[";
int i = 0;
for (const auto& ls : *this)
{
if (i > 0)
{
ss << ",";
}
ss << "[";
for (size_t j = 0; j < ls.size(); ++j)
{
if (j > 0)
{
ss << ",";
}
ss << "[";
const auto& p = ls[j];
for (size_t k = 0; k < p.size(); ++k)
{
if (k > 0)
{
ss << ",";
}
ss << p.coords[k];
}
ss << "]";
++i;
}
ss << "]";
++i;
}
ss << "]}";
return ss.str();
}
// wkt
/// @private
static basic_multilinestring<T> from_wkt_(const std::string& wkt)
{
wkt_reader reader{};
auto result = reader.read(wkt);
const auto& data = result.data;
if (not utils::is_multilinestring(data.geom_type))
{
throw exceptions::parse_error("invalid wkt string");
}
return basic_multilinestring<T>(result.data.coords.begin(), result.data.coords.end(),
result.data.offsets.begin(), result.data.offsets.end());
}
/// @private
std::string wkt_(std::int32_t precision = -1) const
{
std::stringstream ss;
if (precision >= 0)
{
ss << std::setprecision(precision);
}
ss << "MULTILINESTRING";
if (this->has_z())
{
ss << "Z";
}
if (this->has_m())
{
ss << "M";
}
ss << "(";
int i = 0;
for (const auto& ls : *this)
{
if (i > 0)
{
ss << ",";
}
ss << "(";
for (size_t j = 0; j < ls.size(); ++j)
{
if (j > 0)
{
ss << ",";
}
const auto& p = ls[j];
for (size_t k = 0; k < p.size(); ++k)
{
if (k > 0)
{
ss << " ";
}
ss << p.coords[k];
}
}
ss << ")";
++i;
}
ss << ")";
return ss.str();
}
};
template <typename>
struct is_basic_multilinestring : std::false_type
{};
template <typename T>
struct is_basic_multilinestring<basic_multilinestring<basic_linestring<basic_point<T>>>> : std::true_type
{};
template <typename>
struct is_basic_multilinestring_z : std::false_type
{};
template <typename T>
struct is_basic_multilinestring_z<basic_multilinestring<basic_linestring<basic_point_z<T>>>> : std::true_type
{};
template <typename>
struct is_basic_multilinestring_m : std::false_type
{};
template <typename T>
struct is_basic_multilinestring_m<basic_multilinestring<basic_linestring<basic_point_m<T>>>> : std::true_type
{};
template <typename>
struct is_basic_multilinestring_zm : std::false_type
{};
template <typename T>
struct is_basic_multilinestring_zm<basic_multilinestring<basic_linestring<basic_point_zm<T>>>> : std::true_type
{};
} // namespace shapes
} // namespace simo | 27.722388 | 135 | 0.500915 | [
"geometry",
"vector"
] |
a3d95d57d25558777500381d8addd039bd19b44d | 5,927 | cxx | C++ | Qt/ApplicationComponents/pqGlyphScaleFactorPropertyWidget.cxx | biddisco/ParaView | 4d6c93f0456e44b74bf4d188a3a6c0d4eb0d8eec | [
"Apache-2.0"
] | null | null | null | Qt/ApplicationComponents/pqGlyphScaleFactorPropertyWidget.cxx | biddisco/ParaView | 4d6c93f0456e44b74bf4d188a3a6c0d4eb0d8eec | [
"Apache-2.0"
] | null | null | null | Qt/ApplicationComponents/pqGlyphScaleFactorPropertyWidget.cxx | biddisco/ParaView | 4d6c93f0456e44b74bf4d188a3a6c0d4eb0d8eec | [
"Apache-2.0"
] | null | null | null | /*=========================================================================
Program: ParaView
Module: pqGlyphScaleFactorPropertyWidget.cxx
Copyright (c) 2005,2006 Sandia Corporation, Kitware Inc.
All rights reserved.
ParaView is a free software; you can redistribute it and/or modify it
under the terms of the ParaView license version 1.2.
See License_v1.2.txt for the full ParaView license.
A copy of this license can be obtained by contacting
Kitware Inc.
28 Corporate Drive
Clifton Park, NY 12065
USA
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 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.
========================================================================*/
#include "pqGlyphScaleFactorPropertyWidget.h"
#include "pqCoreUtilities.h"
#include "pqHighlightablePushButton.h"
#include "pqLineEdit.h"
#include "vtkCommand.h"
#include "vtkGlyph3D.h"
#include "vtkSMArrayRangeDomain.h"
#include "vtkSMBoundsDomain.h"
#include "vtkSMDoubleVectorProperty.h"
#include "vtkSMUncheckedPropertyHelper.h"
#include <QHBoxLayout>
#include <QPushButton>
#include <QStyle>
#include <QtDebug>
//-----------------------------------------------------------------------------
pqGlyphScaleFactorPropertyWidget::pqGlyphScaleFactorPropertyWidget(
vtkSMProxy* smproxy, vtkSMProperty* smproperty, QWidget* parentObject)
: Superclass(smproperty, smproxy, parentObject)
{
QLayout* layout = this->layout();
Q_ASSERT(layout);
pqHighlightablePushButton* button = new pqHighlightablePushButton(this);
button->setObjectName("Reset");
button->setToolTip("Reset using current data values");
button->setIcon(button->style()->standardIcon(QStyle::SP_BrowserReload));
layout->addWidget(button);
this->ResetButton = button;
this->connect(button, SIGNAL(clicked()), SLOT(resetClicked()));
pqCoreUtilities::connect(smproperty, vtkCommand::DomainModifiedEvent,
this, SLOT(highlightResetButton()));
pqCoreUtilities::connect(smproperty, vtkCommand::UncheckedPropertyModifiedEvent,
this, SLOT(highlightResetButton()));
if (vtkSMProperty* scaleMode = smproxy->GetProperty("ScaleMode"))
{
pqCoreUtilities::connect(scaleMode, vtkCommand::UncheckedPropertyModifiedEvent,
this, SLOT(highlightResetButton()));
}
}
//-----------------------------------------------------------------------------
pqGlyphScaleFactorPropertyWidget::~pqGlyphScaleFactorPropertyWidget()
{
}
//-----------------------------------------------------------------------------
void pqGlyphScaleFactorPropertyWidget::apply()
{
this->Superclass::apply();
this->highlightResetButton(false);
}
//-----------------------------------------------------------------------------
void pqGlyphScaleFactorPropertyWidget::reset()
{
this->Superclass::reset();
this->highlightResetButton(false);
}
//-----------------------------------------------------------------------------
void pqGlyphScaleFactorPropertyWidget::highlightResetButton(bool highlight)
{
this->ResetButton->highlight(/*clear=*/ highlight == false);
}
//-----------------------------------------------------------------------------
void pqGlyphScaleFactorPropertyWidget::resetClicked()
{
// Now this logic to hardcoded for the Glyph filter (hence the name of this
// widget).
// This logic has been ported directly from the old pqGlyphPanel class for the
// most part.
vtkSMProxy* smproxy = this->proxy();
vtkSMProperty* smproperty = this->property();
double scaledExtent = 1.0;
if (vtkSMBoundsDomain* domain = vtkSMBoundsDomain::SafeDownCast(
smproperty->GetDomain("bounds")))
{
if (domain->GetMaximumExists(0))
{
scaledExtent = domain->GetMaximum(0);
}
}
double divisor = 1.0;
switch (vtkSMUncheckedPropertyHelper(smproxy, "ScaleMode", /*quiet*/true).GetAsInt())
{
case VTK_SCALE_BY_SCALAR:
if (vtkSMArrayRangeDomain* domain = vtkSMArrayRangeDomain::SafeDownCast(
smproperty->GetDomain("scalar_range")))
{
if (domain->GetMaximumExists(0) /*&& domain->GetMinimumExists(0)*/)
{
divisor = domain->GetMaximum(0)/*-domain->GetMinimum(0)*/;
}
}
break;
case VTK_SCALE_BY_VECTOR:
case VTK_SCALE_BY_VECTORCOMPONENTS:
if (vtkSMArrayRangeDomain* domain = vtkSMArrayRangeDomain::SafeDownCast(
smproperty->GetDomain("vector_range")))
{
if (domain->GetMaximumExists(3)/* && domain->GetMinimumExists(3)*/)
{
// we use the vector magnitude.
divisor = domain->GetMaximum(3)/*-domain->GetMinimum(3)*/;
}
}
break;
case VTK_DATA_SCALING_OFF:
default:
break;
}
divisor = fabs(divisor);
// the divisor can sometimes be very close to 0, which happens in case the
// vectors indeed have same value but due to precision issues are not reported
// as identical. In that case we just treat it as 0.
divisor = (divisor < 0.000000001)? 1 : divisor;
double scalefactor = scaledExtent / divisor;
vtkSMUncheckedPropertyHelper helper(smproperty);
if (helper.GetAsDouble() != scalefactor)
{
vtkSMUncheckedPropertyHelper(smproperty).Set(scalefactor);
this->highlightResetButton(false);
emit this->changeAvailable();
emit this->changeFinished();
}
}
| 34.063218 | 87 | 0.656656 | [
"vector"
] |
a3dbdb8f99f56ca4277defca25fdcd02810cad2d | 11,240 | cpp | C++ | test/gl/bucket.test.cpp | sonakur/mapbox-gl-native | 0fa5944f39854f42c86ce478da8869a8d4e3f1fe | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | test/gl/bucket.test.cpp | sonakur/mapbox-gl-native | 0fa5944f39854f42c86ce478da8869a8d4e3f1fe | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | test/gl/bucket.test.cpp | sonakur/mapbox-gl-native | 0fa5944f39854f42c86ce478da8869a8d4e3f1fe | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | #include <mbgl/test/util.hpp>
#include <mbgl/test/stub_geometry_tile_feature.hpp>
#include <mbgl/gfx/backend_scope.hpp>
#include <mbgl/renderer/buckets/circle_bucket.hpp>
#include <mbgl/renderer/buckets/fill_bucket.hpp>
#include <mbgl/renderer/buckets/line_bucket.hpp>
#include <mbgl/renderer/buckets/raster_bucket.hpp>
#include <mbgl/renderer/buckets/symbol_bucket.hpp>
#include <mbgl/renderer/bucket_parameters.hpp>
#include <mbgl/style/layers/symbol_layer_properties.hpp>
#include <mbgl/gl/context.hpp>
#include <mbgl/gl/headless_backend.hpp>
#include <mbgl/map/mode.hpp>
namespace mbgl {
template <class Attributes>
bool operator==(const Segment<Attributes>& lhs, const Segment<Attributes>& rhs) {
return std::tie(lhs.vertexOffset, lhs.indexOffset, lhs.vertexLength, lhs.indexLength) ==
std::tie(rhs.vertexOffset, rhs.indexOffset, rhs.vertexLength, rhs.indexLength);
}
namespace gfx {
namespace detail {
template <class A1, class A2>
bool operator==(const VertexType<A1, A2>& lhs, const VertexType<A1, A2>& rhs) {
return std::tie(lhs.a1, lhs.a2) == std::tie(rhs.a1, rhs.a2);
}
} // namespace detail
} // namespace gfx
} // namespace mbgl
using namespace mbgl;
namespace {
PropertyMap properties;
} // namespace
TEST(Buckets, CircleBucket) {
gl::HeadlessBackend backend({ 512, 256 });
gfx::BackendScope scope { backend };
gl::Context context{ backend };
CircleBucket bucket { { {0, 0, 0}, MapMode::Static, 1.0, nullptr }, {} };
ASSERT_FALSE(bucket.hasData());
ASSERT_FALSE(bucket.needsUpload());
GeometryCollection point { { { 0, 0 } } };
bucket.addFeature(StubGeometryTileFeature { {}, FeatureType::Point, point, properties }, point, {}, PatternLayerMap());
ASSERT_TRUE(bucket.hasData());
ASSERT_TRUE(bucket.needsUpload());
auto commandEncoder = context.createCommandEncoder();
auto uploadPass = commandEncoder->createUploadPass("upload");
bucket.upload(*uploadPass);
ASSERT_TRUE(bucket.hasData());
ASSERT_FALSE(bucket.needsUpload());
}
TEST(Buckets, FillBucket) {
gl::HeadlessBackend backend({ 512, 256 });
gfx::BackendScope scope { backend };
style::Properties<>::PossiblyEvaluated layout;
gl::Context context{ backend };
FillBucket bucket { layout, {}, 5.0f, 1};
ASSERT_FALSE(bucket.hasData());
ASSERT_FALSE(bucket.needsUpload());
GeometryCollection polygon { { { 0, 0 }, { 0, 1 }, { 1, 1 } } };
bucket.addFeature(StubGeometryTileFeature { {}, FeatureType::Polygon, polygon, properties }, polygon, {}, PatternLayerMap());
ASSERT_TRUE(bucket.hasData());
ASSERT_TRUE(bucket.needsUpload());
auto commandEncoder = context.createCommandEncoder();
auto uploadPass = commandEncoder->createUploadPass("upload");
bucket.upload(*uploadPass);
ASSERT_FALSE(bucket.needsUpload());
}
TEST(Buckets, LineBucket) {
gl::HeadlessBackend backend({ 512, 256 });
gfx::BackendScope scope { backend };
style::LineLayoutProperties::PossiblyEvaluated layout;
gl::Context context{ backend };
LineBucket bucket { layout, {}, 10.0f, 1 };
ASSERT_FALSE(bucket.hasData());
ASSERT_FALSE(bucket.needsUpload());
// Ignore invalid feature type.
GeometryCollection point { { { 0, 0 } } };
bucket.addFeature(StubGeometryTileFeature { {}, FeatureType::Point, point, properties }, point, {}, PatternLayerMap());
ASSERT_FALSE(bucket.hasData());
GeometryCollection line { { { 0, 0 }, { 1, 1 } } };
bucket.addFeature(StubGeometryTileFeature { {}, FeatureType::LineString, line, properties }, line, {}, PatternLayerMap());
ASSERT_TRUE(bucket.hasData());
ASSERT_TRUE(bucket.needsUpload());
auto commandEncoder = context.createCommandEncoder();
auto uploadPass = commandEncoder->createUploadPass("upload");
bucket.upload(*uploadPass);
ASSERT_FALSE(bucket.needsUpload());
}
TEST(Buckets, SymbolBucket) {
gl::HeadlessBackend backend({ 512, 256 });
gfx::BackendScope scope { backend };
auto layout = makeMutable<style::SymbolLayoutProperties::PossiblyEvaluated>();
bool iconsNeedLinear = false;
bool sortFeaturesByY = false;
std::string bucketLeaderID = "test";
std::vector<SymbolInstance> symbolInstances;
gl::Context context{ backend };
SymbolBucket bucket { std::move(layout), {}, 16.0f, 1.0f, 0, iconsNeedLinear, sortFeaturesByY, bucketLeaderID, std::move(symbolInstances), 1.0f, false, {}};
ASSERT_FALSE(bucket.hasIconData());
ASSERT_FALSE(bucket.hasSdfIconData());
ASSERT_FALSE(bucket.hasTextData());
ASSERT_FALSE(bucket.hasIconCollisionBoxData());
ASSERT_FALSE(bucket.hasTextCollisionBoxData());
ASSERT_FALSE(bucket.hasIconCollisionCircleData());
ASSERT_FALSE(bucket.hasTextCollisionCircleData());
ASSERT_FALSE(bucket.hasData());
ASSERT_FALSE(bucket.needsUpload());
// SymbolBucket::addFeature() is a no-op.
GeometryCollection point { { { 0, 0 } } };
bucket.addFeature(StubGeometryTileFeature { {}, FeatureType::Point, std::move(point), properties }, point, {}, PatternLayerMap());
ASSERT_FALSE(bucket.hasData());
ASSERT_FALSE(bucket.needsUpload());
bucket.text.segments.emplace_back(0, 0);
ASSERT_TRUE(bucket.hasTextData());
ASSERT_TRUE(bucket.hasData());
ASSERT_TRUE(bucket.needsUpload());
auto commandEncoder = context.createCommandEncoder();
auto uploadPass = commandEncoder->createUploadPass("upload");
bucket.upload(*uploadPass);
ASSERT_FALSE(bucket.needsUpload());
}
TEST(Buckets, RasterBucket) {
gl::HeadlessBackend backend({ 512, 256 });
gfx::BackendScope scope { backend };
gl::Context context{ backend };
PremultipliedImage rgba({ 1, 1 });
// RasterBucket::hasData() is always true.
RasterBucket bucket = { std::move(rgba) };
ASSERT_TRUE(bucket.hasData());
ASSERT_TRUE(bucket.needsUpload());
auto commandEncoder = context.createCommandEncoder();
auto uploadPass = commandEncoder->createUploadPass("upload");
bucket.upload(*uploadPass);
ASSERT_FALSE(bucket.needsUpload());
bucket.clear();
ASSERT_TRUE(bucket.needsUpload());
}
TEST(Buckets, RasterBucketMaskEmpty) {
RasterBucket bucket{ nullptr };
bucket.setMask({});
EXPECT_EQ((std::vector<RasterLayoutVertex>{}), bucket.vertices.vector());
EXPECT_EQ((std::vector<uint16_t>{}), bucket.indices.vector());
SegmentVector<RasterAttributes> expectedSegments;
expectedSegments.emplace_back(0, 0, 0, 0);
EXPECT_EQ(expectedSegments, bucket.segments);
}
TEST(Buckets, RasterBucketMaskNoChildren) {
RasterBucket bucket{ nullptr };
bucket.setMask({ CanonicalTileID{ 0, 0, 0 } });
// A mask of 0/0/0 doesn't produce buffers since we're instead using the global shared buffers.
EXPECT_EQ((std::vector<RasterLayoutVertex>{}), bucket.vertices.vector());
EXPECT_EQ((std::vector<uint16_t>{}), bucket.indices.vector());
EXPECT_EQ((SegmentVector<RasterAttributes>{}), bucket.segments);
}
TEST(Buckets, RasterBucketMaskTwoChildren) {
RasterBucket bucket{ nullptr };
bucket.setMask(
{ CanonicalTileID{ 1, 0, 0 }, CanonicalTileID{ 1, 1, 1 } });
EXPECT_EQ(
(std::vector<RasterLayoutVertex>{
// 1/0/1
RasterProgram::layoutVertex({ 0, 0 }, { 0, 0 }),
RasterProgram::layoutVertex({ 4096, 0 }, { 4096, 0 }),
RasterProgram::layoutVertex({ 0, 4096 }, { 0, 4096 }),
RasterProgram::layoutVertex({ 4096, 4096 }, { 4096, 4096 }),
// 1/1/1
RasterProgram::layoutVertex({ 4096, 4096 }, { 4096, 4096 }),
RasterProgram::layoutVertex({ 8192, 4096 }, { 8192, 4096 }),
RasterProgram::layoutVertex({ 4096, 8192 }, { 4096, 8192 }),
RasterProgram::layoutVertex({ 8192, 8192 }, { 8192, 8192 }),
}),
bucket.vertices.vector());
EXPECT_EQ(
(std::vector<uint16_t>{
// 1/0/1
0, 1, 2,
1, 2, 3,
// 1/1/1
4, 5, 6,
5, 6, 7,
}),
bucket.indices.vector());
SegmentVector<RasterAttributes> expectedSegments;
expectedSegments.emplace_back(0, 0, 8, 12);
EXPECT_EQ(expectedSegments, bucket.segments);
}
TEST(Buckets, RasterBucketMaskComplex) {
RasterBucket bucket{ nullptr };
bucket.setMask(
{ CanonicalTileID{ 1, 0, 1 }, CanonicalTileID{ 1, 1, 0 }, CanonicalTileID{ 2, 2, 3 },
CanonicalTileID{ 2, 3, 2 }, CanonicalTileID{ 3, 6, 7 }, CanonicalTileID{ 3, 7, 6 } });
EXPECT_EQ(
(std::vector<RasterLayoutVertex>{
// 1/0/1
RasterProgram::layoutVertex({ 0, 4096 }, { 0, 4096 }),
RasterProgram::layoutVertex({ 4096, 4096 }, { 4096, 4096 }),
RasterProgram::layoutVertex({ 0, 8192 }, { 0, 8192 }),
RasterProgram::layoutVertex({ 4096, 8192 }, { 4096, 8192 }),
// 1/1/0
RasterProgram::layoutVertex({ 4096, 0 }, { 4096, 0 }),
RasterProgram::layoutVertex({ 8192, 0 }, { 8192, 0 }),
RasterProgram::layoutVertex({ 4096, 4096 }, { 4096, 4096 }),
RasterProgram::layoutVertex({ 8192, 4096 }, { 8192, 4096 }),
// 2/2/3
RasterProgram::layoutVertex({ 4096, 6144 }, { 4096, 6144 }),
RasterProgram::layoutVertex({ 6144, 6144 }, { 6144, 6144 }),
RasterProgram::layoutVertex({ 4096, 8192 }, { 4096, 8192 }),
RasterProgram::layoutVertex({ 6144, 8192 }, { 6144, 8192 }),
// 2/3/2
RasterProgram::layoutVertex({ 6144, 4096 }, { 6144, 4096 }),
RasterProgram::layoutVertex({ 8192, 4096 }, { 8192, 4096 }),
RasterProgram::layoutVertex({ 6144, 6144 }, { 6144, 6144 }),
RasterProgram::layoutVertex({ 8192, 6144 }, { 8192, 6144 }),
// 3/6/7
RasterProgram::layoutVertex({ 6144, 7168 }, { 6144, 7168 }),
RasterProgram::layoutVertex({ 7168, 7168 }, { 7168, 7168 }),
RasterProgram::layoutVertex({ 6144, 8192 }, { 6144, 8192 }),
RasterProgram::layoutVertex({ 7168, 8192 }, { 7168, 8192 }),
// 3/7/6
RasterProgram::layoutVertex({ 7168, 6144 }, { 7168, 6144 }),
RasterProgram::layoutVertex({ 8192, 6144 }, { 8192, 6144 }),
RasterProgram::layoutVertex({ 7168, 7168 }, { 7168, 7168 }),
RasterProgram::layoutVertex({ 8192, 7168 }, { 8192, 7168 }),
}),
bucket.vertices.vector());
EXPECT_EQ(
(std::vector<uint16_t>{
// 1/0/1
0, 1, 2,
1, 2, 3,
// 1/1/0
4, 5, 6,
5, 6, 7,
// 2/2/3
8, 9, 10,
9, 10, 11,
// 2/3/2
12, 13, 14,
13, 14, 15,
// 3/6/7
16, 17, 18,
17, 18, 19,
// 3/7/6
20, 21, 22,
21, 22, 23,
}),
bucket.indices.vector());
SegmentVector<RasterAttributes> expectedSegments;
expectedSegments.emplace_back(0, 0, 24, 36);
EXPECT_EQ(expectedSegments, bucket.segments);
}
| 36.141479 | 160 | 0.626335 | [
"vector"
] |
a3e092c22d95d96237d5dd999c64174a8b7b4d8b | 1,721 | cc | C++ | Engine/Functions/random.cc | TrevorShelton/cplot | 8bf40e94519cc4fd69b2e0677d3a3dcf8695245a | [
"MIT"
] | 32 | 2017-11-27T03:04:44.000Z | 2022-01-21T17:03:40.000Z | Engine/Functions/random.cc | TrevorShelton/cplot | 8bf40e94519cc4fd69b2e0677d3a3dcf8695245a | [
"MIT"
] | 30 | 2017-11-10T09:47:16.000Z | 2018-11-21T22:36:47.000Z | Engine/Functions/random.cc | TrevorShelton/cplot | 8bf40e94519cc4fd69b2e0677d3a3dcf8695245a | [
"MIT"
] | 20 | 2018-01-05T17:15:11.000Z | 2021-07-30T14:11:01.000Z | #include "../cnum.h"
#include "../../Graphs/Geometry/Vector.h"
#if 1
#include <random>
#include <cassert>
static std::mt19937 seed_rng; // TODO: lock this
static thread_local std::mt19937 rng(seed_rng());
static std::uniform_real_distribution<> udist(-1.0, 1.0);
#define URND (udist(rng))
#else
#include <cstdlib>
static double rnd()
{
return (double)arc4random_uniform(std::numeric_limits<u_int32_t>::max()) / std::numeric_limits<u_int32_t>::max();
}
// URND: [-1,1]
#define URND (2.0*rnd()-1.0)
#endif
double real_rand()
{
// [-1,1]
return URND;
}
void real_rand(cnum &z)
{
// re(z) in [-1,1], im(z) = 0
// should always be optimized to the real version above
z.real(URND);
z.imag(0.0);
}
double normal_rand()
{
// (0,1)-normal variate (Marsaglia polar)
double r;
cnum z;
do{
z.real(URND);
z.imag(URND);
r = absq(z);
}while(r >= 1.0);
return z.real() * sqrt(-2.0*log(r) / r);
}
void normal_rand(cnum &z)
{
// normal re(z), im(z) = 0
// should always be optimized to the real version above
double r;
do{
z.real(URND);
z.imag(URND);
r = absq(z);
}while(r >= 1.0);
z.real(z.real() * sqrt(-2.0*log(r) / r));
z.imag(0.0);
}
void normal_z_rand(cnum &z)
{
// normal real and imag parts
double r;
do{
z.real(URND);
z.imag(URND);
r = absq(z);
}while(r >= 1.0);
z *= sqrt(-2.0*log(r) / r);
}
void riemann_rand(cnum &z)
{
// uniform distribution on riemann sphere
P3d v; double d;
do{
v.x = URND;
v.y = URND;
d = v.x*v.x + v.y*v.y;
}while(d >= 1.0);
v.z = 1.0 - 2.0*d;
d = 2.0*sqrt(1.0-d);
v.x *= d;
v.y *= d;
riemann(v, z);
}
void disk_rand(cnum &z)
{
// uniform distibution on the unit disk
do{
z.real(URND);
z.imag(URND);
}while(absq(z) >= 1.0);
}
| 16.708738 | 114 | 0.603138 | [
"geometry",
"vector"
] |
a3e14012f0adebd0a74c29e3e34a82a36deee118 | 2,109 | hpp | C++ | windowsbuild/MSVC2017/mfem/4.0/include/mfem/mesh/wedge.hpp | Tech-XCorp/visit-deps | 23e2bd534bf9c332d6b7d32310495f1f65b1b936 | [
"BSD-3-Clause"
] | null | null | null | windowsbuild/MSVC2017/mfem/4.0/include/mfem/mesh/wedge.hpp | Tech-XCorp/visit-deps | 23e2bd534bf9c332d6b7d32310495f1f65b1b936 | [
"BSD-3-Clause"
] | null | null | null | windowsbuild/MSVC2017/mfem/4.0/include/mfem/mesh/wedge.hpp | Tech-XCorp/visit-deps | 23e2bd534bf9c332d6b7d32310495f1f65b1b936 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.
#ifndef MFEM_WEDGE
#define MFEM_WEDGE
#include "../config/config.hpp"
#include "element.hpp"
namespace mfem
{
/// Data type Wedge element
class Wedge : public Element
{
protected:
int indices[6];
public:
typedef Geometry::Constants<Geometry::PRISM> geom_t;
Wedge() : Element(Geometry::PRISM) { }
/// Constructs wedge by specifying the indices and the attribute.
Wedge(const int *ind, int attr = 1);
/// Constructs wedge by specifying the indices and the attribute.
Wedge(int ind1, int ind2, int ind3, int ind4, int ind5, int ind6,
int attr = 1);
/// Return element's type.
virtual Type GetType() const { return Element::WEDGE; }
/// Set the vertices according to the given input.
virtual void SetVertices(const int *ind);
/// Returns the indices of the element's vertices.
virtual void GetVertices(Array<int> &v) const;
virtual int *GetVertices() { return indices; }
virtual int GetNVertices() const { return 6; }
virtual int GetNEdges() const { return 9; }
virtual const int *GetEdgeVertices(int ei) const
{ return geom_t::Edges[ei]; }
virtual int GetNFaces(int &nFaceVertices) const;
virtual int GetNFaceVerticess(int fi) const
{ return ( ( fi < 2 ) ? 3 : 4); }
virtual const int *GetFaceVertices(int fi) const
{ return geom_t::FaceVert[fi]; }
virtual Element *Duplicate(Mesh *m) const
{ return new Wedge(indices, attribute); }
virtual ~Wedge() { }
};
// Defined in fe.cpp to ensure construction after 'mfem::poly1d'.
extern class H1_WedgeElement WedgeFE;
}
#endif
| 27.38961 | 78 | 0.702703 | [
"mesh",
"geometry"
] |
9caed7d95da2c60265c46fc18e542096d6baaca5 | 9,185 | cpp | C++ | GameEngine/CoreEngine/CoreEngine/src/BoundingSphere.cpp | mettaursp/SuddenlyGames | e2ff1c2771d4ca54824650e4f1a33a527536ca61 | [
"Apache-2.0"
] | 1 | 2021-01-17T13:05:20.000Z | 2021-01-17T13:05:20.000Z | GameEngine/CoreEngine/CoreEngine/src/BoundingSphere.cpp | suddenly-games/SuddenlyGames | e2ff1c2771d4ca54824650e4f1a33a527536ca61 | [
"Apache-2.0"
] | null | null | null | GameEngine/CoreEngine/CoreEngine/src/BoundingSphere.cpp | suddenly-games/SuddenlyGames | e2ff1c2771d4ca54824650e4f1a33a527536ca61 | [
"Apache-2.0"
] | null | null | null | #include "BoundingSphere.h"
#include <algorithm>
#include <numeric>
#include "PCA.h"
#include "MeshLoader.h"
#include "ModelAsset.h"
BoundingSphere BoundingSphere::ComputeCentroid(const std::shared_ptr<Engine::ModelAsset>& model)
{
int meshID = model->GetMeshID();
return ComputeCentroid(MeshLoader::GetMeshData(meshID)->VertexBuffer);
}
BoundingSphere BoundingSphere::ComputeRitter(const std::shared_ptr<Engine::ModelAsset>& model)
{
int meshID = model->GetMeshID();
return ComputeRitter(MeshLoader::GetMeshData(meshID)->VertexBuffer);
}
BoundingSphere BoundingSphere::ComputeLarson(const std::shared_ptr<Engine::ModelAsset>& model)
{
int meshID = model->GetMeshID();
return ComputeLarson(MeshLoader::GetMeshData(meshID)->VertexBuffer);
}
BoundingSphere BoundingSphere::ComputePCA(const std::shared_ptr<Engine::ModelAsset>& model)
{
int meshID = model->GetMeshID();
return ComputePCA(MeshLoader::GetMeshData(meshID)->VertexBuffer);
}
bool BoundingSphere::Contains(const Vector3& point)
{
return (point - Center).SquareLength() <= Radius * Radius;
}
void BoundingSphere::ExpandByPoint(const Vector3& point)
{
Vector3 diff = point - Center;
float length = diff.SquareLength();
if (length <= Radius * Radius)
return;
length = sqrtf(length);
diff *= 1 / length;
Center = 0.5f * (Center - Radius * diff + point);
Radius = 0.5f * (length + Radius);
}
BoundingSphere BoundingSphere::ComputeCentroid(const MeshData::VertexVector& vertices)
{
if (vertices.size() == 0)
return BoundingSphere();
else if (vertices.size() == 1)
return BoundingSphere(0, vertices[0].Position);
Vector3 minPoint = vertices[0].Position;
Vector3 maxPoint = vertices[0].Position;
for (int i = 1; i < int(vertices.size()); ++i)
{
minPoint.X = std::min(minPoint.X, vertices[i].Position.X);
minPoint.Y = std::min(minPoint.Y, vertices[i].Position.Y);
minPoint.Z = std::min(minPoint.Z, vertices[i].Position.Z);
maxPoint.X = std::max(maxPoint.X, vertices[i].Position.X);
maxPoint.Y = std::max(maxPoint.Y, vertices[i].Position.Y);
maxPoint.Z = std::max(maxPoint.Z, vertices[i].Position.Z);
}
Vector3 center;
center = 0.5f * (minPoint + maxPoint);
float maxRadius = 0;
for (int i = 0; i < int(vertices.size()); ++i)
maxRadius = std::max(maxRadius, (Vector3(vertices[i].Position) - center).SquareLength());
return BoundingSphere(sqrtf(maxRadius), center);
}
BoundingSphere BoundingSphere::ComputeRitter(const MeshData::VertexVector& vertices)
{
if (vertices.size() == 0)
return BoundingSphere();
else if (vertices.size() == 1)
return BoundingSphere(0, vertices[0].Position);
Vector3 minPoint = vertices[0].Position;
Vector3 maxPoint = vertices[0].Position;
int minX = 0;
int minY = 0;
int minZ = 0;
int maxX = 0;
int maxY = 0;
int maxZ = 0;
for (int i = 1; i < int(vertices.size()); ++i)
{
if (vertices[i].Position.X < minPoint.X)
{
minPoint.X = vertices[i].Position.X;
minX = i;
}
if (vertices[i].Position.Y < minPoint.Y)
{
minPoint.Y = vertices[i].Position.Y;
minY = i;
}
if (vertices[i].Position.Z < minPoint.Z)
{
minPoint.Z = vertices[i].Position.Z;
minZ = i;
}
if (vertices[i].Position.X > maxPoint.X)
{
maxPoint.X = vertices[i].Position.X;
maxX = i;
}
if (vertices[i].Position.Y > maxPoint.Y)
{
maxPoint.Y = vertices[i].Position.Y;
maxY = i;
}
if (vertices[i].Position.Z > maxPoint.Z)
{
maxPoint.Z = vertices[i].Position.Z;
maxZ = i;
}
}
float lengthX = (Vector3(vertices[minX].Position) - vertices[maxX].Position).SquareLength();
float lengthY = (Vector3(vertices[minY].Position) - vertices[maxY].Position).SquareLength();
float lengthZ = (Vector3(vertices[minZ].Position) - vertices[maxZ].Position).SquareLength();
Vector3 bound1;
Vector3 bound2;
if (lengthX > lengthY&& lengthX > lengthZ)
{
bound1 = vertices[minX].Position;
bound2 = vertices[maxX].Position;
}
else if (lengthY > lengthZ)
{
bound1 = vertices[minY].Position;
bound2 = vertices[maxY].Position;
}
else
{
bound1 = vertices[minZ].Position;
bound2 = vertices[maxZ].Position;
}
BoundingSphere sphere(0.5f * (bound1 - bound2).Length(), 0.5f * (bound1 + bound2));
for (int i = 0; i < int(vertices.size()); ++i)
sphere.ExpandByPoint(vertices[i].Position);
return sphere;
}
namespace
{
inline void trySwap(int* x, int* y)
{
if (*x > * y)
std::swap(*x, *y);
}
void fastSort(int* data)
{
trySwap(data + 1, data + 2);
trySwap(data + 0, data + 2);
trySwap(data + 0, data + 1);
trySwap(data + 4, data + 5);
trySwap(data + 3, data + 5);
trySwap(data + 3, data + 4);
trySwap(data + 0, data + 3);
trySwap(data + 1, data + 4);
trySwap(data + 2, data + 5);
trySwap(data + 2, data + 4);
trySwap(data + 1, data + 3);
trySwap(data + 2, data + 3);
}
int removeDuplicates(int* data)
{
int next = 0;
int current = 0;
while (next < 6)
{
if (data[next] != data[current])
{
data[current] = data[next];
++current;
}
++next;
}
return current;
}
}
BoundingSphere BoundingSphere::ComputeLarson(const MeshData::VertexVector& vertices)
{
if (vertices.size() == 0)
return BoundingSphere();
else if (vertices.size() == 1)
return BoundingSphere(0, vertices[0].Position);
if (vertices.size() > 6)
{
int extremePoints[6] = { 0, 0, 0, 0, 0, 0 };
Vector3 min = vertices[0].Position;
Vector3 max = vertices[0].Position;
for (int i = 1; i < int(vertices.size()); ++i)
{
Vector3 point = vertices[i].Position;
if (point.X < min.X)
extremePoints[0] = i;
else if (point.X > max.X)
extremePoints[1] = i;
if (point.Y < min.Y)
extremePoints[2] = i;
else if (point.Y > max.Y)
extremePoints[3] = i;
if (point.Z < min.Z)
extremePoints[4] = i;
else if (point.Z > max.Z)
extremePoints[5] = i;
min.Set(
std::min(min.X, point.X),
std::min(min.Y, point.Y),
std::min(min.Z, point.Z)
);
max.Set(
std::max(max.X, point.X),
std::max(max.Y, point.Y),
std::max(max.Z, point.Z)
);
}
fastSort(extremePoints);
int pointCount = removeDuplicates(extremePoints);
BoundingSphere sphere = ComputeExactSphere(vertices, extremePoints, pointCount);
for (int i = 0; i < int(vertices.size()); ++i)
sphere.ExpandByPoint(vertices[i].Position);
return sphere;
}
else
{
int extremePoints[6] = { 0, 1, 2, 3, 4, 5 };
return ComputeExactSphere(vertices, extremePoints, int(vertices.size()));
}
}
BoundingSphere BoundingSphere::ComputeExactSphere(const MeshData::VertexVector& vertices, int* indices, int indexCount)
{
int farthest1 = 0;
int farthest2 = 0;
float farthestDistance = 0;
for (int i = 0; i < indexCount; ++i)
{
for (int j = 0; j < indexCount; ++j)
{
float distance = (Vector3(vertices[indices[i]].Position) - vertices[indices[j]].Position).SquareLength();
if (distance > farthestDistance)
{
farthestDistance = distance;
farthest1 = i;
farthest2 = j;
}
}
}
Vector3 center = 0.5f * (Vector3(vertices[indices[farthest1]].Position) + vertices[indices[farthest2]].Position);
float radiusSquared = (center + vertices[indices[farthest2]].Position).SquareLength();
float radius = std::sqrt(radiusSquared);
while (indexCount > 0)
{
int expandingTo = -1;
float farthest = radiusSquared;
for (int i = 0; i < indexCount;)
{
float distance = (Vector3(vertices[indices[i]].Position) - center).SquareLength();
if (distance > farthest)
{
farthest = distance;
expandingTo = i;
}
else if (distance <= radiusSquared)
{
std::swap(indices[i], indices[indexCount - 1]);
--indexCount;
}
}
if (indexCount > 0)
{
float distance = std::sqrt(farthest);
center = 0.5f * (1 - radius / distance) * (vertices[indices[expandingTo]].Position - center);
radius += 0.5f * (distance - radius);
radiusSquared = radius * radius;
}
}
return BoundingSphere(radius, center);
}
BoundingSphere BoundingSphere::ComputePCA(const MeshData::VertexVector& vertices)
{
if (vertices.size() == 0)
return BoundingSphere();
else if (vertices.size() == 1)
return BoundingSphere(0, vertices[0].Position);
Matrix3 covariance = PCA::ComputeCovariance(vertices);
PCA eigenData = PCA::Compute(covariance);
Vector3 axis;
Vector3 eigenValues = eigenData.EigenValues;
if (eigenValues.X > eigenValues.Y&& eigenValues.X > eigenValues.Z)
axis = eigenData.Axis1;
else if (eigenValues.Y > eigenValues.X && eigenValues.Y > eigenValues.Z)
axis = eigenData.Axis2;
else
axis = eigenData.Axis3;
float smallestDot = Vector3(vertices[0].Position).Dot(axis);
float largestDot = smallestDot;
int i1 = 0;
int i2 = 0;
for (int i = 1; i < int(vertices.size()); ++i)
{
float dot = Vector3(vertices[i].Position).Dot(axis);
if (dot < smallestDot)
{
smallestDot = dot;
i1 = i;
}
if (dot > largestDot)
{
largestDot = dot;
i2 = i;
}
}
BoundingSphere sphere(0.5f * Vector3(vertices[i1].Position - vertices[i2].Position).Length(), 0.5f * (vertices[i1].Position + vertices[i2].Position));
for (int i = 0; i < int(vertices.size()); ++i)
sphere.ExpandByPoint(vertices[i].Position);
return sphere;
}
| 23.13602 | 151 | 0.659227 | [
"model"
] |
9cb1dbf263ce6456fccc9796aed5f85a6dc93de0 | 3,870 | cpp | C++ | source/FAST/Algorithms/MeshToSegmentation/Tests.cpp | andreped/FAST | 361819190ea0ae5a2f068e7bd808a1c70af5a171 | [
"BSD-2-Clause"
] | null | null | null | source/FAST/Algorithms/MeshToSegmentation/Tests.cpp | andreped/FAST | 361819190ea0ae5a2f068e7bd808a1c70af5a171 | [
"BSD-2-Clause"
] | null | null | null | source/FAST/Algorithms/MeshToSegmentation/Tests.cpp | andreped/FAST | 361819190ea0ae5a2f068e7bd808a1c70af5a171 | [
"BSD-2-Clause"
] | null | null | null | #include "MeshToSegmentation.hpp"
#include "FAST/Testing.hpp"
#include "FAST/Importers/MetaImageImporter.hpp"
#include "FAST/Data/Mesh.hpp"
#include "FAST/Visualization/ImageRenderer/ImageRenderer.hpp"
#include "FAST/Visualization/SegmentationRenderer/SegmentationRenderer.hpp"
#include "FAST/Visualization/SliceRenderer/SliceRenderer.hpp"
#include "FAST/Visualization/TriangleRenderer/TriangleRenderer.hpp"
#include "FAST/Visualization/SimpleWindow.hpp"
#include "FAST/Visualization/DualViewWindow.hpp"
#include "FAST/Algorithms/SurfaceExtraction/SurfaceExtraction.hpp"
using namespace fast;
TEST_CASE("MeshToSegmentation 2D", "[fast][MeshToSegmentation][2d][visual]") {
MetaImageImporter::pointer importer = MetaImageImporter::New();
importer->setFilename(Config::getTestDataPath()+"US/CarotidArtery/Right/US-2D_0.mhd");
std::vector<MeshVertex> vertices = {
MeshVertex(Vector3f(1, 1, 0)),
MeshVertex(Vector3f(1, 25, 0)),
MeshVertex(Vector3f(25, 20, 0)),
MeshVertex(Vector3f(20, 1, 0)),
};
std::vector<MeshLine> lines = {
MeshLine(0, 1),
MeshLine(1, 2),
MeshLine(2, 3),
MeshLine(3, 0)
};
auto mesh = Mesh::create(vertices, lines);
auto meshToSeg = MeshToSegmentation::create()
->connect(mesh)
->connect(1, importer);
//meshToSeg->setOutputImageResolution(50, 50);
auto segRenderer = SegmentationRenderer::New();
segRenderer->addInputConnection(meshToSeg->getOutputPort());
auto imageRenderer = ImageRenderer::New();
imageRenderer->addInputConnection(importer->getOutputPort());
auto window = DualViewWindow::create()
->connectRight(segRenderer)
->connectLeft({imageRenderer, segRenderer});
window->set2DMode();
window->setTimeout(500);
window->run();
}
TEST_CASE("MeshToSegmentation 3D", "[fast][MeshToSegmentation][3d][visual]") {
MetaImageImporter::pointer importer = MetaImageImporter::New();
importer->setFilename(Config::getTestDataPath()+"US/Ball/US-3Dt_0.mhd");
std::vector<MeshVertex> vertices = {
MeshVertex(Vector3f(1, 1, 1)),
MeshVertex(Vector3f(1, 1, 10)),
MeshVertex(Vector3f(1, 10, 10)),
MeshVertex(Vector3f(1, 1, 1)),
MeshVertex(Vector3f(1, 1, 10)),
MeshVertex(Vector3f(30, 15, 15)),
MeshVertex(Vector3f(1, 1, 10)),
MeshVertex(Vector3f(1, 10, 10)),
MeshVertex(Vector3f(30, 15, 15)),
MeshVertex(Vector3f(1, 1, 1)),
MeshVertex(Vector3f(1, 10, 10)),
MeshVertex(Vector3f(30, 15, 15))
};
std::vector<MeshTriangle> triangles = {
MeshTriangle(0, 1, 2),
MeshTriangle(3, 4, 5),
MeshTriangle(6, 7, 8),
MeshTriangle(9, 10, 11)
};
auto mesh = Mesh::create(vertices, {}, triangles);
MeshToSegmentation::pointer meshToSeg = MeshToSegmentation::New();
meshToSeg->setInputData(0, mesh);
meshToSeg->setInputConnection(1, importer->getOutputPort());
meshToSeg->setOutputImageResolution(40, 40, 40);
SliceRenderer::pointer imageRenderer = SliceRenderer::New();
imageRenderer->setInputConnection(importer->getOutputPort());
SurfaceExtraction::pointer extraction = SurfaceExtraction::create();
extraction->setInputConnection(meshToSeg->getOutputPort());
TriangleRenderer::pointer TriangleRenderer = TriangleRenderer::New();
TriangleRenderer->setInputConnection(extraction->getOutputPort());
auto window = DualViewWindow::create(Color::White(), 1024)
->connectLeft(imageRenderer)
->connectRight(TriangleRenderer);
//window->getBottomRightView()->set2DMode();
//window->getTopLeftView()->set2DMode();
window->setTimeout(500);
window->run();
}
| 37.211538 | 90 | 0.662016 | [
"mesh",
"vector",
"3d"
] |
9cb3c43f531895bd99df1890ee64ea407f5d6379 | 100,361 | cpp | C++ | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/widget/NumberPicker.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/widget/NumberPicker.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/widget/NumberPicker.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include "Elastos.Droid.Widget.h"
#include <Elastos.CoreLibrary.Libcore.h>
#include "elastos/droid/widget/NumberPicker.h"
#include "elastos/droid/content/res/CCompatibilityInfo.h"
#include "elastos/droid/graphics/CPaint.h"
#include "elastos/droid/graphics/CRect.h"
#include "elastos/droid/text/TextUtils.h"
#include "elastos/droid/utility/CSparseArray.h"
#include "elastos/droid/utility/CTypedValue.h"
#include "elastos/droid/view/CViewConfiguration.h"
#include "elastos/droid/view/accessibility/CAccessibilityManager.h"
#include "elastos/droid/view/accessibility/CAccessibilityEvent.h"
#include "elastos/droid/view/accessibility/CAccessibilityNodeInfo.h"
#include "elastos/droid/view/inputmethod/CInputMethodManager.h"
#include "elastos/droid/widget/CScroller.h"
#include "elastos/droid/widget/CNumberPicker.h"
#include <elastos/core/CoreUtils.h>
#include <elastos/core/Math.h>
#include <elastos/core/StringUtils.h>
using Elastos::Droid::Content::Res::IResources;
using Elastos::Droid::Content::Res::ICompatibilityInfo;
using Elastos::Droid::Content::Res::CCompatibilityInfo;
using Elastos::Droid::Graphics::CPaint;
using Elastos::Droid::Graphics::CRect;
using Elastos::Droid::Graphics::IColor;
using Elastos::Droid::Text::TextUtils;
using Elastos::Droid::Text::IInputType;
using Elastos::Droid::Utility::CSparseArray;
using Elastos::Droid::Utility::ITypedValue;
using Elastos::Droid::Utility::CTypedValue;
using Elastos::Droid::View::Accessibility::IAccessibilityRecord;
using Elastos::Droid::View::Accessibility::IAccessibilityManager;
using Elastos::Droid::View::Accessibility::CAccessibilityManager;
using Elastos::Droid::View::Accessibility::CAccessibilityEvent;
using Elastos::Droid::View::Accessibility::CAccessibilityNodeInfo;
using Elastos::Droid::View::InputMethod::IInputMethodManager;
using Elastos::Droid::View::InputMethod::CInputMethodManager;
using Elastos::Droid::View::IInputEvent;
using Elastos::Droid::View::EIID_IViewOnClickListener;
using Elastos::Droid::View::EIID_IViewOnLongClickListener;
using Elastos::Droid::View::EIID_IViewOnFocusChangeListener;
using Elastos::Droid::View::EIID_IView;
using Elastos::Droid::View::EIID_IViewGroup;
using Elastos::Droid::View::ILayoutInflater;
using Elastos::Droid::View::IViewConfiguration;
using Elastos::Droid::View::CViewConfiguration;
using Elastos::Droid::Widget::CNumberPicker;
using Elastos::Droid::Widget::CScroller;
using Elastos::Core::CoreUtils;
using Elastos::Core::CInteger32;
using Elastos::Core::Math;
using Elastos::Core::IAppendable;
using Elastos::Core::StringUtils;
using Elastos::Utility::CArrayList;
using Elastos::Utility::CFormatter;
using Elastos::Utility::CLocaleHelper;
using Elastos::Utility::ILocaleHelper;
using Elastos::Utility::ICollections;
using Elastos::Utility::CCollections;
using Libcore::ICU::ILocaleData;
using Libcore::ICU::ILocaleDataHelper;
using Libcore::ICU::CLocaleDataHelper;
namespace Elastos {
namespace Droid {
namespace Widget {
const String NumberPicker::NUMBERPICKER_NAME("NumberPicker");
const Int32 NumberPicker::SELECTOR_WHEEL_ITEM_COUNT = 3;
const Int64 NumberPicker::DEFAULT_LONG_PRESS_UPDATE_INTERVAL = 300;
const Int32 NumberPicker::SELECTOR_MIDDLE_ITEM_INDEX = SELECTOR_WHEEL_ITEM_COUNT / 2;
const Int32 NumberPicker::SELECTOR_MAX_FLING_VELOCITY_ADJUSTMENT = 8;
const Int32 NumberPicker::SELECTOR_ADJUSTMENT_DURATION_MILLIS = 800;
const Int32 NumberPicker::SNAP_SCROLL_DURATION = 300;
const Float NumberPicker::TOP_AND_BOTTOM_FADING_EDGE_STRENGTH = 0.9f;
const Int32 NumberPicker::UNSCALED_DEFAULT_SELECTION_DIVIDER_HEIGHT = 2;
const Int32 NumberPicker::UNSCALED_DEFAULT_SELECTION_DIVIDERS_DISTANCE = 48;
const Int32 NumberPicker::DEFAULT_LAYOUT_RESOURCE_ID = R::layout::number_picker;
const Int32 NumberPicker::SIZE_UNSPECIFIED = -1;
AutoPtr<INumberPickerFormatter> NumberPicker::GetTwoDigitFormatter()
{
AutoPtr<TwoDigitFormatter> formatter = new NumberPicker::TwoDigitFormatter();
return (INumberPickerFormatter*)formatter.Get();
}
AutoPtr<INumberPickerFormatter> NumberPicker::sTwoDigitFormatter = NumberPicker::GetTwoDigitFormatter();
const Char32 NumberPicker::DIGIT_CHARACTERS[]= {
// Latin digits are the common case
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
// Arabic-Indic
0x0660/*'\u0660'*/, 0x0661/*'\u0661'*/, 0x0662/*'\u0662'*/, 0x0663/*'\u0663'*/,
0x0664/*'\u0664'*/, 0x0665/*'\u0665'*/, 0x0666/*'\u0666'*/, 0x0667/*'\u0667'*/,
0x0668/*'\u0668'*/, 0x0669/*'\u0669'*/,
// Extended Arabic-Indic
0x06f0/*'\u06f0'*/, 0x06f1/*'\u06f1'*/, 0x06f2/*'\u06f2'*/, 0x06f3/*'\u06f3'*/,
0x06f4/*'\u06f4'*/, 0x06f5/*'\u06f5'*/, 0x06f6/*'\u06f6'*/, 0x06f7/*'\u06f7'*/,
0x06f8/*'\u06f8'*/, 0x06f9/*'\u06f9'*/,
// Hindi and Marathi (Devanagari script)
0x0966/*'\u0966'*/, 0x0967/*'\u0967'*/, 0x0968/*'\u0968'*/, 0x0969/*'\u0969'*/,
0x096a/*'\u096a'*/, 0x096b/*'\u096b'*/, 0x096c/*'\u096c'*/, 0x096d/*'\u096d'*/,
0x096e/*'\u096e'*/, 0x096f/*'\u096f'*/,
// Bengali
0x09e6/*'\u09e6'*/, 0x09e7/*'\u09e7'*/, 0x09e8/*'\u09e8'*/, 0x09e9/*'\u09e9'*/,
0x09ea/*'\u09ea'*/, 0x09eb/*'\u09eb'*/, 0x09ec/*'\u09ec'*/, 0x09ed/*'\u09ed'*/,
0x09ee/*'\u09ee'*/, 0x09ef/*'\u09ef'*/,
// Kannada
0x0ce6/*'\u0ce6'*/, 0x0ce7/*'\u0ce7'*/, 0x0ce8/*'\u0ce8'*/, 0x0ce9/*'\u0ce9'*/,
0x0cea/*'\u0cea'*/, 0x0ceb/*'\u0ceb'*/, 0x0cec/*'\u0cec'*/, 0x0ced/*'\u0ced'*/,
0x0cee/*'\u0cee'*/, 0x0cef/*'\u0cef'*/
};
const Int32 NumberPicker::AccessibilityNodeProviderImpl::UNDEFINED = Elastos::Core::Math::INT32_MIN_VALUE;
const Int32 NumberPicker::AccessibilityNodeProviderImpl::VIRTUAL_VIEW_ID_INCREMENT;
const Int32 NumberPicker::AccessibilityNodeProviderImpl::VIRTUAL_VIEW_ID_INPUT;
const Int32 NumberPicker::AccessibilityNodeProviderImpl::VIRTUAL_VIEW_ID_DECREMENT;
//==============================================================================================
// NumberPicker::CustomEditText
//==============================================================================================
CAR_INTERFACE_IMPL(NumberPicker::CustomEditText, EditText, INumberPickerCustomEditText);
NumberPicker::CustomEditText::CustomEditText()
{}
NumberPicker::CustomEditText::~CustomEditText()
{}
ECode NumberPicker::CustomEditText::constructor(
/* [in] */ IContext* context,
/* [in] */ IAttributeSet* attrs)
{
return EditText::constructor(context, attrs);
}
ECode NumberPicker::CustomEditText::OnEditorAction(
/* [in] */ Int32 actionCode)
{
EditText::OnEditorAction(actionCode);
if (actionCode == IEditorInfo::IME_ACTION_DONE) {
View::ClearFocus();
}
return NOERROR;
}
//==============================================================================================
// NumberPicker::InputTextFilter
//==============================================================================================
NumberPicker::InputTextFilter::InputTextFilter(
/* [in] */ NumberPicker* host)
: mHost(host)
{
}
ECode NumberPicker::InputTextFilter::GetInputType(
/* [out] */ Int32* type)
{
VALIDATE_NOT_NULL(type);
*type = IInputType::TYPE_CLASS_TEXT;
return NOERROR;
}
AutoPtr<ArrayOf<Char32> > NumberPicker::InputTextFilter::GetAcceptedChars()
{
UInt32 len = sizeof(DIGIT_CHARACTERS) / sizeof(DIGIT_CHARACTERS[0]);
AutoPtr<ArrayOf<Char32> > chars = ArrayOf<Char32>::Alloc(len);
for (Int32 i = 0; i < (Int32)len; i++) {
(*chars)[i] = DIGIT_CHARACTERS[i];
}
return chars;
}
ECode NumberPicker::InputTextFilter::Filter(
/* [in] */ ICharSequence* source,
/* [in] */ Int32 start,
/* [in] */ Int32 end,
/* [in] */ ISpanned* dest,
/* [in] */ Int32 dstart,
/* [in] */ Int32 dend,
/* [out] */ ICharSequence** sou)
{
if (!mHost->mDisplayedValues) {
AutoPtr<ICharSequence> filtered;
NumberKeyListener::Filter(source, start, end, dest, dstart, dend, (ICharSequence**)&filtered);
if (!filtered) {
source->SubSequence(start, end, (ICharSequence**)&filtered);
}
AutoPtr<ICharSequence> res;
ICharSequence::Probe(dest)->SubSequence(0, dstart, (ICharSequence**)&res);
String subString = String(NULL);
res->ToString(&subString);
String result = subString;
filtered->ToString(&subString);
result += subString;
Int32 len = 0;
ICharSequence::Probe(dest)->GetLength(&len);
res = NULL;
ICharSequence::Probe(dest)->SubSequence(dend, len, (ICharSequence**)&res);
res->ToString(&subString);
result += subString;
if (result.Equals("")) {
AutoPtr<ICharSequence> seq = CoreUtils::Convert(result);
*sou = seq;
REFCOUNT_ADD(*sou);
return NOERROR;
}
Int32 val = mHost->GetSelectedPos(result);
/*
* Ensure the user can't type in a value greater than the max
* allowed. We have to allow less than min as the user might
* want to delete some numbers and then type a new number.
* And prevent multiple-"0" that exceeds the length of upper
* bound number.
*/
if (val > mHost->mMaxValue ||
result.GetLength() > StringUtils::ToString(mHost->mMaxValue).GetLength()) {
AutoPtr<ICharSequence> seq = CoreUtils::Convert("");
*sou = seq;
REFCOUNT_ADD(*sou);
return NOERROR;
}
else {
*sou = filtered;
REFCOUNT_ADD(*sou);
return NOERROR;
}
}
else {
AutoPtr<ICharSequence> filtered;
source->SubSequence(start, end, (ICharSequence**)&filtered);
if (TextUtils::IsEmpty(filtered)) {
AutoPtr<ICharSequence> seq = CoreUtils::Convert("");
*sou = seq;
REFCOUNT_ADD(*sou);
return NOERROR;
}
AutoPtr<ICharSequence> res;
ICharSequence::Probe(dest)->SubSequence(0, dstart, (ICharSequence**)&res);
String subString = String(NULL);
res->ToString(&subString);
String result = subString;
filtered->ToString(&subString);
result += subString;
Int32 len = 0;
ICharSequence::Probe(dest)->GetLength(&len);
res = NULL;
ICharSequence::Probe(dest)->SubSequence(dend, len, (ICharSequence**)&res);
res->ToString(&subString);
result += subString;
String str = result.ToLowerCase();
for (Int32 i = 0; i < mHost->mDisplayedValues->GetLength(); i++) {
String val = (*mHost->mDisplayedValues)[i];
String valLowerCase = val.ToLowerCase();
if (valLowerCase.StartWith(str)) {
mHost->PostSetSelectionCommand(result.GetLength(), val.GetLength());
return CoreUtils::Convert(val)->SubSequence(dstart, val.GetLength(), sou);
}
}
AutoPtr<ICharSequence> seq = CoreUtils::Convert("");
*sou = seq;
REFCOUNT_ADD(*sou);
return NOERROR;
}
}
ECode NumberPicker::InputTextFilter::ClearMetaKeyState(
/* [in] */ IView* view,
/* [in] */ IEditable* content,
/* [in] */ Int32 states)
{
return MetaKeyKeyListener::ClearMetaKeyState(view, content, states);
}
ECode NumberPicker::InputTextFilter::OnKeyUp(
/* [in] */ IView* view,
/* [in] */ IEditable* content,
/* [in] */ Int32 keyCode,
/* [in] */ IKeyEvent* event,
/* [out] */ Boolean* ret)
{
VALIDATE_NOT_NULL(ret);
return OnKeyUp(view, content, keyCode, event, ret);
}
//==============================================================================================
// NumberPicker::PressedStateHelper
//==============================================================================================
NumberPicker::PressedStateHelper::PressedStateHelper(
/* [in] */ NumberPicker* host)
: mManagedButton(0)
, mMode(0)
, mHost(host)
{
}
void NumberPicker::PressedStateHelper::Cancel()
{
mMode = 0;
mManagedButton = 0;
Boolean res;
mHost->RemoveCallbacks(this, &res);
if (mHost->mIncrementVirtualButtonPressed) {
mHost->mIncrementVirtualButtonPressed = FALSE;
mHost->Invalidate(0, mHost->mBottomSelectionDividerBottom, mHost->mRight, mHost->mBottom);
}
mHost->mDecrementVirtualButtonPressed = FALSE;
if (mHost->mDecrementVirtualButtonPressed) {
mHost->Invalidate(0, 0, mHost->mRight, mHost->mTopSelectionDividerTop);
}
}
void NumberPicker::PressedStateHelper::ButtonPressDelayed(
/* [in] */ Int32 button)
{
Cancel();
mMode = MODE_PRESS;
mManagedButton = button;
Boolean res;
mHost->PostDelayed(this, CViewConfiguration::GetTapTimeout(), &res);
}
void NumberPicker::PressedStateHelper::ButtonTapped(
/* [in] */ Int32 button)
{
Cancel();
mMode = MODE_TAPPED;
mManagedButton = button;
Boolean res;
mHost->Post(this, &res);
}
ECode NumberPicker::PressedStateHelper::Run()
{
switch (mMode) {
case MODE_PRESS:
switch (mManagedButton) {
case BUTTON_INCREMENT:
mHost->mIncrementVirtualButtonPressed = TRUE;
mHost->Invalidate(0, mHost->mBottomSelectionDividerBottom, mHost->mRight, mHost->mBottom);
break;
case BUTTON_DECREMENT:
mHost->mDecrementVirtualButtonPressed = TRUE;
mHost->Invalidate(0, 0, mHost->mRight, mHost->mTopSelectionDividerTop);
}
break;
case MODE_TAPPED:
switch (mManagedButton) {
Boolean res;
case BUTTON_INCREMENT:
if (!mHost->mIncrementVirtualButtonPressed) {
mHost->PostDelayed(this, CViewConfiguration::GetPressedStateDuration(), &res);
}
mHost->mIncrementVirtualButtonPressed ^= TRUE;
mHost->Invalidate(0, mHost->mBottomSelectionDividerBottom, mHost->mRight, mHost->mBottom);
break;
case BUTTON_DECREMENT:
if (!mHost->mDecrementVirtualButtonPressed) {
mHost->PostDelayed(this, CViewConfiguration::GetPressedStateDuration(), &res);
}
mHost->mDecrementVirtualButtonPressed ^= TRUE;
mHost->Invalidate(0, 0, mHost->mRight, mHost->mTopSelectionDividerTop);
break;
}
}
return NOERROR;
}
//==============================================================================================
// NumberPicker::SetSelectionCommand
//==============================================================================================
NumberPicker::SetSelectionCommand::SetSelectionCommand(
/* [in] */ INumberPicker* host)
: mSelectionStart(0)
, mSelectionEnd(0)
{
IWeakReferenceSource::Probe(host)->GetWeakReference((IWeakReference**)&mWeakHost);
assert(mWeakHost);
}
ECode NumberPicker::SetSelectionCommand::Run()
{
AutoPtr<IInterface> obj;
mWeakHost->Resolve(EIID_IInterface, (IInterface**)&obj);
AutoPtr<INumberPicker> num = INumberPicker::Probe(obj);
if (num == NULL) {
return NOERROR;
}
NumberPicker* host = (NumberPicker*)(CNumberPicker*)num.Get();
host->mInputText->SetSelection(mSelectionStart, mSelectionEnd);
return NOERROR;
}
//==============================================================================================
// NumberPicker::ChangeCurrentByOneFromLongPressCommand
//==============================================================================================
NumberPicker::ChangeCurrentByOneFromLongPressCommand::ChangeCurrentByOneFromLongPressCommand(
/* [in] */ NumberPicker* host)
: mIncrement(FALSE)
, mHost(host)
{
}
void NumberPicker::ChangeCurrentByOneFromLongPressCommand::SetStep(
/* [in] */ Boolean increment)
{
mIncrement = increment;
}
ECode NumberPicker::ChangeCurrentByOneFromLongPressCommand::Run()
{
mHost->ChangeValueByOne(mIncrement);
Boolean res;
mHost->PostDelayed(this, mHost->mLongPressUpdateInterval, &res);
return NOERROR;
}
//==============================================================================================
// NumberPicker::BeginSoftInputOnLongPressCommand
//==============================================================================================
NumberPicker::BeginSoftInputOnLongPressCommand::BeginSoftInputOnLongPressCommand(
/* [in] */ NumberPicker* host)
: mHost(host)
{
}
ECode NumberPicker::BeginSoftInputOnLongPressCommand::Run()
{
Boolean result;
mHost->PerformLongClick(&result);
return NOERROR;
}
//==============================================================================================
// NumberPicker::AccessibilityNodeProviderImpl
//==============================================================================================
NumberPicker::AccessibilityNodeProviderImpl::AccessibilityNodeProviderImpl(
/* [in] */ NumberPicker* host)
: mAccessibilityFocusedView(UNDEFINED)
, mHost(host)
{
CRect::New((IRect**)&mTempRect);
mTempArray = ArrayOf<Int32>::Alloc(2);
}
ECode NumberPicker::AccessibilityNodeProviderImpl::CreateAccessibilityNodeInfo(
/* [in] */ Int32 virtualViewId,
/* [out] */ IAccessibilityNodeInfo** info)
{
VALIDATE_NOT_NULL(info);
switch (virtualViewId) {
case IView::NO_ID: {
AutoPtr<IAccessibilityNodeInfo> nodeInfo = CreateAccessibilityNodeInfoForNumberPicker(mHost->mScrollX, mHost->mScrollY,
mHost->mScrollX + (mHost->mRight - mHost->mLeft), mHost->mScrollY + (mHost->mBottom - mHost->mTop));
*info = nodeInfo;
REFCOUNT_ADD(*info);
return NOERROR;
}
case VIRTUAL_VIEW_ID_DECREMENT: {
AutoPtr<IAccessibilityNodeInfo> nodeInfo = CreateAccessibilityNodeInfoForVirtualButton(VIRTUAL_VIEW_ID_DECREMENT, GetVirtualDecrementButtonText(),
mHost->mScrollX, mHost->mScrollY, mHost->mScrollX + (mHost->mRight - mHost->mLeft),
mHost->mTopSelectionDividerTop + mHost->mSelectionDividerHeight);
*info = nodeInfo;
REFCOUNT_ADD(*info);
return NOERROR;
}
case VIRTUAL_VIEW_ID_INPUT: {
AutoPtr<IAccessibilityNodeInfo> nodeInfo = CreateAccessibiltyNodeInfoForInputText(mHost->mScrollX,
mHost->mTopSelectionDividerTop + mHost->mSelectionDividerHeight,
mHost->mScrollX + (mHost->mRight - mHost->mLeft),
mHost->mBottomSelectionDividerBottom - mHost->mSelectionDividerHeight);
*info = nodeInfo;
REFCOUNT_ADD(*info);
return NOERROR;
}
case VIRTUAL_VIEW_ID_INCREMENT: {
AutoPtr<IAccessibilityNodeInfo> nodeInfo = CreateAccessibilityNodeInfoForVirtualButton(VIRTUAL_VIEW_ID_INCREMENT, GetVirtualIncrementButtonText(),
mHost->mScrollX, mHost->mBottomSelectionDividerBottom - mHost->mSelectionDividerHeight,
mHost->mScrollX + (mHost->mRight - mHost->mLeft), mHost->mScrollY + (mHost->mBottom - mHost->mTop));
*info = nodeInfo;
REFCOUNT_ADD(*info);
return NOERROR;
}
}
AccessibilityNodeProvider::CreateAccessibilityNodeInfo(virtualViewId, info);
return NOERROR;
}
ECode NumberPicker::AccessibilityNodeProviderImpl::FindAccessibilityNodeInfosByText(
/* [in] */ const String& searched,
/* [in] */ Int32 virtualViewId,
/* [out] */ IList** list)
{
VALIDATE_NOT_NULL(list);
if (TextUtils::IsEmpty(searched)) {
AutoPtr<ICollections> coll;
CCollections::AcquireSingleton((ICollections**)&coll);
return coll->GetEmptyList(list);
}
String searchedLowerCase = searched.ToLowerCase();
AutoPtr<IList> result;
CArrayList::New((IList**)&result);
switch (virtualViewId) {
case IView::NO_ID:
FindAccessibilityNodeInfosByTextInChild(searchedLowerCase, VIRTUAL_VIEW_ID_DECREMENT, result);
FindAccessibilityNodeInfosByTextInChild(searchedLowerCase, VIRTUAL_VIEW_ID_INPUT, result);
FindAccessibilityNodeInfosByTextInChild(searchedLowerCase, VIRTUAL_VIEW_ID_INCREMENT, result);
*list = result;
REFCOUNT_ADD(*list);
return NOERROR;
case VIRTUAL_VIEW_ID_DECREMENT:
case VIRTUAL_VIEW_ID_INCREMENT:
case VIRTUAL_VIEW_ID_INPUT:
FindAccessibilityNodeInfosByTextInChild(searchedLowerCase, virtualViewId, result);
*list = result;
REFCOUNT_ADD(*list);
return NOERROR;
}
AccessibilityNodeProvider::FindAccessibilityNodeInfosByText(searched, virtualViewId, list);
return NOERROR;
}
ECode NumberPicker::AccessibilityNodeProviderImpl::PerformAction(
/* [in] */ Int32 virtualViewId,
/* [in] */ Int32 action,
/* [in] */ IBundle* arguments,
/* [out] */ Boolean* res)
{
VALIDATE_NOT_NULL(res);
switch(virtualViewId) {
case IView::NO_ID:
switch (action) {
case IAccessibilityNodeInfo::ACTION_ACCESSIBILITY_FOCUS: {
if (mAccessibilityFocusedView != virtualViewId) {
mAccessibilityFocusedView = virtualViewId;
Boolean result;
mHost->RequestAccessibilityFocus(&result);
*res = TRUE;
return NOERROR;
}
}
*res = FALSE;
return NOERROR;
case IAccessibilityNodeInfo::ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
if (mAccessibilityFocusedView == virtualViewId) {
mAccessibilityFocusedView = UNDEFINED;
mHost->ClearAccessibilityFocus();
*res = TRUE;
return NOERROR;
}
*res = FALSE;
return NOERROR;
}
case IAccessibilityNodeInfo::ACTION_SCROLL_FORWARD: {
Boolean result;
mHost->IsEnabled(&result);
Boolean result2;
mHost->GetWrapSelectorWheel(&result2);
Int32 value;
mHost->GetValue(&value);
Int32 minValue;
mHost->GetMinValue(&minValue);
if (result && (result2 || value < minValue)) {
mHost->ChangeValueByOne(TRUE);
*res = TRUE;
return NOERROR;
}
}
*res = FALSE;
return NOERROR;
case IAccessibilityNodeInfo::ACTION_SCROLL_BACKWARD: {
Boolean result;
mHost->IsEnabled(&result);
Boolean result2;
mHost->GetWrapSelectorWheel(&result2);
Int32 value;
mHost->GetValue(&value);
Int32 minValue;
mHost->GetMinValue(&minValue);
if (result && (result2 || value > minValue)) {
mHost->ChangeValueByOne(TRUE);
*res = TRUE;
return NOERROR;
}
}
*res = FALSE;
return NOERROR;
}
break;
case VIRTUAL_VIEW_ID_INPUT:
switch (action) {
case IAccessibilityNodeInfo::ACTION_FOCUS: {
Boolean isFocused = FALSE;
IView::Probe(mHost->mInputText)->IsFocused(&isFocused);
Boolean result;
mHost->IsEnabled(&result);
if (result && !isFocused) {
return IView::Probe(mHost->mInputText)->RequestFocus(res);
}
}
break;
case IAccessibilityNodeInfo::ACTION_CLEAR_FOCUS: {
Boolean isFocused = FALSE;
IView::Probe(mHost->mInputText)->IsFocused(&isFocused);
Boolean result;
mHost->IsEnabled(&result);
if (result && isFocused) {
IView::Probe(mHost->mInputText)->ClearFocus();
*res = TRUE;
return NOERROR;
}
*res = FALSE;
return NOERROR;
}
case IAccessibilityNodeInfo::ACTION_CLICK: {
Boolean result;
if (mHost->IsEnabled(&result), result) {
mHost->PerformClick(&result);
*res = TRUE;
return NOERROR;
}
*res = FALSE;
return NOERROR;
}
case IAccessibilityNodeInfo::ACTION_LONG_CLICK: {
Boolean result;
if (mHost->IsEnabled(&result), result) {
mHost->PerformLongClick(&result);
*res = TRUE;
return NOERROR;
}
*res = FALSE;
return NOERROR;
}
case IAccessibilityNodeInfo::ACTION_ACCESSIBILITY_FOCUS: {
if (mAccessibilityFocusedView != virtualViewId) {
mAccessibilityFocusedView = virtualViewId;
SendAccessibilityEventForVirtualView(virtualViewId, IAccessibilityEvent::TYPE_VIEW_ACCESSIBILITY_FOCUSED);
IView::Probe(mHost->mInputText)->Invalidate();
*res = TRUE;
return NOERROR;
}
}
*res = FALSE;
return NOERROR;
case IAccessibilityNodeInfo::ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
if (mAccessibilityFocusedView == virtualViewId) {
mAccessibilityFocusedView = UNDEFINED;
SendAccessibilityEventForVirtualView(virtualViewId, IAccessibilityEvent::TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
IView::Probe(mHost->mInputText)->Invalidate();
*res = TRUE;
return NOERROR;
}
}
*res = FALSE;
return NOERROR;
default:
IView::Probe(mHost->mInputText)->PerformAccessibilityAction(action, arguments, res);
return NOERROR;
}
*res = FALSE;
return NOERROR;
case VIRTUAL_VIEW_ID_INCREMENT:
switch (action) {
case IAccessibilityNodeInfo::ACTION_CLICK: {
Boolean result;
if (mHost->IsEnabled(&result), result) {
mHost->ChangeValueByOne(TRUE);
SendAccessibilityEventForVirtualView(virtualViewId, IAccessibilityEvent::TYPE_VIEW_CLICKED);
*res = TRUE;
return NOERROR;
}
}
*res = FALSE;
return NOERROR;
case IAccessibilityNodeInfo::ACTION_ACCESSIBILITY_FOCUS: {
if (mAccessibilityFocusedView != virtualViewId) {
mAccessibilityFocusedView = virtualViewId;
SendAccessibilityEventForVirtualView(virtualViewId, IAccessibilityEvent::TYPE_VIEW_ACCESSIBILITY_FOCUSED);
mHost->Invalidate(0, mHost->mBottomSelectionDividerBottom, mHost->mRight, mHost->mBottom);
*res = TRUE;
return NOERROR;
}
}
*res = FALSE;
return NOERROR;
case IAccessibilityNodeInfo::ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
if (mAccessibilityFocusedView == virtualViewId) {
mAccessibilityFocusedView = UNDEFINED;
SendAccessibilityEventForVirtualView(virtualViewId, IAccessibilityEvent::TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
mHost->Invalidate(0, mHost->mBottomSelectionDividerBottom, mHost->mRight, mHost->mBottom);
*res = TRUE;
return NOERROR;
}
}
*res = FALSE;
return NOERROR;
}
*res = FALSE;
return NOERROR;
case VIRTUAL_VIEW_ID_DECREMENT:
switch (action) {
case IAccessibilityNodeInfo::ACTION_CLICK: {
Boolean result;
if (mHost->IsEnabled(&result), result) {
Boolean increment = (virtualViewId == VIRTUAL_VIEW_ID_INCREMENT);
mHost->ChangeValueByOne(increment);
SendAccessibilityEventForVirtualView(virtualViewId, IAccessibilityEvent::TYPE_VIEW_CLICKED);
*res = TRUE;
return NOERROR;
}
}
*res = FALSE;
return NOERROR;
case IAccessibilityNodeInfo::ACTION_ACCESSIBILITY_FOCUS: {
if (mAccessibilityFocusedView != virtualViewId) {
mAccessibilityFocusedView = virtualViewId;
SendAccessibilityEventForVirtualView(virtualViewId, IAccessibilityEvent::TYPE_VIEW_ACCESSIBILITY_FOCUSED);
mHost->Invalidate(0, 0, mHost->mRight, mHost->mTopSelectionDividerTop);
*res = TRUE;
return NOERROR;
}
}
*res = FALSE;
return NOERROR;
case IAccessibilityNodeInfo::ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
if (mAccessibilityFocusedView == virtualViewId) {
mAccessibilityFocusedView = UNDEFINED;
SendAccessibilityEventForVirtualView(virtualViewId, IAccessibilityEvent::TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
mHost->Invalidate(0, 0, mHost->mRight, mHost->mTopSelectionDividerTop);
*res = TRUE;
return NOERROR;
}
}
*res = FALSE;
return NOERROR;
}
*res = FALSE;
return NOERROR;
}
AccessibilityNodeProvider::PerformAction(virtualViewId, action, arguments, res);
return NOERROR;
}
void NumberPicker::AccessibilityNodeProviderImpl::SendAccessibilityEventForVirtualView(
/* [in] */ Int32 virtualViewId,
/* [in] */ Int32 eventType)
{
switch (virtualViewId) {
case VIRTUAL_VIEW_ID_DECREMENT: {
if (HasVirtualDecrementButton()) {
SendAccessibilityEventForVirtualButton(virtualViewId, eventType, GetVirtualDecrementButtonText());
}
break;
}
case VIRTUAL_VIEW_ID_INPUT: {
SendAccessibilityEventForVirtualText(eventType);
break;
}
case VIRTUAL_VIEW_ID_INCREMENT: {
if (HasVirtualIncrementButton()) {
SendAccessibilityEventForVirtualButton(virtualViewId, eventType, GetVirtualIncrementButtonText());
}
break;
}
}
}
void NumberPicker::AccessibilityNodeProviderImpl::SendAccessibilityEventForVirtualText(
/* [in] */ Int32 eventType)
{
AutoPtr<IAccessibilityManager> am;
CAccessibilityManager::GetInstance(mHost->mContext, (IAccessibilityManager**)&am);
Boolean isEnabled = FALSE;
am->IsEnabled(&isEnabled);
if (isEnabled) {
AutoPtr<IAccessibilityEvent> event;
CAccessibilityEvent::Obtain(eventType, (IAccessibilityEvent**)&event);
IView::Probe(mHost->mInputText)->OnInitializeAccessibilityEvent(event);
IView::Probe(mHost->mInputText)->OnPopulateAccessibilityEvent(event);
IAccessibilityRecord::Probe(event)->SetSource(mHost, VIRTUAL_VIEW_ID_INPUT);
Boolean res;
mHost->RequestSendAccessibilityEvent(mHost, event, &res);
}
}
void NumberPicker::AccessibilityNodeProviderImpl::SendAccessibilityEventForVirtualButton(
/* [in] */ Int32 virtualViewId,
/* [in] */ Int32 eventType,
/* [in] */ const String& text)
{
AutoPtr<IAccessibilityManager> am;
CAccessibilityManager::GetInstance(mHost->mContext, (IAccessibilityManager**)&am);
Boolean isEnabled = FALSE;
am->IsEnabled(&isEnabled);
if (isEnabled) {
AutoPtr<IAccessibilityEvent> event;
CAccessibilityEvent::Obtain(eventType, (IAccessibilityEvent**)&event);
AutoPtr<IAccessibilityRecord> eventProbe = IAccessibilityRecord::Probe(event);
eventProbe->SetClassName(CoreUtils::Convert("Button"));
String packageName;
mHost->mContext->GetPackageName(&packageName);
event->SetPackageName(CoreUtils::Convert(packageName));
AutoPtr<IList> list;
eventProbe->GetText((IList**)&list);
list->Add(CoreUtils::Convert(text));
Boolean result;
mHost->IsEnabled(&result);
eventProbe->SetEnabled(result);
eventProbe->SetSource(mHost, virtualViewId);
Boolean res;
mHost->RequestSendAccessibilityEvent(mHost, event, &res);
}
}
void NumberPicker::AccessibilityNodeProviderImpl::FindAccessibilityNodeInfosByTextInChild(
/* [in] */ const String& searchedLowerCase,
/* [in] */ Int32 virtualViewId,
/* [in] */ IList* outResult)
{
switch (virtualViewId) {
case VIRTUAL_VIEW_ID_DECREMENT: {
String text = GetVirtualDecrementButtonText();
text = text.ToLowerCase();
if (text.IsEmpty() && text.Contains(searchedLowerCase)) {
AutoPtr<IAccessibilityNodeInfo> info;
CreateAccessibilityNodeInfo(VIRTUAL_VIEW_ID_DECREMENT, (IAccessibilityNodeInfo**)&info);
outResult->Add(info);
}
return;
}
case VIRTUAL_VIEW_ID_INPUT: {
AutoPtr<ICharSequence> text;
ITextView::Probe(mHost->mInputText)->GetText((ICharSequence**)&text);
String textStr = String(NULL);
text->ToString(&textStr);
textStr = textStr.ToLowerCase();
AutoPtr<IAccessibilityNodeInfo> info;
CreateAccessibilityNodeInfo(VIRTUAL_VIEW_ID_INPUT, (IAccessibilityNodeInfo**)&info);
if (!TextUtils::IsEmpty(text) && textStr.Contains(searchedLowerCase)) {
outResult->Add(info);
}
AutoPtr<ICharSequence> contentDesc;
ITextView::Probe(mHost->mInputText)->GetText((ICharSequence**)&contentDesc);
String contStr = String(NULL);
text->ToString(&contStr);
contStr = contStr.ToLowerCase();
if (!TextUtils::IsEmpty(text) && contStr.Contains(searchedLowerCase)) {
outResult->Add(info);
}
break;
}
case VIRTUAL_VIEW_ID_INCREMENT: {
String text = GetVirtualIncrementButtonText();
text = text.ToLowerCase();
if (!text.IsEmpty() && text.Contains(searchedLowerCase)) {
AutoPtr<IAccessibilityNodeInfo> info;
CreateAccessibilityNodeInfo(VIRTUAL_VIEW_ID_INCREMENT, (IAccessibilityNodeInfo**)&info);
outResult->Add(info);
}
return;
}
}
}
AutoPtr<IAccessibilityNodeInfo> NumberPicker::AccessibilityNodeProviderImpl::CreateAccessibiltyNodeInfoForInputText(
/* [in] */ Int32 left,
/* [in] */ Int32 top,
/* [in] */ Int32 right,
/* [in] */ Int32 bottom)
{
AutoPtr<IAccessibilityNodeInfo> info;
IView::Probe(mHost->mInputText)->CreateAccessibilityNodeInfo((IAccessibilityNodeInfo**)&info);
info->SetSource(mHost, VIRTUAL_VIEW_ID_INPUT);
if (mAccessibilityFocusedView != VIRTUAL_VIEW_ID_INPUT) {
info->AddAction(IAccessibilityNodeInfo::ACTION_ACCESSIBILITY_FOCUS);
}
if (mAccessibilityFocusedView == VIRTUAL_VIEW_ID_INPUT) {
info->AddAction(IAccessibilityNodeInfo::ACTION_CLEAR_ACCESSIBILITY_FOCUS);
}
AutoPtr<IRect> boundsInParent = mTempRect;
boundsInParent->Set(left, top, right, bottom);
info->SetVisibleToUser(mHost->IsVisibleToUser(boundsInParent));
info->SetBoundsInParent(boundsInParent);
AutoPtr<IRect> boundsInScreen = boundsInParent;
AutoPtr<ArrayOf<Int32> > locationOnScreen = mTempArray;
mHost->GetLocationOnScreen(locationOnScreen);
boundsInScreen->Offset((*locationOnScreen)[0], (*locationOnScreen)[1]);
info->SetBoundsInScreen(boundsInScreen);
return info;
}
AutoPtr<IAccessibilityNodeInfo> NumberPicker::AccessibilityNodeProviderImpl::CreateAccessibilityNodeInfoForVirtualButton(
/* [in] */ Int32 virtualViewId,
/* [in] */ const String& text,
/* [in] */ Int32 left,
/* [in] */ Int32 top,
/* [in] */ Int32 right,
/* [in] */ Int32 bottom)
{
AutoPtr<IAccessibilityNodeInfo> info;
CAccessibilityNodeInfo::Obtain((IAccessibilityNodeInfo**)&info);
info->SetClassName(CoreUtils::Convert("Button"));
String packageName;
mHost->mContext->GetPackageName(&packageName);
info->SetPackageName(CoreUtils::Convert(packageName));
info->SetSource(mHost, virtualViewId);
info->SetParent(mHost);
info->SetText(CoreUtils::Convert(text));
info->SetClickable(TRUE);
info->SetLongClickable(TRUE);
Boolean result;
mHost->IsEnabled(&result);
info->SetEnabled(result);
AutoPtr<IRect> boundsInParent = mTempRect;
boundsInParent->Set(mHost->mLeft, mHost->mTop, mHost->mRight, mHost->mBottom);
info->SetVisibleToUser(mHost->IsVisibleToUser(boundsInParent));
info->SetBoundsInParent(boundsInParent);
AutoPtr<IRect> boundsInScreen = boundsInParent;
AutoPtr<ArrayOf<Int32> > locationOnScreen = mTempArray;
mHost->GetLocationOnScreen(locationOnScreen);
boundsInScreen->Offset((*locationOnScreen)[0], (*locationOnScreen)[1]);
info->SetBoundsInScreen(boundsInScreen);
if (mAccessibilityFocusedView != virtualViewId) {
info->AddAction(IAccessibilityNodeInfo::ACTION_ACCESSIBILITY_FOCUS);
}
if (mAccessibilityFocusedView == virtualViewId) {
info->AddAction(IAccessibilityNodeInfo::ACTION_CLEAR_ACCESSIBILITY_FOCUS);
}
if (mHost->IsEnabled(&result), result) {
info->AddAction(IAccessibilityNodeInfo::ACTION_CLICK);
}
return info;
}
AutoPtr<IAccessibilityNodeInfo> NumberPicker::AccessibilityNodeProviderImpl::CreateAccessibilityNodeInfoForNumberPicker(
/* [in] */ Int32 left,
/* [in] */ Int32 top,
/* [in] */ Int32 right,
/* [in] */ Int32 bottom)
{
AutoPtr<IAccessibilityNodeInfo> info;
CAccessibilityNodeInfo::Obtain((IAccessibilityNodeInfo**)&info);
info->SetClassName(CoreUtils::Convert(NUMBERPICKER_NAME));
String packageName;
mHost->mContext->GetPackageName(&packageName);
info->SetPackageName(CoreUtils::Convert(packageName));
info->SetSource(mHost);
if (HasVirtualDecrementButton()) {
info->AddChild(mHost, VIRTUAL_VIEW_ID_DECREMENT);
}
info->AddChild(mHost, VIRTUAL_VIEW_ID_INPUT);
if (HasVirtualIncrementButton()) {
info->AddChild(mHost, VIRTUAL_VIEW_ID_INCREMENT);
}
AutoPtr<IViewParent> parent;
mHost->GetParentForAccessibility((IViewParent**)&parent);
info->SetParent(IView::Probe(parent));
Boolean result;
mHost->IsEnabled(&result);
info->SetEnabled(result);
info->SetScrollable(TRUE);
AutoPtr<IContext> context;
mHost->GetContext((IContext**)&context);
AutoPtr<IResources> resources;
context->GetResources((IResources**)&resources);
AutoPtr<ICompatibilityInfo> cominfo;
resources->GetCompatibilityInfo((ICompatibilityInfo**)&cominfo);
AutoPtr<CCompatibilityInfo> cInof = (CCompatibilityInfo*)cominfo.Get();
Float applicationScale = cInof->mApplicationScale;
AutoPtr<IRect> boundsInParent = mTempRect;
boundsInParent->Set(mHost->mLeft, mHost->mTop, mHost->mRight, mHost->mBottom);
boundsInParent->Scale(applicationScale);
info->SetBoundsInParent(boundsInParent);
info->SetVisibleToUser(mHost->IsVisibleToUser());
AutoPtr<IRect> boundsInScreen = boundsInParent;
AutoPtr<ArrayOf<Int32> > locationOnScreen = mTempArray;
mHost->GetLocationOnScreen(locationOnScreen);
boundsInScreen->Offset((*locationOnScreen)[0], (*locationOnScreen)[1]);
boundsInScreen->Scale(applicationScale);
info->SetBoundsInScreen(boundsInScreen);
if (mAccessibilityFocusedView != IView::NO_ID) {
info->AddAction(IAccessibilityNodeInfo::ACTION_ACCESSIBILITY_FOCUS);
}
if (mAccessibilityFocusedView == IView::NO_ID) {
info->AddAction(IAccessibilityNodeInfo::ACTION_CLEAR_ACCESSIBILITY_FOCUS);
}
if (mHost->IsEnabled(&result), result) {
Boolean res;
mHost->GetWrapSelectorWheel(&res);
Int32 value;
mHost->GetValue(&value);
Int32 minValue;
mHost->GetMinValue(&minValue);
if (res || value < minValue) {
info->AddAction(IAccessibilityNodeInfo::ACTION_SCROLL_FORWARD);
}
if (res || value > minValue) {
info->AddAction(IAccessibilityNodeInfo::ACTION_SCROLL_BACKWARD);
}
}
return info;
}
Boolean NumberPicker::AccessibilityNodeProviderImpl::HasVirtualDecrementButton()
{
Boolean res;
mHost->GetWrapSelectorWheel(&res);
Int32 value;
mHost->GetValue(&value);
Int32 minValue;
mHost->GetMinValue(&minValue);
return res || value > minValue;
}
Boolean NumberPicker::AccessibilityNodeProviderImpl::HasVirtualIncrementButton()
{
Boolean res;
mHost->GetWrapSelectorWheel(&res);
Int32 value;
mHost->GetValue(&value);
Int32 maxValue;
mHost->GetMaxValue(&maxValue);
return res || value < maxValue;
}
String NumberPicker::AccessibilityNodeProviderImpl::GetVirtualDecrementButtonText()
{
Int32 value = mHost->mValue - 1;
if (mHost->mWrapSelectorWheel) {
value = mHost->GetWrappedSelectorIndex(value);
}
if (value >= mHost->mMinValue) {
return (mHost->mDisplayedValues == NULL) ? mHost->FormatNumber(value)
: (*mHost->mDisplayedValues)[value - mHost->mMinValue];
}
return String(NULL);
}
String NumberPicker::AccessibilityNodeProviderImpl::GetVirtualIncrementButtonText()
{
Int32 value = mHost->mValue + 1;
if (mHost->mWrapSelectorWheel) {
value = mHost->GetWrappedSelectorIndex(value);
}
if (value <= mHost->mMaxValue) {
return (mHost->mDisplayedValues == NULL) ? mHost->FormatNumber(value)
: (*mHost->mDisplayedValues)[value - mHost->mMinValue];
}
return String(NULL);
}
//==============================================================================================
// NumberPicker::TwoDigitFormatter
//==============================================================================================
CAR_INTERFACE_IMPL(NumberPicker::TwoDigitFormatter, Object, INumberPickerFormatter);
NumberPicker::TwoDigitFormatter::TwoDigitFormatter()
{
mBuilder = new StringBuilder();
mArgs = ArrayOf<IInterface*>::Alloc(1);
AutoPtr<ILocaleHelper> helper;
CLocaleHelper::AcquireSingleton((ILocaleHelper**)&helper);
AutoPtr<ILocale> locale;
helper->GetDefault((ILocale**)&locale);
Init(locale);
}
ECode NumberPicker::TwoDigitFormatter::Init(
/* [in] */ ILocale* locale)
{
mFmt = CreateFormatter(locale);
mZeroDigit = GetZeroDigit(locale);
return NOERROR;
}
ECode NumberPicker::TwoDigitFormatter::Format(
/* [in] */ Int32 value,
/* [out] */ String* str)
{
VALIDATE_NOT_NULL(str);
AutoPtr<ILocaleHelper> helper;
CLocaleHelper::AcquireSingleton((ILocaleHelper**)&helper);
AutoPtr<ILocale> currentLocale;
helper->GetDefault((ILocale**)¤tLocale);
if (mZeroDigit != GetZeroDigit(currentLocale)) {
Init(currentLocale);
}
AutoPtr<IInteger32> integer;
CInteger32::New(value, (IInteger32**)&integer);
mArgs->Set(0, integer);
Int32 length = 0;
mBuilder->GetLength(&length);
mBuilder->Delete(0, length);
mFmt->Format(String("%02d"), mArgs);
mFmt->ToString(str);
return NOERROR;
}
Char32 NumberPicker::TwoDigitFormatter::GetZeroDigit(
/* [in] */ ILocale* locale)
{
AutoPtr<ILocaleDataHelper> helper;
CLocaleDataHelper::AcquireSingleton((ILocaleDataHelper**)&helper);
AutoPtr<ILocaleData> data;
helper->Get(locale, (ILocaleData**)&data);
Char32 zerodigit = 0;
data->GetZeroDigit(&zerodigit);
return zerodigit;
}
AutoPtr<IFormatter> NumberPicker::TwoDigitFormatter::CreateFormatter(
/* [in] */ ILocale* locale)
{
AutoPtr<IFormatter> formatter;
CFormatter::New((IAppendable*)mBuilder.Get(), locale, (IFormatter**)&formatter);
return formatter;
}
//==============================================================================================
// NumberPicker::NumberPickerOnClickListener
//==============================================================================================
CAR_INTERFACE_IMPL(NumberPicker::NumberPickerOnClickListener, Object, IViewOnClickListener);
NumberPicker::NumberPickerOnClickListener::NumberPickerOnClickListener(
/* [in] */ NumberPicker* host)
: mHost(host)
{
}
ECode NumberPicker::NumberPickerOnClickListener::OnClick(
/* [in] */ IView* v)
{
mHost->HideSoftInput();
IView::Probe(mHost->mInputText)->ClearFocus();
Int32 id = 0;
v->GetId(&id);
if (id == R::id::increment) {
mHost->ChangeValueByOne(TRUE);
}
else {
mHost->ChangeValueByOne(FALSE);
}
return NOERROR;
}
//==============================================================================================
// NumberPicker::NumberPickerOnLongCliskListener
//==============================================================================================
CAR_INTERFACE_IMPL(NumberPicker::NumberPickerOnLongCliskListener, Object, IViewOnLongClickListener);
NumberPicker::NumberPickerOnLongCliskListener::NumberPickerOnLongCliskListener(
/* [in] */ NumberPicker* host)
: mHost(host)
{
}
ECode NumberPicker::NumberPickerOnLongCliskListener::OnLongClick(
/* [in] */ IView* v,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result);
mHost->HideSoftInput();
IView::Probe(mHost->mInputText)->ClearFocus();
Int32 id = 0;
v->GetId(&id);
if (id == R::id::increment) {
mHost->PostChangeCurrentByOneFromLongPress(TRUE, 0);
}
else {
mHost->PostChangeCurrentByOneFromLongPress(FALSE, 0);
}
*result = FALSE;
return NOERROR;
}
//==============================================================================================
// NumberPicker::NumberPickerOnFocusChangeListener
//==============================================================================================
CAR_INTERFACE_IMPL(NumberPicker::NumberPickerOnFocusChangeListener, Object, IViewOnFocusChangeListener);
NumberPicker::NumberPickerOnFocusChangeListener::NumberPickerOnFocusChangeListener(
/* [in] */ NumberPicker* host)
: mHost(host)
{
}
ECode NumberPicker::NumberPickerOnFocusChangeListener::OnFocusChange(
/* [in] */ IView* v,
/* [in] */ Boolean hasFocus)
{
if (hasFocus) {
mHost->mInputText->SelectAll();
}
else {
mHost->mInputText->SetSelection(0, 0);
mHost->ValidateInputTextView(v);
}
return NOERROR;
}
//==============================================================================================
// NumberPicker::InputTextFilter
//==============================================================================================
CAR_INTERFACE_IMPL(NumberPicker, LinearLayout, INumberPicker);
NumberPicker::NumberPicker()
: mSelectionDividersDistance(0)
, mMinHeight(0)
, mMaxHeight(0)
, mMinWidth(0)
, mMaxWidth(0)
, mComputeMaxWidth(FALSE)
, mTextSize(0)
, mSelectorTextGapHeight(0)
, mMinValue(0)
, mMaxValue(0)
, mValue(0)
, mLongPressUpdateInterval(DEFAULT_LONG_PRESS_UPDATE_INTERVAL)
, mSelectorElementHeight(0)
, mInitialScrollOffset(Elastos::Core::Math::INT32_MIN_VALUE)
, mCurrentScrollOffset(0)
, mPreviousScrollerY(0)
, mLastDownEventY(0.f)
, mLastDownEventTime(0LL)
, mLastDownOrMoveEventY(0.f)
, mTouchSlop(0)
, mMinimumFlingVelocity(0)
, mMaximumFlingVelocity(0)
, mWrapSelectorWheel(FALSE)
, mSolidColor(0)
, mHasSelectorWheel(FALSE)
, mSelectionDividerHeight(0)
, mScrollState(INumberPickerOnScrollListener::SCROLL_STATE_IDLE)
, mIgnoreMoveEvents(FALSE)
, mPerformClickOnTap(FALSE)
, mTopSelectionDividerTop(0)
, mBottomSelectionDividerBottom(0)
, mLastHoveredChildVirtualViewId(0)
, mIncrementVirtualButtonPressed(FALSE)
, mDecrementVirtualButtonPressed(FALSE)
, mLastHandledDownDpadKeyCode(-1)
, mHideWheelUntilFocused(FALSE)
{
CSparseArray::New((ISparseArray**)&mSelectorIndexToStringCache);
mSelectorIndices = ArrayOf<Int32>::Alloc(SELECTOR_WHEEL_ITEM_COUNT);
}
NumberPicker::~NumberPicker()
{}
ECode NumberPicker::constructor(
/* [in] */ IContext* context)
{
return constructor(context, NULL);
}
ECode NumberPicker::constructor(
/* [in] */ IContext* context,
/* [in] */ IAttributeSet* attrs)
{
return constructor(context, attrs, R::attr::numberPickerStyle);
}
ECode NumberPicker::constructor(
/* [in] */ IContext* context,
/* [in] */ IAttributeSet* attrs,
/* [in] */ Int32 defStyleAttr)
{
return constructor(context, attrs, defStyleAttr, 0);
}
ECode NumberPicker::constructor(
/* [in] */ IContext* context,
/* [in] */ IAttributeSet* attrs,
/* [in] */ Int32 defStyleAttr,
/* [in] */ Int32 defStyleRes)
{
LinearLayout::constructor(context, attrs, defStyleAttr, defStyleRes);
AutoPtr<ArrayOf<Int32> > attrIds = TO_ATTRS_ARRAYOF(R::styleable::NumberPicker);
AutoPtr<ITypedArray> attributesArray;
FAIL_RETURN(context->ObtainStyledAttributes(attrs, attrIds, defStyleAttr, defStyleRes, (ITypedArray**)&attributesArray));
Int32 layoutResID = 0;
attributesArray->GetResourceId(R::styleable::NumberPicker_internalLayout, DEFAULT_LAYOUT_RESOURCE_ID, &layoutResID);
mHasSelectorWheel = (layoutResID != DEFAULT_LAYOUT_RESOURCE_ID);
attributesArray->GetBoolean(
R::styleable::NumberPicker_hideWheelUntilFocused, FALSE, &mHideWheelUntilFocused);
attributesArray->GetColor(R::styleable::NumberPicker_solidColor, 0, &mSolidColor);
attributesArray->GetDrawable(R::styleable::NumberPicker_selectionDivider, (IDrawable**)&mSelectionDivider);
AutoPtr<IResources> resources;
GetResources((IResources**)&resources);
AutoPtr<IDisplayMetrics> display;
resources->GetDisplayMetrics((IDisplayMetrics**)&display);
Int32 defSelectionDividerHeight = (Int32)CTypedValue::ApplyDimension(ITypedValue::COMPLEX_UNIT_DIP, UNSCALED_DEFAULT_SELECTION_DIVIDER_HEIGHT, display);
attributesArray->GetDimensionPixelSize(R::styleable::NumberPicker_selectionDividerHeight, defSelectionDividerHeight, &mSelectionDividerHeight);
Int32 defSelectionDividerDistance = (Int32)CTypedValue::ApplyDimension(ITypedValue::COMPLEX_UNIT_DIP, UNSCALED_DEFAULT_SELECTION_DIVIDERS_DISTANCE, display);
attributesArray->GetDimensionPixelSize(R::styleable::NumberPicker_selectionDividersDistance, defSelectionDividerDistance, &mSelectionDividersDistance);
attributesArray->GetDimensionPixelSize(R::styleable::NumberPicker_internalMinHeight, SIZE_UNSPECIFIED, &mMinHeight);
attributesArray->GetDimensionPixelSize(R::styleable::NumberPicker_internalMaxHeight, SIZE_UNSPECIFIED, &mMaxHeight);
if (mMinHeight != SIZE_UNSPECIFIED && mMaxHeight != SIZE_UNSPECIFIED && mMinHeight > mMaxHeight) {
return E_ILLEGAL_ARGUMENT_EXCEPTION;
}
attributesArray->GetDimensionPixelSize(R::styleable::NumberPicker_internalMinWidth, SIZE_UNSPECIFIED, &mMinWidth);
attributesArray->GetDimensionPixelSize(R::styleable::NumberPicker_internalMaxWidth, SIZE_UNSPECIFIED, &mMaxWidth);
if (mMinWidth != SIZE_UNSPECIFIED && mMaxWidth != SIZE_UNSPECIFIED && mMinWidth > mMaxWidth) {
return E_ILLEGAL_ARGUMENT_EXCEPTION;
}
mComputeMaxWidth = (mMaxWidth == SIZE_UNSPECIFIED);
attributesArray->GetDrawable(R::styleable::NumberPicker_virtualButtonPressedDrawable, (IDrawable**)&mVirtualButtonPressedDrawable);
attributesArray->Recycle();
mPressedStateHelper = new PressedStateHelper(this);
SetWillNotDraw(!mHasSelectorWheel);
AutoPtr<IContext> con;
GetContext((IContext**)&con);
AutoPtr<IInterface> i;
con->GetSystemService(IContext::LAYOUT_INFLATER_SERVICE, (IInterface**)&i);
AutoPtr<ILayoutInflater> inflater = ILayoutInflater::Probe(i);
AutoPtr<IView> v;
inflater->Inflate(layoutResID, this, TRUE, (IView**)&v);
AutoPtr<IViewOnClickListener> onClickListener = new NumberPickerOnClickListener(this);
AutoPtr<IViewOnLongClickListener> onLongClickListener = new NumberPickerOnLongCliskListener(this);
if (!mHasSelectorWheel) {
AutoPtr<IView> view;
FindViewById(R::id::increment, (IView**)&view);
mInCrementButton = IImageButton::Probe(view);
view->SetOnClickListener(onClickListener);
view->SetOnLongClickListener(onLongClickListener);
}
else {
mInCrementButton = NULL;
}
if (!mHasSelectorWheel) {
AutoPtr<IView> view;
FindViewById(R::id::decrement, (IView**)&view);
mDecrementButton = IImageButton::Probe(view);
view->SetOnClickListener(onClickListener);
view->SetOnLongClickListener(onLongClickListener);
}
else {
mDecrementButton = NULL;
}
AutoPtr<IView> view;
FindViewById(R::id::numberpicker_input, (IView**)&view);
mInputText = IEditText::Probe(view);
AutoPtr<IViewOnFocusChangeListener> listener = new NumberPickerOnFocusChangeListener(this);
IView::Probe(mInputText)->SetOnFocusChangeListener(listener);
using Elastos::Droid::Text::IInputFilter;
AutoPtr<ArrayOf<IInputFilter*> > array = ArrayOf<IInputFilter*>::Alloc(1);
AutoPtr<InputTextFilter> inputFilter = new InputTextFilter(this);
array->Set(0, (IInputFilter*)inputFilter.Get());
AutoPtr<ITextView> mInputTextProbe = ITextView::Probe(mInputText);
mInputTextProbe->SetFilters(array);
mInputTextProbe->SetRawInputType(IInputType::TYPE_CLASS_NUMBER);
mInputTextProbe->SetImeOptions(IEditorInfo::IME_ACTION_DONE);
AutoPtr<IViewConfiguration> configuration = CViewConfiguration::Get(context);
configuration->GetScaledTouchSlop(&mTouchSlop);
configuration->GetScaledMinimumFlingVelocity(&mMinimumFlingVelocity);
configuration->GetScaledMaximumFlingVelocity(&mMaximumFlingVelocity);
mMaximumFlingVelocity = mMaximumFlingVelocity / SELECTOR_MAX_FLING_VELOCITY_ADJUSTMENT;
Float size = 0;
mInputTextProbe->GetTextSize(&size);
mTextSize = (Int32)size;
AutoPtr<IPaint> paint;
FAIL_RETURN(CPaint::New((IPaint**)&paint));
paint->SetAntiAlias(TRUE);
paint->SetTextAlign(Elastos::Droid::Graphics::PaintAlign_CENTER);
paint->SetTextSize(mTextSize);
AutoPtr<ITypeface> face;
mInputTextProbe->GetTypeface((ITypeface**)&face);
paint->SetTypeface(face);
AutoPtr<IColorStateList> colors;
mInputTextProbe->GetTextColors((IColorStateList**)&colors);
Int32 color = 0;
colors->GetColorForState(ENABLED_STATE_SET, IColor::WHITE, &color);
paint->SetColor(color);
mSelectorWheelPaint = paint;
CScroller::New(context, NULL, TRUE, (IScroller**)&mFlingScroller);
CScroller::New(context, (IScroller**)&mAdjustScroller);
UpdateInputTextView();
Int32 accessibility;
GetImportantForAccessibility(&accessibility);
if (accessibility == IView::IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
SetImportantForAccessibility(IView::IMPORTANT_FOR_ACCESSIBILITY_YES);
}
return NOERROR;
}
ECode NumberPicker::OnInterceptTouchEvent(
/* [in] */ IMotionEvent* event,
/* [out] */ Boolean* res)
{
VALIDATE_NOT_NULL(res);
*res = FALSE;
Boolean result;
if (!mHasSelectorWheel || (IsEnabled(&result), !result)) {
return NOERROR;
}
Int32 action = 0;
event->GetActionMasked(&action);
switch (action) {
case IMotionEvent::ACTION_DOWN: {
RemoveAllCallbacks();
IView::Probe(mInputText)->SetVisibility(IView::INVISIBLE);
event->GetY(&mLastDownEventY);
event->GetY(&mLastDownOrMoveEventY);
IInputEvent::Probe(event)->GetEventTime(&mLastDownEventTime);
mIgnoreMoveEvents = FALSE;
mPerformClickOnTap = FALSE;
if (mLastDownEventY < mTopSelectionDividerTop) {
if (mScrollState == INumberPickerOnScrollListener::SCROLL_STATE_IDLE) {
mPressedStateHelper->ButtonPressDelayed(PressedStateHelper::BUTTON_DECREMENT);
}
}
else if (mLastDownEventY > mBottomSelectionDividerBottom) {
if (mScrollState == INumberPickerOnScrollListener::SCROLL_STATE_IDLE) {
mPressedStateHelper->ButtonPressDelayed(PressedStateHelper::BUTTON_INCREMENT);
}
}
AutoPtr<IViewParent> parent;
GetParent((IViewParent**)&parent);
parent->RequestDisallowInterceptTouchEvent(TRUE);
Boolean isFlingFinished = FALSE;
mFlingScroller->IsFinished(&isFlingFinished);
Boolean isAdjustFinished = FALSE;
mAdjustScroller->IsFinished(&isAdjustFinished);
if (!isFlingFinished) {
mFlingScroller->ForceFinished(TRUE);
mAdjustScroller->ForceFinished(TRUE);
OnScrollStateChange(INumberPickerOnScrollListener::SCROLL_STATE_IDLE);
}
else if (!isAdjustFinished) {
mFlingScroller->ForceFinished(TRUE);
mAdjustScroller->ForceFinished(TRUE);
}
else if (mLastDownEventY < mTopSelectionDividerTop) {
HideSoftInput();
PostChangeCurrentByOneFromLongPress(FALSE, CViewConfiguration::GetLongPressTimeout());
}
else if (mLastDownEventY > mBottomSelectionDividerBottom) {
HideSoftInput();
PostChangeCurrentByOneFromLongPress(TRUE, CViewConfiguration::GetLongPressTimeout());
}
else {
mPerformClickOnTap = TRUE;
PostBeginSoftInputOnLongPressCommand();
}
*res = TRUE;
return NOERROR;
}
}
return NOERROR;
}
ECode NumberPicker::OnTouchEvent(
/* [in] */ IMotionEvent* event,
/* [out] */ Boolean* res)
{
VALIDATE_NOT_NULL(res);
*res = FALSE;
Boolean result;
if ((IsEnabled(&result), result) || !mHasSelectorWheel) {
return NOERROR;
}
if (mVelocityTracker == NULL) {
mVelocityTracker = VelocityTracker::Obtain();
}
mVelocityTracker->AddMovement(event);
Int32 action = 0;
event->GetActionMasked(&action);
switch (action) {
case IMotionEvent::ACTION_MOVE: {
if (mIgnoreMoveEvents) {
break;
}
Float currentMoveY = 0;
event->GetY(¤tMoveY);
if (mScrollState != INumberPickerOnScrollListener::SCROLL_STATE_TOUCH_SCROLL) {
Int32 deltaDownY = (Int32)Elastos::Core::Math::Abs(currentMoveY - mLastDownEventY);
if (deltaDownY > mTouchSlop) {
RemoveAllCallbacks();
OnScrollStateChange(INumberPickerOnScrollListener::SCROLL_STATE_TOUCH_SCROLL);
}
}
else {
Int32 deltaMoveY = (Int32)(currentMoveY - mLastDownOrMoveEventY);
ScrollBy(0, deltaMoveY);
Invalidate();
}
mLastDownOrMoveEventY = currentMoveY;
}
break;
case IMotionEvent::ACTION_UP: {
RemoveBeginSoftInputCommand();
RemoveChangeCurrentByOneFromLongPress();
mPressedStateHelper->Cancel();
AutoPtr<VelocityTracker> velocityTracker = mVelocityTracker;
velocityTracker->ComputeCurrentVelocity(1000, (Float)mMaximumFlingVelocity);
Float y;
velocityTracker->GetYVelocity(&y);
Int32 initialVelocity = (Int32)y;
if (Elastos::Core::Math::Abs(initialVelocity) > mMinimumFlingVelocity) {
Fling(initialVelocity);
OnScrollStateChange(INumberPickerOnScrollListener::SCROLL_STATE_FLING);
}
else {
Float fy = 0;
event->GetY(&fy);
Int32 eventY = (Int32)fy;
Int32 deltaMoveY = (Int32)(Elastos::Core::Math::Abs(eventY - mLastDownEventY));
Int64 deltaTime = 0;
IInputEvent::Probe(event)->GetEventTime(&deltaTime);
deltaTime -= mLastDownEventTime;
if (deltaMoveY <= mTouchSlop && deltaTime < CViewConfiguration::GetTapTimeout()) {
if (mPerformClickOnTap) {
mPerformClickOnTap = FALSE;
PerformClick(&result);
}
else {
Int32 selectorIndexOffset = (eventY / mSelectorElementHeight) - SELECTOR_MIDDLE_ITEM_INDEX;
if (selectorIndexOffset > 0) {
ChangeValueByOne(TRUE);
mPressedStateHelper->ButtonTapped(PressedStateHelper::BUTTON_INCREMENT);
}
else if (selectorIndexOffset < 0) {
ChangeValueByOne(FALSE);
mPressedStateHelper->ButtonTapped(PressedStateHelper::BUTTON_DECREMENT);
}
}
}
else {
EnsureScrollWheelAdjusted();
}
OnScrollStateChange(INumberPickerOnScrollListener::SCROLL_STATE_IDLE);
}
mVelocityTracker->Recycle();
mVelocityTracker = NULL;
}
break;
}
*res = TRUE;
return NOERROR;
}
ECode NumberPicker::DispatchTouchEvent(
/* [in] */ IMotionEvent* event,
/* [out] */ Boolean* res)
{
VALIDATE_NOT_NULL(res);
Int32 action = 0;
event->GetActionMasked(&action);
switch (action) {
case IMotionEvent::ACTION_CANCEL:
case IMotionEvent::ACTION_UP:
RemoveAllCallbacks();
break;
}
return LinearLayout::DispatchTouchEvent(event, res);
}
ECode NumberPicker::DispatchKeyEvent(
/* [in] */ IKeyEvent* event,
/* [out] */ Boolean* res)
{
VALIDATE_NOT_NULL(res);
Int32 keyCode = 0;
event->GetKeyCode(&keyCode);
switch (keyCode) {
case IKeyEvent::KEYCODE_DPAD_CENTER:
case IKeyEvent::KEYCODE_ENTER:
RemoveAllCallbacks();
break;
case IKeyEvent::KEYCODE_DPAD_DOWN:
case IKeyEvent::KEYCODE_DPAD_UP: {
if (!mHasSelectorWheel) {
break;
}
Int32 action;
event->GetAction(&action);
switch (action) {
case IKeyEvent::ACTION_DOWN: {
Int32 value, maxValue, minValue;
GetValue(&value);
GetMaxValue(&maxValue);
GetMinValue(&minValue);
if (mWrapSelectorWheel || ((keyCode == IKeyEvent::KEYCODE_DPAD_DOWN)
? value < maxValue : value > minValue)) {
Boolean result;
RequestFocus(&result);
mLastHandledDownDpadKeyCode = keyCode;
RemoveAllCallbacks();
Boolean isFinished;
mFlingScroller->IsFinished(&isFinished);
if (isFinished) {
ChangeValueByOne(keyCode == IKeyEvent::KEYCODE_DPAD_DOWN);
}
*res = TRUE;
return NOERROR;
}
break;
}
case IKeyEvent::ACTION_UP:
if (mLastHandledDownDpadKeyCode == keyCode) {
mLastHandledDownDpadKeyCode = -1;
*res = TRUE;
return NOERROR;
}
break;
}
}
}
return LinearLayout::DispatchKeyEvent(event, res);
}
ECode NumberPicker::DispatchTrackballEvent(
/* [in] */ IMotionEvent* event,
/* [out] */ Boolean* res)
{
VALIDATE_NOT_NULL(res);
Int32 action = 0;
event->GetActionMasked(&action);
switch (action) {
case IMotionEvent::ACTION_CANCEL:
case IMotionEvent::ACTION_UP:
RemoveAllCallbacks();
break;
}
return LinearLayout::DispatchTrackballEvent(event, res);
}
Boolean NumberPicker::DispatchHoverEvent(
/* [in] */ IMotionEvent* event)
{
if (!mHasSelectorWheel) {
return LinearLayout::DispatchHoverEvent(event);
}
AutoPtr<IAccessibilityManager> am;
CAccessibilityManager::GetInstance(mContext, (IAccessibilityManager**)&am);
Boolean isEnabled = FALSE;
am->IsEnabled(&isEnabled);
if (isEnabled) {
Float fy = 0;
event->GetY(&fy);
Int32 eventY = (Int32)fy;
Int32 hoveredVirtualViewId = 0;
if (eventY < mTopSelectionDividerTop) {
hoveredVirtualViewId = AccessibilityNodeProviderImpl::VIRTUAL_VIEW_ID_DECREMENT;
}
else if (eventY > mBottomSelectionDividerBottom) {
hoveredVirtualViewId = AccessibilityNodeProviderImpl::VIRTUAL_VIEW_ID_INCREMENT;
}
else {
hoveredVirtualViewId = AccessibilityNodeProviderImpl::VIRTUAL_VIEW_ID_INPUT;
}
Int32 action = 0;
event->GetActionMasked(&action);
AutoPtr<IAccessibilityNodeProvider> provider;
GetAccessibilityNodeProvider((IAccessibilityNodeProvider**)&provider);
AutoPtr<AccessibilityNodeProviderImpl> providerImpl = (AccessibilityNodeProviderImpl*)provider.Get();
Boolean res = FALSE;
switch (action) {
case IMotionEvent::ACTION_HOVER_ENTER:
providerImpl->SendAccessibilityEventForVirtualView(hoveredVirtualViewId, IAccessibilityEvent::TYPE_VIEW_HOVER_ENTER);
mLastHoveredChildVirtualViewId = hoveredVirtualViewId;
providerImpl->PerformAction(hoveredVirtualViewId, IAccessibilityNodeInfo::ACTION_ACCESSIBILITY_FOCUS, NULL, &res);
break;
case IMotionEvent::ACTION_HOVER_MOVE:
if (mLastHoveredChildVirtualViewId != hoveredVirtualViewId &&
mLastHoveredChildVirtualViewId != IView::NO_ID) {
providerImpl->SendAccessibilityEventForVirtualView(mLastHoveredChildVirtualViewId, IAccessibilityEvent::TYPE_VIEW_HOVER_EXIT);
providerImpl->SendAccessibilityEventForVirtualView(hoveredVirtualViewId, IAccessibilityEvent::TYPE_VIEW_HOVER_ENTER);
mLastHoveredChildVirtualViewId = hoveredVirtualViewId;
providerImpl->PerformAction(hoveredVirtualViewId, IAccessibilityNodeInfo::ACTION_ACCESSIBILITY_FOCUS, NULL, &res);
}
break;
case IMotionEvent::ACTION_HOVER_EXIT:
providerImpl->SendAccessibilityEventForVirtualView(hoveredVirtualViewId, IAccessibilityEvent::TYPE_VIEW_HOVER_EXIT);
mLastHoveredChildVirtualViewId = IView::NO_ID;
break;
}
}
return FALSE;
}
ECode NumberPicker::ComputeScroll()
{
AutoPtr<IScroller> scroller = mFlingScroller;
Boolean flingFinished = FALSE;
scroller->IsFinished(&flingFinished);
if (flingFinished) {
scroller = mAdjustScroller;
Boolean adjustFinished = FALSE;
scroller->IsFinished(&adjustFinished);
if (adjustFinished) {
return NOERROR;
}
}
Boolean res = FALSE;
scroller->ComputeScrollOffset(&res);
Int32 currentScrollerY = 0;
scroller->GetCurrY(¤tScrollerY);
if (mPreviousScrollerY == 0) {
scroller->GetStartY(&mPreviousScrollerY);
}
ScrollBy(0, currentScrollerY - mPreviousScrollerY);
mPreviousScrollerY = currentScrollerY;
Boolean isFinished = FALSE;
scroller->IsFinished(&isFinished);
if (isFinished) {
OnScrollerFinished(scroller);
}
else {
Invalidate();
}
return NOERROR;
}
ECode NumberPicker::SetEnabled(
/* [in] */ Boolean enabled)
{
LinearLayout::SetEnabled(enabled);
if (!mHasSelectorWheel) {
IView::Probe(mInCrementButton)->SetEnabled(enabled);
}
if (!mHasSelectorWheel) {
IView::Probe(mDecrementButton)->SetEnabled(enabled);
}
IView::Probe(mInputText)->SetEnabled(enabled);
return NOERROR;
}
ECode NumberPicker::ScrollBy(
/* [in] */ Int32 x,
/* [in] */ Int32 y)
{
AutoPtr<ArrayOf<Int32> > selectorIndices = mSelectorIndices;
if (!mWrapSelectorWheel && y > 0
&& (*selectorIndices)[SELECTOR_MIDDLE_ITEM_INDEX] <= mMinValue) {
mCurrentScrollOffset = mInitialScrollOffset;
return NOERROR;
}
if (!mWrapSelectorWheel && y < 0
&& (*selectorIndices)[SELECTOR_MIDDLE_ITEM_INDEX] >= mMaxValue) {
mCurrentScrollOffset = mInitialScrollOffset;
return NOERROR;
}
mCurrentScrollOffset += y;
while (mCurrentScrollOffset - mInitialScrollOffset > mSelectorTextGapHeight) {
mCurrentScrollOffset -= mSelectorElementHeight;
DecrementSelectorIndices(selectorIndices);
SetValueInternal((*selectorIndices)[SELECTOR_MIDDLE_ITEM_INDEX], TRUE);
if (!mWrapSelectorWheel && (*selectorIndices)[SELECTOR_MIDDLE_ITEM_INDEX] <= mMinValue) {
mCurrentScrollOffset = mInitialScrollOffset;
}
}
while (mCurrentScrollOffset - mInitialScrollOffset < -mSelectorTextGapHeight) {
mCurrentScrollOffset += mSelectorElementHeight;
IncrementSelectorIndices(selectorIndices);
SetValueInternal((*selectorIndices)[SELECTOR_MIDDLE_ITEM_INDEX], TRUE);
if (!mWrapSelectorWheel && (*selectorIndices)[SELECTOR_MIDDLE_ITEM_INDEX] >= mMaxValue) {
mCurrentScrollOffset = mInitialScrollOffset;
}
}
return NOERROR;
}
Int32 NumberPicker::ComputeVerticalScrollOffset()
{
return mCurrentScrollOffset;
}
Int32 NumberPicker::ComputeVerticalScrollRange()
{
return (mMaxValue - mMinValue + 1) * mSelectorElementHeight;
}
Int32 NumberPicker::ComputeVerticalScrollExtent()
{
Int32 height;
GetHeight(&height);
return height;
}
ECode NumberPicker::GetSolidColor(
/* [out] */ Int32* color)
{
VALIDATE_NOT_NULL(color);
*color = mSolidColor;
return NOERROR;
}
ECode NumberPicker::SetOnValueChangedListener(
/* [in] */ INumberPickerOnValueChangeListener* onValueChangedListener)
{
mOnValueChangeListener = onValueChangedListener;
return NOERROR;
}
ECode NumberPicker::SetOnScrollListener(
/* [in] */ INumberPickerOnScrollListener* onScrollListener)
{
mOnScrollListener = onScrollListener;
return NOERROR;
}
ECode NumberPicker::SetFormatter(
/* [in] */ INumberPickerFormatter* formatter)
{
if (formatter == mFormatter) {
return NOERROR;
}
mFormatter = formatter;
InitializeSelectorWheelIndices();
UpdateInputTextView();
return NOERROR;
}
ECode NumberPicker::SetValue(
/* [in] */ Int32 value)
{
SetValueInternal(value, FALSE);
return NOERROR;
}
ECode NumberPicker::PerformClick(
/* [out] */ Boolean* res)
{
VALIDATE_NOT_NULL(res);
Boolean result;
if (!mHasSelectorWheel) {
return LinearLayout::PerformClick(res);
}
else if (LinearLayout::PerformClick(&result), !result) {
ShowSoftInput();
}
*res = TRUE;
return NOERROR;
}
ECode NumberPicker::PerformLongClick(
/* [out] */ Boolean* res)
{
VALIDATE_NOT_NULL(res);
Boolean result;
if (!mHasSelectorWheel) {
return LinearLayout::PerformLongClick(res);
}
else if (LinearLayout::PerformLongClick(&result), !result) {
ShowSoftInput();
mIgnoreMoveEvents = TRUE;
}
*res = TRUE;
return NOERROR;
}
ECode NumberPicker::GetWrapSelectorWheel(
/* [out] */ Boolean* res)
{
VALIDATE_NOT_NULL(res);
*res = mWrapSelectorWheel;
return NOERROR;
}
ECode NumberPicker::SetWrapSelectorWheel(
/* [in] */ Boolean wrapSelectorWheel)
{
Boolean wrappingAllowed = (mMaxValue - mMinValue) >= mSelectorIndices->GetLength();
if ((!wrapSelectorWheel || wrappingAllowed) && wrapSelectorWheel != mWrapSelectorWheel) {
mWrapSelectorWheel = wrapSelectorWheel;
}
return NOERROR;
}
ECode NumberPicker::SetOnLongPressUpdateInterval(
/* [in] */ Int64 intervalMillis)
{
mLongPressUpdateInterval = intervalMillis;
return NOERROR;
}
ECode NumberPicker::GetValue(
/* [out] */ Int32* value)
{
VALIDATE_NOT_NULL(value);
*value = mValue;
return NOERROR;
}
ECode NumberPicker::GetMinValue(
/* [out] */ Int32* minValue)
{
VALIDATE_NOT_NULL(minValue);
*minValue = mMinValue;
return NOERROR;
}
ECode NumberPicker::SetMinValue(
/* [in] */ Int32 minValue)
{
if (mMinValue == minValue) {
return NOERROR;
}
if (minValue < 0) {
return E_ILLEGAL_ARGUMENT_EXCEPTION;
}
mMinValue = minValue;
if (mMinValue > mValue) {
mValue = mMinValue;
}
Boolean wrapSelectorWheel = mMaxValue - mMinValue > mSelectorIndices->GetLength();
SetWrapSelectorWheel(wrapSelectorWheel);
InitializeSelectorWheelIndices();
UpdateInputTextView();
TryComputeMaxWidth();
Invalidate();
return NOERROR;
}
ECode NumberPicker::GetMaxValue(
/* [out] */ Int32* maxValue)
{
VALIDATE_NOT_NULL(maxValue);
*maxValue = mMaxValue;
return NOERROR;
}
ECode NumberPicker::SetMaxValue(
/* [in] */ Int32 maxValue)
{
if (mMaxValue == maxValue) {
return NOERROR;
}
if (maxValue < 0) {
return E_ILLEGAL_ARGUMENT_EXCEPTION;
}
mMaxValue = maxValue;
if (mMaxValue < mValue) {
mValue = mMaxValue;
}
Boolean wrapSelectorWheel = mMaxValue - mMinValue > mSelectorIndices->GetLength();
SetWrapSelectorWheel(wrapSelectorWheel);
InitializeSelectorWheelIndices();
UpdateInputTextView();
TryComputeMaxWidth();
Invalidate();
return NOERROR;
}
ECode NumberPicker::GetDisplayedValues(
/* [out, callee] */ ArrayOf<String>** displayedValues)
{
VALIDATE_NOT_NULL(displayedValues);
*displayedValues = mDisplayedValues;
REFCOUNT_ADD(*displayedValues);
return NOERROR;
}
ECode NumberPicker::SetDisplayedValues(
/* [in] */ ArrayOf<String>* displayedValues)
{
if (mDisplayedValues.Get() == displayedValues) {
return NOERROR;
}
mDisplayedValues = displayedValues;
if (mDisplayedValues) {
ITextView::Probe(mInputText)->SetRawInputType(IInputType::TYPE_CLASS_TEXT
| IInputType::TYPE_TEXT_FLAG_NO_SUGGESTIONS);
}
else {
ITextView::Probe(mInputText)->SetRawInputType(IInputType::TYPE_CLASS_NUMBER);
}
UpdateInputTextView();
InitializeSelectorWheelIndices();
TryComputeMaxWidth();
return NOERROR;
}
ECode NumberPicker::OnInitializeAccessibilityEvent(
/* [in] */ IAccessibilityEvent* event)
{
LinearLayout::OnInitializeAccessibilityEvent(event);
AutoPtr<IAccessibilityRecord> record = IAccessibilityRecord::Probe(event);
record->SetClassName(CoreUtils::Convert(NUMBERPICKER_NAME));
record->SetScrollable(TRUE);
record->SetScrollY((mMinValue + mValue) * mSelectorElementHeight);
record->SetMaxScrollY((mMaxValue - mMinValue) * mSelectorElementHeight);
return NOERROR;
}
ECode NumberPicker::GetAccessibilityNodeProvider(
/* [out] */ IAccessibilityNodeProvider** provider)
{
VALIDATE_NOT_NULL(provider);
if (!mHasSelectorWheel) {
return LinearLayout::GetAccessibilityNodeProvider(provider);
}
if (mAccessibilityNodeProvider == NULL) {
mAccessibilityNodeProvider = new AccessibilityNodeProviderImpl(this);
}
*provider = mAccessibilityNodeProvider;
REFCOUNT_ADD(*provider);
return NOERROR;
}
ECode NumberPicker::OnLayout(
/* [in] */ Boolean changed,
/* [in] */ Int32 letf,
/* [in] */ Int32 top,
/* [in] */ Int32 right,
/* [in] */ Int32 bottom)
{
if (!mHasSelectorWheel) {
LinearLayout::OnLayout(changed, letf, top, right, bottom);
return NOERROR;
}
Int32 msrdWdth;
GetMeasuredWidth(&msrdWdth);
Int32 msrdHght;
GetMeasuredHeight(&msrdHght);
AutoPtr<IView> view = IView::Probe(mInputText);
Int32 inptTxtMsrdWdth = 0;
view->GetMeasuredWidth(&inptTxtMsrdWdth);
Int32 inptTxtMsrdHght = 0;
view->GetMeasuredHeight(&inptTxtMsrdHght);
Int32 inptTxtLeft = (msrdWdth - inptTxtMsrdWdth) / 2;
Int32 inptTxtTop = (msrdHght - inptTxtMsrdHght) / 2;
Int32 inptTxtRight = inptTxtLeft + inptTxtMsrdWdth;
Int32 inptTxtBottom = inptTxtTop + inptTxtMsrdHght;
view->Layout(inptTxtLeft, inptTxtTop, inptTxtRight, inptTxtBottom);
if (changed) {
InitializeSelectorWheel();
InitializeFadingEdges();
Int32 height;
GetHeight(&height);
mTopSelectionDividerTop = (height - mSelectionDividersDistance) / 2 - mSelectionDividerHeight;
mBottomSelectionDividerBottom = mTopSelectionDividerTop + 2 * mSelectionDividerHeight + mSelectionDividersDistance;
}
return NOERROR;
}
ECode NumberPicker::OnMeasure(
/* [in] */ Int32 widthMeasureSpec,
/* [in] */ Int32 heightMeasureSpec)
{
if (!mHasSelectorWheel) {
LinearLayout::OnMeasure(widthMeasureSpec, heightMeasureSpec);
return NOERROR;
}
Int32 newWihthMeasureSpec = MakeMeasureSpec(widthMeasureSpec, mMaxWidth);
Int32 newHeightMeasureSpec = MakeMeasureSpec(heightMeasureSpec, mMaxHeight);
LinearLayout::OnMeasure(newWihthMeasureSpec, newHeightMeasureSpec);
Int32 width, height;
GetMeasuredWidth(&width);
GetMeasuredHeight(&height);
Int32 widthSize = ResolveSizeAndStateRespectingMinSize(mMinWidth, width, widthMeasureSpec);
Int32 heightSize = ResolveSizeAndStateRespectingMinSize(mMinHeight, height, heightMeasureSpec);
SetMeasuredDimension(widthSize, heightSize);
return NOERROR;
}
Float NumberPicker::GetTopFadingEdgeStrength()
{
return TOP_AND_BOTTOM_FADING_EDGE_STRENGTH;
}
Float NumberPicker::GetBottomFadingEdgeStrength()
{
return TOP_AND_BOTTOM_FADING_EDGE_STRENGTH;
}
ECode NumberPicker::OnDetachedFromWindow()
{
LinearLayout::OnDetachedFromWindow();
RemoveAllCallbacks();
return NOERROR;
}
void NumberPicker::OnDraw(
/* [in] */ ICanvas* canvas)
{
if (!mHasSelectorWheel) {
LinearLayout::OnDraw(canvas);
return;
}
Boolean focus;
const Boolean showSelectorWheel = mHideWheelUntilFocused ? (HasFocus(&focus), focus) : TRUE;
Float x = (mRight - mLeft) / 2;
Float y = mCurrentScrollOffset;
// draw the virtual buttons pressed state if needed
if (showSelectorWheel && mVirtualButtonPressedDrawable && mScrollState == INumberPickerOnScrollListener::SCROLL_STATE_IDLE) {
Boolean res = FALSE;
if (mDecrementVirtualButtonPressed) {
mVirtualButtonPressedDrawable->SetState(PRESSED_STATE_SET, &res);
mVirtualButtonPressedDrawable->SetBounds(0, 0, mRight, mTopSelectionDividerTop);
mVirtualButtonPressedDrawable->Draw(canvas);
}
if (mIncrementVirtualButtonPressed) {
mVirtualButtonPressedDrawable->SetState(PRESSED_STATE_SET, &res);
mVirtualButtonPressedDrawable->SetBounds(0, mBottomSelectionDividerBottom, mRight, mBottom);
mVirtualButtonPressedDrawable->Draw(canvas);
}
}
// draw the selector wheel
AutoPtr<ArrayOf<Int32> > selectorIndices = mSelectorIndices;
for(Int32 i = 0; i < selectorIndices->GetLength(); i++) {
Int32 selectorIndex = (*selectorIndices)[i];
AutoPtr<IInterface> obj;
mSelectorIndexToStringCache->Get(selectorIndex, (IInterface**)&obj);
AutoPtr<ICharSequence> seq = ICharSequence::Probe(obj);
String scrollSelectorValue;
seq->ToString(&scrollSelectorValue);
// Do not draw the middle item if input is visible since the input
// is shown only if the wheel is static and it covers the middle
// item. Otherwise, if the user starts editing the text via the
// IME he may see a dimmed version of the old value intermixed
// with the new one.
Int32 visible = 0;
IView::Probe(mInputText)->GetVisibility(&visible);
if ((showSelectorWheel && i != SELECTOR_MIDDLE_ITEM_INDEX) ||
(i == SELECTOR_MIDDLE_ITEM_INDEX && visible != VISIBLE)) {
canvas->DrawText(scrollSelectorValue, x, y, mSelectorWheelPaint);
}
y += mSelectorElementHeight;
}
// draw the selection dividers
if (showSelectorWheel && mSelectionDivider != NULL) {
// draw the top divider
Int32 topOfTopDivider = mTopSelectionDividerTop;
Int32 bottomOfTopDivider = topOfTopDivider + mSelectionDividerHeight;
mSelectionDivider->SetBounds(0, topOfTopDivider, mRight, bottomOfTopDivider);
mSelectionDivider->Draw(canvas);
// draw the bottom divider
Int32 bottomOfBottomDivider = mBottomSelectionDividerBottom;
Int32 topOfBottomDivider = bottomOfBottomDivider - mSelectionDividerHeight;
mSelectionDivider->SetBounds(0, topOfBottomDivider, mRight, bottomOfBottomDivider);
mSelectionDivider->Draw(canvas);
}
}
Boolean NumberPicker::MoveToFinalScrollerPosition(
/* [in] */ IScroller* scroller)
{
scroller->ForceFinished(TRUE);
Int32 finalY = 0;
scroller->GetFinalY(&finalY);
Int32 currY = 0;
scroller->GetCurrY(&currY);
Int32 amountToScroll = finalY - currY;
Int32 futureScrollOffset = (mCurrentScrollOffset + amountToScroll) % mSelectorElementHeight;
Int32 overshootAdjustment = mInitialScrollOffset - futureScrollOffset;
if (overshootAdjustment != 0) {
if (Elastos::Core::Math::Abs(overshootAdjustment) > mSelectorElementHeight / 2) {
if (overshootAdjustment > 0) {
overshootAdjustment -= mSelectorElementHeight;
}
else {
overshootAdjustment += mSelectorElementHeight;
}
}
amountToScroll += overshootAdjustment;
ScrollBy(0, amountToScroll);
return TRUE;
}
return FALSE;
}
void NumberPicker::ShowSoftInput()
{
AutoPtr<IInputMethodManager> inputMethodManager = CInputMethodManager::PeekInstance();
if (inputMethodManager != NULL) {
if (mHasSelectorWheel) {
IView::Probe(mInputText)->SetVisibility(IView::VISIBLE);
}
Boolean res = FALSE;
IView::Probe(mInputText)->RequestFocus(&res);
inputMethodManager->ShowSoftInput(IView::Probe(mInputText), 0, &res);
}
}
void NumberPicker::HideSoftInput()
{
AutoPtr<IInputMethodManager> inputMethodManager = CInputMethodManager::PeekInstance();
if (inputMethodManager == NULL) {
return;
}
Boolean isActive = FALSE;
inputMethodManager->IsActive(IView::Probe(mInputText), &isActive);
if (inputMethodManager && isActive) {
Boolean res = FALSE;
AutoPtr<IBinder> binder;
GetWindowToken((IBinder**)&binder);
inputMethodManager->HideSoftInputFromWindow(binder, 0, &res);
if (mHasSelectorWheel) {
IView::Probe(mInputText)->SetVisibility(IView::INVISIBLE);
}
}
}
void NumberPicker::TryComputeMaxWidth()
{
if (!mComputeMaxWidth) {
return;
}
Int32 maxTextWidth = 0;
if (mDisplayedValues == NULL) {
Float maxDigitWidth = 0;
for (Int32 i = 0; i <= 9; i++) {
Float digitWidth = 0;
mSelectorWheelPaint->MeasureText(FormatNumberWithLocale(i), &digitWidth);
if (digitWidth > maxDigitWidth) {
maxDigitWidth = digitWidth;
}
}
Int32 numberOfDigits = 0;
Int32 current = mMaxValue;
while (current > 0) {
numberOfDigits++;
current /= 10;
}
maxTextWidth = (Int32)(numberOfDigits * maxDigitWidth);
}
else {
Int32 valueCount = mDisplayedValues->GetLength();
for (Int32 i = 0; i < valueCount; i++) {
Float textWidth = 0;
mSelectorWheelPaint->MeasureText((*mDisplayedValues)[i], &textWidth);
if (textWidth > maxTextWidth) {
maxTextWidth = (Int32)textWidth;
}
}
}
Int32 paddingLeft = 0;
IView::Probe(mInputText)->GetPaddingLeft(&paddingLeft);
Int32 paddingRight = 0;
IView::Probe(mInputText)->GetPaddingRight(&paddingRight);
maxTextWidth += paddingLeft + paddingRight;
if (mMaxWidth != maxTextWidth) {
if (maxTextWidth > mMinWidth){
mMaxWidth = maxTextWidth;
}
else {
mMaxWidth = mMinWidth;
}
Invalidate();
}
}
Int32 NumberPicker::MakeMeasureSpec(
/* [in] */ Int32 measureSpec,
/* [in] */ Int32 maxSize)
{
if (maxSize == SIZE_UNSPECIFIED) {
return measureSpec;
}
Int32 size = View::MeasureSpec::GetSize(measureSpec);
Int32 mode = View::MeasureSpec::GetMode(measureSpec);
switch (mode) {
case View::MeasureSpec::EXACTLY:
return measureSpec;
case View::MeasureSpec::AT_MOST:
return View::MeasureSpec::MakeMeasureSpec(Elastos::Core::Math::Min(size, maxSize), View::MeasureSpec::EXACTLY);
case View::MeasureSpec::UNSPECIFIED:
return View::MeasureSpec::MakeMeasureSpec(maxSize, View::MeasureSpec::EXACTLY);
default:
return E_ILLEGAL_ARGUMENT_EXCEPTION;
}
}
Int32 NumberPicker::ResolveSizeAndStateRespectingMinSize(
/* [in] */ Int32 minSize,
/* [in] */ Int32 measuredSize,
/* [in] */ Int32 measureSpec)
{
if (minSize != SIZE_UNSPECIFIED) {
Int32 desiredWidth = Elastos::Core::Math::Max(minSize, measuredSize);
return ResolveSizeAndState(desiredWidth, measureSpec, 0);
}
else {
return measuredSize;
}
}
void NumberPicker::InitializeSelectorWheelIndices()
{
mSelectorIndexToStringCache->Clear();
AutoPtr<ArrayOf<Int32> > selectorIndices = mSelectorIndices;
Int32 current;
GetValue(¤t);
for (Int32 i = 0; i < mSelectorIndices->GetLength(); i++) {
Int32 selectorIndex = current + (i - SELECTOR_MIDDLE_ITEM_INDEX);
if (mWrapSelectorWheel) {
selectorIndex = GetWrappedSelectorIndex(selectorIndex);
}
(*selectorIndices)[i] = selectorIndex;
EnsureCachedScrollSelectorValue((*selectorIndices)[i]);
}
}
void NumberPicker::SetValueInternal(
/* [in] */ Int32 current,
/* [in] */ Boolean notifyChange)
{
if (mValue == current) {
return;
}
if (mWrapSelectorWheel) {
current = GetWrappedSelectorIndex(current);
}
else {
current = Elastos::Core::Math::Max(current, mMinValue);
current = Elastos::Core::Math::Min(current, mMaxValue);
}
Int32 previous = mValue;
mValue = current;
UpdateInputTextView();
if (notifyChange) {
NotifyChange(previous, current);
}
InitializeSelectorWheelIndices();
Invalidate();
}
void NumberPicker::ChangeValueByOne(
/* [in] */ Boolean increment)
{
if (mHasSelectorWheel) {
IView::Probe(mInputText)->SetVisibility(IView::INVISIBLE);
if (!MoveToFinalScrollerPosition(mFlingScroller)) {
MoveToFinalScrollerPosition(mAdjustScroller);
}
mPreviousScrollerY = 0;
if (increment) {
mFlingScroller->StartScroll(0, 0, 0, -mSelectorElementHeight, SNAP_SCROLL_DURATION);
}
else {
mFlingScroller->StartScroll(0, 0, 0, mSelectorElementHeight, SNAP_SCROLL_DURATION);
}
Invalidate();
}
else {
if (increment) {
SetValueInternal(mValue + 1, TRUE);
}
else {
SetValueInternal(mValue - 1, TRUE);
}
}
}
void NumberPicker::InitializeSelectorWheel()
{
InitializeSelectorWheelIndices();
AutoPtr<ArrayOf<Int32> > selectorIndices = mSelectorIndices;
Int32 totalTextHeight = (selectorIndices->GetLength()) * mTextSize;
Float totalTextGapHeight = (mBottom - mTop) - totalTextHeight;
Float TextGapCount = selectorIndices->GetLength();
mSelectorTextGapHeight = (Int32)(totalTextGapHeight / TextGapCount + 0.5f);
mSelectorElementHeight = mTextSize + mSelectorTextGapHeight;
Int32 baseLine = 0;
IView::Probe(mInputText)->GetBaseline(&baseLine);
Int32 top = 0;
IView::Probe(mInputText)->GetTop(&top);
Int32 editTextTextPosition = baseLine + top;
mInitialScrollOffset = editTextTextPosition - (mSelectorElementHeight * SELECTOR_MIDDLE_ITEM_INDEX);
mCurrentScrollOffset = mInitialScrollOffset;
UpdateInputTextView();
}
void NumberPicker::InitializeFadingEdges()
{
SetVerticalFadingEdgeEnabled(TRUE);
SetFadingEdgeLength((mBottom - mTop - mTextSize) / 2);
}
void NumberPicker::OnScrollerFinished(
/* [in] */ IScroller* scroller)
{
if (scroller == mFlingScroller) {
if (!EnsureScrollWheelAdjusted()) {
UpdateInputTextView();
}
OnScrollStateChange(INumberPickerOnScrollListener::SCROLL_STATE_IDLE);
}
else {
if (mScrollState != INumberPickerOnScrollListener::SCROLL_STATE_TOUCH_SCROLL) {
UpdateInputTextView();
}
}
}
void NumberPicker::OnScrollStateChange(
/* [in] */ Int32 scrollState)
{
if (mScrollState == scrollState) {
return;
}
mScrollState = scrollState;
if (mOnScrollListener) {
mOnScrollListener->OnScrollStateChange(this, scrollState);
}
}
void NumberPicker::Fling(
/* [in] */ Int32 velocityY)
{
mPreviousScrollerY = 0;
if (velocityY > 0) {
mFlingScroller->Fling(0, 0, 0, velocityY, 0, 0, 0, Elastos::Core::Math::INT32_MAX_VALUE);
}
else {
mFlingScroller->Fling(0, Elastos::Core::Math::INT32_MAX_VALUE, 0, velocityY, 0, 0, 0, Elastos::Core::Math::INT32_MAX_VALUE);
}
Invalidate();
}
Int32 NumberPicker::GetWrappedSelectorIndex(
/* [in] */ Int32 selectorIndex)
{
if (selectorIndex > mMaxValue) {
return mMinValue + (selectorIndex - mMaxValue) % (mMaxValue - mMinValue) - 1;
}
else if (selectorIndex < mMinValue) {
return mMaxValue - (mMinValue - selectorIndex) % (mMaxValue - mMinValue) + 1;
}
return selectorIndex;
}
void NumberPicker::IncrementSelectorIndices(
/* [in] */ ArrayOf<Int32>* selectorIndices)
{
for (Int32 i = 0; i < selectorIndices->GetLength() - 1; i++) {
(*selectorIndices)[i] = (*selectorIndices)[i + 1];
}
Int32 nextScrollSelectorIndex = (*selectorIndices)[selectorIndices->GetLength() - 2] + 1;
if (mWrapSelectorWheel && nextScrollSelectorIndex > mMaxValue) {
nextScrollSelectorIndex = mMinValue;
}
(*selectorIndices)[selectorIndices->GetLength() - 1] = nextScrollSelectorIndex;
EnsureCachedScrollSelectorValue(nextScrollSelectorIndex);
}
void NumberPicker::DecrementSelectorIndices(
/* [in] */ ArrayOf<Int32>* selectorIndices)
{
for (Int32 i = selectorIndices->GetLength() - 1; i > 0; i--) {
(*selectorIndices)[i] = (*selectorIndices)[i - 1];
}
Int32 nextScrollSelectorIndex = (*selectorIndices)[1] - 1;
if (mWrapSelectorWheel && nextScrollSelectorIndex < mMinValue) {
nextScrollSelectorIndex = mMaxValue;
}
(*selectorIndices)[0] = nextScrollSelectorIndex;
EnsureCachedScrollSelectorValue(nextScrollSelectorIndex);
}
void NumberPicker::EnsureCachedScrollSelectorValue(
/* [in] */ Int32 selectorIndex)
{
AutoPtr<ISparseArray> cache = mSelectorIndexToStringCache;
AutoPtr<IInterface> obj;
cache->Get(selectorIndex, (IInterface**)&obj);
AutoPtr<ICharSequence> seq = ICharSequence::Probe(obj);
String scrollSelectorValue;
if (seq != NULL) {
seq->ToString(&scrollSelectorValue);
}
if (!scrollSelectorValue.IsNull()) {
return;
}
if (selectorIndex < mMinValue || selectorIndex > mMaxValue) {
scrollSelectorValue = "";
}
else {
if (mDisplayedValues) {
Int32 displayedValuesIndex = selectorIndex - mMinValue;
scrollSelectorValue = (*mDisplayedValues)[displayedValuesIndex];
}
else {
scrollSelectorValue = FormatNumber(selectorIndex);
}
}
cache->Put(selectorIndex, CoreUtils::Convert(scrollSelectorValue));
}
String NumberPicker::FormatNumber(
/* [in] */ Int32 value)
{
if (mFormatter) {
String str = String(NULL);
mFormatter->Format(value, &str);
return str;
}
else {
return FormatNumberWithLocale(value);
}
}
void NumberPicker::ValidateInputTextView(
/* [in] */ IView* v)
{
AutoPtr<ICharSequence> charSeq;
ITextView::Probe(v)->GetText((ICharSequence**)&charSeq);
String str = String(NULL);
charSeq->ToString(&str);
if (str.IsEmpty()) {
UpdateInputTextView();
}
else {
Int32 current = GetSelectedPos(str);
SetValueInternal(current, TRUE);
}
}
Boolean NumberPicker::UpdateInputTextView()
{
String text = String(NULL);
if (!mDisplayedValues) {
text = FormatNumber(mValue);
}
else {
text = (*mDisplayedValues)[mValue - mMinValue];
}
AutoPtr<ICharSequence> csq = CoreUtils::Convert(text);
AutoPtr<ICharSequence> itext;
ITextView::Probe(mInputText)->GetText((ICharSequence**)&itext);
String inputText = String(NULL);
itext->ToString(&inputText);
if (!TextUtils::IsEmpty(csq) && !text.Equals(inputText)) {
ITextView::Probe(mInputText)->SetText(csq);
return TRUE;
}
return FALSE;
}
void NumberPicker::NotifyChange(
/* [in] */ Int32 previous,
/* [in] */ Int32 current)
{
if (mOnValueChangeListener) {
mOnValueChangeListener->OnValueChange(this, previous, mValue);
}
}
void NumberPicker::PostChangeCurrentByOneFromLongPress(
/* [in] */ Boolean increment,
/* [in] */ Int64 delayMillis)
{
Boolean res;
if (!mChangeCurrentByOneFromLongPressCommand) {
mChangeCurrentByOneFromLongPressCommand = new ChangeCurrentByOneFromLongPressCommand(this);
}
else {
RemoveCallbacks(mChangeCurrentByOneFromLongPressCommand, &res);
}
mChangeCurrentByOneFromLongPressCommand->SetStep(increment);
PostDelayed(mChangeCurrentByOneFromLongPressCommand, delayMillis, &res);
}
void NumberPicker::RemoveChangeCurrentByOneFromLongPress()
{
if (mChangeCurrentByOneFromLongPressCommand) {
Boolean res;
RemoveCallbacks(mChangeCurrentByOneFromLongPressCommand, &res);
}
}
void NumberPicker::PostBeginSoftInputOnLongPressCommand()
{
Boolean res;
if (!mBeginSoftInputOnLongPressCommand) {
mBeginSoftInputOnLongPressCommand = new BeginSoftInputOnLongPressCommand(this);
}
else {
RemoveCallbacks(mBeginSoftInputOnLongPressCommand, &res);
}
PostDelayed(mBeginSoftInputOnLongPressCommand, CViewConfiguration::GetLongPressTimeout(), &res);
}
void NumberPicker::RemoveBeginSoftInputCommand()
{
if (mBeginSoftInputOnLongPressCommand) {
Boolean res;
RemoveCallbacks(mBeginSoftInputOnLongPressCommand, &res);
}
}
void NumberPicker::RemoveAllCallbacks()
{
Boolean res;
if (mChangeCurrentByOneFromLongPressCommand) {
RemoveCallbacks(mChangeCurrentByOneFromLongPressCommand, &res);
}
if (mSetSelectionCommand) {
RemoveCallbacks(mSetSelectionCommand, &res);
}
if (mBeginSoftInputOnLongPressCommand) {
RemoveCallbacks(mBeginSoftInputOnLongPressCommand, &res);
}
mPressedStateHelper->Cancel();
}
Int32 NumberPicker::GetSelectedPos(
/* [in] */ const String& value)
{
if (!mDisplayedValues) {
//try{
return StringUtils::ParseInt32(value);
//} catch{
//}
}
else {
String str;
for (Int32 i = 0; i < mDisplayedValues->GetLength(); i++) {
str = (*mDisplayedValues)[i];
if (str.StartWithIgnoreCase(value)) {
return mMinValue + i;
}
}
//try{
return StringUtils::ParseInt32(value);
//} catch{
//}
}
return mMinValue;
}
void NumberPicker::PostSetSelectionCommand(
/* [in] */ Int32 selectionStart,
/* [in] */ Int64 selectionEnd)
{
Boolean res;
if (!mSetSelectionCommand) {
mSetSelectionCommand = new SetSelectionCommand(this);
}
else {
RemoveCallbacks(mSetSelectionCommand, &res);
}
mSetSelectionCommand->mSelectionStart = selectionStart;
mSetSelectionCommand->mSelectionEnd = selectionEnd;
Post(mSetSelectionCommand, &res);
}
Boolean NumberPicker::EnsureScrollWheelAdjusted()
{
Int32 deltaY = mInitialScrollOffset - mCurrentScrollOffset;
if (deltaY != 0) {
mPreviousScrollerY = 0;
if (Elastos::Core::Math::Abs(deltaY) > mSelectorElementHeight / 2) {
deltaY += (deltaY > 0) ? -mSelectorElementHeight : mSelectorElementHeight;
}
mAdjustScroller->StartScroll(0, 0, 0, deltaY, SELECTOR_ADJUSTMENT_DURATION_MILLIS);
Invalidate();
return TRUE;
}
return FALSE;
}
String NumberPicker::FormatNumberWithLocale(
/* [in] */ Int32 value)
{
AutoPtr<ILocaleHelper> helper;
CLocaleHelper::AcquireSingleton((ILocaleHelper**)&helper);
AutoPtr<ILocale> locale;
helper->GetDefault((ILocale**)&locale);
AutoPtr< ArrayOf<IInterface*> > args = ArrayOf<IInterface*>::Alloc(1);
args->Set(0, CoreUtils::Convert(value));
return StringUtils::Format(locale, String("%d"), args);
}
}// namespace Widget
}// namespace Droid
}// namespace Elastos
| 35.715658 | 161 | 0.626827 | [
"object"
] |
9cb43c45f19d3512ff1e8d5595e9debe397a842c | 3,090 | cpp | C++ | tutorial-2-mixedprocessing/jni/VideoRenderer.cpp | forestsen/CVGLBasedSimpleAndroidAR | a0efb11759d61de28dd441649298f5d13ce9f7cd | [
"MIT"
] | 6 | 2020-05-09T03:23:31.000Z | 2021-02-26T13:49:11.000Z | tutorial-2-mixedprocessing/jni/VideoRenderer.cpp | forestsen/CVGLBasedSimpleAndroidAR | a0efb11759d61de28dd441649298f5d13ce9f7cd | [
"MIT"
] | null | null | null | tutorial-2-mixedprocessing/jni/VideoRenderer.cpp | forestsen/CVGLBasedSimpleAndroidAR | a0efb11759d61de28dd441649298f5d13ce9f7cd | [
"MIT"
] | 2 | 2020-08-28T20:24:51.000Z | 2021-02-26T13:49:12.000Z | #include <GLES/gl.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "Texture.hpp"
#include "Shader.hpp"
#include "VideoRenderer.hpp"
#define LOG_TAG "VideoRenderer"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
bool sen::VideoRenderer::setup(const char *vertex_shader_code, const char *fragment_shader_code)
{
programID = createShaderProgram(vertex_shader_code, fragment_shader_code);
MatrixID = glGetUniformLocation(programID, "MVP");
return true;
}
bool sen::VideoRenderer::initTexture(const cv::Mat &frame)
{
texture_id = createTexture();
TextureID = glGetUniformLocation(programID, "myTextureSampler");
int texture_width = frame.size().width;
int texture_height = frame.size().height;
const GLfloat bgTextureVertices[] = {0, 0, (float)texture_width, 0, 0, (float)texture_height, (float)texture_width, (float)texture_height};
const GLfloat bgTextureCoords[] = {1, 0, 1, 1, 0, 0, 0, 1};
glGenBuffers(1, &vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(bgTextureVertices), bgTextureVertices, GL_STATIC_DRAW);
glGenBuffers(1, &uvBuffer);
glBindBuffer(GL_ARRAY_BUFFER, uvBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(bgTextureCoords), bgTextureCoords, GL_STATIC_DRAW);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture_width, texture_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, frame.data);
return true;
}
void sen::VideoRenderer::render(const cv::Mat &frame)
{
int texture_width = frame.size().width;
int texture_height = frame.size().height;
const GLfloat proj[] = {
0, -2.f / texture_width, 0, 0,
-2.f / texture_height, 0, 0, 0,
0, 0, 1, 0,
1, 1, 0, 1};
glm::mat4 Projection = glm::make_mat4(proj);
glm::mat4 View = glm::mat4(1.0f);
glm::mat4 Model = glm::mat4(1.0f);
MVP = Projection * View * Model;
glClearColor(1, 1, 1, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(programID);
glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture_id);
glUniform1i(TextureID, 0);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture_width, texture_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, frame.data);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void *)0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, uvBuffer);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, (void *)0);
glColor4f(1, 1, 1, 1);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
}
void sen::VideoRenderer::deleteBuffer()
{
glDeleteBuffers(1, &vertexBuffer);
glDeleteBuffers(1, &uvBuffer);
glDeleteProgram(programID);
glDeleteTextures(1, &texture_id);
} | 32.87234 | 143 | 0.714887 | [
"render",
"model"
] |
9cb45cfd07e18329fd98906ed4d442caffd65a43 | 269,302 | cpp | C++ | media_driver/agnostic/common/os/mos_utilities.cpp | xhaihao/media-driver | fc044798bd07a21aacfdd6deeb5a9cb77ff34a54 | [
"Intel",
"BSD-3-Clause",
"MIT"
] | null | null | null | media_driver/agnostic/common/os/mos_utilities.cpp | xhaihao/media-driver | fc044798bd07a21aacfdd6deeb5a9cb77ff34a54 | [
"Intel",
"BSD-3-Clause",
"MIT"
] | null | null | null | media_driver/agnostic/common/os/mos_utilities.cpp | xhaihao/media-driver | fc044798bd07a21aacfdd6deeb5a9cb77ff34a54 | [
"Intel",
"BSD-3-Clause",
"MIT"
] | 1 | 2021-06-10T09:27:22.000Z | 2021-06-10T09:27:22.000Z | /*
* Copyright (c) 2009-2021, Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
//!
//! \file mos_utilities.cpp
//! \brief Common OS service across different platform
//! \details Common OS service across different platform
//!
#include "mos_utilities.h"
#include "mos_utilities_specific.h"
#ifdef __cplusplus
#include "media_user_settings_mgr.h"
#include <sstream>
#include <chrono>
#endif
#include "mos_os.h"
#include <fcntl.h> //open
#include <malloc.h> // For memalign
#include <string.h> // memset
#include <stdlib.h> // atoi atol
#include <math.h>
#if MOS_MESSAGES_ENABLED
#include <time.h> //for simulate random memory allcation failure
#endif
#define Mos_SwizzleOffset __Mos_SwizzleOffset
#ifdef _MOS_UTILITY_EXT
#include "mos_utilities_ext.h"
#endif
#ifdef __cplusplus
std::shared_ptr<PerfUtility> PerfUtility::instance = nullptr;
std::mutex PerfUtility::perfMutex;
PerfUtility *PerfUtility::getInstance()
{
if (instance == nullptr)
{
instance = std::make_shared<PerfUtility>();
}
return instance.get();
}
PerfUtility::PerfUtility()
{
bPerfUtilityKey = false;
dwPerfUtilityIsEnabled = 0;
}
PerfUtility::~PerfUtility()
{
for (const auto &data : records)
{
if (data.second)
{
delete data.second;
}
}
records.clear();
}
void PerfUtility::setupFilePath(char *perfFilePath)
{
MOS_SecureStrcpy(sSummaryFileName, MOS_MAX_PERF_FILENAME_LEN, perfFilePath);
MOS_SecureStrcat(sSummaryFileName, MOS_MAX_PERF_FILENAME_LEN, "perf_sumamry.csv");
MOS_SecureStrcpy(sDetailsFileName, MOS_MAX_PERF_FILENAME_LEN, perfFilePath);
MOS_SecureStrcat(sDetailsFileName, MOS_MAX_PERF_FILENAME_LEN, "perf_details.txt");
}
void PerfUtility::setupFilePath()
{
MOS_SecureStrcpy(sSummaryFileName, MOS_MAX_PERF_FILENAME_LEN, "perf_sumamry.csv");
MOS_SecureStrcpy(sDetailsFileName, MOS_MAX_PERF_FILENAME_LEN, "perf_details.txt");
}
void PerfUtility::savePerfData()
{
printPerfSummary();
printPerfDetails();
}
void PerfUtility::printPerfSummary()
{
std::ofstream fout;
fout.open(sSummaryFileName);
printHeader(fout);
printBody(fout);
fout.close();
}
void PerfUtility::printPerfDetails()
{
std::ofstream fout;
fout.open(sDetailsFileName);
for (auto data : records)
{
fout << getDashString((uint32_t)data.first.length());
fout << data.first << std::endl;
fout << getDashString((uint32_t)data.first.length());
for (auto t : *data.second)
{
fout << t.time << std::endl;
}
fout << std::endl;
}
fout.close();
}
void PerfUtility::printHeader(std::ofstream& fout)
{
fout << "Summary: " << std::endl;
std::stringstream ss;
ss << "CPU Latency Tag,";
ss << "Hit Count,";
ss << "Average (ms),";
ss << "Minimum (ms),";
ss << "Maximum (ms)" << std::endl;
fout << ss.str();
}
void PerfUtility::printBody(std::ofstream& fout)
{
for (const auto& data : records)
{
fout << formatPerfData(data.first, *data.second);
}
}
std::string PerfUtility::formatPerfData(std::string tag, std::vector<Tick>& record)
{
std::stringstream ss;
PerfInfo info = {};
getPerfInfo(record, &info);
ss << tag;
ss << ",";
ss.precision(3);
ss.setf(std::ios::fixed, std::ios::floatfield);
ss << info.count;
ss << ",";
ss << info.avg;
ss << ",";
ss << info.min;
ss << ",";
ss << info.max << std::endl;
return ss.str();
}
void PerfUtility::getPerfInfo(std::vector<Tick>& record, PerfInfo* info)
{
if (record.size() <= 0)
return;
info->count = (uint32_t)record.size();
double sum = 0, max = 0, min = 10000000.0;
for (auto t : record)
{
sum += t.time;
max = (max < t.time) ? t.time : max;
min = (min > t.time) ? t.time : min;
}
info->avg = sum / info->count;
info->max = max;
info->min = min;
}
void PerfUtility::printFooter(std::ofstream& fout)
{
fout << getDashString(80);
}
std::string PerfUtility::getDashString(uint32_t num)
{
std::stringstream ss;
ss.width(num);
ss.fill('-');
ss << std::left << "" << std::endl;
return ss.str();
}
uint64_t MOS_GetCurTime()
{
using us = std::chrono::microseconds;
using clock = std::chrono::steady_clock;
clock::time_point Timer = clock::now();
uint64_t usStartTime =
std::chrono::duration_cast<us>(Timer.time_since_epoch()).count();
return usStartTime;
}
#endif // __cplusplus
int32_t MosMemAllocFakeCounter;
uint8_t MosUltFlag;
#ifdef __cplusplus
extern "C" {
#endif
MOS_FUNC_EXPORT void MOS_SetUltFlag(uint8_t ultFlag)
{
MosUtilities::MosSetUltFlag(ultFlag);
}
MOS_FUNC_EXPORT int32_t MOS_GetMemNinjaCounter()
{
return MosUtilities::MosGetMemNinjaCounter();
}
MOS_FUNC_EXPORT int32_t MOS_GetMemNinjaCounterGfx()
{
return MosUtilities::MosGetMemNinjaCounterGfx();
}
#ifdef __cplusplus
}
#endif
#define __MOS_USER_FEATURE_VALUE_SINGLE_SLICE_VEBOX_DEFAULT_VALUE "1"
#define __MAX_MULTI_STRING_COUNT 128
static char gcXMLFilePath[MOS_USER_CONTROL_MAX_DATA_SIZE];
static MOS_USER_FEATURE_VALUE_MAP gc_UserFeatureKeysMap[__MOS_USER_FEATURE_KEY_MAX_ID];
static MOS_USER_FEATURE_VALUE MOSUserFeatureDescFields[__MOS_USER_FEATURE_KEY_MAX_ID] =
{
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_MEDIA_RESET_ENABLE_ID,
"Media Reset",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"General",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"If enabled, media reset will be enabled."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_MEDIA_RESET_TH_ID,
"Media Reset TH",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"General",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"If enabled, media reset will be enabled."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_SOFT_RESET_ENABLE_ID,
"Soft Reset",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"General",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"If enabled, soft reset will be enabled. This key is not valid on Linux."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_SIM_IN_USE_ID,
"Simulation In Use",
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Reports whether the media driver is used in simulation/emulation mode."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_LINUX_PERFORMANCETAG_ENABLE_ID,
"Linux PerformanceTag Enable",
__MEDIA_USER_FEATURE_SUBKEY_PERFORMANCE,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"General",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Linux Performance Tag"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_PERF_PROFILER_ENABLE_ID,
"Perf Profiler Enable",
__MEDIA_USER_FEATURE_SUBKEY_PERFORMANCE,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"General",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"Perf Profiler Enable Control Flag"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_PERF_PROFILER_FE_BE_TIMING,
"Perf Profiler FE BE timing measurement",
__MEDIA_USER_FEATURE_SUBKEY_PERFORMANCE,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"General",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"Perf Profiler FE and BE Timing Measurement Flag"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_PERF_PROFILER_OUTPUT_FILE,
"Perf Profiler Output File Name",
__MEDIA_USER_FEATURE_SUBKEY_PERFORMANCE,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"General",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_STRING,
"Perf_DATA_00_00.bin",
"Performance Profiler Output File Name"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_PERF_PROFILER_BUFFER_SIZE,
"Perf Profiler Buffer Size",
__MEDIA_USER_FEATURE_SUBKEY_PERFORMANCE,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"General",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"10000000",
"Performance Profiler Buffer Size"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_PERF_PROFILER_TIMER_REG,
"Perf Profiler Timer Reg",
__MEDIA_USER_FEATURE_SUBKEY_PERFORMANCE,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"General",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Performance Profiler Timer Register"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_PERF_PROFILER_ENABLE_MULTI_PROCESS,
"Perf Profiler Multi Process Support",
__MEDIA_USER_FEATURE_SUBKEY_PERFORMANCE,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"General",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Performance Profiler Multi Process Support"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_PERF_PROFILER_REGISTER_1,
"Perf Profiler Register 1",
__MEDIA_USER_FEATURE_SUBKEY_PERFORMANCE,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"General",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Performance Profiler Memory Information Register"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_PERF_PROFILER_REGISTER_2,
"Perf Profiler Register 2",
__MEDIA_USER_FEATURE_SUBKEY_PERFORMANCE,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"General",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Performance Profiler Memory Information Register"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_PERF_PROFILER_REGISTER_3,
"Perf Profiler Register 3",
__MEDIA_USER_FEATURE_SUBKEY_PERFORMANCE,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"General",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Performance Profiler Memory Information Register"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_PERF_PROFILER_REGISTER_4,
"Perf Profiler Register 4",
__MEDIA_USER_FEATURE_SUBKEY_PERFORMANCE,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"General",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Performance Profiler Memory Information Register"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_PERF_PROFILER_REGISTER_5,
"Perf Profiler Register 5",
__MEDIA_USER_FEATURE_SUBKEY_PERFORMANCE,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"General",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Performance Profiler Memory Information Register"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_PERF_PROFILER_REGISTER_6,
"Perf Profiler Register 6",
__MEDIA_USER_FEATURE_SUBKEY_PERFORMANCE,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"General",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Performance Profiler Memory Information Register"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_PERF_PROFILER_REGISTER_7,
"Perf Profiler Register 7",
__MEDIA_USER_FEATURE_SUBKEY_PERFORMANCE,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"General",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Performance Profiler Memory Information Register"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_PERF_PROFILER_REGISTER_8,
"Perf Profiler Register 8",
__MEDIA_USER_FEATURE_SUBKEY_PERFORMANCE,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"General",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Performance Profiler Memory Information Register"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_DISABLE_KMD_WATCHDOG_ID,
"Disable KMD Watchdog",
__MEDIA_USER_FEATURE_SUBKEY_PERFORMANCE,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"General",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Disable KMD Watchdog"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_SINGLE_TASK_PHASE_ENABLE_ID,
"Single Task Phase Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enables/Disables single task phase mode. This feature is only enabled for AVC and HEVC encode."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_AUX_TABLE_16K_GRANULAR_ID,
"Aux Table 16K Granular",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"General",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"1",
"Switches between 1-16K and 0-64K Granularity for Aux Table."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_MFE_MBENC_ENABLE_ID,
"MFE MBEnc Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enables/Disables MFE MBEnc Mode. This feature is only enabled for AVC encode."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_MFE_FIRST_BUFFER_SUBMIT_ID,
"MFE First Buffer Submit",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Used to indicate MFE work on UMD level"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_RC_PANIC_ENABLE_ID,
"RC Panic Mode",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"1",
"Enables/Disables PAK panic mode feature."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_SLICE_SHUTDOWN_ENABLE_ID,
"Slice Shutdown Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"1",
"Used to Enable/Disable Slice shutdown. Only has impact on HSW."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_FORCE_YFYS_ID,
"Force to allocate YfYs",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Media",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Force to allocate internal surface as Yf or Ys"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_DECODE_LOCK_DISABLE_ID,
__MEDIA_USER_FEATURE_VALUE_DECODE_LOCK_DISABLE,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Decode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"If decode output surface can be locked for sync. "),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENCODE_HW_WALKER_ID,
"Encode HW Walker",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Used to Enable/Disable HW walker."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENCODE_SUPPRESS_RECON_PIC_ENABLE_ID,
"Encode Suppress Recon Pic",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Used to suppress recon pic generation for non-ref surfaces."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_ENCODE_ME_IN_USE_ID,
"Encode HME In Use",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Used to report if HME is in use."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_ENCODE_16xME_IN_USE_ID,
"Encode SuperHME In Use",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Used to report if SuperHme is in use."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_ENCODE_32xME_IN_USE_ID,
"Encode UltraHME In Use",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Used to report if UltraHme is in use."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_ENCODE_RATECONTROL_METHOD_ID,
"Encode RateControl Method",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Used to report the RateControl Method."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENCODE_TARGET_USAGE_OVERRIDE_ID,
"Encode TU Override",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Used to override TU value "),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_AVC_ENCODE_ME_ENABLE_ID,
"AVC Encode HME",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enables/Disables HME for AVC."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_AVC_ENCODE_16xME_ENABLE_ID,
"AVC Encode SuperHME",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"255",
"Enables/Disables SHME for AVC."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_AVC_ENCODE_32xME_ENABLE_ID,
"AVC Encode UltraHME",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"255",
"Enables/Disables UHME for AVC."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_AVC_ENCODE_MULTIPRED_ENABLE_ID,
"AVC Encode MultiPred",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enables/Disables MultiPred feature for AVC."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_AVC_ENCODE_INTRA_REFRESH_QP_THRESHOLD_ID,
"AVC Encode Intra Refresh Qp Threshold",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Gives Intra Refresh Qp Threshold value."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_AVC_FTQ_ENABLE_ID,
"AVC FTQ Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enable/Disable FTQ for AVC."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_AVC_CAF_ENABLE_ID,
"AVC CAF Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enable/Disable CAF for AVC."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_AVC_CAF_DISABLE_HD_ID,
"AVC CAF Disable HD",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enable/Disable CAF for HD resolutions for AVC."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_AVC_MB_BRC_ENABLE_ID,
"AVC Encode MB BRC",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"255",
"Enables/Disables MBBRC for AVC "),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_AVC_FORCE_TO_SKIP_ENABLE_ID,
"AVC Force to Skip Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"1",
"Enables/Disables Force to Skip for AVC Encode."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_AVC_SLIDING_WINDOW_SIZE_ID,
"AVC Sliding Window Size",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Sliding Window Size for AVC Encode."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_AVC_ROUNDING_INTER_ENABLE_ID,
"AVC Encode Rounding Inter Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enables/Disables Rounding Inter feature for AVC."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_AVC_ROUNDING_INTER_P_ID,
"AVC Encode Rounding Inter P",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"255",
"Sets the PAK Inter Rounding value for P frame for AVC "),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_AVC_ROUNDING_INTER_B_ID,
"AVC Encode Rounding Inter B",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"255",
"Sets the PAK Inter Rounding value for B frame for AVC "),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_AVC_ROUNDING_INTER_BREF_ID,
"AVC Encode Rounding Inter BRef",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"255",
"Sets the PAK Inter Rounding value for B ref frame for AVC "),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_AVC_ADAPTIVE_ROUNDING_INTER_ENABLE_ID,
"AVC Encode Adaptive Rounding Inter Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enables/Disables Adaptive Inter Rounding for AVC."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_AVC_SKIP_BIAS_ADJUSTMENT_ENABLE_ID,
"AVC Encode Skip Bias Adjustment Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enables/Disables Skip Bias Adjustment feature for AVC."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_AVC_ADAPTIVE_INTRA_SCALING_ENABLE_ID,
"AVC Encode Adaptive Intra Scaling Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enables/Disables Adaptive Intra Scaling feature for AVC."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_AVC_OLD_MODE_COST_ENABLE_ID,
"AVC Encode Old Mode Cost Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Enables/Disables Old Mode Cost tables for AVC."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_VDENC_TAIL_INSERTION_DELAY_COUNT_ID,
"VDENC Encode Tail Insertion Delay Count",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1500",
"Sets the VDENC Delay count."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_VDENC_CRE_PREFETCH_ENABLE_ID,
"AVC VDEnc CRE Prefetch Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enables/Disables CRE Prefetch for AVC VDEnc. Enabled by default for perf improvement."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_VDENC_TLB_PREFETCH_ENABLE_ID,
"AVC VDEnc TLB Prefetch Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enables/Disables TLB Prefetch for AVC VDEnc. Enabled by default for perf improvement."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_VDENC_TLB_ALLOCATION_WA_ENABLE_ID,
"AVC VDEnc TLB WA Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enables/Disables TLB Allocation WA for AVC VDEnc."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_VDENC_PERMB_STREAMOUT_ENABLE_ID,
"AVC VDEnc PerMB StreamOut Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Enables/Disables PerMB StreamOut for AVC VDEnc."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_MMIO_MFX_LRA_0_OVERRIDE_ID,
"MFX_LRA_0 Override",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Override Register MFX_LRA_0. Valid Only When AVC VDEnc TLB Allocation WA is Enabled."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_MMIO_MFX_LRA_1_OVERRIDE_ID,
"MFX_LRA_1 Override",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Override Register MFX_LRA_1. Valid Only When AVC VDEnc TLB Allocation WA is Enabled."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_MMIO_MFX_LRA_2_OVERRIDE_ID,
"MFX_LRA_2 Override",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Override Register MFX_LRA_2. Valid Only When AVC VDEnc TLB Allocation WA is Enabled."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_FLATNESS_CHECK_ENABLE_ID,
"Flatness Check Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enables/Disables Flatness Check feature. This feature is only supported for AVC."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_AVC_ADAPTIVE_SEARCH_WINDOW_ENABLE_ID,
"Adaptive Search Window Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enables/Disables Adaptive Search Window feature. This feature is only supported for AVC."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ADAPTIVE_TRANSFORM_DECISION_ENABLE_ID,
"Adaptive transform decision Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
__MOS_USER_FEATURE_VALUE_ADAPTIVE_TRANSFORM_DECISION_ENABLE_DEFAULT_VALUE,
"Enables/Disables Adaptive transform decision feature. This feature is only supported for AVC."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_WEIGHTED_PREDICTION_L0_IN_USE_ID,
"Weighted prediction used for L0 reference",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"1",
"Weighted prediction used for L0 reference."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_WEIGHTED_PREDICTION_L1_IN_USE_ID,
"Weighted prediction used for L1 reference",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"1",
"Weighted prediction used for L1 reference."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_FBR_BYPASS_ENABLE_ID,
"FBR Bypass Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"1",
"Enables/Disables FBR Bypass feature. Starting SKL for AVC."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_STATIC_FRAME_DETECTION_ENABLE_ID,
"Static Frame Detection Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"1",
"Enables/Disables Static Frame Detection feature. Starting BDW for AVC."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_VDENC_SINGLE_PASS_ENABLE_ID,
"VDEnc Single Pass Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Enables/Disables VDEnc single pass feature. Starting from KBL for AVC VDEnc."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_VDENC_BRC_MOTION_ADAPTIVE_ENABLE_ID,
"VDEnc BRC Motion Adaptive Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Enables/Disables VDEnc motion adaptive BRC for AVC VDEnc."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENCODE_ENABLE_FRAME_TRACKING_ID,
"Enable Frame Tracking",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enables/Disables Frame Tracking."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_COLOR_BIT_SUPPORT_ENABLE_ID,
"Colorbit Support Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enables/Disables Colorbit Support. This feature is only supported for AVC."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_GROUP_ID_SELECT_ENABLE_ID,
"Group ID Select Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Enables/Disables Group Id Select."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_AVC_BRC_ENABLE_ID,
"AVC Encode BRC Mode",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Report."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_AVC_MULTIREF_QP_ID,
"AVC Encode Multiref Qp",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Used to enable or disable multiref QP feature for BRC."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_AVC_BRC_VAR_COMPU_BYPASS_ID,
"BRC Variance Computation Bypass",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"1",
"Enables/Disables BRC Variance Computation Bypass feature. for GLK perf debug."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_AVC_BRC_SOFTWARE_ID,
"AVC BRC SW Simulation",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Used to enable BRC SW simulation."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_AVC_BRC_SOFTWARE_IN_USE_ID,
"AVC BRC SW Simulation In Use",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Used to report if AVC BRC SW Simulation is in use."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENABLE_CNL_AVC_ENCODE_ARB_WA_ID,
"Enable CNL AVC Encode ARB WA",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Enable/Disable CNL AVC Encode ARB WA for hang reproducing."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_VP9_ENCODE_ME_ENABLE_ID,
"VP9 Encode HME",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enables VP9 ME Encode."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_VP9_ENCODE_16xME_ENABLE_ID,
"VP9 Encode SuperHME",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enables VP9 16xME Encode."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_VP9_ENCODE_HUC_ENABLE_ID,
"VP9 Encode HUC Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Enables VP9 Huc."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENCODE_BRC_IN_USE_ID,
"Encode BRC In Use",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Report key to indicate if BRC is turned on"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_VP9_ENCODE_MULTIPASS_BRC_ENABLE_ID,
"VP9 Encode Multipass BRC Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enables VP9 Encode Multipass BRC."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_VP9_ENCODE_MULTIPASS_BRC_IN_USE_ID,
"VP9 Encode Multipass BRC In Use",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Report key to indicate if Multipass BRC is turned on."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_VP9_ENCODE_ADAPTIVE_REPAK_ENABLE_ID,
"VP9 Encode Adaptive RePAK Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Enables VP9 Encode Adaptive RePAK."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_VP9_ENCODE_ADAPTIVE_REPAK_IN_USE_ID,
"VP9 Encode Adaptive RePAK In Use",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Report key to indicate if Adaptive RePAK is turned on."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_VP9_ENCODE_SINGLE_PASS_DYS_ENABLE_ID,
"VP9 Encode Single Pass Dys Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Report key to indicate if Single Pass Dys is turned on."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_MEMNINJA_COUNTER_ID,
__MEDIA_USER_FEATURE_VALUE_MEMNINJA_COUNTER,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Reports out the internal allocation counter value. If this value is not 0, the test has a memory leak."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENCODE_ENABLE_CMD_INIT_HUC_ID,
"VDEnc CmdInitializer Huc Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Enable CmdInitializer HuC FW for HEVC/VP9 VDEnc."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_ENCODE_ENABLE_ID,
"HEVC Encode",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enables/Disables HEVC Encode."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_ENCODE_SECURE_INPUT_ID,
"Secure HEVC Encode",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Secure HEVC Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Secure HEVC Encode."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_ENCODE_ENABLE_MEDIARESET_TEST_ID,
"Enable MediaReset Test",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Enable HEVC Encode Media Reset Test, by default:0(disabled)."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_ENCODE_ENABLE_WP_SUPPORT_ID,
"Enable WP Support",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enable Weighted Prediction support in HEVC Encoder."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_ENCODE_MODE_ID,
"HEVC Encode Mode",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Reports out the internal HEVC encode mode."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_HEVC_ENCODE_ME_ENABLE_ID,
"HEVC Encode HME",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enables/Disables HME for HEVC."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_HEVC_ENCODE_16xME_ENABLE_ID,
"HEVC Encode SuperHME",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enables/Disables SuperHme for HEVC."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_HEVC_ENCODE_32xME_ENABLE_ID,
"HEVC Encode UltraHME",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Enables/Disables UHME for HEVC."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_HEVC_VDENC_16xME_ENABLE_ID,
"Enable HEVC VDEnc SuperHME",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enable/Disable SuperHme for HEVC VDEnc."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_HEVC_VDENC_32xME_ENABLE_ID,
"Enable HEVC VDEnc UltraHME",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enables/Disables UHME for HEVC VDEnc."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_ENCODE_26Z_ENABLE_ID,
"HEVC Encode 26Z Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enables/Disables 26Z for HEVC."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_ENCODE_REGION_NUMBER_ID,
"HEVC Encode WP Number",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"4",
"Enables/Disables WP for HEVC."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_ENCODE_NUM_B_KERNEL_SPLIT,
"HEVC Encode B Kernel Split Num",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Number of B kernel splits for HEVC."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_ENCODE_POWER_SAVING,
"HEVC Encode Power Save Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Enable power saving mode in HEVC Enc"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_ENCODE_NUM_8x8_INTRA_KERNEL_SPLIT,
"HEVC Encode 8x8 Intra Kernel Split Num",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Number of 8x8 intra kernel splits for HEVC."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_ENCODE_RDOQ_ENABLE_ID,
"HEVC RDOQ Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enable RDOQ for HEVC"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_ENCODE_IFRAME_RDOQ_ENABLE_ID,
"HEVC I Frame RDOQ Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enable I Frame RDOQ for HEVC"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_ENCODE_MULTIPASS_BRC_ENABLE_ID,
"HEVC Encode Multipass BRC Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enables HEVC Encode Multipass BRC."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_ENCODE_MULTIPASS_BRC_IN_USE_ID,
"HEVC Encode Multipass BRC In Use",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Report key to indicate if Multipass BRC is turned on."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENCODE_BRC_SOFTWARE_ID,
"BRC SW Simulation",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Used to enable BRC SW simulation Mode"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENCODE_BRC_SOFTWARE_PATH_ID,
"BRC SW Simulation Modules Path",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_STRING,
"0",
"Used to enable ENCODE BRC SW simulation Custom Path"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENCODE_BRC_SOFTWARE_IN_USE_ID,
"BRC SW Simulation In Use",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Used to report if ENCODE BRC SW Simulation is in use."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENCODE_LA_SOFTWARE_ID,
"LA SW Simulation",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Used to enable lookahead SW simulation Mode"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENCODE_LA_SOFTWARE_PATH_ID,
"LA SW Simulation Modules Path",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_STRING,
"0",
"Used to enable ENCODE lookahead SW simulation Custom Path"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENCODE_LA_SOFTWARE_IN_USE_ID,
"LA SW Simulation In Use",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Used to report if ENCODE lookahead SW Simulation is in use."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_VDENC_ACQP_ENABLE_ID,
"HEVC VDEnc ACQP Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Enable ACQP for HEVC VDEnc"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_VDENC_VQI_ENABLE_ID,
"HEVC VDEnc VQI Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enable VQI for HEVC VDEnc"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_FORCE_PAK_PASS_NUM_ID,
"Force PAK Pass Num",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Force dual pipe PAK pass number.by default = 0: not forcing"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_VDENC_ROUNDING_ENABLE_ID,
"HEVC VDEnc Rounding Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enable Rounding for HEVC VDEnc"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_VDENC_PAKOBJCMD_STREAMOUT_ENABLE_ID,
"HEVC VDEnc PakObjCmd StreamOut Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Enable PakObjCmd StreamOut for HEVC VDEnc"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_VDENC_LBCONLY_ENABLE_ID,
"HEVC VDEnc LBC Only Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Enable LBC Only for IBC for HEVC VDEnc"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_VDENC_PARTIAL_FRAME_UPDATE_ENABLE_ID,
"HEVC VDEnc Partial Frame Update Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Enable Partial Frame Update for HEVC VDEnc"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_NUM_THREADS_PER_LCU_ID,
"HEVC Num Threads Per LCU",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"8",
"Sets the number of threads per LCU. Currently used only for CNL."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_ENCODE_MDF_DISABLE_ID,
"HEVC Encode MDF Disable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Enables/Disables MDF for HEVC Encoder."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_CODEC_MMC_ENABLE_ID,
"Enable Codec MMC",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Enable Codec MMCD. (0: Disable codec MMCD; other values: enable codec MMCD)."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_DECODE_MMC_ENABLE_ID,
"Enable Decode MMC",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Decode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Enable Decode MMCD. (0: Disable decode MMCD; other values: enable decode MMCD)."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_ENCODE_MMC_ENABLE_ID,
"Enable Encode MMC",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Enable Encode MMCD. (0: Disable encode MMCD; other values: enable encode MMCD)."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_CODEC_MMC_IN_USE_ID,
"Codec MMC In Use",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Report key to indicate if codec MMC is turned on "),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_DECODE_MMC_IN_USE_ID,
"Decode MMC In Use",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Report key to indicate if decode MMC is turned on "),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_DECODE_MPEG2_MODE_ID,
"MPEG2 Decode Mode",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Report key to indicate if MPEG2 decode mode is turned on "),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_DECODE_VC1_MODE_ID,
"VC1 Decode Mode",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Report key to indicate if VC1 decode mode is turned on "),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_DECODE_AVC_MODE_ID,
"AVC Decode Mode",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Report key to indicate if AVC decode mode is turned on "),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_DECODE_JPEG_MODE_ID,
"JPEG Decode Mode",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Report key to indicate if JPEG decode mode is turned on "),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_DECODE_VP8_MODE_ID,
"VP8 Decode Mode",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Report key to indicate if VP8 decode mode is turned on "),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_DECODE_HEVC_MODE_ID,
"HEVC Decode Mode",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Report key to indicate if HEVC decode mode is turned on "),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_DECODE_VP9_MODE_ID,
"VP9 Decode Mode",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Report key to indicate if VP9 decode mode is turned on "),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_DECODE_HISTOGRAM_FROM_VEBOX_ID,
"Decode Histogram from VEBox",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Report key to indicate if decode histogram is from VEBox "),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_DECODE_EXTENDED_MMC_IN_USE_ID,
"Decode Extended MMC In Use",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Report key to indicate if decode extended MMC is turned on "),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_ENCODE_MMC_IN_USE_ID,
"Encode MMC In Use",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Report key to indicate if encode MMC is turned on "),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_ENCODE_EXTENDED_MMC_IN_USE_ID,
"Encode Extended MMC In Use",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Report key to indicate if encode extended MMC is turned on "),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENCODE_USED_VDBOX_NUM_ID,
"Media Encode Used VDBOX Number",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Media Encode Used VDBOX Number."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENCODE_ENABLE_COMPUTE_CONTEXT_ID,
"Enable Compute Context",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Enable Compute Context. default:0 disabled."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_DECODE_ENABLE_COMPUTE_CONTEXT_ID,
"Enable Compute Context",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Enable Compute Context. default:0 disabled."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_MMC_DEC_RT_COMPRESSIBLE_ID,
"Decode RT Compressible",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Report Key to indicate if the surface is MMCD capable (0: no; 1: yes)."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_MMC_DEC_RT_COMPRESSMODE_ID,
"Decode RT Compress Mode",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Report Key to indicate the MMCD compression mode of a surface "),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_MMC_ENC_RECON_COMPRESSIBLE_ID,
"Encode Recon Compressible",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Report Key to indicate if the surface is MMCD capable (0: no; 1: yes)."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_MMC_ENC_RECON_COMPRESSMODE_ID,
"Encode Recon Compress Mode",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Report Key to indicate the MMCD compression mode of a surface "),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_SSEU_SETTING_OVERRIDE_ID,
__MEDIA_USER_FEATURE_VALUE_SSEU_SETTING_OVERRIDE,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"-559038242", //0xDEADC0DE
"Override Slice/Sub-Slice/EU request"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_SLICE_SHUTDOWN_DEFAULT_STATE_ID,
"Slice Shutdown Default State",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Slice Shutdown default state."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_SLICE_SHUTDOWN_REQUEST_STATE_ID,
"Slice Shutdown Request State",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Slice Shutdown requested state ."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_SLICE_SHUTDOWN_RESOLUTION_THRESHOLD_ID,
"Slice Shutdown Resolution Threshold",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Slice Shutdown Resolution Threshold "),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_SLICE_SHUTDOWN_TARGET_USAGE_THRESHOLD_ID,
"Slice Shutdown Target Usage Threshold",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Slice Shutdown Target Usage Threshold "),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_SLICE_COUNT_SET_SUPPORT_ID,
"Slice Count Set Support",
__MEDIA_USER_FEATURE_SUBKEY_PERFORMANCE,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"General",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"Support Slice Count Set "),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_DYNAMIC_SLICE_SHUTDOWN_ID,
"Dynamic Slice Shutdown",
__MEDIA_USER_FEATURE_SUBKEY_PERFORMANCE,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"General",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Enables/Disables Dynamic Slice Shutdown "),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_MPEG2_SLICE_STATE_ENABLE_ID,
"Mpeg2 Encode Slice State Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Slice Shutdown related param for Mpeg2."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_MPEG2_ENCODE_BRC_DISTORTION_BUFFER_ENABLE_ID,
"Mpeg2 Encode BRC Distorion Buffer enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Enables/Disables BRC distorion buffer dump for MPEG2 Encoder"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_ENABLE_VDBOX_BALANCING_ID,
"Enable VDBox load balancing",
__MEDIA_USER_FEATURE_SUBKEY_PERFORMANCE,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"Enable balancing of VDBox load by KMD hint. (Default FALSE: disabled"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_NUMBER_OF_CODEC_DEVICES_ON_VDBOX1_ID,
"Num of Codec Devices on VDBOX1",
__MEDIA_USER_FEATURE_SUBKEY_REPORT,//read path and write path are the same
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Report number of Codec devices created on VDBox #1."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_NUMBER_OF_CODEC_DEVICES_ON_VDBOX2_ID,
"Num of Codec Devices on VDBOX2",
__MEDIA_USER_FEATURE_SUBKEY_REPORT,//read path and write path are the same
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Report number of Codec devices created on VDBox #2"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_VDI_MODE_ID,
__MEDIA_USER_FEATURE_VALUE_VDI_MODE,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"1",
"Always true for Gen7.5+"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_MEDIA_WALKER_MODE_ID,
__MEDIA_USER_FEATURE_VALUE_MEDIA_WALKER_MODE,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"-1",
"Media Walker Mode: Disabled(0), Repel(1), Dual(2), Quad(3), default(-1):Not Set"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_CSC_COEFF_PATCH_MODE_DISABLE_ID,
__MEDIA_USER_FEATURE_VALUE_CSC_COEFF_PATCH_MODE_DISABLE,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"FALSE if CSC coefficient setting mode is Patch mode, otherwise Curbe mode."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_VP8_HW_SCOREBOARD_ENABLE_ID,
"VP8 HW Scoreboard",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enables VP8 Encode HW Scoreboard Feature."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_VP8_ENCODE_ME_ENABLE_ID,
"VP8 Encode HME",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enables VP8 Encode HME Feature."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_VP8_ENCODE_16xME_ENABLE_ID,
"VP8 Encode SuperHME",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enables VP8 Encode SuperHME Feature"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_VP8_ENCODE_REPAK_ENABLE_ID,
"VP8 Encode Repak",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enables VP8 Encode Repak Feature."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_VP8_ENCODE_MULTIPASS_BRC_ENABLE_ID,
"VP8 Encode Multipass BRC Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enables VP8 Encode Multipass BRC."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_VP8_ENCODE_ADAPTIVE_REPAK_ENABLE_ID,
"VP8 Encode Adpative Repak Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enables VP8 Encode Adaptive Repak Feature."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_DISABLE_HEVC_REALTILE_DECODE_ID,
"Disable HEVC Real Tile Decode",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Decode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Disable HEVC real tile decode mode. Default is not disabled"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENABLE_HEVC_REALTILE_MULTI_PHASE_DECODE_ID,
"Enable HEVC Real Tile Multi Phase Decode",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Decode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"1",
"Enable HEVC real tile multi-phase decode mode. Default is enabled"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HCP_DECODE_USER_PIPE_NUM_ID,
"HCP Decode User Pipe Num",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"2",
"When vdbox >= 4, pipe num equals to the value set by user. (Default 2: use 2 pipes)"), //This is WA for scalability when vdbox num >= 4 because of kmd not ready
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_APOGEIOS_AV1D_ENABLE_ID,
"ApogeiosAv1dEnable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"1",
"Enable Apogeios av1 decode path. 1: enable, 0: disable. "),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_ENABLE_HEVC_DECODE_RT_FRAME_COUNT_ID,
"RT Decoded Count",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Reports out real tile decoded frame count."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_ENABLE_HEVC_DECODE_VT_FRAME_COUNT_ID,
"VT Decoded Count",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Reports out virtual tile decoded frame count."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_ENABLE_HEVC_DECODE_SP_FRAME_COUNT_ID,
"SP Decoded Count",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Reports out single pipe decoded frame count."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_AV1BTDLROWSTORECACHE_DISABLE_ID,
"DisableAv1BtdlRowstoreCache",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Decode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Disable AV1 BSD Rowstore Cache flag. 0: Enable, 1: Disable."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_AV1SMVLROWSTORECACHE_DISABLE_ID,
"DisableAv1SmvlRowstoreCache",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Decode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Disable AV1 SMV Rowstore Cache flag. 0: Enable, 1: Disable."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_AV1IPDLROWSTORECACHE_DISABLE_ID,
"DisableAv1IpdlRowstoreCache",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Decode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Disable AV1 IPD Rowstore Cache flag. 0: Enable, 1: Disable."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_AV1DFLYROWSTORECACHE_DISABLE_ID,
"DisableAv1DflyRowstoreCache",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Decode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Disable AV1 DFLY Rowstore Cache flag. 0: Enable, 1: Disable."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_AV1DFLUROWSTORECACHE_DISABLE_ID,
"DisableAv1DfluRowstoreCache",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Decode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Disable AV1 DFLU Rowstore Cache flag. 0: Enable, 1: Disable."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_AV1DFLVROWSTORECACHE_DISABLE_ID,
"DisableAv1DflvRowstoreCache",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Decode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Disable AV1 DFLV Rowstore Cache flag. 0: Enable, 1: Disable."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_AV1CDEFROWSTORECACHE_DISABLE_ID,
"DisableAv1CdefRowstoreCache",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Decode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Disable AV1 CDEF Rowstore Cache flag. 0: Enable, 1: Disable."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENABLE_AVP_SCALABILITY_DECODE_ID,
"Enable AVP Scalability Decode",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"Enable AVP Scalability decode mode. Default 0: Scalable Decode Mode "),
#if MOS_COMMAND_BUFFER_DUMP_SUPPORTED
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_DUMP_COMMAND_BUFFER_ENABLE_ID,
"Dump Command Buffer Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"If enabled, all of the command buffers submitted through MOS will be dumped (0: disabled, 1: to a file, 2: as a normal message)."),
#endif // MOS_COMMAND_BUFFER_DUMP_SUPPORTED
#if MOS_COMMAND_RESINFO_DUMP_SUPPORTED
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_DUMP_COMMAND_INFO_ENABLE_ID,
"Dump Command Info Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"If enabled, gpu command info will be dumped (0: disabled, 1: to a file)."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_DUMP_COMMAND_INFO_PATH_ID,
"Dump Command Info Path",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_STRING,
"",
"Path where command info will be dumped, for example: ./"),
#endif // MOS_COMMAND_RESINFO_DUMP_SUPPORTED
#if (_DEBUG || _RELEASE_INTERNAL)
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_MHW_BASE_VDENC_INTERFACE_ID,
"Use Mhw Base Vdenc Interface",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Mhw Base Vdenc Interface Active Flag"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_MEDIA_PREEMPTION_ENABLE_ID,
"Media Preemption Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Media",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1", // Enable media UMD preemption by default under release internal version and debug version for CNL+ even if there is no user feature setting.
"Enable/Disable Pre-emption for media"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_MDF_OVERRIDE_L3ALLOC_REG,
"MDF L3ALLOC register override",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Media",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0xff00ff00",
"Override L3 ALLOC register value in MDF"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_MDF_OVERRIDE_L3TCCNTRL_REG,
"MDF L3TCCNTRL register override",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Media",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0xff00ff00",
"Override L3 TCCNTRL register value in MDF"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_MDF_OVERRIDE_MOCS_INDEX,
"MDF MOCS index override",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Media",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"5",
"Override MOCS index value in MDF"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_MDF_FORCE_RAMODE,
"MDF Force RAMode",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Media",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Force GPU context be created in RAMode"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_GROUP_ID_ID,
"Group ID",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Sets the value of Group ID"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENCODE_VFE_MAX_THREADS_ID,
"Encode VFE Max Threads",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Used to set the max number of threads for VFE."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENCODE_VFE_MAX_THREADS_SCALING_ID,
"Encode VFE Max Threads For Scaling",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Used to set the max number of threads for VFE."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_AVC_FTQ_IN_USE_ID,
"AVC FTQ Enable In Use",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Used to report if FTQ is enabled."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_AVC_CAF_IN_USE_ID,
"AVC CAF Enable In Use",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Used to report if CAF is enabled."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENCODE_HW_WALKER_MODE_ID,
"Encode HW Walker Mode",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Used to set walker mode - useful in HSW. Not used for BDW+. ."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENCODE_L3_CACHE_CNTLREG_OVERRIDE_ID,
"Encode L3CNTLREG Override",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Used to override the L3CNTLREG value."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENCODE_L3_CACHE_CNTLREG2_OVERRIDE_ID,
"Encode L3CNTLREG2 Override",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Used to override the L3CNTLREG2 value for HSW. Not yet used for BDW+."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENCODE_L3_CACHE_CNTLREG3_OVERRIDE_ID,
"Encode L3CNTLREG3 Override",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Used to override the L3CNTLREG3 value for HSW. Not yet used for BDW+."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENCODE_L3_CACHE_SQCREG1_OVERRIDE_ID,
"Encode L3SQCREG1 Override",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Used to override the L3SQCREG1 value for HSW. Not yet used for BDW+."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENCODE_L3_CACHE_SQCREG4_OVERRIDE_ID,
"Encode L3SQCREG4 Override",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Used to override the L3SQCREG2 value for HSW. Not yet used for BDW+."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENCODE_L3_LRA_1_REG1_OVERRIDE_ID,
"L3LRA1RegOverride",
__MEDIA_USER_FEATURE_SUBKEY_PERFORMANCE,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Used to override the L3LRA1Reg value for HSW. Not yet used for BDW+."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_NULL_HW_ACCELERATION_ENABLE_ID,
"NullHWAccelerationEnable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"General",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"If enabled, go through the nullptr HW driver. (0: Disable, 1: Null HW enabled)."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_FORCE_VDBOX_ID,
"Force VDBOX",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Force the VDBox to be used. (Default 0: FORCE_VDBOX_NONE "),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_VDBOX_ID_USED,
"Used VDBOX ID",
__MEDIA_USER_FEATURE_SUBKEY_REPORT,//read path and write path are the same
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Which VDBox ID is used. (Default 0: Not used, 1: VDBox used. Each Hex symbol represents one VDBOX, e.g. bits[3:0] means VDBOX0, bits[7:4] means VDBOX1)."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_VDENC_IN_USE_ID,
"VDENC In Use",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Reports out if VDEnc is used."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_ENCODE_CSC_METHOD_ID,
"Encode CSC Method",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Reports out which CSC method is in use."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_ENCODE_RAW_TILE_ID,
"Encode Raw Surface Tile",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Reports out raw surface tile."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_ENCODE_RAW_FORMAT_ID,
"Encode Raw Surface Format",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Reports out raw surface format."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENCODE_CQM_QP_THRESHOLD_ID,
"CQM QP Threshold",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"40",
"QP threshuld for CQM enable/disable hint. Used by lookahead analysis kernel in LPLA."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_ISA_ASM_DEBUG_ENABLE_ID,
__MEDIA_USER_FEATURE_VALUE_ISA_ASM_DEBUG_ENABLE,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"TRUE for enabling GD2 kernel debug on VPHAL, otherwise disabling"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_ISA_ASM_DEBUG_SURF_BTI_ID,
__MEDIA_USER_FEATURE_VALUE_ISA_ASM_DEBUG_SURF_BTI,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"39",
"BTI for GD2 kernel debug surface on VPHAL."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ROWSTORE_CACHE_DISABLE_ID,
"Disable RowStore Cache",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Disable cache for RowStore buffer. "),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_INTRAROWSTORECACHE_DISABLE_ID,
"DisableIntraRowStoreCache",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Disable Intra prediction RowStore buffer cache. "),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_DEBLOCKINGFILTERROWSTORECACHE_DISABLE_ID,
"DisableDeblockingFilterRowStoreCache",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Disable Intra prediction RowStore buffer cache. "),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_BSDMPCROWSTORECACHE_DISABLE_ID,
"DisableBsdMpcRowStoreCache",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Disable decoder BSD/encoder MPC RowStore buffer cache. "),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_MPRROWSTORECACHE_DISABLE_ID,
"DisableMprRowStoreCache",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Decode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Disable MPR RowStore buffer cache. "),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_VDENCROWSTORECACHE_DISABLE_ID,
"DisableVDEncRowStoreCache",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"If enabled, disable rowstore cache for VDEnc."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_BREAK_IN_CODECHAL_CREATE_ID,
"Break In CodecHal_Create",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"If enabled, asserts in CodecHal_Create."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_MEDIASOLO_ENABLE_ID,
__MEDIA_USER_FEATURE_VALUE_MEDIASOLO_ENABLE,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"If enabled, triggers the MediaSolo code path in MOS for pre-si testing."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_STREAM_OUT_ENABLE_ID,
"Stream Out",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Decode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Enable decode stream out "),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_DECOMPRESS_DECODE_OUTPUT_ID,
"Decompress Decode Output",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Decode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Call Vebox decompress for decode output at decode endframe"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_DECOMPRESS_DECODE_SFC_OUTPUT_ID,
"Decompress Decode Sfc Output",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Decode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Call Vebox decompress for sfc output at decode endframe"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_CODECHAL_DEBUG_OUTPUT_DIRECTORY_ID,
"CodecHal Debug Output Directory",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_STRING,
"",
"Directory where all CodecHal debug interface can locate cfg file and dump."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_CODECHAL_DUMP_OUTPUT_DIRECTORY_ID,
"CodecHal Dump Output Directory",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_STRING,
"",
"CodecHal Dump Output Directory."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_MEDIA_DEBUG_CFG_GENERATION_ID,
"Media Debug Cfg Generation",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Enable the Generation of Media Debug Cfg file."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_CODECHAL_RDOQ_INTRA_TU_OVERRIDE_ID,
"RDOQ Intra TU Override",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Override Intra RDOQ TU setting."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_CODECHAL_RDOQ_INTRA_TU_DISABLE_ID,
"RDOQ Intra TU Disable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Disable RDOQ for Intra TU."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_CODECHAL_RDOQ_INTRA_TU_THRESHOLD_ID,
"RDOQ Intra TU Threshold",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"RDOQ Intra TU Threshold"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_CODECHAL_ENABLE_FAKE_HEADER_SIZE_ID,
"Fake Header Size Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Enable Fake Header Size"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_CODECHAL_FAKE_IFRAME_HEADER_SIZE_ID,
"Fake IFrame Header Size",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"128",
"Fake I Frame Header Size"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_CODECHAL_FAKE_PBFRAME_HEADER_SIZE_ID,
"Fake PBFrame Header Size",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"16",
"Fake P/B Frame Header Size"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_COMMAND_OVERRIDE_INPUT_FILE_PATH_ID,
"Command Override Input File Path",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Media",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_STRING,
"",
"Path of command override input file"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HUC_DEMO_KERNEL_ID, // Used to indicate which huc kernel to load for the Huc Demo feature
"Media Huc Demo kernel Id",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Media",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"3", // Default is 3 which is huc copy kernel
"Id of demo huc kernel to load"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_SIM_ENABLE_ID,
"Simulation Enable",
__MEDIA_USER_FEATURE_SUBKEY_PERMANENT,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"If enabled, specify this is in pre-si simulation/emulation mode."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_IS_CODEC_ROW_STORE_CACHE_ENABLED_ID,
"Codec Row Store Cache Enabled",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Reports out whether codec row store cache is enabled or not."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_FORCE_AV1_TILE_BASED_DECODE_ID,
"Force Av1 Tile Based Decode",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"If enabled, av1 decode will be forced to tile based submission mode."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_AV1_ERROR_STATUS_ADDR_VALUE_ID,
"Av1 Error Status Addr Value",
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"If value is not 0, HW detected error during av1 decode."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_DECODE_HISTOGRAM_DEBUG_ID,
"Decode Histogram Debug",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Decode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Enable Decode Histogram StreamOut debug. 0:Disable, 1:Enable"),
#endif // (_DEBUG || _RELEASE_INTERNAL
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_STATUS_REPORTING_ENABLE_ID,
"Status Reporting",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Decode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"1",
"Enable decode status reporting"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_SPLIT_SCREEN_DEMO_POSITION_ID,
__MEDIA_USER_FEATURE_VALUE_SPLIT_SCREEN_DEMO_POSITION,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Demo position: Disable(0), Left(1), Right(2), Top(3), Bottom(4)"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_SPLIT_SCREEN_DEMO_PARAMETERS_ID,
__MEDIA_USER_FEATURE_VALUE_SPLIT_SCREEN_DEMO_PARAMETERS,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Specify which VP features on/off for Demo mode"),
#if MOS_MESSAGES_ENABLED
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_MESSAGE_HLT_ENABLED_ID,
__MOS_USER_FEATURE_KEY_MESSAGE_HLT_ENABLED,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Enables the creation of a log file where all of the enabled messages will be written."),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_MESSAGE_HLT_OUTPUT_DIRECTORY_ID,
__MOS_USER_FEATURE_KEY_MESSAGE_HLT_OUTPUT_DIRECTORY,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_STRING,
"",
"Specifies the location of the log file where all of the enabled messages will be written."),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_MESSAGE_PRINT_ENABLED_ID,
__MOS_USER_FEATURE_KEY_MESSAGE_PRINT_ENABLED,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Prints out all of the enabled messages either to a debugger or to the Android log."),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_MESSAGE_OS_TAG_ID,
__MOS_USER_FEATURE_KEY_MESSAGE_OS_TAG,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
__MOS_USER_FEATURE_KEY_MESSAGE_DEFAULT_VALUE_STR,
"Enables messages and/or asserts for all of MOS. "),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_BY_SUB_COMPONENT_OS_ID,
__MOS_USER_FEATURE_KEY_BY_SUB_COMPONENT_OS,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"If enabled, will allow the subcomponent tags to take effect."),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_SUB_COMPONENT_OS_TAG_ID,
__MOS_USER_FEATURE_KEY_SUB_COMPONENT_OS_TAG,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT64,
"0",
"Allows different MOS subcomponents to have different debug levels."),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_MESSAGE_HW_TAG_ID,
"Mhw Message Tags",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
__MOS_USER_FEATURE_KEY_MESSAGE_DEFAULT_VALUE_STR,
"Enables messages and/or asserts for all of MHW. "),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_BY_SUB_COMPONENT_HW_ID,
"Mhw Tags By Sub Component",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"If enabled, will allow the subcomponent tags to take effect."),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_SUB_COMPONENT_HW_TAG_ID,
"Mhw Sub Components Tags",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT64,
"0",
"Allows different MHW subcomponents to have different debug levels."),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_MESSAGE_CODEC_TAG_ID,
__MOS_USER_FEATURE_KEY_MESSAGE_CODEC_TAG,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
__MOS_USER_FEATURE_KEY_MESSAGE_DEFAULT_VALUE_STR,
"Enables messages and/or asserts for all of Codec. "),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_BY_SUB_COMPONENT_CODEC_ID,
__MOS_USER_FEATURE_KEY_BY_SUB_COMPONENT_CODEC,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"If enabled, will allow the subcomponent tags to take effect."),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_SUB_COMPONENT_CODEC_TAG_ID,
__MOS_USER_FEATURE_KEY_SUB_COMPONENT_CODEC_TAG,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT64,
"0",
"Allows different Codec subcomponents to have different debug levels. "),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_MESSAGE_VP_TAG_ID,
__MOS_USER_FEATURE_KEY_MESSAGE_VP_TAG,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
__MOS_USER_FEATURE_KEY_MESSAGE_DEFAULT_VALUE_STR,
"Enables messages and/or asserts for all of VP"),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_BY_SUB_COMPONENT_VP_ID,
__MOS_USER_FEATURE_KEY_BY_SUB_COMPONENT_VP,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"If enabled, will allow the subcomponent tags to take effect."),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_SUB_COMPONENT_VP_TAG_ID,
__MOS_USER_FEATURE_KEY_SUB_COMPONENT_VP_TAG,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT64,
"0",
"Allows different VP subcomponents to have different debug levels."),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_MESSAGE_CP_TAG_ID,
__MOS_USER_FEATURE_KEY_MESSAGE_CP_TAG,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
__MOS_USER_FEATURE_KEY_MESSAGE_DEFAULT_VALUE_STR,
"Enables messages and/or asserts for all of CP"),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_BY_SUB_COMPONENT_CP_ID,
__MOS_USER_FEATURE_KEY_BY_SUB_COMPONENT_CP,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"If enabled, will allow the subcomponent tags to take effect."),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_SUB_COMPONENT_CP_TAG_ID,
__MOS_USER_FEATURE_KEY_SUB_COMPONENT_CP_TAG,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT64,
"0",
"Allows different CP subcomponents to have different debug levels. "),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_MESSAGE_DDI_TAG_ID,
__MOS_USER_FEATURE_KEY_MESSAGE_DDI_TAG,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
__MOS_USER_FEATURE_KEY_MESSAGE_DEFAULT_VALUE_STR,
"Enables messages and/or asserts for all of DDI"),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_BY_SUB_COMPONENT_DDI_ID,
__MOS_USER_FEATURE_KEY_BY_SUB_COMPONENT_DDI,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"If enabled, will allow the subcomponent tags to take effect."),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_SUB_COMPONENT_DDI_TAG_ID,
__MOS_USER_FEATURE_KEY_SUB_COMPONENT_DDI_TAG,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT64,
"0",
"Allows different MOS subcomponents to have different debug levels. "),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_MESSAGE_CM_TAG_ID,
__MOS_USER_FEATURE_KEY_MESSAGE_CM_TAG,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
__MOS_USER_FEATURE_KEY_MESSAGE_DEFAULT_VALUE_STR,
"Enables messages and/or asserts for all of CM "),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_BY_SUB_COMPONENT_CM_ID,
__MOS_USER_FEATURE_KEY_BY_SUB_COMPONENT_CM,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"If enabled, will allow the subcomponent tags to take effect."),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_SUB_COMPONENT_CM_TAG_ID,
__MOS_USER_FEATURE_KEY_SUB_COMPONENT_CM_TAG,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT64,
"0",
"Allows different CM subcomponents to have different debug levels. "),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_MESSAGE_SCALABILITY_TAG_ID,
__MOS_USER_FEATURE_KEY_MESSAGE_SCALABILITY_TAG,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
__MOS_USER_FEATURE_KEY_MESSAGE_DEFAULT_VALUE_STR,
"Enables messages and/or asserts for all of SCALABILITY "),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_BY_SUB_COMPONENT_SCALABILITY_ID,
__MOS_USER_FEATURE_KEY_BY_SUB_COMPONENT_SCALABILITY,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"If enabled, will allow the subcomponent tags to take effect."),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_SUB_COMPONENT_SCALABILITY_TAG_ID,
__MOS_USER_FEATURE_KEY_SUB_COMPONENT_SCALABILITY_TAG,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT64,
"0",
"Allows different SCALABILITY subcomponents to have different debug levels. "),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_MESSAGE_MMC_TAG_ID,
__MOS_USER_FEATURE_KEY_MESSAGE_MMC_TAG,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
__MOS_USER_FEATURE_KEY_MESSAGE_DEFAULT_VALUE_STR,
"Enables messages and/or asserts for all of MMC "),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_BY_SUB_COMPONENT_MMC_ID,
__MOS_USER_FEATURE_KEY_BY_SUB_COMPONENT_MMC,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"If enabled, will allow the subcomponent tags to take effect."),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_SUB_COMPONENT_MMC_TAG_ID,
__MOS_USER_FEATURE_KEY_SUB_COMPONENT_MMC_TAG,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT64,
"0",
"Allows different MMC subcomponents to have different debug levels. "),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_MESSAGE_MCPY_TAG_ID,
__MOS_USER_FEATURE_KEY_MESSAGE_MCPY_TAG,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
__MOS_USER_FEATURE_KEY_MESSAGE_DEFAULT_VALUE_STR,
"Enables messages and/or asserts for all of MediaCopy "),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_BY_SUB_COMPONENT_MCPY_ID,
__MOS_USER_FEATURE_KEY_BY_SUB_COMPONENT_MCPY,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"If enabled, will allow the subcomponent tags to take effect."),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_SUB_COMPONENT_MCPY_TAG_ID,
__MOS_USER_FEATURE_KEY_SUB_COMPONENT_MCPY_TAG,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT64,
"0",
"Allows different MediaCopy subcomponents to have different debug levels. "),
#endif // MOS_MESSAGES_ENABLED
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_SF_2_DMA_SUBMITS_ENABLE_ID,
"Enable HEVC SF 2 DMA Submits",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Decode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Specify if send HuC and HCP commands in one DMA buffer or two DMA buffer. "),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVCDATROWSTORECACHE_DISABLE_ID,
"DisableHevcDatRowStoreCache",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Decode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Decide if put the DatRowStore buffer to cache or driver allocated buffer. "),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVCDFROWSTORECACHE_DISABLE_ID,
"DisableHevcDfRowStoreCache",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Decode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Decide if put the DfRowStore buffer to cache or driver allocated buffer. "),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVCSAOROWSTORECACHE_DISABLE_ID,
"DisableHevcSaoRowStoreCache",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Decode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Decide if put the SAORowStore buffer to cache or driver allocated buffer."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_VP9_HVDROWSTORECACHE_DISABLE_ID,
"DisableVp9HvdRowStoreCache",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Decode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"VP9"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_VP9_DATROWSTORECACHE_DISABLE_ID,
"DisableVp9DatRowStoreCache",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Decode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"VP9"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_VP9_DFROWSTORECACHE_DISABLE_ID,
"DisableVp9DfRowStoreCache",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Decode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"VP9"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_DDI_DUMP_DIRECTORY_ID,
"DDI Dump Directory",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_STRING,
"",
"DDI DUMP DIR"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENCODE_DDI_DUMP_ENABLE_ID,
"Encode DDI Dump Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"DDI DUMP ENCODE Enable"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_MDF_ETW_ENABLE_ID,
__MEDIA_USER_FEATURE_VALUE_MDF_ETW_ENABLE,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MDF",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Enable MDF ETW Log"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_MDF_LOG_LEVEL_ID,
__MEDIA_USER_FEATURE_VALUE_MDF_LOG_LEVEL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MDF",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Enable MDF Log Level"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_MDF_UMD_ULT_ENABLE_ID,
__MEDIA_USER_FEATURE_VALUE_MDF_UMD_ULT_ENABLE,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MDF",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Enable MDF UMD ULT"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_MDF_CMD_DUMP_ENABLE_ID,
__MEDIA_USER_FEATURE_VALUE_MDF_CMD_DUMP_ENABLE,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MDF",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Enable MDF Command buffer Dump"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_MDF_CURBE_DUMP_ENABLE_ID,
__MEDIA_USER_FEATURE_VALUE_MDF_CURBE_DUMP_ENABLE,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MDF",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Enable MDF Curbe Dump"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_MDF_SURFACE_DUMP_ENABLE_ID,
__MEDIA_USER_FEATURE_VALUE_MDF_SURFACE_DUMP_ENABLE,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MDF",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Enable MDF Surface Dump"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_MDF_SURFACE_STATE_DUMP_ENABLE_ID,
__MEDIA_USER_FEATURE_VALUE_MDF_SURFACE_STATE_DUMP_ENABLE,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MDF",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Enable MDF Surface State Dump"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_MDF_CMD_DUMP_COUNTER_ID,
__MEDIA_USER_FEATURE_VALUE_MDF_CMD_DUMP_COUNTER,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MDF",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Record MDF Command Buffer Dump counter for multiple device create/destroy"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_MDF_SURFACE_STATE_DUMP_COUNTER_ID,
__MEDIA_USER_FEATURE_VALUE_MDF_SURFACE_STATE_DUMP_COUNTER,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MDF",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Record MDF Surface state Dump counter for multiple device create/destroy"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_MDF_INTERFACE_DESCRIPTOR_DATA_DUMP_ID,
__MEDIA_USER_FEATURE_VALUE_MDF_INTERFACE_DESCRIPTOR_DATA_DUMP,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MDF",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Enable MDF interface descriptor data dump"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_MDF_INTERFACE_DESCRIPTOR_DATA_COUNTER_ID,
__MEDIA_USER_FEATURE_VALUE_MDF_INTERFACE_DESCRIPTOR_DATA_COUNTER,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MDF",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Record MDF Interface descriptor data Dump counter for multiple device create/destroy"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_MDF_DUMPPATH_USER_ID,
__MEDIA_USER_FEATURE_VALUE_MDF_DUMPPATH_USER,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MDF",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_STRING,
"",
"MDF dump path specified by user"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_MDF_FORCE_EXECUTION_PATH_ID,
__MEDIA_USER_FEATURE_VALUE_MDF_FORCE_EXECUTION_PATH,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MDF",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"MDF execution path specified by user"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_MDF_MAX_THREAD_NUM_ID,
__MEDIA_USER_FEATURE_VALUE_MDF_MAX_THREAD_NUM,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MDF",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"MDF maximun thread number specified by user"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_MDF_FORCE_COHERENT_STATELESSBTI_ID,
__MEDIA_USER_FEATURE_VALUE_MDF_FORCE_COHERENT_STATELESSBTI,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MDF",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"MDF coherent stateless BTI specified by user"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_MDF_EMU_MODE_ENABLE_ID,
__MEDIA_USER_FEATURE_VALUE_MDF_EMU_MODE_ENABLE,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MDF",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"MDF EMU Enable"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_MDF_DEFAULT_CM_QUEUE_TYPE_ID,
"MDF Default Queue Type",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MDF",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Program default CM_QUEUE_TYPE for debug."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_MDF_CCS_USE_VE_INTERFACE,
"MDF CCS Use VE Interface",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MDF",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Switch to use mos virtual engine interface for compute CS."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_MDF_CCS_USE_VE_DEBUG_OVERRIDE,
"MDF CCS Use VE Debug Override",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MDF",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Set debug override for mos virtual engine interface for compute CS."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_MCPY_MODE_ID,
"MediaCopy Mode",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MCPY",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_STRING,
"",
"For Notify which Media Copy Engine used"),
MOS_DECLARE_UF_KEY(__VPHAL_VEBOX_OUTPUTPIPE_MODE_ID,
"VPOutputPipe Mode",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"For Notify which datapath Vebox used"),
MOS_DECLARE_UF_KEY(__VPHAL_VEBOX_FEATURE_INUSE_ID,
"VeBox Feature In use",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"For Notify which feature Vebox used"),
MOS_DECLARE_UF_KEY_DBGONLY(__VPHAL_RNDR_SSD_CONTROL_ID,
"SSD Control",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Slice Shutdown Control"),
MOS_DECLARE_UF_KEY_DBGONLY(__VPHAL_RNDR_SCOREBOARD_CONTROL_ID,
"SCOREBOARD Control",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"1",
"Software Scoreboard enable Control"),
MOS_DECLARE_UF_KEY_DBGONLY(__VPHAL_RNDR_CMFC_CONTROL_ID,
"CMFC Control",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"CM based FC enable Control"),
#if (_DEBUG || _RELEASE_INTERNAL)
MOS_DECLARE_UF_KEY_DBGONLY(__VPHAL_ENABLE_1K_1DLUT_ID,
"Enable 1K 1DLUT",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Enable 1K 1DLUT"),
MOS_DECLARE_UF_KEY_DBGONLY(__VPHAL_RNDR_FORCE_VP_DECOMPRESSED_OUTPUT_ID,
"FORCE VP DECOMPRESSED OUTPUT",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"FORCE VP DECOMPRESSED OUTPUT"),
MOS_DECLARE_UF_KEY(__VPHAL_DBG_SURF_DUMP_OUTFILE_KEY_NAME_ID,
"outfileLocation",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_STRING,
"",
"Surface Dump Outfile"),
MOS_DECLARE_UF_KEY(__VPHAL_DBG_SURF_DUMP_LOCATION_KEY_NAME_ID,
"dumpLocations",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_STRING,
"",
"VP Surface Dump Location"),
MOS_DECLARE_UF_KEY(__VPHAL_DBG_SURF_DUMP_MANUAL_TRIGGER_KEY_NAME_ID,
"VphalSurfaceDumpManualTrigger",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"-1",
"Manual trigger to start VP Surface Dump"),
MOS_DECLARE_UF_KEY(__VPHAL_DBG_SURF_DUMP_START_FRAME_KEY_NAME_ID,
"startFrame",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"VP Surface Dump Start Frame"),
MOS_DECLARE_UF_KEY(__VPHAL_DBG_SURF_DUMP_END_FRAME_KEY_NAME_ID,
"endFrame",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
MOS_USER_FEATURE_MAX_UINT32_STR_VALUE,
"VP Surface Dump End Frame"),
MOS_DECLARE_UF_KEY(__VPHAL_DBG_SURF_DUMPER_ENABLE_PLANE_DUMP,
"enablePlaneDump",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"VP Surface dump each plance seprately"),
MOS_DECLARE_UF_KEY(__VPHAL_DBG_SURF_DUMP_ENABLE_AUX_DUMP_ID,
"enableAuxDump",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"VP Surface dump aux data enable"),
MOS_DECLARE_UF_KEY(__VPHAL_DBG_SURF_DUMPER_RESOURCE_LOCK_ID,
"SurfaceDumperResourceLockError",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"VP Surface Dump: Locking Resource"),
MOS_DECLARE_UF_KEY(__VPHAL_DBG_STATE_DUMP_OUTFILE_KEY_NAME_ID,
"outfileLocation",
__MEDIA_USER_FEATURE_VALUE_VP_DBG_STATE_DUMP_LOCATION,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_STRING,
"",
"VP State Dump Output File"),
MOS_DECLARE_UF_KEY(__VPHAL_DBG_STATE_DUMP_LOCATION_KEY_NAME_ID,
"dumpLocations",
__MEDIA_USER_FEATURE_VALUE_VP_DBG_STATE_DUMP_LOCATION,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_STRING,
"",
"VP State Dump Location"),
MOS_DECLARE_UF_KEY(__VPHAL_DBG_STATE_DUMP_START_FRAME_KEY_NAME_ID,
"startFrame",
__MEDIA_USER_FEATURE_VALUE_VP_DBG_STATE_DUMP_LOCATION,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"VP State Dump Start Frame"),
MOS_DECLARE_UF_KEY(__VPHAL_DBG_STATE_DUMP_END_FRAME_KEY_NAME_ID,
"endFrame",
__MEDIA_USER_FEATURE_VALUE_VP_DBG_STATE_DUMP_LOCATION,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
MOS_USER_FEATURE_MAX_UINT32_STR_VALUE,
"VP State Dump End Frame"),
MOS_DECLARE_UF_KEY(__VPHAL_DBG_PARAM_DUMP_OUTFILE_KEY_NAME_ID,
"outxmlLocation",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_STRING,
"",
"VP Parameters Dump Outfile"),
MOS_DECLARE_UF_KEY(__VPHAL_DBG_PARAM_DUMP_START_FRAME_KEY_NAME_ID,
"startxmlFrame",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"1",
"VP Parameters Dump Start Frame"),
MOS_DECLARE_UF_KEY(__VPHAL_DBG_PARAM_DUMP_END_FRAME_KEY_NAME_ID,
"endxmlFrame",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"VP Parameters Dump End Frame"),
MOS_DECLARE_UF_KEY(__VPHAL_DBG_DUMP_OUTPUT_DIRECTORY_ID,
"Vphal Debug Dump Output Directory",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_STRING,
"",
"Vphal Debug Dump Output Directory"),
MOS_DECLARE_UF_KEY(__VPHAL_DBG_PARA_DUMP_ENABLE_SKUWA_DUMP_ID,
"enableSkuWaDump",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"VP parameter dump sku and wa info enable"),
MOS_DECLARE_UF_KEY_DBGONLY(__VPHAL_VEBOX_FORCE_VP_MEMCOPY_OUTPUTCOMPRESSED_ID,
"Force VP Memorycopy Outputcompressed",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"Force VP Memorycopy Outputcompressed"),
#endif
#if (_DEBUG || _RELEASE_INTERNAL)
MOS_DECLARE_UF_KEY(__VPHAL_ENABLE_SFC_NV12_P010_LINEAR_OUTPUT_ID,
"Enable SFC NV12 P010 Linear Output",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"Set SFC NV12/P010 Linear Output"),
#endif
MOS_DECLARE_UF_KEY_DBGONLY(__VPHAL_SET_SINGLE_SLICE_VEBOX_ID,
"SetSingleSliceVeboxEnable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
__MOS_USER_FEATURE_VALUE_SINGLE_SLICE_VEBOX_DEFAULT_VALUE,
"VP VEBOX: true for enabling single slice"),
MOS_DECLARE_UF_KEY(__VPHAL_BYPASS_COMPOSITION_ID,
"Bypass Composition",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"VP Bypass Composition Mode"),
MOS_DECLARE_UF_KEY(__VPHAL_VEBOX_DISABLE_SFC_ID,
"Disable SFC",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"For debugging purpose. true for disabling SFC"),
MOS_DECLARE_UF_KEY(__VPHAL_ENABLE_SUPER_RESOLUTION_ID,
"Enable VP Super Resolution",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"For debugging purpose. true for enabling VPP super resolution scaling"),
MOS_DECLARE_UF_KEY(__VPHAL_SUPER_RESOLUTION_MODE_ID,
"Super Resolution Mode",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"For debugging purpose. 0 is to use default setting, 1 means FP32 mode, 2 means Hybrid mode, 3 means FP16 mode"),
MOS_DECLARE_UF_KEY(__VPHAL_SUPER_RESOLUTION_SCENARIO_ID,
"Super Resolution Scenario",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"For debugging purpose. 0 is to use default setting, 1 means DN + SR"),
MOS_DECLARE_UF_KEY(__VPHAL_FORCE_TO_ENABLE_SR_ID,
"ForceToEnableSR",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"For debugging purpose. true to force enabling SR"),
MOS_DECLARE_UF_KEY(__VPHAL_ENABLE_SUPER_RESOLUTION_EDSR_ID,
"Enable VP Super Resolution EDSR",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"For debugging purpose. true for enabling VPP super resolution EDSR scaling"),
MOS_DECLARE_UF_KEY(__VPHAL_SUPER_RESOLUTION_EDSR_MODE_ID,
"Super Resolution EDSR Mode",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"For debugging purpose. 0 is to use default setting, 1 means 20 channels, 2 means 24 channels, 3 means 25 channels"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_SUPER_RESOLUTION_ENABLE_ID,
"SuperResolutionEnable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Eanble Super Resolution. 1: enable, 0: disable."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_SUPER_RESOLUTION_MODEL_ID,
"SuperResolutionModel",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Super Resolution Model. 1: EDSR, 2: FSR, 3: FSR*."),
MOS_DECLARE_UF_KEY(__VPHAL_ENABLE_VEBOX_MMC_DECOMPRESS_ID,
"Enable Vebox Decompress",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"For debugging purpose. Enable Vebox In-Place decompression"),
MOS_DECLARE_UF_KEY(__VPHAL_ENABLE_MMC_ID,
"Enable VP MMC",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"Enable memory compression"),
MOS_DECLARE_UF_KEY(__VPHAL_ENABLE_MMC_IN_USE_ID,
"VP MMC In Use",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"VP use memory compression"),
MOS_DECLARE_UF_KEY(__VPHAL_PRIMARY_SURFACE_COMPRESS_MODE_ID,
"VP Primary Surface Compress Mode",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"VP primary surface compress mode"),
MOS_DECLARE_UF_KEY(__VPHAL_PRIMARY_SURFACE_COMPRESSIBLE_ID,
"VP Primary Surface Compressible",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"VP primary surface compressible"),
MOS_DECLARE_UF_KEY(__VPHAL_RT_COMPRESS_MODE_ID,
"VP RT Compress Mode",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"VP render target compress mode"),
MOS_DECLARE_UF_KEY(__VPHAL_RT_COMPRESSIBLE_ID,
"VP RT Compressible",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"VP render target compressible"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_ENABLE_RENDER_ENGINE_MMC_ID,
"Enable Media RenderEngine MMC",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"Enable media render engine memory compression in media workload"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_DISABLE_MMC_ID,
"Disable MMC",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Media",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"Disable MMC for all components"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_FORCE_MMC_ON_ID,
"Force MMC Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Media",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"Disable MMC for all components"),
MOS_DECLARE_UF_KEY_DBGONLY(__VPHAL_VEBOX_DISABLE_TEMPORAL_DENOISE_FILTER_ID,
"Disable Temporal Denoise Filter",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"Temporal denoise filter disable flag"),
#if (_DEBUG || _RELEASE_INTERNAL)
MOS_DECLARE_UF_KEY_DBGONLY(__VPHAL_COMP_8TAP_ADAPTIVE_ENABLE_ID,
"8-TAP Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"VP Composition 8Tap Adaptive Enable"),
#endif
#if ((_DEBUG || _RELEASE_INTERNAL) && !EMUL)
MOS_DECLARE_UF_KEY(__VPHAL_RNDR_VEBOX_MODE_0_ID,
"VEBOX_MODE_0",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Render Vebox Mode 0"),
MOS_DECLARE_UF_KEY(__VPHAL_RNDR_VEBOX_MODE_0_TO_2_ID,
"VEBOX_MODE_0_TO_2",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Render Vebox Mode 0 to 2"),
MOS_DECLARE_UF_KEY(__VPHAL_RNDR_VEBOX_MODE_2_ID,
"VEBOX_MODE_2",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Render Vebox Mode 2"),
MOS_DECLARE_UF_KEY(__VPHAL_RNDR_VEBOX_MODE_2_TO_0_ID,
"VEBOX_MODE_2_TO_0",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Render Vebox Mode 2 to 0"),
#endif
#if (_DEBUG || _RELEASE_INTERNAL)
MOS_DECLARE_UF_KEY(__VPHAL_ENABLE_COMPUTE_CONTEXT_ID,
"VP Enable Compute Context",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"VP Enable Compute Context"),
MOS_DECLARE_UF_KEY(__VPHAL_DISPLAY_COLORIMETRIC_CONTROL_ID,
"VP Display Colorimetric Control",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"VP Display Colorimetric Control"),
#endif
MOS_DECLARE_UF_KEY_DBGONLY(__MOS_USER_FEATURE_KEY_VP_CAPS_FF_OVERRIDE_ID,
"VP_CAPS_FF_OVERRIDE",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"VP_CAPS_FF_OVERRIDE"),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_XML_AUTOGEN_ID,
__MOS_USER_FEATURE_KEY_XML_AUTOGEN,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Enable"),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_XML_FILEPATH_ID,
__MOS_USER_FEATURE_KEY_XML_FILEPATH,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_STRING,
__MOS_USER_FEATURE_KEY_XML_FILEPATH_LOCATION,
"Enable"),
MOS_DECLARE_UF_KEY(__MOS_USER_FEATURE_KEY_XML_DUMP_GROUPS_ID,
__MOS_USER_FEATURE_KEY_XML_DUMP_GROUPS,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_STRING,
"MOS",
"Enable"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_FORCE_VEBOX_ID,
"Force VEBOX",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Force the VEBox to be used. (Default 0: FORCE_VEBOX_NONE "),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_ENABLE_VEBOX_SCALABILITY_MODE_ID,
"Enable Vebox Scalability",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"TRUE for Enabling Vebox Scalability. (Default FALSE: disabled"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_VEBOX_SPLIT_RATIO_ID,
"Vebox Split Ratio",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"50",
"Vebox Scalability Split Ratio. (Default 50: 50 percent"),
/* codec gen11 based */
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HCP_DECODE_MODE_SWITCH_THRESHOLD1_ID,
"HCP Decode Mode Switch TH1",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Decode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Hcp Decode mode switch single pipe - 2 pipe"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HCP_DECODE_MODE_SWITCH_THRESHOLD2_ID,
"HCP Decode Mode Switch TH2",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Decode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Hcp Decode mode switch single pipe - 2/3 pipe"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_ENCODE_ENABLE_VE_DEBUG_OVERRIDE,
"Enable VE Debug Override",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT64,
"0",
"Enable VE Debug Override."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_ENCODE_ENABLE_HW_SEMAPHORE,
"Enable HW Semaphore",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enable HW Semaphore."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_ENCODE_ENABLE_VDBOX_HW_SEMAPHORE,
"Enable HEVC Per VDBOX HW Semaphore in GEN11",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"Enable HEVC Per VDBOX HW Semaphore in GEN11."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_ENCODE_ENABLE_HW_STITCH,
"HEVC Encode Enable HW Stitch",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"HEVC Encode Enable HW Stitch."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_ENCODE_SUBTHREAD_NUM_ID,
"HEVC Encode SubThread Number",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"2",
"Used to enable HEVC ENCODE SubThread Number in the ENC kernel."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_ENCODE_PAK_ONLY_ID,
"HEVC PAK Only Mode",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_STRING,
"",
"Set the PAK command/CU record folder name for HEVC encoder"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_VME_ENCODE_SSE_ENABLE_ID,
"HEVC Encode SSE Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Used to enable HEVC VME ENCODE SSE.(default 0:disabled)"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENCODE_DISABLE_SCALABILITY,
"Disable Media Encode Scalability",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Disable Media Encode Scalability."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_ENCODE_RDOQ_PERF_DISABLE_ID,
"Disable HEVC RDOQ Perf",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Encode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"1",
"HEVC"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_WATCHDOG_TIMER_THRESHOLD,
"Watchdog Timer Threshold",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Decode",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"120",
"Used to override default watchdog timer threshold"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENABLE_DECODE_VIRTUAL_ENGINE_ID,
"Enable Decode VE",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"1",
"TRUE for Enabling Decode Virtual Engine. (Default TRUE: enabled"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENABLE_DECODE_VE_CTXSCHEDULING_ID,
"Enable Decode VE CtxBasedScheduling",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"TRUE for Enabling Decode Virtual Engine context based scheduling. (Default false: disabled"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENABLE_LINUX_FRAME_SPLIT_ID,
"Enable Linux Frame Split",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"TRUE for Enabling Frame Split. (Default false: disabled"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENABLE_ENCODE_VIRTUAL_ENGINE_ID,
"Enable Encode VE",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"1",
"TRUE for Enabling Encode Virtual Engine. (Default TRUE: enabled"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENABLE_ENCODE_VE_CTXSCHEDULING_ID,
"Enable Encode VE CtxBasedScheduling",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"TRUE for Enabling Encode Virtual Engine context based scheduling. (Default false: disabled"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENABLE_VE_DEBUG_OVERRIDE_ID,
"Enable VE Debug Override",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"TRUE for Enabling KMD Virtual Engine Debug Override. (Default FALSE: not override"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_ENABLE_HCP_SCALABILITY_DECODE_ID,
"Enable HCP Scalability Decode",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"1",
"Enable HCP Scalability decode mode. (Default 1: Scalable Decode Mode "),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HCP_DECODE_ALWAYS_FRAME_SPLIT_ID,
"HCP Decode Always Frame Split",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"HCP Decode always does frame split instead of make decision based on LZ table. (Default 0: using LZ table "),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_SCALABILITY_OVERRIDE_SPLIT_WIDTH_IN_MINCB,
"Scalability Split Width In MinCb",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Override virtual tile scalability width. (Default 0: not overroded "),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_SCALABILITY_FE_SEPARATE_SUBMISSION_ENABLED_ID,
"FE Separate Submission Enabled",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0", //Disable FE separate submission by default. Will change it to "Enable" after proving it has performance enhancement.
"Enable FE separate submission in Scalability decode. (Default 0: Disable FE separate submission "),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_SCALABILITY_FE_SEPARATE_SUBMISSION_IN_USE_ID,
"FE Separate Submission In Use",
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Report FE separate submission is in use in Scalability decode. (Default 0: Disable FE separate submission "),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_VME_BRC_LTR_DISABLE_ID,
"HEVC VME BRC LTR Disable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"Disable long term reference in hevc vme brc. (Default 0: LTR Enable"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_VME_BRC_LTR_INTERVAL_ID,
"HEVC VME BRC LTR Interval",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"HEVC Vme encode BRC Long term reference interval. (Default 0: interval=0"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_VME_FORCE_SCALABILITY_ID,
"HEVC VME Force Scalability For Low Size",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"HEVC Vme encode force scalability for low (below 4K) resolution. (Default 0"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_HEVC_VDENC_SEMA_RESET_DELAY_ID,
"HEVC VDEnc Semaphore Reset Delay",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"15",
"Control the num of placeholder cmds which are used for the delay of VDEnc sync semaphore"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_SET_CMD_DEFAULT_PARS_FROM_FILES_ID,
"Set CMD Default Parameters From File",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"Enable to set cmd default parameters from file (Default 0)"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_CMD_PARS_FILES_DIRECORY_ID,
"CMD Parameters Input File Directory",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_STRING,
"",
"Set CMD Parameters Input File Directory"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_APOGEIOS_ENABLE_ID,
"ApogeiosEnable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Eanble Apogeios path. 1: enable, 0: disable."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_VPP_APOGEIOS_ENABLE_ID,
"VP Apogeios Enabled",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Eanble Apogeios path in VP PipeLine. 1: enabled, 0: disabled."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_ENABLE_UMD_OCA_ID,
__MEDIA_USER_FEATURE_VALUE_ENABLE_UMD_OCA,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"1",
"Enable UMD_OCA in media driver. This key is not valid on Linux."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_COUNT_FOR_OCA_BUFFER_LEAKED_ID,
__MEDIA_USER_FEATURE_VALUE_COUNT_FOR_OCA_BUFFER_LEAKED,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Reports out the count for OCA buffer leaked. This key is not valid on Linux."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_COUNT_FOR_OCA_1ST_LEVEL_BB_END_MISSED_ID,
__MEDIA_USER_FEATURE_VALUE_COUNT_FOR_OCA_1ST_LEVEL_BB_END_MISSED,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Reports out the count for OCA buffer which missed to call On1stLevelBBEnd. This key is not valid on Linux."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_COUNT_FOR_ADDITIONAL_OCA_BUFFER_ALLOCATED_ID,
__MEDIA_USER_FEATURE_VALUE_COUNT_FOR_ADDITIONAL_OCA_BUFFER_ALLOCATED,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Reports out the count for additional OCA buffer allocated. This key is not valid on Linux."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_OCA_STATUS_ID,
__MEDIA_USER_FEATURE_VALUE_OCA_STATUS,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Reports out the first OCA error. This key is not valid on Linux."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_OCA_ERROR_HINT_ID,
__MEDIA_USER_FEATURE_VALUE_OCA_ERROR_HINT,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Reports out the line number of first OCA error. This key is not valid on Linux."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_IS_INDIRECT_STATE_HEAP_INVALID_ID,
__MEDIA_USER_FEATURE_VALUE_IS_INDIRECT_STATE_HEAP_INVALID,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Report",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Reports out whether indirect state heap invalid. This key is not valid on Linux."),
#if (_DEBUG || _RELEASE_INTERNAL)
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_INIT_CP_OUTPUT_SURFACE_ID,
"Init CP Output Surface",
__MEDIA_USER_FEATURE_SUBKEY_PERMANENT,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Init CP output surface with protected 0."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_ALLOC_MEMORY_FAIL_SIMULATE_MODE_ID,
__MEDIA_USER_FEATURE_VALUE_ALLOC_MEMORY_FAIL_SIMULATE_MODE,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"MOS memory alloc fail simulate mode, 0-Disable, 1-Random, 2-Traverse."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_ALLOC_MEMORY_FAIL_SIMULATE_FREQ_ID,
__MEDIA_USER_FEATURE_VALUE_ALLOC_MEMORY_FAIL_SIMULATE_FREQ,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"MOS memory alloc fail simulate frequence."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_ALLOC_MEMORY_FAIL_SIMULATE_HINT_ID,
__MEDIA_USER_FEATURE_VALUE_ALLOC_MEMORY_FAIL_SIMULATE_HINT,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"MOS memory alloc fail simulate counter."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_OS_API_FAIL_SIMULATE_TYPE_ID,
__MEDIA_USER_FEATURE_VALUE_OS_API_FAIL_SIMULATE_TYPE,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"the OS API fail type to simulate"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_OS_API_FAIL_SIMULATE_MODE_ID,
__MEDIA_USER_FEATURE_VALUE_OS_API_FAIL_SIMULATE_MODE,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"MOS OS API fail simulate mode, 0-Disable, 1-Random, 2-Traverse."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_OS_API_FAIL_SIMULATE_FREQ_ID,
__MEDIA_USER_FEATURE_VALUE_OS_API_FAIL_SIMULATE_FREQ,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"MOS OS API fail simulate frequence."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_OS_API_FAIL_SIMULATE_HINT_ID,
__MEDIA_USER_FEATURE_VALUE_OS_API_FAIL_SIMULATE_HINT,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"MOS OS API fail simulate counter."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_MEDIA_TILE_ENCODING_1_DEFAULT_ID,
__MEDIA_USER_FEATURE_VALUE_MEDIA_TILE_ENCODING_1_DEFAULT,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"DDI Res tile as 1 used"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_TILE_ENCODING_1_INTERNAL_USED_ID,
__MEDIA_USER_FEATURE_VALUE_TILE_ENCODING_1_INTERNAL_USED,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Internal Res tile as 1 used"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_TILE_ENCODING_3_INTERNAL_USED_ID,
__MEDIA_USER_FEATURE_VALUE_TILE_ENCODING_3_INTERNAL_USED,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Internal Res tile as 3 used"),
#endif //(_DEBUG || _RELEASE_INTERNAL)
#if (_DEBUG || _RELEASE_INTERNAL)
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_ENABLE_GUC_SUBMISSION_ID,
"Enable Guc Submission",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"1",
"To decide if using guc submission."),
#endif //(_DEBUG || _RELEASE_INTERNAL)
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_PERF_UTILITY_TOOL_ENABLE_ID,
__MEDIA_USER_FEATURE_VALUE_PERF_UTILITY_TOOL_ENABLE,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Enable Perf Utility Tool. "),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_PERF_OUTPUT_DIRECTORY_ID,
__MEDIA_USER_FEATURE_VALUE_PERF_OUTPUT_DIRECTORY,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_STRING,
"",
" Perf Utility Tool Customize Output Directory. "),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_APO_MOS_PATH_ENABLE_ID,
"ApoMosEnable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Eanble mos Apogeios path. 1: enable, 0: disable."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_APOGEIOS_HEVCD_ENABLE_ID,
"ApogeiosHevcdEnable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Eanble Apogeios hevc decode path. 1: enable, 0: disable."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_APOGEIOS_AVCD_ENABLE_ID,
"ApogeiosAvcdEnable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Eanble Apogeios avc decode path. 1: enable, 0: disable."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_APOGEIOS_VP9D_ENABLE_ID,
"ApogeiosVp9dEnable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Eanble Apogeios VP9 decode path. 1: enable, 0: disable."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_APOGEIOS_MPEG2D_ENABLE_ID,
"ApogeiosMpeg2dEnable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"Codec",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Enable Apogeios mpeg2 decode path. 1: enable, 0: disable."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_RESOURCE_ADDR_DUMP_ENABLE_ID,
"Resource Addr Dump Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Eanble Apogeios Resource virtual address dump."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_RA_MODE_ENABLE_ID,
"RA Mode Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Eanble RA Mode. 1: enable, 0: disable."),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_INTER_FRAME_MEMORY_NINJA_START_COUNTER_ID,
"InterFrameNinjaStartCounter",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Inter frame ninja start counter"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_INTER_FRAME_MEMORY_NINJA_END_COUNTER_ID,
"InterFrameNinjaEndCounter",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Inter frame ninja counter"),
MOS_DECLARE_UF_KEY(__MEDIA_USER_FEATURE_VALUE_LOCAL_MEMORY_LEVEL_SWITCH_ID,
"EnableLocalMemoryLevelSwitch",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_UINT32,
"0",
"Enable local memory level switch."),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_NULLHW_ENABLE_ID,
"NULL HW Enable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_BOOL,
"0",
"Enable NULL HW or not"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_MOCKADAPTOR_PLATFORM_ID,
"MockAdaptor Platform",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"33",
"Sets the platform for MockAdaptor, default is tgllp"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_MOCKADAPTOR_STEPPING_ID,
"MockAdaptor Stepping",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_STRING,
"a0",
"Sets the platform stepping for MockAdaptor. (For example a0, b1, c0, etc)"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_MOCKADAPTOR_DEVICE_ID,
"MockAdaptor Device ID",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"MOS",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"39497",
"Device ID of mock device, default is 0x9A49"),
MOS_DECLARE_UF_KEY_DBGONLY(__MEDIA_USER_FEATURE_VALUE_RENDER_ENABLE_EUFUSION_ID,
"EUFusionEnable",
__MEDIA_USER_FEATURE_SUBKEY_INTERNAL,
__MEDIA_USER_FEATURE_SUBKEY_REPORT,
"VP",
MOS_USER_FEATURE_TYPE_USER,
MOS_USER_FEATURE_VALUE_TYPE_INT32,
"0",
"Enable EuFusion path. 1: enable, 0: disable."),
};
PMOS_USER_FEATURE_VALUE const MosUtilities::m_mosUserFeatureDescFields = MOSUserFeatureDescFields;
#if (_DEBUG || _RELEASE_INTERNAL)
uint32_t MosAllocMemoryFailSimulateMode;
uint32_t MosAllocMemoryFailSimulateFreq;
uint32_t MosAllocMemoryFailSimulateHint;
uint32_t MosAllocMemoryFailSimulateAllocCounter;
#define MEMORY_ALLOC_FAIL_SIMULATE_MODE_DEFAULT (0)
#define MEMORY_ALLOC_FAIL_SIMULATE_MODE_RANDOM (1)
#define MEMORY_ALLOC_FAIL_SIMULATE_MODE_TRAVERSE (2)
#define MIN_MEMORY_ALLOC_FAIL_FREQ (1) //max memory allcation fail rate 100%
#define MAX_MEMORY_ALLOC_FAIL_FREQ (10000) //min memory allcation fail rate 1/10000
#define MosAllocMemoryFailSimulationEnabled \
(MosAllocMemoryFailSimulateMode == MEMORY_ALLOC_FAIL_SIMULATE_MODE_RANDOM || \
MosAllocMemoryFailSimulateMode == MEMORY_ALLOC_FAIL_SIMULATE_MODE_TRAVERSE)
//!
//! \brief Init simulate random memory allocation fail flag
//! \details init MosSimulateRandomAllocMemoryFailFlag according user feature value:
//! __MEDIA_USER_FEATURE_VALUE_SIMULATE_RANDOM_ALLOC_MEMORY_FAIL
//! \param [in] mosCtx
//! os device ctx handle
//! \return void
//!
void MOS_InitAllocMemoryFailSimulateFlag(MOS_CONTEXT_HANDLE mosCtx)
{
MOS_USER_FEATURE_VALUE_DATA userFeatureValueData;
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
//default off for simulate random fail
MosAllocMemoryFailSimulateMode = MEMORY_ALLOC_FAIL_SIMULATE_MODE_DEFAULT;
MosAllocMemoryFailSimulateFreq = 0;
MosAllocMemoryFailSimulateHint = 0;
MosAllocMemoryFailSimulateAllocCounter = 0;
// Read Config : memory allocation failure simulate mode
MOS_ZeroMemory(&userFeatureValueData, sizeof(userFeatureValueData));
MOS_UserFeature_ReadValue_ID(
nullptr,
__MEDIA_USER_FEATURE_VALUE_ALLOC_MEMORY_FAIL_SIMULATE_MODE_ID,
&userFeatureValueData,
mosCtx);
if ((userFeatureValueData.u32Data == MEMORY_ALLOC_FAIL_SIMULATE_MODE_DEFAULT) ||
(userFeatureValueData.u32Data == MEMORY_ALLOC_FAIL_SIMULATE_MODE_RANDOM) ||
(userFeatureValueData.u32Data == MEMORY_ALLOC_FAIL_SIMULATE_MODE_TRAVERSE))
{
MosAllocMemoryFailSimulateMode = userFeatureValueData.u32Data;
MOS_OS_NORMALMESSAGE("Init MosSimulateAllocMemoryFailSimulateMode as %d \n ", MosAllocMemoryFailSimulateMode);
}
else
{
MosAllocMemoryFailSimulateMode = MEMORY_ALLOC_FAIL_SIMULATE_MODE_DEFAULT;
MOS_OS_NORMALMESSAGE("Invalid Alloc Memory Fail Simulate Mode from config: %d \n ", userFeatureValueData.u32Data);
}
// Read Config : memory allocation failure simulate frequence
MOS_ZeroMemory(&userFeatureValueData, sizeof(userFeatureValueData));
MOS_UserFeature_ReadValue_ID(
nullptr,
__MEDIA_USER_FEATURE_VALUE_ALLOC_MEMORY_FAIL_SIMULATE_FREQ_ID,
&userFeatureValueData,
mosCtx);
if ((userFeatureValueData.u32Data >= MIN_MEMORY_ALLOC_FAIL_FREQ) &&
(userFeatureValueData.u32Data <= MAX_MEMORY_ALLOC_FAIL_FREQ))
{
MosAllocMemoryFailSimulateFreq = userFeatureValueData.u32Data;
MOS_OS_NORMALMESSAGE("Init MosSimulateRandomAllocMemoryFailFreq as %d \n ", MosAllocMemoryFailSimulateFreq);
if (MosAllocMemoryFailSimulateMode == MEMORY_ALLOC_FAIL_SIMULATE_MODE_RANDOM)
{
srand((unsigned int)time(nullptr));
}
}
else
{
MosAllocMemoryFailSimulateFreq = 0;
MOS_OS_NORMALMESSAGE("Invalid Alloc Memory Fail Simulate Freq from config: %d \n ", userFeatureValueData.u32Data);
}
// Read Config : memory allocation failure simulate counter
MOS_ZeroMemory(&userFeatureValueData, sizeof(userFeatureValueData));
MOS_UserFeature_ReadValue_ID(
nullptr,
__MEDIA_USER_FEATURE_VALUE_ALLOC_MEMORY_FAIL_SIMULATE_HINT_ID,
&userFeatureValueData,
mosCtx);
if (userFeatureValueData.u32Data <= MosAllocMemoryFailSimulateFreq)
{
MosAllocMemoryFailSimulateHint = userFeatureValueData.u32Data;
MOS_OS_NORMALMESSAGE("Init MosAllocMemoryFailSimulateHint as %d \n ", MosAllocMemoryFailSimulateHint);
}
else
{
MosAllocMemoryFailSimulateHint = MosAllocMemoryFailSimulateFreq;
MOS_OS_NORMALMESSAGE("Set MosAllocMemoryFailSimulateHint as %d since INVALID CONFIG %d \n ", MosAllocMemoryFailSimulateHint, userFeatureValueData.u32Data);
}
}
bool MOS_SimulateAllocMemoryFail(
size_t size,
size_t alignment,
const char *functionName,
const char *filename,
int32_t line)
{
bool bSimulateAllocFail = false;
if (!MosAllocMemoryFailSimulationEnabled)
{
return false;
}
if (MosAllocMemoryFailSimulateMode == MEMORY_ALLOC_FAIL_SIMULATE_MODE_RANDOM)
{
int32_t Rn = rand();
MosAllocMemoryFailSimulateAllocCounter++;
if (Rn % MosAllocMemoryFailSimulateFreq == 1)
{
bSimulateAllocFail = true;
MOS_DEBUGMESSAGE(MOS_MESSAGE_LVL_CRITICAL, MOS_COMPONENT_OS, MOS_SUBCOMP_SELF, \
"Simulated Allocate Memory Fail (Rn=%d, SimulateAllocCounter=%d) for: functionName: %s, filename: %s, line: %d, size: %d, alignment: %d \n", \
Rn, MosAllocMemoryFailSimulateAllocCounter, functionName, filename, line, size, alignment);
}
else
{
bSimulateAllocFail = false;
}
}
else if (MosAllocMemoryFailSimulateMode == MEMORY_ALLOC_FAIL_SIMULATE_MODE_TRAVERSE)
{
if (MosAllocMemoryFailSimulateAllocCounter++ == MosAllocMemoryFailSimulateHint)
{
MOS_DEBUGMESSAGE(MOS_MESSAGE_LVL_CRITICAL, MOS_COMPONENT_OS, MOS_SUBCOMP_SELF, \
"Simulated Allocate Memory Fail (hint=%d) for: functionName: %s, filename: %s, line: %d, size: %d \n", \
MosAllocMemoryFailSimulateHint, functionName, filename, line, size, alignment);
bSimulateAllocFail = true;
}
else
{
bSimulateAllocFail = false;
}
}
else
{
MOS_OS_NORMALMESSAGE("Invalid MosAllocMemoryFailSimulateMode: %d \n ", MosAllocMemoryFailSimulateMode);
bSimulateAllocFail = false;
}
return bSimulateAllocFail;
}
#endif //(_DEBUG || _RELEASE_INTERNAL)
//!
//! \brief Wrapper for user feature value string free(). Performs error checking.
//! \details Wrapper for user feature value string free(). Performs error checking.
//! \param PMOS_USER_FEATURE_VALUE_STRING pUserString
//! [in] Pointer to the string structure with memory to be freed
//! \return void
//!
void MOS_Free_UserFeatureValueString(PMOS_USER_FEATURE_VALUE_STRING pUserString)
{
if (pUserString != nullptr)
{
if (pUserString->uSize > 0)
{
if (pUserString->pStringData)
{
MOS_FreeMemAndSetNull(pUserString->pStringData);
}
pUserString->uSize = 0;
}
}
}
//!
//! \brief Allocates aligned memory and performs error checking
//! \details Wrapper for aligned_malloc(). Performs error checking.
//! It increases memory allocation counter variable
//! MosMemAllocCounter for checking memory leaks.
//! \param size_t size
//! [in] Size of memorry to be allocated
//! \param size_t alignment
//! [in] alignment
//! \return void *
//! Pointer to allocated memory
//!
#if MOS_MESSAGES_ENABLED
void *MOS_AlignedAllocMemoryUtils(
size_t size,
size_t alignment,
const char *functionName,
const char *filename,
int32_t line)
#else
void *MOS_AlignedAllocMemory(
size_t size,
size_t alignment)
#endif // MOS_MESSAGES_ENABLED
{
#if MOS_MESSAGES_ENABLED
return MosUtilities::MosAlignedAllocMemoryUtils(size, alignment, functionName, filename, line);
#else
return MosUtilities::MosAlignedAllocMemory(size, alignment);
#endif
}
//!
//! \brief Wrapper for aligned_free(). Performs error checking.
//! \details Wrapper for aligned_free() - Free a block of memory that was allocated by MOS_AlignedAllocMemory.
//! Performs error checking.
//! It decreases memory allocation counter variable
//! MosMemAllocCounter for checking memory leaks.
//! \param void *ptr
//! [in] Pointer to the memory to be freed
//! \return void
//!
#if MOS_MESSAGES_ENABLED
void MOS_AlignedFreeMemoryUtils(
void *ptr,
const char *functionName,
const char *filename,
int32_t line)
#else
void MOS_AlignedFreeMemory(void *ptr)
#endif // MOS_MESSAGES_ENABLED
{
#if MOS_MESSAGES_ENABLED
return MosUtilities::MosAlignedFreeMemoryUtils(ptr, functionName, filename, line);
#else
return MosUtilities::MosAlignedFreeMemory(ptr);
#endif
}
//!
//! \brief Allocates memory and performs error checking
//! \details Wrapper for malloc(). Performs error checking.
//! It increases memory allocation counter variable
//! MosMemAllocCounter for checking memory leaks.
//! \param size_t size
//! [in] Size of memorry to be allocated
//! \return void *
//! Pointer to allocated memory
//!
#if MOS_MESSAGES_ENABLED
void *MOS_AllocMemoryUtils(
size_t size,
const char *functionName,
const char *filename,
int32_t line)
#else
void *MOS_AllocMemory(size_t size)
#endif // MOS_MESSAGES_ENABLED
{
#if MOS_MESSAGES_ENABLED
return MosUtilities::MosAllocMemoryUtils(size, functionName, filename, line);
#else
return MosUtilities::MosAllocMemory(size);
#endif
}
//!
//! \brief Allocates and fills memory with 0
//! \details Wrapper for malloc(). Performs error checking,
//! and fills the allocated memory with 0.
//! It increases memory allocation counter variable
//! MosMemAllocCounter for checking memory leaks.
//! \param size_t size
//! [in] Size of memorry to be allocated
//! \return void *
//! Pointer to allocated memory
//!
#if MOS_MESSAGES_ENABLED
void *MOS_AllocAndZeroMemoryUtils(
size_t size,
const char *functionName,
const char *filename,
int32_t line)
#else
void *MOS_AllocAndZeroMemory(size_t size)
#endif // MOS_MESSAGES_ENABLED
{
#if MOS_MESSAGES_ENABLED
return MosUtilities::MosAllocAndZeroMemoryUtils(size, functionName, filename, line);
#else
return MosUtilities::MosAllocAndZeroMemory(size);
#endif
}
//!
//! \brief Reallocate memory
//! \details Wrapper for realloc(). Performs error checking.
//! It modifies memory allocation counter variable
//! MosMemAllocCounter for checking memory leaks.
//! \param [in] ptr
//! Pointer to be reallocated
//! \param [in] new_size
//! Size of memory to be allocated
//! \return void *
//! Pointer to allocated memory
//!
#if MOS_MESSAGES_ENABLED
void *MOS_ReallocMemoryUtils(
void *ptr,
size_t newSize,
const char *functionName,
const char *filename,
int32_t line)
#else
void *MOS_ReallocMemory(
void *ptr,
size_t newSize)
#endif // MOS_MESSAGES_ENABLED
{
#if MOS_MESSAGES_ENABLED
return MosUtilities::MosReallocMemoryUtils(ptr, newSize, functionName, filename, line);
#else
return MosUtilities::MosReallocMemory(ptr, newSize);
#endif
}
//!
//! \brief Wrapper for free(). Performs error checking.
//! \details Wrapper for free(). Performs error checking.
//! It decreases memory allocation counter variable
//! MosMemAllocCounter for checking memory leaks.
//! \param void *ptr
//! [in] Pointer to the memory to be freed
//! \return void
//!
#if MOS_MESSAGES_ENABLED
void MOS_FreeMemoryUtils(
void *ptr,
const char *functionName,
const char *filename,
int32_t line)
#else
void MOS_FreeMemory(void *ptr)
#endif // MOS_MESSAGES_ENABLED
{
#if MOS_MESSAGES_ENABLED
return MosUtilities::MosFreeMemoryUtils(ptr, functionName, filename, line);
#else
return MosUtilities::MosFreeMemory(ptr);
#endif
}
//!
//! \brief Wrapper to set a block of memory with zeros.
//! \details Wrapper to set a block of memory with zeros.
//! \param void *pDestination
//! [in] A pointer to the starting address of the memory
//! block to fill with zeros.
//! \param size_t stLength
//! [in] Size of the memory block in bytes to be filled
//! \return void
//!
void MOS_ZeroMemory(void *pDestination, size_t stLength)
{
MOS_OS_ASSERT(pDestination != nullptr);
if(pDestination != nullptr)
{
memset(pDestination, 0, stLength);
}
}
//!
//! \brief Wrapper to set a block of memory with a specified value.
//! \details Wrapper to set a block of memory with a specified value.
//! \param void *pDestination
//! [in] A pointer to the starting address of the memory
//! block to fill with specified value bFill
//! \param size_t stLength
//! [in] Size of the memory block in bytes to be filled
//! \param uint8_t bFill
//! [in] The byte value with which to fill the memory block
//! \return void
//!
void MOS_FillMemory(void *pDestination, size_t stLength, uint8_t bFill)
{
MOS_OS_ASSERT(pDestination != nullptr);
if(pDestination != nullptr)
{
memset(pDestination, bFill, stLength);
}
}
/***************************************************************************|
| |
| File I/O Functions |
| |
****************************************************************************/
//!
//! \brief Allocate a buffer and read contents from a file into this buffer
//! \details Allocate a buffer and read contents from a file into this buffer
//! \param const char *pFilename
//! [in] Pointer to the filename from which to read
//! \param uint32_t *lpNumberOfBytesRead,
//! [out] pointer to return the number of bytes read
//! \param void ** ppReadBuffer
//! [out] Pointer to return the buffer pointer where
//! the contents from the file are read to
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
MOS_STATUS MOS_ReadFileToPtr(
const char *pFilename,
uint32_t *lpNumberOfBytesRead,
void **ppReadBuffer)
{
HANDLE hFile;
void *lpBuffer;
uint32_t fileSize;
uint32_t bytesRead;
MOS_STATUS eStatus;
*ppReadBuffer = nullptr;
*lpNumberOfBytesRead = 0;
eStatus = MOS_CreateFile(&hFile, (char *)pFilename, O_RDONLY);
if (eStatus != MOS_STATUS_SUCCESS)
{
MOS_OS_ASSERTMESSAGE("Failed to open file '%s'.", pFilename);
return eStatus;
}
eStatus = MOS_GetFileSize(hFile, &fileSize, nullptr);
if (eStatus != MOS_STATUS_SUCCESS)
{
MOS_OS_ASSERTMESSAGE("Failed to get size of file '%s'.", pFilename);
MOS_CloseHandle(hFile);
return eStatus;
}
lpBuffer = MOS_AllocAndZeroMemory(fileSize);
if (lpBuffer == nullptr)
{
MOS_OS_ASSERTMESSAGE("Failed to allocate memory.");
MOS_CloseHandle(hFile);
return MOS_STATUS_NO_SPACE;
}
if((eStatus = MOS_ReadFile(hFile, lpBuffer, fileSize, &bytesRead, nullptr)) != MOS_STATUS_SUCCESS)
{
MOS_OS_ASSERTMESSAGE("Failed to read from file '%s'.", pFilename);
MOS_CloseHandle(hFile);
MOS_FreeMemory(lpBuffer);
lpBuffer = nullptr;
return eStatus;
}
MOS_CloseHandle(hFile);
*lpNumberOfBytesRead = bytesRead;
*ppReadBuffer = lpBuffer;
return eStatus;
}
//!
//! \brief Writes contents of buffer into a file
//! \details Writes contents of buffer into a file
//! \param const char *pFilename
//! [in] Pointer to the filename to write the contents to
//! \param void *lpBuffer
//! [in] Pointer to the buffer whose contents will be written
//! to the file
//! \param uint32_t writeSize
//! [in] Number of bytes to write to the file
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
MOS_STATUS MOS_WriteFileFromPtr(
const char *pFilename,
void *lpBuffer,
uint32_t writeSize)
{
HANDLE hFile;
uint32_t bytesWritten;
MOS_STATUS eStatus;
MOS_OS_CHK_NULL(pFilename);
MOS_OS_CHK_NULL(lpBuffer);
if (writeSize == 0)
{
MOS_OS_ASSERTMESSAGE("Attempting to write 0 bytes to a file");
eStatus = MOS_STATUS_INVALID_PARAMETER;
goto finish;
}
bytesWritten = 0;
eStatus = MOS_CreateFile(&hFile, (char *)pFilename, O_WRONLY|O_CREAT);
if (eStatus != MOS_STATUS_SUCCESS)
{
MOS_OS_ASSERTMESSAGE("Failed to open file '%s'.", pFilename);
goto finish;
}
if((eStatus = MOS_WriteFile(hFile, lpBuffer, writeSize, &bytesWritten, nullptr)) != MOS_STATUS_SUCCESS)
{
MOS_OS_ASSERTMESSAGE("Failed to write to file '%s'.", pFilename);
MOS_CloseHandle(hFile);
goto finish;
}
MOS_CloseHandle(hFile);
finish:
return eStatus;
}
//!
//! \brief Appends at the end of File
//! \details Appends at the end of File
//! \param const char *pFilename
//! [in] Pointer to the filename to append the contents to
//! \param void *pData
//! [in] Pointer to the buffer whose contents will be appeneded
//! to the file
//! \param uint32_t dwSize
//! [in] Number of bytes to append to the file
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
MOS_STATUS MOS_AppendFileFromPtr(
const char *pFilename,
void *pData,
uint32_t dwSize)
{
MOS_STATUS eStatus;
HANDLE hFile;
uint32_t dwWritten;
//------------------------------
MOS_OS_ASSERT(pFilename);
MOS_OS_ASSERT(pData);
//------------------------------
dwWritten = 0;
eStatus = MOS_CreateFile(&hFile, (char *)pFilename, O_WRONLY | O_CREAT | O_APPEND);
if (eStatus != MOS_STATUS_SUCCESS)
{
MOS_OS_ASSERTMESSAGE("Failed to open file '%s'.", pFilename);
return eStatus;
}
eStatus = MOS_SetFilePointer(hFile, 0, nullptr, SEEK_END);
if (eStatus != MOS_STATUS_SUCCESS)
{
MOS_OS_ASSERTMESSAGE("Failed to set file pointer'%s'.", pFilename);
MOS_CloseHandle(hFile);
return eStatus;
}
// Write the file
if((eStatus = MOS_WriteFile(hFile, pData, dwSize, &dwWritten, nullptr)) != MOS_STATUS_SUCCESS)
{
MOS_OS_ASSERTMESSAGE("Failed to write to file '%s'.", pFilename);
MOS_CloseHandle(hFile);
return eStatus;
}
MOS_CloseHandle(hFile);
return eStatus;
}
/*****************************************************************************
|
| USER FEATURE Functions
|
*****************************************************************************/
#if (_DEBUG || _RELEASE_INTERNAL)
//!
//! \brief Generate a User Feature Keys XML file according to user feature keys table in MOS
//! \details Generate a User Feature Keys XML files according to MOSUserFeatureDescFields
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
MOS_FUNC_EXPORT MOS_STATUS MOS_EXPORT_DECL DumpUserFeatureKeyDefinitionsMedia()
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
// Init MOS User Feature Key from mos desc table
MOS_OS_CHK_STATUS(MOS_DeclareUserFeatureKeysForAllDescFields());
MOS_OS_CHK_STATUS(MOS_GenerateUserFeatureKeyXML(nullptr));
finish:
return eStatus;
}
#endif
//!
//! \brief Write one user feature key into XML file
//! \details Write one user feature key into XML file
//! \param [out] keyValueMap
//! Unused in this function
//! \param [in] pUserFeature
//! Pointer to User Feature Value that is needed to be written
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
MOS_STATUS MOS_WriteOneUserFeatureKeyToXML(MOS_USER_FEATURE_VALUE_MAP *keyValueMap, PMOS_USER_FEATURE_VALUE pUserFeature)
{
char sOutBuf[MOS_USER_CONTROL_MAX_DATA_SIZE];
char ValueType[MAX_USER_FEATURE_FIELD_LENGTH];
char KeyPath[MOS_USER_CONTROL_MAX_DATA_SIZE];
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
//------------------------------
MOS_UNUSED(keyValueMap);
MOS_OS_ASSERT(pUserFeature);
//------------------------------
switch (pUserFeature->Type)
{
case MOS_USER_FEATURE_TYPE_USER:
MOS_SecureStringPrint(
KeyPath,
sizeof(KeyPath),
sizeof(KeyPath),
"UFINT\\%s",
pUserFeature->pcPath);
break;
case MOS_USER_FEATURE_TYPE_SYSTEM:
MOS_SecureStringPrint(
KeyPath,
sizeof(KeyPath),
sizeof(KeyPath),
"UFEXT\\%s",
pUserFeature->pcPath);
break;
default:
MOS_SecureStringPrint(
KeyPath,
sizeof(KeyPath),
sizeof(KeyPath),
"%s",pUserFeature->pcPath);
break;
}
switch (pUserFeature->ValueType)
{
case MOS_USER_FEATURE_VALUE_TYPE_BOOL:
MOS_SecureStringPrint(
ValueType,
sizeof(ValueType),
sizeof(ValueType),
"bool");
break;
case MOS_USER_FEATURE_VALUE_TYPE_FLOAT:
case MOS_USER_FEATURE_VALUE_TYPE_UINT32:
case MOS_USER_FEATURE_VALUE_TYPE_INT32:
MOS_SecureStringPrint(
ValueType,
sizeof(ValueType),
sizeof(ValueType),
"dword");
break;
case MOS_USER_FEATURE_VALUE_TYPE_UINT64:
case MOS_USER_FEATURE_VALUE_TYPE_INT64:
MOS_SecureStringPrint(
ValueType,
sizeof(ValueType),
sizeof(ValueType),
"qword");
break;
case MOS_USER_FEATURE_VALUE_TYPE_MULTI_STRING:
case MOS_USER_FEATURE_VALUE_TYPE_STRING:
MOS_SecureStringPrint(
ValueType,
sizeof(ValueType),
sizeof(ValueType),
"string");
break;
default:
MOS_SecureStringPrint(
ValueType,
sizeof(ValueType),
sizeof(ValueType),
"unknown");
break;
}
memset(
sOutBuf,
0,
sizeof(sOutBuf));
MOS_SecureStringPrint(
sOutBuf,
sizeof(sOutBuf),
sizeof(sOutBuf),
" <Key name=\"%s\" type=\"%s\" location=\"%s\" defaultval=\"%s\" description=\"%s\" />\n",
pUserFeature->pValueName,
ValueType,
KeyPath,
pUserFeature->DefaultValue,
pUserFeature->pcDescription);
MOS_AppendFileFromPtr(
gcXMLFilePath,
sOutBuf,
(uint32_t)strlen(sOutBuf));
return eStatus;
}
//!
//! \brief Write one User Feature Group into XML file
//! \details Write one User Feature Group into XML file
//! \param MOS_USER_FEATURE_VALUE UserFeatureFilter
//! [in] Pointer to User Feature Value filter that contains the targeted group
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
MOS_STATUS MOS_WriteOneUserFeatureGroupToXML(MOS_USER_FEATURE_VALUE UserFeatureFilter)
{
char sOutBuf[MAX_USER_FEATURE_FIELD_LENGTH];
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
// Group Header Start
memset(
sOutBuf,
0,
sizeof(sOutBuf));
MOS_SecureStringPrint(
sOutBuf,
sizeof(sOutBuf),
sizeof(sOutBuf),
" <Group name=\"%s\">\n",
UserFeatureFilter.pcGroup);
eStatus = MOS_AppendFileFromPtr(
gcXMLFilePath,
sOutBuf,
(uint32_t)strlen(sOutBuf));
// Group User Feature Keys
eStatus = MOS_GetItemFromMOSUserFeatureDescField(
MOSUserFeatureDescFields,
__MOS_USER_FEATURE_KEY_MAX_ID,
__MOS_USER_FEATURE_KEY_MAX_ID,
gc_UserFeatureKeysMap,
&MOS_WriteOneUserFeatureKeyToXML,
&UserFeatureFilter);
// Group Header End
memset(
sOutBuf,
0,
sizeof(sOutBuf));
MOS_SecureStringPrint(
sOutBuf,
sizeof(sOutBuf),
sizeof(sOutBuf),
" </Group>\n",
UserFeatureFilter.pcGroup);
eStatus = MOS_AppendFileFromPtr(
gcXMLFilePath,
sOutBuf,
(uint32_t)strlen(sOutBuf));
return eStatus;
}
MOS_STATUS MOS_GenerateUserFeatureKeyXML(MOS_CONTEXT_HANDLE mosCtx)
{
return MosUtilities::MosGenerateUserFeatureKeyXML(mosCtx);
}
//!
//! \brief Set the Multi String Value to Settings Data
//! \details Set the Multi String Value to Settings Data
//! It parses the given multi string value,
//! assign UserFeatureValue's multistring data
//! with pointers to the strings
//! \param PMOS_USER_FEATURE_VALUE_DATA pFeatureData
//! [out] Pointer to User Feature Data
//! \param void *pvData
//! [in] Pointer to the multi string value
//! \param uint32_t dwSize
//! [in] Size of the multi string value
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
static MOS_STATUS MOS_UserFeature_SetMultiStringValue(
PMOS_USER_FEATURE_VALUE_DATA pFeatureData,
uint32_t dwSize)
{
PMOS_USER_FEATURE_VALUE_STRING pStrings;
uint32_t uiNumStrings;
uint32_t ui;
char *pData;
char *pCurData;
uint32_t dwLen;
uint32_t dwPos;
MOS_OS_ASSERT(pFeatureData);
MOS_OS_ASSERT(dwSize);
pStrings = pFeatureData->MultiStringData.pStrings;
pData = pFeatureData->MultiStringData.pMultStringData;
dwPos = 0;
uiNumStrings = 0;
MOS_OS_ASSERT(pStrings);
MOS_OS_ASSERT(pData);
// Find number of strings in the multi string array
do
{
pCurData = pData + dwPos;
dwLen = (uint32_t)strlen(pCurData);
if (dwLen == 0)
{
MOS_OS_NORMALMESSAGE("Invalid user feature key entry.");
return MOS_STATUS_INVALID_PARAMETER;
}
uiNumStrings++;
dwPos += dwLen + 1;
if (dwPos >= (dwSize - 1))
{
// last entry
break;
}
} while (true);
// Check the size of MultiStringData
if (pFeatureData->MultiStringData.uCount < uiNumStrings)
{
MOS_OS_NORMALMESSAGE("pFeatureValue->MultiStringData.uCount is smaller than the actual necessary number.");
return MOS_STATUS_UNKNOWN;
}
// Populate Array
dwPos = 0;
for (ui = 0; ui < uiNumStrings; ui++)
{
pCurData = pData + dwPos;
dwLen = (uint32_t)strlen(pCurData);
MOS_OS_ASSERT(dwLen > 0);
pStrings[ui].pStringData = pCurData;
pStrings[ui].uSize = dwLen;
dwPos += dwLen + 1;
}
pFeatureData->MultiStringData.uCount = uiNumStrings;
pFeatureData->MultiStringData.uSize = dwPos;
return MOS_STATUS_SUCCESS;
}
//!
//! \brief Copy the VALUE_DATA from source to destination pointer
//! \details Copy the VALUE_DATA from source to destination pointer
//! \param PMOS_USER_FEATURE_VALUE_DATA pSrcData
//! [in] Pointer to the Source Value Data
//! \param PMOS_USER_FEATURE_VALUE_DATA pDstData
//! [in] Pointer to the Destination Value Data
//! \param MOS_USER_FEATURE_VALUE_TYPE ValueType
//! [in] Value Type for the copy data
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
MOS_STATUS MOS_CopyUserFeatureValueData(
PMOS_USER_FEATURE_VALUE_DATA pSrcData,
PMOS_USER_FEATURE_VALUE_DATA pDstData,
MOS_USER_FEATURE_VALUE_TYPE ValueType)
{
return MosUtilities::MosCopyUserFeatureValueData(pSrcData, pDstData, ValueType);
}
//!
//! \brief Assign the value as a string type to destination Value Data pointer
//! \details Assign the value as a string type to destination Value Data pointer
//! \param PMOS_USER_FEATURE_VALUE_DATA pDstData
//! [in] Pointer to the Destination Value Data
//! \param const char * pData
//! [in] Pointer to the Value Data as string type
//! \param MOS_USER_FEATURE_VALUE_TYPE ValueType
//! [in] Value Type for the copy data
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
MOS_STATUS MOS_AssignUserFeatureValueData(
PMOS_USER_FEATURE_VALUE_DATA pDstData,
const char *pData,
MOS_USER_FEATURE_VALUE_TYPE ValueType
)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
uint32_t dwUFSize = 0;
//------------------------------
MOS_OS_ASSERT(pData);
MOS_OS_ASSERT(pDstData);
MOS_OS_ASSERT(ValueType != MOS_USER_FEATURE_VALUE_TYPE_INVALID);
//------------------------------
switch(ValueType)
{
case MOS_USER_FEATURE_VALUE_TYPE_BOOL:
pDstData->bData = atoi(pData);
break;
case MOS_USER_FEATURE_VALUE_TYPE_INT32:
pDstData->i32Data = atoi(pData);
break;
case MOS_USER_FEATURE_VALUE_TYPE_INT64:
pDstData->i64Data = atol(pData);
break;
case MOS_USER_FEATURE_VALUE_TYPE_UINT32:
pDstData->u32Data = atoi(pData);
break;
case MOS_USER_FEATURE_VALUE_TYPE_UINT64:
pDstData->u64Data = atol(pData);
break;
case MOS_USER_FEATURE_VALUE_TYPE_FLOAT:
pDstData->fData = (float)atol(pData);
break;
case MOS_USER_FEATURE_VALUE_TYPE_STRING:
pDstData->StringData.uMaxSize = MOS_USER_CONTROL_MAX_DATA_SIZE;
if ((pData != nullptr) && (strlen(pData) != 0))
{
pDstData->StringData.uSize = (uint32_t)strlen(pData) + 1;
if (pDstData->StringData.uSize > pDstData->StringData.uMaxSize)
{
pDstData->StringData.uSize = pDstData->StringData.uMaxSize;
}
pDstData->StringData.pStringData = (char *)MOS_AllocAndZeroMemory(strlen(pData) + 1);
if (pDstData->StringData.pStringData == nullptr)
{
MOS_OS_ASSERTMESSAGE("Failed to allocate memory.");
return MOS_STATUS_NULL_POINTER;
}
eStatus = MOS_SecureStrcpy(
pDstData->StringData.pStringData,
pDstData->StringData.uSize,
(char *)pData);
}
break;
case MOS_USER_FEATURE_VALUE_TYPE_MULTI_STRING:
pDstData->MultiStringData.uCount = MOS_USER_MAX_STRING_COUNT;
pDstData->MultiStringData.uMaxSize = MOS_USER_CONTROL_MAX_DATA_SIZE;
pDstData->MultiStringData.pStrings = (PMOS_USER_FEATURE_VALUE_STRING)MOS_AllocAndZeroMemory(sizeof(MOS_USER_FEATURE_VALUE_STRING) * __MAX_MULTI_STRING_COUNT);
if (pDstData->MultiStringData.pStrings == nullptr)
{
MOS_OS_ASSERTMESSAGE("Failed to allocate memory.");
pDstData->MultiStringData.pMultStringData = nullptr;
pDstData->MultiStringData.uSize = 0;
pDstData->MultiStringData.uCount = 0;
return MOS_STATUS_NULL_POINTER;
}
if ((pData != nullptr) && (strlen(pData) != 0))
{
MOS_SafeFreeMemory(pDstData->MultiStringData.pMultStringData);
pDstData->MultiStringData.pMultStringData = (char *)MOS_AllocAndZeroMemory(strlen(pData) + 1);
if (pDstData->MultiStringData.pMultStringData == nullptr)
{
MOS_OS_ASSERTMESSAGE("Failed to allocate memory.");
return MOS_STATUS_NULL_POINTER;
}
eStatus = MOS_SecureMemcpy(
pDstData->MultiStringData.pMultStringData,
strlen(pData),
(char *)pData,
strlen(pData));
if ((eStatus = MOS_UserFeature_SetMultiStringValue(
pDstData,
dwUFSize)) != MOS_STATUS_SUCCESS)
{
MOS_OS_ASSERTMESSAGE("Failed to set multi string value.");
return eStatus;
}
}
break;
default:
break;
}
return eStatus;
}
//!
//! \brief Set the User Feature Default Value
//! \details Set the User Feature Default Value in the user feature key map
//! \param PMOS_USER_FEATURE_INTERFACE pOsUserFeatureInterface
//! [in] Pointer to OS User Interface structure
//! \param PMOS_USER_FEATURE_VALUE_WRITE_DATA pWriteValues
//! [in] Pointer to User Feature Write Datas
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
MOS_STATUS MOS_UserFeature_SetDefaultValues(
PMOS_USER_FEATURE_INTERFACE pOsUserFeatureInterface,
PMOS_USER_FEATURE_VALUE_WRITE_DATA pWriteValues,
uint32_t uiNumOfValues)
{
uint32_t ui;
PMOS_USER_FEATURE_VALUE pUserFeature = nullptr;
uint32_t ValueID = __MOS_USER_FEATURE_KEY_INVALID_ID;
MOS_STATUS eStatus = MOS_STATUS_UNKNOWN;
MOS_UNUSED(pOsUserFeatureInterface);
//--------------------------------------------------
MOS_OS_ASSERT(pWriteValues);
//--------------------------------------------------
for (ui = 0; ui < uiNumOfValues; ui++)
{
ValueID = pWriteValues[ui].ValueID;
#ifdef __cplusplus
pUserFeature = MosUtilUserInterface::GetValue(ValueID);
#else
if (ValueID < __MOS_USER_FEATURE_KEY_MAX_ID)
{
pUserFeature = gc_UserFeatureKeysMap[ValueID].pUserFeatureValue;
}
else
{
pUserFeature = nullptr;
}
#endif
MOS_OS_CHK_NULL(pUserFeature);
// Copy the write data into corresponding user feature value
MOS_CopyUserFeatureValueData(
&pWriteValues[ui].Value,
&pUserFeature->Value, pUserFeature->ValueType);
}
eStatus = MOS_STATUS_SUCCESS;
finish:
return eStatus;
}
//!
//! \brief Link the user feature key Desc Fields table items to key value map
//! \details Link the user feature key Desc Fields table items to key value map
//! according to ID sequence and do some post processing by calling MOS_AssignUserFeatureValueData
//! \param [out] keyValueMap
//! Optional pointer to the map table to add the user feature key. Could be nullptr
//! \param [in] pUserFeatureKey
//! Pointer to the User Feature Value needed to be declared
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
MOS_STATUS MOS_DeclareUserFeatureKey(MOS_USER_FEATURE_VALUE_MAP *keyValueMap, PMOS_USER_FEATURE_VALUE pUserFeatureKey)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
//------------------------------
MOS_OS_ASSERT(pUserFeatureKey);
//------------------------------
eStatus = MOS_AssignUserFeatureValueData(
&pUserFeatureKey->Value,
pUserFeatureKey->DefaultValue,
pUserFeatureKey->ValueType);
if (eStatus == MOS_STATUS_SUCCESS)
{
if (keyValueMap)
{
keyValueMap[pUserFeatureKey->ValueID].pUserFeatureValue = pUserFeatureKey; // legacy path, keep for compatibilty temporally
}
#ifdef __cplusplus
MosUtilUserInterface::AddEntry(pUserFeatureKey->ValueID, pUserFeatureKey);
#endif
}
return eStatus;
}
//!
//! \brief Free the allocated memory for the related Value type
//! \details Free the allocated memory for the related Value type
//! \param PMOS_USER_FEATURE_VALUE_DATA pData
//! [in] Pointer to the User Feature Value Data
//! \param MOS_USER_FEATURE_VALUE_TYPE ValueType
//! [in] related Value Type needed to be deallocated.
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
MOS_STATUS MOS_DestroyUserFeatureData(PMOS_USER_FEATURE_VALUE_DATA pData,MOS_USER_FEATURE_VALUE_TYPE ValueType)
{
uint32_t ui;
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
//------------------------------
if (pData == nullptr)
{
return eStatus;
}
//------------------------------
switch (ValueType)
{
case MOS_USER_FEATURE_VALUE_TYPE_STRING:
MOS_Free_UserFeatureValueString(&pData->StringData);
break;
case MOS_USER_FEATURE_VALUE_TYPE_MULTI_STRING:
for (ui = 0; ui < pData->MultiStringData.uCount; ui++)
{
MOS_Free_UserFeatureValueString(&pData->MultiStringData.pStrings[ui]);
}
MOS_SafeFreeMemory(pData->MultiStringData.pStrings);
pData->MultiStringData.pStrings = nullptr;
pData->MultiStringData.pMultStringData = nullptr;
pData->MultiStringData.uSize = 0;
pData->MultiStringData.uCount = 0;
break;
default:
break;
}
return eStatus;
}
//!
//! \brief Unlink the user feature key Desc Fields table items to key value map
//! \details Unlink the user feature key Desc Fields table items to key value map
//! according to ID sequence and do some post processing by calling MOS_DestroyUserFeatureData
//! \param [out] keyValueMap
//! Optional pointer to the map table to destroy the user feature key, could be nullptr
//! \param [in] pUserFeatureKey
//! Pointer to the User Feature Value needed to be destroyed
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
MOS_STATUS MOS_DestroyUserFeatureKey(MOS_USER_FEATURE_VALUE_MAP *keyValueMap, PMOS_USER_FEATURE_VALUE pUserFeatureKey)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
//------------------------------
MOS_OS_ASSERT(pUserFeatureKey);
//------------------------------
#ifdef __cplusplus
MosUtilUserInterface::DelEntry(pUserFeatureKey->ValueID);
#endif
if (keyValueMap)
{
keyValueMap[pUserFeatureKey->ValueID].pUserFeatureValue = nullptr; // keep legacy path temporally for compatibility
}
eStatus = MOS_DestroyUserFeatureData(
&pUserFeatureKey->Value,
pUserFeatureKey->ValueType);
return eStatus;
}
//!
//! \brief check the input Default Value type
//! \details check the input Default Value type
//! \param const char * pData
//! [in] Pointer to the Default Value String
//! \param MOS_USER_FEATURE_VALUE_TYPE ValueType
//! [in] User Feature Value type needed to be check
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
MOS_STATUS MOS_isCorrectDefaultValueType(
const char *pData,
MOS_USER_FEATURE_VALUE_TYPE ValueType)
{
uint32_t dwLen;
uint32_t ui;
int32_t IntVal;
MOS_STATUS eStatus = MOS_STATUS_INVALID_PARAMETER;
dwLen = (uint32_t)strlen(pData);
//------------------------------
MOS_OS_ASSERT(pData);
MOS_OS_ASSERT(ValueType != MOS_USER_FEATURE_VALUE_TYPE_INVALID);
//------------------------------
switch (ValueType)
{
case MOS_USER_FEATURE_VALUE_TYPE_BOOL:
if ((!strcmp(pData, "0")) || (!strcmp(pData, "1")))
{
eStatus = MOS_STATUS_SUCCESS;
}
break;
case MOS_USER_FEATURE_VALUE_TYPE_INT32:
case MOS_USER_FEATURE_VALUE_TYPE_INT64:
case MOS_USER_FEATURE_VALUE_TYPE_UINT32:
case MOS_USER_FEATURE_VALUE_TYPE_UINT64:
case MOS_USER_FEATURE_VALUE_TYPE_FLOAT:
eStatus = MOS_STATUS_SUCCESS;
for (ui = 0; ui<dwLen; ui++)
{
IntVal = pData[ui] - '0';
if ((0 > IntVal) || (9 < IntVal))
{
if ((((ui == 0)&&(pData[ui] - '-') != 0)) && ((pData[ui] - '.') != 0))
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
break;
}
}
}
break;
case MOS_USER_FEATURE_VALUE_TYPE_STRING:
eStatus = MOS_STATUS_SUCCESS;
break;
case MOS_USER_FEATURE_VALUE_TYPE_MULTI_STRING:
eStatus = MOS_STATUS_SUCCESS;
break;
default:
break;
}
return eStatus;
}
//!
//! \brief Check the User Feature Value correct or not
//! \details Check the User Feature Value correct or not
//! \param [in] pUserFeatureKey
//! Pointer to the User Feature Value needed to be checked
//! \param [in] maxKeyID
//! The max possible key ID in the corresponding table
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
MOS_STATUS MOS_isCorrectUserFeatureDescField(PMOS_USER_FEATURE_VALUE pUserFeatureKey, uint32_t maxKeyID)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
//------------------------------
MOS_OS_ASSERT(pUserFeatureKey);
//------------------------------
if ((pUserFeatureKey->ValueID <= __MOS_USER_FEATURE_KEY_INVALID_ID) ||
(pUserFeatureKey->ValueID >= maxKeyID))
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
return eStatus;
}
if (pUserFeatureKey->pValueName == nullptr)
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
return eStatus;
}
if (pUserFeatureKey->pcPath == nullptr)
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
return eStatus;
}
if (pUserFeatureKey->pcWritePath == nullptr)
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
return eStatus;
}
if (pUserFeatureKey->pcGroup == nullptr)
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
return eStatus;
}
if ((pUserFeatureKey->pcDescription != nullptr) &&
(strlen(pUserFeatureKey->pcDescription) > MAX_USER_FEATURE_FIELD_LENGTH))
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
return eStatus;
}
eStatus = MOS_isCorrectDefaultValueType(
pUserFeatureKey->DefaultValue,
pUserFeatureKey->ValueType);
return eStatus;
}
//!
//! \brief Get the User Feature Value from Table
//! \details Get the related User Feature Value item according to Filter rules, and pass the item
//! into return callback function
//! \param [in] descTable
//! The user feature key description table
//! \param [in] numOfItems
//! Number of user feature keys described in the table
//! \param [in] maxId
//! Max value ID in the table
//! \param [out] keyValueMap
//! Optional pointer to the value map where the table items will be linked to. could be nullptr
//! \param [in] CallbackFunc
//! Pointer to the Callback function, and pass the User Feature Value item as its parameter
//! \param [in] pDescFilter
//! use the filter rule to select some User Feature Value item
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
MOS_STATUS MOS_GetItemFromMOSUserFeatureDescField(
MOS_USER_FEATURE_VALUE *descTable,
uint32_t numOfItems,
uint32_t maxId,
MOS_USER_FEATURE_VALUE_MAP *keyValueMap,
MOS_STATUS (*CallbackFunc)(MOS_USER_FEATURE_VALUE_MAP *, PMOS_USER_FEATURE_VALUE),
PMOS_USER_FEATURE_VALUE pUserFeatureKeyFilter)
{
uint32_t uiIndex = 0;
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
//------------------------------
MOS_OS_ASSERT(CallbackFunc);
MOS_OS_ASSERT(pUserFeatureKeyFilter);
//MOS_OS_CHK_NULL_RETURN(descTable);
//------------------------------
for (uiIndex = __MOS_USER_FEATURE_KEY_INVALID_ID; uiIndex < numOfItems; uiIndex++)
{
if (MOS_isCorrectUserFeatureDescField(&descTable[uiIndex], maxId) != MOS_STATUS_SUCCESS)
{
continue;
}
if ((pUserFeatureKeyFilter->ValueID != __MOS_USER_FEATURE_KEY_INVALID_ID) && (pUserFeatureKeyFilter->ValueID != descTable[uiIndex].ValueID))
{
continue;
}
if ((pUserFeatureKeyFilter->pValueName != nullptr) && (strcmp(pUserFeatureKeyFilter->pValueName, descTable[uiIndex].pValueName) != 0))
{
continue;
}
if ((pUserFeatureKeyFilter->pcPath != nullptr) && (strcmp(pUserFeatureKeyFilter->pcPath, descTable[uiIndex].pcPath) != 0))
{
continue;
}
if ((pUserFeatureKeyFilter->pcWritePath != nullptr) && (strcmp(pUserFeatureKeyFilter->pcWritePath, descTable[uiIndex].pcWritePath) != 0))
{
continue;
}
if ((pUserFeatureKeyFilter->pcGroup != nullptr) && (strcmp(pUserFeatureKeyFilter->pcGroup, descTable[uiIndex].pcGroup) != 0))
{
continue;
}
if ((pUserFeatureKeyFilter->Type != MOS_USER_FEATURE_TYPE_INVALID) && (pUserFeatureKeyFilter->Type != descTable[uiIndex].Type))
{
continue;
}
if ((pUserFeatureKeyFilter->ValueType != MOS_USER_FEATURE_VALUE_TYPE_INVALID) && (pUserFeatureKeyFilter->ValueType != descTable[uiIndex].ValueType))
{
continue;
}
eStatus = (*CallbackFunc)(keyValueMap, &descTable[uiIndex]);
}
return eStatus;
}
//!
//! \brief Link user feature key description table items to specified UserFeatureKeyTable
//! \details Link user feature key description table items to specified UserFeatureKeyTable
//! according to ID sequence and do some post processing such as malloc related memory
//! \param [in] descTable
//! The user feature key description table
//! \param [in] numOfItems
//! Number of user feature keys described in the table
//! \param [in] maxId
//! Max value ID in the table
//! \param [out] keyValueMap
//! Optional pointer to the value map where the table items will be linked to, could be nullptr
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
MOS_STATUS MOS_DeclareUserFeatureKeysFromDescFields(
MOS_USER_FEATURE_VALUE *descTable,
uint32_t numOfItems,
uint32_t maxId,
MOS_USER_FEATURE_VALUE_MAP *keyValueMap)
{
return MosUtilities::MosDeclareUserFeatureKeysFromDescFields(descTable, numOfItems, maxId);
}
//!
//! \brief Link the MOSUserFeatureDescFields table items to gc_UserFeatureKeysMap
//! \details Link the MOSUserFeatureDescFields table items to gc_UserFeatureKeysMap
//! according to ID sequence and do some post processing such as malloc related memory
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
MOS_STATUS MOS_DeclareUserFeatureKeysForAllDescFields()
{
MOS_OS_CHK_STATUS_RETURN(MOS_DeclareUserFeatureKeysFromDescFields(
MOSUserFeatureDescFields,
__MOS_USER_FEATURE_KEY_MAX_ID,
__MOS_USER_FEATURE_KEY_MAX_ID,
gc_UserFeatureKeysMap));
return MOS_STATUS_SUCCESS;
}
//!
//! \brief Destroy the User Feature Value pointer according to the DescField Table
//! \details Destroy the User Feature Value pointer according to the DescField Table
//! destroy the user feature key value Map according to Declare Count
//! \param [in] descTable
//! The user feature key description table
//! \param [in] numOfItems
//! Number of user feature keys described in the table
//! \param [in] maxId
//! Max value ID in the table
//! \param [out] keyValueMap
//! optional pointer to the value map where the table items will be destroyed, could be nullptr
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
MOS_STATUS MOS_DestroyUserFeatureKeysFromDescFields(
MOS_USER_FEATURE_VALUE *descTable,
uint32_t numOfItems,
uint32_t maxId,
MOS_USER_FEATURE_VALUE_MAP *keyValueMap)
{
return MosUtilities::MosDestroyUserFeatureKeysFromDescFields(descTable, numOfItems, maxId);
}
//!
//! \brief Destroy the User Feature Value pointer according to the Global DescField Table
//! \details Destroy the User Feature Value pointer according to the Global DescField Table
//! destroy the gc_UserFeatureKeysMap according to Declare Count
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
MOS_STATUS MOS_DestroyUserFeatureKeysForAllDescFields()
{
MOS_USER_FEATURE_VALUE UserFeatureKeyFilter = __NULL_USER_FEATURE_VALUE__;
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
MOS_OS_CHK_STATUS_RETURN(MOS_DestroyUserFeatureKeysFromDescFields(
MOSUserFeatureDescFields,
__MOS_USER_FEATURE_KEY_MAX_ID,
__MOS_USER_FEATURE_KEY_MAX_ID,
gc_UserFeatureKeysMap));
return eStatus;
}
//!
//! \brief Initializes read user feature value function
//! \details Initializes read user feature value function
//! This is an internal function of MOS utilities.
//! It is implemented to support two differnt usages of MOS_UserFeature_ReadValue()
//! One usage comes with user pre-allocated user value,
//! the other comes with nullptr user value, and this function will allocate for it.
//! Please refer to MOS_UserFeature_ReadValue() or function body for details.
//! \param PMOS_USER_FEATURE_INTERFACE pOsUserFeatureInterface
//! [in] Pointer to OS user feature interface
//! \param PMOS_USER_FEATURE pUserFeature
//! [in/out] Pointer to user feature interface
//! \param char *pValueName,
//! [in] Pointer to value name
//! \param MOS_USER_FEATURE_VALUE_TYPE ValueType
//! [in] User Feature Value type
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
static MOS_STATUS MOS_UserFeature_ReadValueInit(
PMOS_USER_FEATURE_INTERFACE pOsUserFeatureInterface,
uint32_t uiNumValues,
MOS_USER_FEATURE_VALUE_DATA Value,
const char *pValueName,
MOS_USER_FEATURE_VALUE_TYPE ValueType)
{
MOS_STATUS eStatus;
MOS_UNUSED(pOsUserFeatureInterface);
MOS_UNUSED(Value);
MOS_UNUSED(pValueName);
MOS_UNUSED(ValueType);
eStatus = MOS_STATUS_SUCCESS;
//------------------------------
MOS_OS_ASSERT(pValueName);
//------------------------------
// Check if memory is allocated
if (uiNumValues == 0)
{
MOS_OS_ASSERTMESSAGE("pUserFeature->uiNumValues is 0.");
eStatus = MOS_STATUS_UNKNOWN;
goto finish;
}
finish:
return eStatus;
}
//!
//! \brief User Feature Callback function
//! \details User Feature Callback function
//! Notifies the caller that the CB is triggered
//! \param void *pvParameter
//! [out] Pointer to the User Feature Notification Data for
//! which callback is requested
//! \param int32_t TimerOrWait
//! [in/out] Flag to indicate if a timer or wait is applied
//! (Not used currently)
//! \return void
//!
static void MOS_UserFeature_Callback(
PTP_CALLBACK_INSTANCE Instance,
void *pvParameter,
PTP_WAIT Wait,
TP_WAIT_RESULT WaitResult)
{
PMOS_USER_FEATURE_NOTIFY_DATA pNotifyData;
MOS_UNUSED(Instance);
MOS_UNUSED(Wait);
MOS_UNUSED(WaitResult);
MOS_OS_ASSERT(pvParameter);
pNotifyData = (PMOS_USER_FEATURE_NOTIFY_DATA)pvParameter;
pNotifyData->bTriggered = true;
}
//!
//! \brief Open the user feature based on the access type requested
//! \details Open the user feature based on the access type requested
//! MOS_USER_FEATURE_TYPE_USER will be UFINT
//! MOS_USER_FEATURE_TYPE_SYSTEM will be UFEXT
//! \param MOS_USER_FEATURE_TYPE KeyType
//! [in] User Feature Type
//! \param char *pSubKey
//! [in] Pointer to the subkey
//! \param uint32_t dwAccess,
//! [in] Desired access rights
//! \param void ** pUFKey
//! [out] Pointer to the variable that accepts the handle to
//! the user feature key opened
//! [in] in ConfigFS implementation, use pUFKey to pass the pUserFeature as a handler
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
static MOS_STATUS MOS_UserFeature_Open(
MOS_USER_FEATURE_TYPE KeyType,
const char *pSubKey,
uint32_t dwAccess,
void **pUFKey,
MOS_USER_FEATURE_KEY_PATH_INFO *ufInfo = nullptr)
{
MOS_STATUS eStatus;
void *RootKey = 0;
MOS_OS_ASSERT(pSubKey);
MOS_OS_ASSERT(pUFKey);
if (KeyType == MOS_USER_FEATURE_TYPE_USER)
{
RootKey = (void *)UFKEY_INTERNAL;
}
else if (KeyType == MOS_USER_FEATURE_TYPE_SYSTEM)
{
RootKey = (void *)UFKEY_EXTERNAL;
}
else
{
MOS_OS_ASSERTMESSAGE("Invalid Key Type %d.", KeyType);
return MOS_STATUS_UNKNOWN;
}
if((eStatus = MOS_UserFeatureOpenKey(
RootKey,
pSubKey,
0,
dwAccess,
pUFKey,
ufInfo)) != MOS_STATUS_SUCCESS)
{
MOS_OS_NORMALMESSAGE("Unable to open user feature key %s.", pSubKey);
}
return eStatus;
}
//!
//! \brief Read binary value from the user feature
//! \details Read binary value from the user feature,
//! and store it into the user feature data
//! \param void *UFKey
//! [in] Handle to the user feature key
//! \param PMOS_USER_FEATURE_VALUE pFeatureValue
//! [in/out] Pointer to User Feature Data
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
static MOS_STATUS MOS_UserFeature_ReadValueBinary(
void *UFKey,
PMOS_USER_FEATURE_VALUE pFeatureValue)
{
MOS_STATUS eStatus;
void *pvData;
uint32_t dwUFSize;
MOS_OS_ASSERT(UFKey);
MOS_OS_ASSERT(pFeatureValue);
MOS_OS_ASSERT(pFeatureValue->pValueName);
MOS_OS_ASSERT(pFeatureValue->ValueType == MOS_USER_FEATURE_VALUE_TYPE_BINARY);
pvData = pFeatureValue->Value.BinaryData.pBinaryData;
if (!pvData)
{
MOS_OS_ASSERTMESSAGE("pFeatureValue->BinaryData.pBinaryData is NULL.");
return MOS_STATUS_NULL_POINTER;
}
dwUFSize = pFeatureValue->Value.BinaryData.uMaxSize;
if (dwUFSize == 0)
{
MOS_OS_ASSERTMESSAGE("pFeatureValue->BinaryData.uMaxSize is 0.");
return MOS_STATUS_UNKNOWN;
}
eStatus = MOS_UserFeatureGetValue(
UFKey,
nullptr,
pFeatureValue->pValueName,
RRF_RT_UF_BINARY,
nullptr,
pvData,
&dwUFSize);
if (eStatus != MOS_STATUS_SUCCESS)
{
if (dwUFSize > pFeatureValue->Value.BinaryData.uMaxSize) // Buffer size is not enough
{
MOS_OS_NORMALMESSAGE("Size %d exceeds max %d.", dwUFSize, pFeatureValue->Value.BinaryData.uMaxSize);
return MOS_STATUS_UNKNOWN;
}
else // This error case can be hit if the user feature key does not exist.
{
MOS_OS_NORMALMESSAGE("Failed to read binary user feature value '%s'.", pFeatureValue->pValueName);
return MOS_STATUS_USER_FEATURE_KEY_READ_FAILED;
}
}
pFeatureValue->Value.BinaryData.uSize = dwUFSize;
return MOS_STATUS_SUCCESS;
}
//!
//! \brief Read string value from the user feature
//! \details Read string value from the user feature,
//! and store it into the user feature data
//! \param void *UFKey
//! [in] Handle to the user feature key
//! \param PMOS_USER_FEATURE_VALUE pFeatureValue
//! [in/out] Pointer to User Feature Data
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
static MOS_STATUS MOS_UserFeature_ReadValueString(
void *UFKey,
PMOS_USER_FEATURE_VALUE pFeatureValue)
{
MOS_STATUS eStatus;
uint32_t dwUFSize;
char pcTmpStr[MOS_USER_CONTROL_MAX_DATA_SIZE];
//--------------------------------------------------
MOS_OS_ASSERT(UFKey);
MOS_OS_ASSERT(pFeatureValue);
MOS_OS_ASSERT(pFeatureValue->pValueName);
MOS_OS_ASSERT(pFeatureValue->ValueType == MOS_USER_FEATURE_VALUE_TYPE_STRING);
//--------------------------------------------------
MOS_ZeroMemory(pcTmpStr, MOS_USER_CONTROL_MAX_DATA_SIZE);
dwUFSize = pFeatureValue->Value.StringData.uMaxSize;
if (dwUFSize == 0)
{
MOS_OS_ASSERTMESSAGE("pFeatureValue->StringData.uMaxSize is 0.");
return MOS_STATUS_UNKNOWN;
}
eStatus = MOS_UserFeatureGetValue(
UFKey,
nullptr,
pFeatureValue->pValueName,
RRF_RT_UF_SZ,
nullptr,
pcTmpStr,
&dwUFSize);
if (eStatus != MOS_STATUS_SUCCESS)
{
if (dwUFSize > pFeatureValue->Value.StringData.uMaxSize) // Buffer size is not enough
{
MOS_OS_NORMALMESSAGE("Size %d exceeds max %d.", dwUFSize, pFeatureValue->Value.StringData.uMaxSize);
return MOS_STATUS_UNKNOWN;
}
else // This error case can be hit if the user feature key does not exist.
{
MOS_OS_NORMALMESSAGE("Failed to read single string user feature value '%s'.", pFeatureValue->pValueName);
return MOS_STATUS_USER_FEATURE_KEY_READ_FAILED;
}
}
if (strlen(pcTmpStr) > 0)
{
MOS_OS_CHK_NULL_RETURN(pFeatureValue->Value.StringData.pStringData = (char *)MOS_AllocAndZeroMemory(strlen(pcTmpStr) + 1));
MOS_SecureMemcpy(pFeatureValue->Value.StringData.pStringData, strlen(pcTmpStr), pcTmpStr, strlen(pcTmpStr));
pFeatureValue->Value.StringData.uSize = dwUFSize;
}
return eStatus;
}
//!
//! \brief Read multi string value from the user feature
//! \details Read multi string value from the user feature,
//! and store it into the user feature data
//! \param void *UFKey
//! [in] Handle to the user feature key
//! \param PMOS_USER_FEATURE_VALUE pFeatureValue
//! [in/out] Pointer to User Feature Data
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
static MOS_STATUS MOS_UserFeature_ReadValueMultiString(
void *UFKey,
PMOS_USER_FEATURE_VALUE pFeatureValue)
{
MOS_STATUS eStatus;
uint32_t dwUFSize;
char pcTmpStr[MOS_USER_CONTROL_MAX_DATA_SIZE];
MOS_OS_ASSERT(UFKey);
MOS_OS_ASSERT(pFeatureValue);
MOS_OS_ASSERT(pFeatureValue->pValueName);
MOS_OS_ASSERT(pFeatureValue->ValueType == MOS_USER_FEATURE_VALUE_TYPE_MULTI_STRING);
if (!pFeatureValue->Value.MultiStringData.pStrings)
{
MOS_OS_ASSERTMESSAGE("pFeatureValue->MultiStringData.pStrings is NULL.");
return MOS_STATUS_NULL_POINTER;
}
MOS_ZeroMemory(pcTmpStr, MOS_USER_CONTROL_MAX_DATA_SIZE);
dwUFSize = pFeatureValue->Value.MultiStringData.uMaxSize;
if (dwUFSize == 0)
{
MOS_OS_ASSERTMESSAGE("pFeatureValue->MultiStringData.uMaxSize is 0.");
return MOS_STATUS_UNKNOWN;
}
eStatus = MOS_UserFeatureGetValue(
UFKey,
nullptr,
pFeatureValue->pValueName,
RRF_RT_UF_MULTI_SZ,
nullptr,
pcTmpStr,
&dwUFSize);
if (eStatus != MOS_STATUS_SUCCESS)
{
if (dwUFSize > pFeatureValue->Value.MultiStringData.uMaxSize) // Buffer size is not enough
{
MOS_OS_NORMALMESSAGE("Size %d exceeds max %d.", dwUFSize, pFeatureValue->Value.MultiStringData.uMaxSize);
return MOS_STATUS_UNKNOWN;
}
else // This error case can be hit if the user feature key does not exist.
{
MOS_OS_NORMALMESSAGE("Failed to read single string user feature value '%s'.", pFeatureValue->pValueName);
return MOS_STATUS_USER_FEATURE_KEY_READ_FAILED;
}
}
if (strlen(pcTmpStr) > 0)
{
MOS_SafeFreeMemory(pFeatureValue->Value.MultiStringData.pMultStringData);
pFeatureValue->Value.MultiStringData.pMultStringData = (char *)MOS_AllocAndZeroMemory(strlen(pcTmpStr) + 1);
MosMemAllocFakeCounter++;
if (pFeatureValue->Value.MultiStringData.pMultStringData == nullptr)
{
MOS_OS_ASSERTMESSAGE("Failed to allocate memory.");
return MOS_STATUS_NULL_POINTER;
}
MOS_SecureMemcpy(
pFeatureValue->Value.MultiStringData.pMultStringData,
strlen(pcTmpStr),
pcTmpStr,
strlen(pcTmpStr));
if((eStatus = MOS_UserFeature_SetMultiStringValue(
&pFeatureValue->Value,
dwUFSize)) != MOS_STATUS_SUCCESS)
{
MOS_OS_ASSERTMESSAGE("Failed to set multi string value.");
return eStatus;
}
}
return MOS_STATUS_SUCCESS;
}
//!
//! \brief Read Primitive data value from the user feature
//! \details Read Primitive data value from the user feature,
//! and store it into the user feature data
//! \param void *UFKey
//! [in] Handle to the user feature key
//! \param PMOS_USER_FEATURE_VALUE pFeatureValue
//! [in/out] Pointer to User Feature Data
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
static MOS_STATUS MOS_UserFeature_ReadValuePrimitive(
void *UFKey,
PMOS_USER_FEATURE_VALUE pFeatureValue)
{
MOS_STATUS eStatus;
uint32_t dwUFType = 0;
uint32_t dwUFSize;
void *pvData = nullptr;
MOS_OS_ASSERT(UFKey);
MOS_OS_ASSERT(pFeatureValue);
MOS_OS_ASSERT(pFeatureValue->pValueName);
MOS_OS_ASSERT(pFeatureValue->ValueType != MOS_USER_FEATURE_VALUE_TYPE_INVALID);
switch(pFeatureValue->ValueType)
{
case MOS_USER_FEATURE_VALUE_TYPE_BOOL:
case MOS_USER_FEATURE_VALUE_TYPE_INT32:
case MOS_USER_FEATURE_VALUE_TYPE_UINT32:
case MOS_USER_FEATURE_VALUE_TYPE_FLOAT:
dwUFType = RRF_RT_UF_DWORD;
dwUFSize = sizeof(uint32_t);
pvData = &pFeatureValue->Value.fData;
break;
case MOS_USER_FEATURE_VALUE_TYPE_INT64:
case MOS_USER_FEATURE_VALUE_TYPE_UINT64:
dwUFType = RRF_RT_UF_QWORD;
dwUFSize = sizeof(uint64_t);
pvData = &pFeatureValue->Value.u64Data;
break;
default:
MOS_OS_ASSERTMESSAGE("Invalid primitive value type.");
return MOS_STATUS_UNKNOWN;
}
eStatus = MOS_UserFeatureGetValue(
UFKey,
nullptr,
pFeatureValue->pValueName,
dwUFType,
nullptr,
pvData,
&dwUFSize);
if (eStatus != MOS_STATUS_SUCCESS)
{
// This error case can be hit if the user feature key does not exist.
MOS_OS_NORMALMESSAGE("Failed to read primitive user feature value \"%s\".", pFeatureValue->pValueName);
return MOS_STATUS_USER_FEATURE_KEY_READ_FAILED;
}
return eStatus;
}
//!
//! \brief Write string value to the user feature
//! \details Write string value to the user feature
//! \param void *UFKey
//! [in] Handle to the user feature key
//! \param PMOS_USER_FEATURE_VALUE pFeatureValue
//! [in] Pointer to User Feature that contains user feature key info
//! \param PMOS_USER_FEATURE_VALUE_DATA pDataValue
//! [in] Pointer to User Feature Data that contains the string
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
static MOS_STATUS MOS_UserFeature_WriteValueString(
void *UFKey,
PMOS_USER_FEATURE_VALUE pFeatureValue,
PMOS_USER_FEATURE_VALUE_DATA pDataValue)
{
MOS_STATUS eStatus;
MOS_OS_ASSERT(UFKey);
MOS_OS_ASSERT(pFeatureValue);
MOS_OS_ASSERT(pFeatureValue->pValueName);
MOS_OS_ASSERT(pFeatureValue->ValueType == MOS_USER_FEATURE_VALUE_TYPE_STRING);
MOS_OS_ASSERT(pDataValue);
if((eStatus = MOS_UserFeatureSetValueEx(
UFKey,
pFeatureValue->pValueName,
0,
UF_SZ,
(uint8_t*)pDataValue->StringData.pStringData,
pDataValue->StringData.uSize)) != MOS_STATUS_SUCCESS)
{
MOS_OS_ASSERTMESSAGE("Failed to write string user feature value.");
}
return eStatus;
}
//!
//! \brief Write multi string value to the user feature
//! \details Write multi string value to the user feature
//! It combines the multi string into a temp buffer
//! and call routine to write the user feature
//! \param void *UFKey
//! [in] Handle to the user feature key
//! \param PMOS_USER_FEATURE_VALUE pFeatureValue
//! [in] Pointer to User Feature that contains user feature key info
//! \param PMOS_USER_FEATURE_VALUE_DATA pDataValue
//! [in] Pointer to User Feature Data that contains the multi string
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
static MOS_STATUS MOS_UserFeature_WriteValueMultiString(
void *UFKey,
PMOS_USER_FEATURE_VALUE pFeatureValue,
PMOS_USER_FEATURE_VALUE_DATA pDataValue)
{
PMOS_USER_FEATURE_VALUE_STRING pStringData;
uint8_t *pData;
uint8_t *pCurData;
uint32_t dwDataSize;
uint32_t dwAvailableSize;
uint32_t ui;
MOS_STATUS eStatus;
MOS_OS_ASSERT(UFKey);
MOS_OS_ASSERT(pFeatureValue);
MOS_OS_ASSERT(pFeatureValue->pValueName);
MOS_OS_ASSERT(pFeatureValue->ValueType == MOS_USER_FEATURE_VALUE_TYPE_MULTI_STRING);
MOS_OS_ASSERT(pDataValue);
MOS_OS_ASSERT(pDataValue->MultiStringData.uCount > 0);
pData = nullptr;
dwDataSize = 0;
for (ui = 0; ui < pDataValue->MultiStringData.uCount; ui++)
{
pStringData = &pDataValue->MultiStringData.pStrings[ui];
dwDataSize += pStringData->uSize;
dwDataSize += 1; // for \0
}
dwDataSize += 1; // for \0 at the very end (see MULTI_SZ spec)
// Allocate memory to store data
pData = (uint8_t*)MOS_AllocAndZeroMemory(dwDataSize);
if(pData == nullptr)
{
MOS_OS_ASSERTMESSAGE("Failed to allocate memory.");
return MOS_STATUS_NO_SPACE;
}
// Copy data from original string array
pCurData = pData;
dwAvailableSize = dwDataSize;
for (ui = 0; ui < pDataValue->MultiStringData.uCount; ui++)
{
pStringData = &pDataValue->MultiStringData.pStrings[ui];
eStatus = MOS_SecureMemcpy(pCurData, dwAvailableSize, pStringData->pStringData, pStringData->uSize);
if(eStatus != MOS_STATUS_SUCCESS)
{
MOS_OS_ASSERTMESSAGE("Failed to copy memory.");
goto finish;
}
pCurData += pStringData->uSize;
pCurData++; // \0 is already added since we zeroed the memory
// Very last \0 is already added since we zeroed the memory
dwAvailableSize -= pStringData->uSize + 1;
}
// Write the user feature MULTI_SZ entry
if((eStatus = MOS_UserFeatureSetValueEx(
UFKey,
pFeatureValue->pValueName,
0,
UF_MULTI_SZ,
pData,
dwDataSize)) != MOS_STATUS_SUCCESS)
{
MOS_OS_ASSERTMESSAGE("Failed to write multi string user feature value.");
}
finish:
MOS_FreeMemory(pData);
return eStatus;
}
//!
//! \brief Write Binary value to the user feature
//! \details Write Binary value to the user feature
//! \param void *UFKey
//! [in] Handle to the user feature key
//! \param PMOS_USER_FEATURE_VALUE pFeatureValue
//! [in] Pointer to User Feature that contains user feature key info
//! \param PMOS_USER_FEATURE_VALUE_DATA pDataValue
//! [in] Pointer to User Feature Data that contains the binary data
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
static MOS_STATUS MOS_UserFeature_WriteValueBinary(
void *UFKey,
PMOS_USER_FEATURE_VALUE pFeatureValue,
PMOS_USER_FEATURE_VALUE_DATA pDataValue)
{
MOS_STATUS eStatus;
MOS_OS_ASSERT(UFKey);
MOS_OS_ASSERT(pFeatureValue);
MOS_OS_ASSERT(pFeatureValue->pValueName);
MOS_OS_ASSERT(pFeatureValue->ValueType == MOS_USER_FEATURE_VALUE_TYPE_BINARY);
MOS_OS_ASSERT(pDataValue);
if((eStatus = MOS_UserFeatureSetValueEx(
UFKey,
pFeatureValue->pValueName,
0,
UF_BINARY,
(uint8_t*)pDataValue->BinaryData.pBinaryData,
pDataValue->BinaryData.uSize)) != MOS_STATUS_SUCCESS)
{
MOS_OS_ASSERTMESSAGE("Failed to write binary user feature value.");
}
return eStatus;
}
//!
//! \brief Write Primitive data value to the user feature
//! \details Write Primitive data value to the user feature
//! \param void *UFKey
//! [in] Handle to the user feature key
//! \param PMOS_USER_FEATURE_VALUE pFeatureValue
//! [in] Pointer to User Feature that contains user feature key info
//! \param PMOS_USER_FEATURE_VALUE_DATA pDataValue
//! [in] Pointer to User Feature Data that contains the primitive data
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
static MOS_STATUS MOS_UserFeature_WriteValuePrimitive(
void *UFKey,
PMOS_USER_FEATURE_VALUE pFeatureValue,
PMOS_USER_FEATURE_VALUE_DATA pDataValue)
{
MOS_STATUS eStatus;
uint32_t dwUFType = UF_NONE;
uint32_t dwUFSize = 0;
void *pvData = nullptr;
MOS_OS_ASSERT(UFKey);
MOS_OS_ASSERT(pFeatureValue);
MOS_OS_ASSERT(pFeatureValue->pValueName);
MOS_OS_ASSERT(pFeatureValue->ValueType != MOS_USER_FEATURE_VALUE_TYPE_INVALID);
MOS_OS_ASSERT(pDataValue);
switch(pFeatureValue->ValueType)
{
case MOS_USER_FEATURE_VALUE_TYPE_BOOL:
case MOS_USER_FEATURE_VALUE_TYPE_INT32:
case MOS_USER_FEATURE_VALUE_TYPE_UINT32:
case MOS_USER_FEATURE_VALUE_TYPE_FLOAT:
dwUFType = UF_DWORD;
dwUFSize = sizeof(uint32_t);
pvData = &pDataValue->fData;
break;
case MOS_USER_FEATURE_VALUE_TYPE_INT64:
case MOS_USER_FEATURE_VALUE_TYPE_UINT64:
dwUFType = UF_QWORD;
dwUFSize = sizeof(uint64_t);
pvData = &pDataValue->u64Data;
break;
default:
MOS_OS_ASSERTMESSAGE("Invalid primitive value type.");
return MOS_STATUS_UNKNOWN;
}
if((eStatus = MOS_UserFeatureSetValueEx(
UFKey,
pFeatureValue->pValueName,
0,
dwUFType,
(uint8_t*)pvData,
dwUFSize)) != MOS_STATUS_SUCCESS)
{
MOS_OS_ASSERTMESSAGE("Failed to write primitive user feature value.");
}
return eStatus;
}
//!
//! \brief Read Single Value from User Feature based on value of enum type in MOS_USER_FEATURE_VALUE_TYPE
//! \details This is a unified funtion to read user feature key for all components.
//! (Codec/VP/CP/CM)
//! It is required to prepare all memories for buffers before calling this function.
//! User can choose to use array variable or allocated memory for the buffer.
//! If the buffer is allocated dynamically, it must be freed by user to avoid memory leak.
//! ------------------------------------------------------------------------------------
//! Usage example:
//! a) Initiation:
//! MOS_ZeroMemory(&UserFeatureData, sizeof(UserFeatureData));
//! b.0) Don't need to input a default value if the default value in MOSUserFeatureDescFields is good
//! for your case
//! b.1) For uint32_t type:
//! UserFeatureData.u32Data = 1; // overwrite a custom default value
//! UserFeatureData.i32DataFlag = MOS_USER_FEATURE_VALUE_DATA_FLAG_CUSTOM_DEFAULT_VALUE_TYPE;
//! // raise a flag to use this custom default value instead of
//! default value in MOSUserFeatureDescFields
//! b.2) For String/Binary type:
//! char cStringData[MOS_USER_CONTROL_MAX_DATA_SIZE];
//! UserFeatureData.StringData.pStringData = cStringData; // make sure the pointer is valid
//! b.3) For MultiString type:
//! char cStringData[MOS_USER_CONTROL_MAX_DATA_SIZE];
//! MOS_USER_FEATURE_VALUE_STRING Strings[__MAX_MULTI_STRING_COUNT];
//! UserFeatureData.MultiStringData.pMultStringData = cStringData; // make sure the pointer is valid
//! for (ui = 0; ui < VPHAL_3P_MAX_LIB_PATH_COUNT; ui++)
//! {
//! Strings[ui].pStringData = (char *)MOS_AllocAndZeroMemory(MOS_USER_CONTROL_MAX_DATA_SIZE);
//! }
//! UserFeatureData.MultiStringData.pStrings = Strings;
//! c) Read user feature key:
//! MOS_UserFeature_ReadValue_ID();
//! -------------------------------------------------------------------------------------
//! Important note: The pointer pStringData/pMultStringData may be modified if the
//! previous MOS_UserFeature_ReadValue() doesn't read a same user feature key type. So it's
//! suggested to set the union members in UserFeatureValue every time before
//! MOS_UserFeature_ReadValue() if you are not familiar with the details of this function.
//! If a new key is added, please make sure to declare a definition in MOSUserFeatureDescFields
//! by MOS_DECLARE_UF_KEY
//! \param [in] pOsUserFeatureInterface
//! Pointer to OS User Interface structure
//! \param [in] ValueID
//! value of enum type in MOS_USER_FEATURE_VALUE_TYPE. declares the user feature key to be readed
//! \param [in/out] pUserData
//! Pointer to User Feature Data
//! \param [in] mosCtx
//! Pointer to ddi device ctx
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//! For pValueData return value:
//! MOS_STATUS_SUCCESS: pValueData is from User Feature Key
//! MOS_STATUS_USER_FEATURE_KEY_OPEN_FAILED: pValueData is from default value
//! MOS_STATUS_UNKNOWN: pValueData is from default value
//! MOS_STATUS_USER_FEATURE_KEY_READ_FAILED: pValueData is from default value
//! MOS_STATUS_NULL_POINTER: NO USER FEATURE KEY DEFINITION in corresponding user feature key Desc Field table,
//! No default value or User Feature Key value return
//!
//!
MOS_STATUS MOS_UserFeature_ReadValue_ID(
PMOS_USER_FEATURE_INTERFACE pOsUserFeatureInterface,
uint32_t ValueID,
PMOS_USER_FEATURE_VALUE_DATA pValueData,
MOS_CONTEXT_HANDLE mosCtx)
{
return MosUtilities::MosUserFeatureReadValueID(
pOsUserFeatureInterface,
ValueID,
pValueData,
mosCtx);
}
//!
//! \brief Lookup the user feature value name associated with the ID
//! \param [in] ValueId
//! The user feature value ID to be looked up
//! \return pointer to the char array holding the user feature key value name
//!
const char* MOS_UserFeature_LookupValueName(
uint32_t ValueID)
{
return MosUtilities::MosUserFeatureLookupValueName(ValueID);
}
//!
//! \brief Lookup the read path associated with the ID
//! \param [in] ValueId
//! The user feature value ID to be looked up
//! \return pointer to the char array holding the read path
//!
const char* MOS_UserFeature_LookupReadPath(
uint32_t ValueID)
{
return MosUtilities::MosUserFeatureLookupReadPath(ValueID);
}
//!
//! \brief Lookup the write path associated with the ID
//! \param [in] ValueId
//! The user feature value ID to be looked up
//! \return pointer to the char array holding the write path
//!
const char* MOS_UserFeature_LookupWritePath(
uint32_t ValueID)
{
return MosUtilities::MosUserFeatureLookupWritePath(ValueID);
}
//!
//! \brief Write Values to User Feature
//! \details Write Values to User Feature
//! The caller is responsible to allocate values / names
//! and free them later if necessary
//! \param PMOS_USER_FEATURE_INTERFACE pOsUserFeatureInterface
//! [in] Pointer to OS User Interface structure
//! \param PMOS_USER_FEATURE_VALUE_WRITE_DATA pWriteValues
//! [in] Pointer to User Feature Data, and related User Feature Key ID (enum type in MOS_USER_FEATURE_VALUE_TYPE)
//! \param uint32_t uiNumOfValues
//! [in] number of user feature keys to be written.
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
MOS_STATUS MOS_UserFeature_WriteValues_ID(
PMOS_USER_FEATURE_INTERFACE pOsUserFeatureInterface,
PMOS_USER_FEATURE_VALUE_WRITE_DATA pWriteValues,
uint32_t uiNumOfValues,
MOS_CONTEXT_HANDLE mosCtx)
{
return MosUtilities::MosUserFeatureWriteValuesID(
pOsUserFeatureInterface,
pWriteValues,
uiNumOfValues,
mosCtx);
}
//!
//! \brief Enable user feature change notification
//! \details Enable user feature change notification
//! Create notification data and register the wait event
//! \param PMOS_USER_FEATURE_INTERFACE pOsUserFeatureInterface
//! [in] Pointer to OS User Interface structure
//! \param PMOS_USER_FEATURE_NOTIFY_DATA pNotification
//! [in/out] Pointer to User Feature Notification Data
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
MOS_STATUS MOS_UserFeature_EnableNotification(
PMOS_USER_FEATURE_INTERFACE pOsUserFeatureInterface,
PMOS_USER_FEATURE_NOTIFY_DATA pNotification,
MOS_CONTEXT_HANDLE mosCtx)
{
PMOS_USER_FEATURE_NOTIFY_DATA_COMMON pNotifyCommon;
int32_t bResult;
MOS_STATUS eStatus;
MOS_UNUSED(pOsUserFeatureInterface);
//---------------------------------------
MOS_OS_ASSERT(pNotification);
MOS_OS_ASSERT(pNotification->NotifyType != MOS_USER_FEATURE_NOTIFY_TYPE_INVALID);
MOS_OS_ASSERT(pNotification->pPath);
//---------------------------------------
// Reset the triggered flag
pNotification->bTriggered = false;
if (pNotification->pHandle == nullptr)
{
// Allocate private data as well
pNotification->pHandle = MOS_AllocAndZeroMemory(sizeof(MOS_USER_FEATURE_NOTIFY_DATA));
if(pNotification->pHandle == nullptr)
{
MOS_OS_ASSERTMESSAGE("Failed to allocate memory.");
return MOS_STATUS_NO_SPACE;
}
}
pNotifyCommon = (PMOS_USER_FEATURE_NOTIFY_DATA_COMMON)pNotification->pHandle;
MOS_USER_FEATURE_KEY_PATH_INFO *ufInfo = Mos_GetDeviceUfPathInfo((PMOS_CONTEXT)mosCtx);
// Open User Feature for Reading
if (pNotifyCommon->UFKey == 0)
{
if((eStatus = MOS_UserFeature_Open(
pNotification->Type,
pNotification->pPath,
KEY_READ,
&pNotifyCommon->UFKey,
ufInfo)) != MOS_STATUS_SUCCESS)
{
MOS_OS_ASSERTMESSAGE("Failed to open user feature for reading.");
return MOS_STATUS_USER_FEATURE_KEY_OPEN_FAILED;
}
}
// Create Event for notification
if (pNotifyCommon->hEvent == nullptr)
{
pNotifyCommon->hEvent = MOS_CreateEventEx(
nullptr,
nullptr,
0);
if(pNotifyCommon->hEvent == nullptr)
{
MOS_OS_ASSERTMESSAGE("Failed to allocate memory.");
return MOS_STATUS_NO_SPACE;
}
}
// Unregister wait event if already registered
if (pNotifyCommon->hWaitEvent)
{
if ((bResult = MOS_UnregisterWaitEx(pNotifyCommon->hWaitEvent)) == false)
{
MOS_OS_ASSERTMESSAGE("Unable to unregiser wait event.");
return MOS_STATUS_EVENT_WAIT_UNREGISTER_FAILED;
}
pNotifyCommon->hWaitEvent = nullptr;
}
// Register a Callback
if((eStatus = MOS_UserFeatureNotifyChangeKeyValue(
pNotifyCommon->UFKey,
false,
pNotifyCommon->hEvent,
true)) != MOS_STATUS_SUCCESS)
{
MOS_OS_ASSERTMESSAGE("Unable to setup user feature key notification.");
return MOS_STATUS_UNKNOWN;
}
// Create a wait object
if ((bResult = MOS_UserFeatureWaitForSingleObject(
&pNotifyCommon->hWaitEvent,
pNotifyCommon->hEvent,
(void *)MOS_UserFeature_Callback,
pNotification)) == false)
{
MOS_OS_ASSERTMESSAGE("Failed to create a wait object.");
return MOS_STATUS_EVENT_WAIT_REGISTER_FAILED;
}
return MOS_STATUS_SUCCESS;
}
//!
//! \brief Disable user feature change notification
//! \details Disable user feature change notification
//! Unregister the wait event and frees notification data
//! \param PMOS_USER_FEATURE_INTERFACE pOsUserFeatureInterface
//! [in] Pointer to OS User Interface structure
//! \param PMOS_USER_FEATURE_NOTIFY_DATA pNotification
//! [in/out] Pointer to User Feature Notification Data
//! \return MOS_STATUS
//! Returns one of the MOS_STATUS error codes if failed,
//! else MOS_STATUS_SUCCESS
//!
MOS_STATUS MOS_UserFeature_DisableNotification(
PMOS_USER_FEATURE_INTERFACE pOsUserFeatureInterface,
PMOS_USER_FEATURE_NOTIFY_DATA pNotification)
{
PMOS_USER_FEATURE_NOTIFY_DATA_COMMON pNotifyDataCommon;
int32_t bResult;
MOS_STATUS eStatus;
MOS_UNUSED(pOsUserFeatureInterface);
//---------------------------------------
MOS_OS_ASSERT(pNotification);
//---------------------------------------
if (pNotification->pHandle)
{
pNotifyDataCommon = (PMOS_USER_FEATURE_NOTIFY_DATA_COMMON)
pNotification->pHandle;
if (pNotifyDataCommon->hWaitEvent)
{
if ((bResult = MOS_UnregisterWaitEx(pNotifyDataCommon->hWaitEvent)) == false)
{
MOS_OS_ASSERTMESSAGE("Unable to unregiser wait event.");
return MOS_STATUS_EVENT_WAIT_UNREGISTER_FAILED;
}
}
if (pNotifyDataCommon->UFKey)
{
if ((eStatus = MOS_UserFeatureCloseKey(pNotifyDataCommon->UFKey)) != MOS_STATUS_SUCCESS)
{
MOS_OS_ASSERTMESSAGE("User feature key close failed.");
return eStatus;
}
}
if (pNotifyDataCommon->hEvent)
{
MOS_CloseHandle(pNotifyDataCommon->hEvent);
}
// Free Notify Data Memory
MOS_FreeMemory(pNotifyDataCommon);
pNotification->pHandle = nullptr;
}
return MOS_STATUS_SUCCESS;
}
//!
//! \brief sinc
//! \details Calculate sinc(x)
//! \param float x
//! [in] float
//! \return float
//! sinc(x)
//!
float MOS_Sinc(float x)
{
return (MOS_ABS(x) < 1e-9f) ? 1.0F : (float)(sin(x) / x);
}
//!
//! \brief Lanczos
//! \details Calculate lanczos(x)
//! Basic formula is: lanczos(x)= MOS_Sinc(x) * MOS_Sinc(x / fLanczosT)
//! \param float x
//! [in] float
//! \param uint32_t dwNumEntries
//! [in] dword
//! \param float fLanczosT
//! [in]
//! \return float
//! lanczos(x)
//!
float MOS_Lanczos(float x, uint32_t dwNumEntries, float fLanczosT)
{
uint32_t dwNumHalfEntries;
dwNumHalfEntries = dwNumEntries >> 1;
if (fLanczosT < dwNumHalfEntries)
{
fLanczosT = (float)dwNumHalfEntries;
}
if (MOS_ABS(x) >= dwNumHalfEntries)
{
return 0.0;
}
x *= MOS_PI;
return MOS_Sinc(x) * MOS_Sinc(x / fLanczosT);
}
//!
//! \brief General Lanczos
//! \details Calculate lanczos(x) with odd entry num support
//! Basic formula is: lanczos(x)= MOS_Sinc(x) * MOS_Sinc(x / fLanczosT)
//! \param float x
//! [in] float
//! \param uint32_t dwNumEntries
//! [in] dword
//! \param float fLanczosT
//! [in]
//! \return float
//! lanczos(x)
//!
float MOS_Lanczos_g(float x, uint32_t dwNumEntries, float fLanczosT)
{
uint32_t dwNumHalfEntries;
dwNumHalfEntries = (dwNumEntries >> 1) + (dwNumEntries & 1);
if (fLanczosT < dwNumHalfEntries)
{
fLanczosT = (float)dwNumHalfEntries;
}
if (x > (dwNumEntries >> 1) || (- x) >= dwNumHalfEntries)
{
return 0.0;
}
x *= MOS_PI;
return MOS_Sinc(x) * MOS_Sinc(x / fLanczosT);
}
//!
//! \brief GCD
//! \details Recursive GCD calculation of two numbers
//! \param Number a
//! [in] uint32_t
//! \param Number b
//! [in] uint32_t
//! \return uint32_t
//! MOS_GCD(a, b)
//!
uint32_t MOS_GCD(uint32_t a, uint32_t b)
{
if (b == 0)
{
return a;
}
else
{
return MOS_GCD(b, a % b);
}
}
__inline int32_t __Mos_SwizzleOffset(
int32_t OffsetX,
int32_t OffsetY,
int32_t Pitch,
MOS_TILE_TYPE TileFormat,
int32_t CsxSwizzle,
int32_t ExtFlags)
{
// When dealing with a tiled surface, logical linear accesses to the
// surface (y * pitch + x) must be translated into appropriate tile-
// formated accesses--This is done by swizzling (rearranging/translating)
// the given access address--though it is important to note that the
// swizzling is actually done on the accessing OFFSET into a TILED
// REGION--not on the absolute address itself.
// (!) Y-MAJOR TILING, REINTERPRETATION: For our purposes here, Y-Major
// tiling will be thought of in a different way, we will deal with
// the 16-byte-wide columns individually--i.e., we will treat a single
// Y-Major tile as 8 separate, thinner tiles--Doing so allows us to
// deal with both X- and Y-Major tile formats in the same "X-Major"
// way--just with different dimensions: either 512B x 8 rows, or
// 16B x 32 rows, respectively.
// A linear offset into a surface is of the form
// y * pitch + x = y:x (Shorthand, meaning: y * (x's per y) + x)
//
// To treat a surface as being composed of tiles (though still being
// linear), just as a linear offset has a y:x composition--its y and x
// components can be thought of as having Row:Line and Column:X
// compositions, respectively, where Row specifies a row of tiles, Line
// specifies a row of pixels within a tile, Column specifies a column
// of tiles, and X in this context refers to a byte within a Line--i.e.,
// offset = y:x
// y = Row:Line
// x = Col:X
// offset = y:x = Row:Line:Col:X
// Given the Row:Line:Col:X composition of a linear offset, all that
// tile swizzling does is swap the Line and Col components--i.e.,
// Linear Offset: Row:Line:Col:X
// Swizzled Offset: Row:Col:Line:X
// And with our reinterpretation of the Y-Major tiling format, we can now
// describe both the X- and Y-Major tiling formats in two simple terms:
// (1) The bit-depth of their Lines component--LBits, and (2) the
// swizzled bit-position of the Lines component (after it swaps with the
// Col component)--LPos.
int32_t Row, Line, Col, x; // Linear Offset Components
int32_t LBits, LPos; // Size and swizzled position of the Line component.
int32_t SwizzledOffset;
if (TileFormat == MOS_TILE_LINEAR)
{
return(OffsetY * Pitch + OffsetX);
}
if (TileFormat == MOS_TILE_Y)
{
LBits = 5; // Log2(TileY.Height = 32)
LPos = 4; // Log2(TileY.PseudoWidth = 16)
}
else //if (TileFormat == MOS_TILE_X)
{
LBits = 3; // Log2(TileX.Height = 8)
LPos = 9; // Log2(TileX.Width = 512)
}
Row = OffsetY >> LBits; // OffsetY / LinesPerTile
Line = OffsetY & ((1 << LBits) - 1); // OffsetY % LinesPerTile
Col = OffsetX >> LPos; // OffsetX / BytesPerLine
x = OffsetX & ((1 << LPos) - 1); // OffsetX % BytesPerLine
SwizzledOffset =
(((((Row * (Pitch >> LPos)) + Col) << LBits) + Line) << LPos) + x;
// V V V
// / BytesPerLine * LinesPerTile * BytesPerLine
/// Channel Select XOR Swizzling ///////////////////////////////////////////
if (CsxSwizzle)
{
if (TileFormat == MOS_TILE_Y) // A6 = A6 ^ A9
{
SwizzledOffset ^= ((SwizzledOffset >> (9 - 6)) & 0x40);
}
else //if (TileFormat == VPHAL_TILE_X) // A6 = A6 ^ A9 ^ A10
{
SwizzledOffset ^= (((SwizzledOffset >> (9 - 6)) ^ (SwizzledOffset >> (10 - 6))) & 0x40);
}
}
return(SwizzledOffset);
}
//!
//! \brief Wrapper function for SwizzleOffset
//! \details Wrapper function for SwizzleOffset in Mos
//! \param [in] pSrc
//! Pointer to source data.
//! \param [out] pDst
//! Pointer to destiny data.
//! \param [in] SrcTiling
//! Source Tile Type
//! \param [in] DstTiling
//! Destiny Tile Type
//! \param [in] iHeight
//! Height
//! \param [in] iPitch
//! Pitch
//! \return void
//!
void Mos_SwizzleData(
uint8_t *pSrc,
uint8_t *pDst,
MOS_TILE_TYPE SrcTiling,
MOS_TILE_TYPE DstTiling,
int32_t iHeight,
int32_t iPitch,
int32_t extFlags)
{
#define IS_TILED(_a) ((_a) != MOS_TILE_LINEAR)
#define IS_TILED_TO_LINEAR(_a, _b) (IS_TILED(_a) && !IS_TILED(_b))
#define IS_LINEAR_TO_TILED(_a, _b) (!IS_TILED(_a) && IS_TILED(_b))
int32_t LinearOffset;
int32_t TileOffset;
int32_t x;
int32_t y;
// Translate from one format to another
for (y = 0, LinearOffset = 0, TileOffset = 0; y < iHeight; y++)
{
for (x = 0; x < iPitch; x++, LinearOffset++)
{
// x or y --> linear
if (IS_TILED_TO_LINEAR(SrcTiling, DstTiling))
{
TileOffset = Mos_SwizzleOffset(
x,
y,
iPitch,
SrcTiling,
false,
extFlags);
*(pDst + LinearOffset) = *(pSrc + TileOffset);
}
// linear --> x or y
else if (IS_LINEAR_TO_TILED(SrcTiling, DstTiling))
{
TileOffset = Mos_SwizzleOffset(
x,
y,
iPitch,
DstTiling,
false,
extFlags);
*(pDst + TileOffset) = *(pSrc + LinearOffset);
}
else
{
MOS_OS_ASSERT(0);
}
}
}
}
| 38.995366 | 169 | 0.684406 | [
"render",
"object",
"vector",
"model",
"transform"
] |
9cb8c149fac41b54c40107d9263d029a6abe1417 | 24,137 | cc | C++ | chrome/browser/translate/translate_manager.cc | anirudhSK/chromium | a8f23c87e656ab9ba49de9ccccbc53f614cdcb41 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/translate/translate_manager.cc | anirudhSK/chromium | a8f23c87e656ab9ba49de9ccccbc53f614cdcb41 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/translate/translate_manager.cc | anirudhSK/chromium | a8f23c87e656ab9ba49de9ccccbc53f614cdcb41 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2015-04-17T13:19:09.000Z | 2021-10-21T12:55:15.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/translate/translate_manager.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram.h"
#include "base/prefs/pref_service.h"
#include "base/strings/string_split.h"
#include "base/strings/stringprintf.h"
#include "base/time/time.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/translate/translate_tab_helper.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/url_constants.h"
#include "components/translate/core/browser/language_state.h"
#include "components/translate/core/browser/page_translated_details.h"
#include "components/translate/core/browser/translate_accept_languages.h"
#include "components/translate/core/browser/translate_browser_metrics.h"
#include "components/translate/core/browser/translate_download_manager.h"
#include "components/translate/core/browser/translate_error_details.h"
#include "components/translate/core/browser/translate_language_list.h"
#include "components/translate/core/browser/translate_prefs.h"
#include "components/translate/core/browser/translate_script.h"
#include "components/translate/core/browser/translate_url_util.h"
#include "components/translate/core/common/language_detection_details.h"
#include "components/translate/core/common/translate_constants.h"
#include "components/translate/core/common/translate_pref_names.h"
#include "components/translate/core/common/translate_switches.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "net/base/url_util.h"
#include "net/http/http_status_code.h"
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/file_manager/app_id.h"
#include "extensions/common/constants.h"
#endif
using content::NavigationController;
using content::NavigationEntry;
using content::WebContents;
namespace {
// Callbacks for translate errors.
TranslateManager::TranslateErrorCallbackList* g_callback_list_ = NULL;
const char kReportLanguageDetectionErrorURL[] =
"https://translate.google.com/translate_error?client=cr&action=langidc";
// Used in kReportLanguageDetectionErrorURL to specify the original page
// language.
const char kSourceLanguageQueryName[] = "sl";
// Used in kReportLanguageDetectionErrorURL to specify the page URL.
const char kUrlQueryName[] = "u";
// The maximum number of attempts we'll do to see if the page has finshed
// loading before giving up the translation
const int kMaxTranslateLoadCheckAttempts = 20;
// Notifies |g_callback_list_| of translate errors.
void NotifyTranslateError(const TranslateErrorDetails& details) {
if (!g_callback_list_)
return;
g_callback_list_->Notify(details);
}
} // namespace
TranslateManager::~TranslateManager() {}
// static
bool TranslateManager::IsTranslatableURL(const GURL& url) {
// A URLs is translatable unless it is one of the following:
// - empty (can happen for popups created with window.open(""))
// - an internal URL (chrome:// and others)
// - the devtools (which is considered UI)
// - Chrome OS file manager extension
// - an FTP page (as FTP pages tend to have long lists of filenames that may
// confuse the CLD)
return !url.is_empty() &&
!url.SchemeIs(content::kChromeUIScheme) &&
!url.SchemeIs(content::kChromeDevToolsScheme) &&
#if defined(OS_CHROMEOS)
!(url.SchemeIs(extensions::kExtensionScheme) &&
url.DomainIs(file_manager::kFileManagerAppId)) &&
#endif
!url.SchemeIs(content::kFtpScheme);
}
void TranslateManager::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
switch (type) {
case content::NOTIFICATION_NAV_ENTRY_COMMITTED: {
NavigationController* controller =
content::Source<NavigationController>(source).ptr();
DCHECK_EQ(&translate_tab_helper_->GetWebContents()->GetController(),
controller);
content::LoadCommittedDetails* load_details =
content::Details<content::LoadCommittedDetails>(details).ptr();
NavigationEntry* entry = controller->GetActiveEntry();
if (!entry) {
NOTREACHED();
return;
}
if (!translate_tab_helper_->GetWebContents())
return;
// If the navigation happened while offline don't show the translate
// bar since there will be nothing to translate.
if (load_details->http_status_code == 0 ||
load_details->http_status_code == net::HTTP_INTERNAL_SERVER_ERROR) {
return;
}
if (!load_details->is_main_frame &&
translate_tab_helper_->GetLanguageState().translation_declined()) {
// Some sites (such as Google map) may trigger sub-frame navigations
// when the user interacts with the page. We don't want to show a new
// infobar if the user already dismissed one in that case.
return;
}
if (entry->GetTransitionType() != content::PAGE_TRANSITION_RELOAD &&
load_details->type != content::NAVIGATION_TYPE_SAME_PAGE) {
return;
}
// When doing a page reload, TAB_LANGUAGE_DETERMINED is not sent,
// so the translation needs to be explicitly initiated, but only when the
// page needs translation.
if (!translate_tab_helper_->GetLanguageState().page_needs_translation())
return;
// Note that we delay it as the TranslateManager gets this notification
// before the WebContents and the WebContents processing might remove the
// current infobars. Since InitTranslation might add an infobar, it must
// be done after that.
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(
&TranslateManager::InitiateTranslationPosted,
weak_method_factory_.GetWeakPtr(),
translate_tab_helper_->GetLanguageState().original_language(),
0));
break;
}
case chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED: {
const LanguageDetectionDetails* lang_det_details =
content::Details<const LanguageDetectionDetails>(details).ptr();
WebContents* tab = content::Source<WebContents>(source).ptr();
DCHECK_EQ(translate_tab_helper_->GetWebContents(), tab);
if (!translate_tab_helper_->GetWebContents())
return;
// We may get this notifications multiple times. Make sure to translate
// only once.
LanguageState& language_state = translate_tab_helper_->GetLanguageState();
if (language_state.page_needs_translation() &&
!language_state.translation_pending() &&
!language_state.translation_declined() &&
!language_state.IsPageTranslated()) {
std::string language = lang_det_details->adopted_language;
InitiateTranslation(language);
}
break;
}
case chrome::NOTIFICATION_PAGE_TRANSLATED: {
// Only add translate infobar if it doesn't exist; if it already exists,
// just update the state, the actual infobar would have received the same
// notification and update the visual display accordingly.
PageTranslatedDetails* page_translated_details =
content::Details<PageTranslatedDetails>(details).ptr();
PageTranslated(page_translated_details);
break;
}
default:
NOTREACHED();
}
}
// static
scoped_ptr<TranslateManager::TranslateErrorCallbackList::Subscription>
TranslateManager::RegisterTranslateErrorCallback(
const TranslateManager::TranslateErrorCallback& callback) {
if (!g_callback_list_)
g_callback_list_ = new TranslateErrorCallbackList;
return g_callback_list_->Add(callback);
}
TranslateManager::TranslateManager(TranslateTabHelper* helper)
: max_reload_check_attempts_(kMaxTranslateLoadCheckAttempts),
translate_tab_helper_(helper),
weak_method_factory_(this) {
WebContents* web_contents = translate_tab_helper_->GetWebContents();
notification_registrar_.Add(
this, content::NOTIFICATION_NAV_ENTRY_COMMITTED,
content::Source<NavigationController>(&web_contents->GetController()));
notification_registrar_.Add(this,
chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
content::Source<WebContents>(web_contents));
notification_registrar_.Add(this,
chrome::NOTIFICATION_PAGE_TRANSLATED,
content::Source<WebContents>(web_contents));
}
void TranslateManager::InitiateTranslation(const std::string& page_lang) {
WebContents* web_contents = translate_tab_helper_->GetWebContents();
DCHECK(web_contents);
Profile* profile =
Profile::FromBrowserContext(web_contents->GetBrowserContext());
Profile* original_profile = profile->GetOriginalProfile();
PrefService* prefs = original_profile->GetPrefs();
if (!prefs->GetBoolean(prefs::kEnableTranslate)) {
TranslateBrowserMetrics::ReportInitiationStatus(
TranslateBrowserMetrics::INITIATION_STATUS_DISABLED_BY_PREFS);
const std::string& locale =
TranslateDownloadManager::GetInstance()->application_locale();
TranslateBrowserMetrics::ReportLocalesOnDisabledByPrefs(locale);
return;
}
// Allow disabling of translate from the command line to assist with
// automated browser testing.
if (CommandLine::ForCurrentProcess()->HasSwitch(
translate::switches::kDisableTranslate)) {
TranslateBrowserMetrics::ReportInitiationStatus(
TranslateBrowserMetrics::INITIATION_STATUS_DISABLED_BY_SWITCH);
return;
}
// MHTML pages currently cannot be translated.
// See bug: 217945.
if (web_contents->GetContentsMimeType() == "multipart/related") {
TranslateBrowserMetrics::ReportInitiationStatus(
TranslateBrowserMetrics::INITIATION_STATUS_MIME_TYPE_IS_NOT_SUPPORTED);
return;
}
// Don't translate any Chrome specific page, e.g., New Tab Page, Download,
// History, and so on.
GURL page_url = web_contents->GetURL();
if (!IsTranslatableURL(page_url)) {
TranslateBrowserMetrics::ReportInitiationStatus(
TranslateBrowserMetrics::INITIATION_STATUS_URL_IS_NOT_SUPPORTED);
return;
}
std::string target_lang = GetTargetLanguage(prefs);
std::string language_code =
TranslateDownloadManager::GetLanguageCode(page_lang);
// Don't translate similar languages (ex: en-US to en).
if (language_code == target_lang) {
TranslateBrowserMetrics::ReportInitiationStatus(
TranslateBrowserMetrics::INITIATION_STATUS_SIMILAR_LANGUAGES);
return;
}
// Nothing to do if either the language Chrome is in or the language of the
// page is not supported by the translation server.
if (target_lang.empty() ||
!TranslateDownloadManager::IsSupportedLanguage(language_code)) {
TranslateBrowserMetrics::ReportInitiationStatus(
TranslateBrowserMetrics::INITIATION_STATUS_LANGUAGE_IS_NOT_SUPPORTED);
TranslateBrowserMetrics::ReportUnsupportedLanguageAtInitiation(
language_code);
return;
}
scoped_ptr<TranslatePrefs> translate_prefs(
TranslateTabHelper::CreateTranslatePrefs(profile->GetPrefs()));
TranslateAcceptLanguages* accept_languages =
TranslateTabHelper::GetTranslateAcceptLanguages(profile);
// Don't translate any user black-listed languages.
if (!translate_prefs->CanTranslateLanguage(accept_languages,
language_code)) {
TranslateBrowserMetrics::ReportInitiationStatus(
TranslateBrowserMetrics::INITIATION_STATUS_DISABLED_BY_CONFIG);
return;
}
// Don't translate any user black-listed URLs.
if (translate_prefs->IsSiteBlacklisted(page_url.HostNoBrackets())) {
TranslateBrowserMetrics::ReportInitiationStatus(
TranslateBrowserMetrics::INITIATION_STATUS_DISABLED_BY_CONFIG);
return;
}
// If the user has previously selected "always translate" for this language we
// automatically translate. Note that in incognito mode we disable that
// feature; the user will get an infobar, so they can control whether the
// page's text is sent to the translate server.
if (!web_contents->GetBrowserContext()->IsOffTheRecord()) {
std::string auto_target_lang = GetAutoTargetLanguage(language_code, prefs);
if (!auto_target_lang.empty()) {
TranslateBrowserMetrics::ReportInitiationStatus(
TranslateBrowserMetrics::INITIATION_STATUS_AUTO_BY_CONFIG);
TranslatePage(language_code, auto_target_lang, false);
return;
}
}
LanguageState& language_state = translate_tab_helper_->GetLanguageState();
std::string auto_translate_to = language_state.AutoTranslateTo();
if (!auto_translate_to.empty()) {
// This page was navigated through a click from a translated page.
TranslateBrowserMetrics::ReportInitiationStatus(
TranslateBrowserMetrics::INITIATION_STATUS_AUTO_BY_LINK);
TranslatePage(language_code, auto_translate_to, false);
return;
}
TranslateBrowserMetrics::ReportInitiationStatus(
TranslateBrowserMetrics::INITIATION_STATUS_SHOW_INFOBAR);
// Prompts the user if he/she wants the page translated.
translate_tab_helper_->ShowTranslateUI(TranslateTabHelper::BEFORE_TRANSLATE,
language_code,
target_lang,
TranslateErrors::NONE,
false);
}
void TranslateManager::InitiateTranslationPosted(const std::string& page_lang,
int attempt) {
WebContents* web_contents = translate_tab_helper_->GetWebContents();
DCHECK(web_contents);
if (translate_tab_helper_->GetLanguageState().translation_pending())
return;
// During a reload we need web content to be available before the
// translate script is executed. Otherwise we will run the translate script on
// an empty DOM which will fail. Therefore we wait a bit to see if the page
// has finished.
if ((web_contents->IsLoading()) && attempt < kMaxTranslateLoadCheckAttempts) {
int backoff = attempt * max_reload_check_attempts_;
base::MessageLoop::current()->PostDelayedTask(
FROM_HERE, base::Bind(&TranslateManager::InitiateTranslationPosted,
weak_method_factory_.GetWeakPtr(),
page_lang, ++attempt),
base::TimeDelta::FromMilliseconds(backoff));
return;
}
InitiateTranslation(TranslateDownloadManager::GetLanguageCode(page_lang));
}
void TranslateManager::TranslatePage(const std::string& original_source_lang,
const std::string& target_lang,
bool triggered_from_menu) {
WebContents* web_contents = translate_tab_helper_->GetWebContents();
DCHECK(web_contents);
NavigationEntry* entry = web_contents->GetController().GetActiveEntry();
if (!entry) {
NOTREACHED();
return;
}
// Translation can be kicked by context menu against unsupported languages.
// Unsupported language strings should be replaced with
// kUnknownLanguageCode in order to send a translation request with enabling
// server side auto language detection.
std::string source_lang(original_source_lang);
if (!TranslateDownloadManager::IsSupportedLanguage(source_lang))
source_lang = std::string(translate::kUnknownLanguageCode);
translate_tab_helper_->ShowTranslateUI(TranslateTabHelper::TRANSLATING,
source_lang,
target_lang,
TranslateErrors::NONE,
triggered_from_menu);
TranslateScript* script = TranslateDownloadManager::GetInstance()->script();
DCHECK(script != NULL);
const std::string& script_data = script->data();
if (!script_data.empty()) {
DoTranslatePage(script_data, source_lang, target_lang);
return;
}
// The script is not available yet. Queue that request and query for the
// script. Once it is downloaded we'll do the translate.
TranslateScript::RequestCallback callback =
base::Bind(&TranslateManager::OnTranslateScriptFetchComplete,
weak_method_factory_.GetWeakPtr(),
entry->GetPageID(),
source_lang,
target_lang);
script->Request(callback);
}
void TranslateManager::RevertTranslation() {
WebContents* web_contents = translate_tab_helper_->GetWebContents();
NavigationEntry* entry = web_contents->GetController().GetActiveEntry();
if (!entry) {
NOTREACHED();
return;
}
web_contents->GetRenderViewHost()->Send(new ChromeViewMsg_RevertTranslation(
web_contents->GetRenderViewHost()->GetRoutingID(), entry->GetPageID()));
translate_tab_helper_->GetLanguageState().SetCurrentLanguage(
translate_tab_helper_->GetLanguageState().original_language());
}
void TranslateManager::ReportLanguageDetectionError() {
TranslateBrowserMetrics::ReportLanguageDetectionError();
// We'll open the URL in a new tab so that the user can tell us more.
WebContents* web_contents = translate_tab_helper_->GetWebContents();
Browser* browser = chrome::FindBrowserWithWebContents(web_contents);
if (!browser) {
NOTREACHED();
return;
}
GURL report_error_url = GURL(kReportLanguageDetectionErrorURL);
GURL page_url = web_contents->GetController().GetActiveEntry()->GetURL();
report_error_url = net::AppendQueryParameter(
report_error_url,
kUrlQueryName,
page_url.spec());
report_error_url = net::AppendQueryParameter(
report_error_url,
kSourceLanguageQueryName,
translate_tab_helper_->GetLanguageState().original_language());
report_error_url = TranslateURLUtil::AddHostLocaleToUrl(report_error_url);
report_error_url = TranslateURLUtil::AddApiKeyToUrl(report_error_url);
chrome::AddSelectedTabWithURL(browser, report_error_url,
content::PAGE_TRANSITION_AUTO_BOOKMARK);
}
void TranslateManager::DoTranslatePage(const std::string& translate_script,
const std::string& source_lang,
const std::string& target_lang) {
WebContents* web_contents = translate_tab_helper_->GetWebContents();
DCHECK(web_contents);
NavigationEntry* entry = web_contents->GetController().GetActiveEntry();
if (!entry) {
NOTREACHED();
return;
}
translate_tab_helper_->GetLanguageState().set_translation_pending(true);
web_contents->GetRenderViewHost()->Send(new ChromeViewMsg_TranslatePage(
web_contents->GetRenderViewHost()->GetRoutingID(), entry->GetPageID(),
translate_script, source_lang, target_lang));
}
void TranslateManager::PageTranslated(PageTranslatedDetails* details) {
if ((details->error_type == TranslateErrors::NONE) &&
details->source_language != translate::kUnknownLanguageCode &&
!TranslateDownloadManager::IsSupportedLanguage(
details->source_language)) {
details->error_type = TranslateErrors::UNSUPPORTED_LANGUAGE;
}
DCHECK(translate_tab_helper_->GetWebContents());
translate_tab_helper_->ShowTranslateUI(TranslateTabHelper::AFTER_TRANSLATE,
details->source_language,
details->target_language,
details->error_type,
false);
WebContents* web_contents = translate_tab_helper_->GetWebContents();
if (details->error_type != TranslateErrors::NONE &&
!web_contents->GetBrowserContext()->IsOffTheRecord()) {
TranslateErrorDetails error_details;
error_details.time = base::Time::Now();
error_details.url = web_contents->GetLastCommittedURL();
error_details.error = details->error_type;
NotifyTranslateError(error_details);
}
}
void TranslateManager::OnTranslateScriptFetchComplete(
int page_id,
const std::string& source_lang,
const std::string& target_lang,
bool success,
const std::string& data) {
WebContents* web_contents = translate_tab_helper_->GetWebContents();
DCHECK(web_contents);
NavigationEntry* entry = web_contents->GetController().GetActiveEntry();
if (!entry || entry->GetPageID() != page_id) {
// We navigated away from the page the translation was triggered on.
return;
}
if (success) {
// Translate the page.
TranslateScript* translate_script =
TranslateDownloadManager::GetInstance()->script();
DCHECK(translate_script);
DoTranslatePage(translate_script->data(), source_lang, target_lang);
} else {
translate_tab_helper_->ShowTranslateUI(TranslateTabHelper::TRANSLATE_ERROR,
source_lang,
target_lang,
TranslateErrors::NETWORK,
false);
if (!web_contents->GetBrowserContext()->IsOffTheRecord()) {
TranslateErrorDetails error_details;
error_details.time = base::Time::Now();
error_details.url = entry->GetURL();
error_details.error = TranslateErrors::NETWORK;
NotifyTranslateError(error_details);
}
}
}
// static
std::string TranslateManager::GetTargetLanguage(PrefService* prefs) {
std::string ui_lang = TranslatePrefs::ConvertLangCodeForTranslation(
TranslateDownloadManager::GetLanguageCode(
TranslateDownloadManager::GetInstance()->application_locale()));
if (TranslateDownloadManager::IsSupportedLanguage(ui_lang))
return ui_lang;
// Getting the accepted languages list
std::string accept_langs_str = prefs->GetString(prefs::kAcceptLanguages);
std::vector<std::string> accept_langs_list;
base::SplitString(accept_langs_str, ',', &accept_langs_list);
// Will translate to the first supported language on the Accepted Language
// list or not at all if no such candidate exists
std::vector<std::string>::iterator iter;
for (iter = accept_langs_list.begin();
iter != accept_langs_list.end(); ++iter) {
std::string lang_code = TranslateDownloadManager::GetLanguageCode(*iter);
if (TranslateDownloadManager::IsSupportedLanguage(lang_code))
return lang_code;
}
return std::string();
}
// static
std::string TranslateManager::GetAutoTargetLanguage(
const std::string& original_language,
PrefService* prefs) {
std::string auto_target_lang;
scoped_ptr<TranslatePrefs> translate_prefs(
TranslateTabHelper::CreateTranslatePrefs(prefs));
if (translate_prefs->ShouldAutoTranslate(original_language,
&auto_target_lang)) {
// We need to confirm that the saved target language is still supported.
// Also, GetLanguageCode will take care of removing country code if any.
auto_target_lang =
TranslateDownloadManager::GetLanguageCode(auto_target_lang);
if (TranslateDownloadManager::IsSupportedLanguage(auto_target_lang))
return auto_target_lang;
}
return std::string();
}
| 40.910169 | 80 | 0.712309 | [
"vector"
] |
9cb927bf30edec8db0b52cd87ad18e5994c6d9cd | 40,551 | cpp | C++ | Userland/Libraries/LibTLS/TLSv12.cpp | sidkapoor97/serenity | 325febf4e534fde96c01abad4a69deb6fdc832e5 | [
"BSD-2-Clause"
] | 1 | 2021-06-11T13:40:55.000Z | 2021-06-11T13:40:55.000Z | Userland/Libraries/LibTLS/TLSv12.cpp | sidkapoor97/serenity | 325febf4e534fde96c01abad4a69deb6fdc832e5 | [
"BSD-2-Clause"
] | null | null | null | Userland/Libraries/LibTLS/TLSv12.cpp | sidkapoor97/serenity | 325febf4e534fde96c01abad4a69deb6fdc832e5 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2020, Ali Mohammad Pur <mpfard@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/Debug.h>
#include <AK/Endian.h>
#include <LibCore/ConfigFile.h>
#include <LibCore/DateTime.h>
#include <LibCore/File.h>
#include <LibCore/FileStream.h>
#include <LibCore/Timer.h>
#include <LibCrypto/ASN1/ASN1.h>
#include <LibCrypto/ASN1/DER.h>
#include <LibCrypto/ASN1/PEM.h>
#include <LibCrypto/PK/Code/EMSA_PSS.h>
#include <LibTLS/TLSv12.h>
#include <errno.h>
#ifndef SOCK_NONBLOCK
# include <sys/ioctl.h>
#endif
namespace TLS {
constexpr static Array<int, 4>
common_name_oid { 2, 5, 4, 3 },
country_name_oid { 2, 5, 4, 6 },
locality_name_oid { 2, 5, 4, 7 },
organization_name_oid { 2, 5, 4, 10 },
organizational_unit_name_oid { 2, 5, 4, 11 };
constexpr static Array<int, 7>
rsa_encryption_oid { 1, 2, 840, 113549, 1, 1, 1 },
rsa_md5_encryption_oid { 1, 2, 840, 113549, 1, 1, 4 },
rsa_sha1_encryption_oid { 1, 2, 840, 113549, 1, 1, 5 },
rsa_sha256_encryption_oid { 1, 2, 840, 113549, 1, 1, 11 },
rsa_sha512_encryption_oid { 1, 2, 840, 113549, 1, 1, 13 };
constexpr static Array<int, 4>
subject_alternative_name_oid { 2, 5, 29, 17 };
Optional<Certificate> TLSv12::parse_asn1(ReadonlyBytes buffer, bool) const
{
#define ENTER_SCOPE_WITHOUT_TYPECHECK(scope) \
do { \
if (auto result = decoder.enter(); result.has_value()) { \
dbgln_if(TLS_DEBUG, "Failed to enter object (" scope "): {}", result.value()); \
return {}; \
} \
} while (0)
#define ENTER_SCOPE_OR_FAIL(kind_name, scope) \
do { \
if (auto tag = decoder.peek(); tag.is_error() || tag.value().kind != Crypto::ASN1::Kind::kind_name) { \
if constexpr (TLS_DEBUG) { \
if (tag.is_error()) \
dbgln(scope " data was invalid: {}", tag.error()); \
else \
dbgln(scope " data was not of kind " #kind_name); \
} \
return {}; \
} \
ENTER_SCOPE_WITHOUT_TYPECHECK(scope); \
} while (0)
#define EXIT_SCOPE(scope) \
do { \
if (auto error = decoder.leave(); error.has_value()) { \
dbgln_if(TLS_DEBUG, "Error while exiting scope " scope ": {}", error.value()); \
return {}; \
} \
} while (0)
#define ENSURE_OBJECT_KIND(_kind_name, scope) \
do { \
if (auto tag = decoder.peek(); tag.is_error() || tag.value().kind != Crypto::ASN1::Kind::_kind_name) { \
if constexpr (TLS_DEBUG) { \
if (tag.is_error()) \
dbgln(scope " data was invalid: {}", tag.error()); \
else \
dbgln(scope " data was not of kind " #_kind_name ", it was {}", Crypto::ASN1::kind_name(tag.value().kind)); \
} \
return {}; \
} \
} while (0)
#define READ_OBJECT_OR_FAIL(kind_name, type_name, value_name, scope) \
auto value_name##_result = decoder.read<type_name>(Crypto::ASN1::Class::Universal, Crypto::ASN1::Kind::kind_name); \
if (value_name##_result.is_error()) { \
dbgln_if(TLS_DEBUG, scope " read of kind " #kind_name " failed: {}", value_name##_result.error()); \
return {}; \
} \
auto value_name = value_name##_result.release_value();
#define DROP_OBJECT_OR_FAIL(scope) \
do { \
if (auto error = decoder.drop(); error.has_value()) { \
dbgln_if(TLS_DEBUG, scope " read failed: {}", error.value()); \
} \
} while (0)
Certificate certificate;
Crypto::ASN1::Decoder decoder { buffer };
// Certificate ::= Sequence {
// certificate TBSCertificate,
// signature_algorithm AlgorithmIdentifier,
// signature_value BitString
// }
ENTER_SCOPE_OR_FAIL(Sequence, "Certificate");
// TBSCertificate ::= Sequence {
// version (0) EXPLICIT Version DEFAULT v1,
// serial_number CertificateSerialNumber,
// signature AlgorithmIdentifier,
// issuer Name,
// validity Validity,
// subject Name,
// subject_public_key_info SubjectPublicKeyInfo,
// issuer_unique_id (1) IMPLICIT UniqueIdentifer OPTIONAL (if present, version > v1),
// subject_unique_id (2) IMPLICIT UniqueIdentiier OPTIONAL (if present, version > v1),
// extensions (3) EXPLICIT Extensions OPTIONAL (if present, version > v2)
// }
ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate");
// version
{
// Version :: Integer { v1(0), v2(1), v3(2) } (Optional)
if (auto tag = decoder.peek(); !tag.is_error() && tag.value().type == Crypto::ASN1::Type::Constructed) {
ENTER_SCOPE_WITHOUT_TYPECHECK("Certificate::version");
READ_OBJECT_OR_FAIL(Integer, Crypto::UnsignedBigInteger, value, "Certificate::version");
if (!(value < 3)) {
dbgln_if(TLS_DEBUG, "Certificate::version Invalid value for version: {}", value.to_base10());
return {};
}
certificate.version = value.words()[0];
EXIT_SCOPE("Certificate::version");
} else {
certificate.version = 0;
}
}
// serial_number
{
// CertificateSerialNumber :: Integer
READ_OBJECT_OR_FAIL(Integer, Crypto::UnsignedBigInteger, value, "Certificate::serial_number");
certificate.serial_number = move(value);
}
auto parse_algorithm_identifier = [&](CertificateKeyAlgorithm& field) -> Optional<bool> {
// AlgorithmIdentifier ::= Sequence {
// algorithm ObjectIdentifier,
// parameters ANY OPTIONAL
// }
ENTER_SCOPE_OR_FAIL(Sequence, "AlgorithmIdentifier");
READ_OBJECT_OR_FAIL(ObjectIdentifier, Vector<int>, identifier, "AlgorithmIdentifier::algorithm");
if (identifier == rsa_encryption_oid)
field = CertificateKeyAlgorithm ::RSA_RSA;
else if (identifier == rsa_md5_encryption_oid)
field = CertificateKeyAlgorithm ::RSA_MD5;
else if (identifier == rsa_sha1_encryption_oid)
field = CertificateKeyAlgorithm ::RSA_SHA1;
else if (identifier == rsa_sha256_encryption_oid)
field = CertificateKeyAlgorithm ::RSA_SHA256;
else if (identifier == rsa_sha512_encryption_oid)
field = CertificateKeyAlgorithm ::RSA_SHA512;
else
return {};
EXIT_SCOPE("AlgorithmIdentifier");
return true;
};
// signature
{
if (!parse_algorithm_identifier(certificate.algorithm).has_value())
return {};
}
auto parse_name = [&](auto& name_struct) -> Optional<bool> {
// Name ::= Choice {
// rdn_sequence RDNSequence
// } // NOTE: since this is the only alternative, there's no index
// RDNSequence ::= Sequence OF RelativeDistinguishedName
ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::issuer/subject");
// RelativeDistinguishedName ::= Set OF AttributeTypeAndValue
// AttributeTypeAndValue ::= Sequence {
// type AttributeType,
// value AttributeValue
// }
// AttributeType ::= ObjectIdentifier
// AttributeValue ::= Any
while (!decoder.eof()) {
// Parse only the the required fields, and ignore the rest.
ENTER_SCOPE_OR_FAIL(Set, "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName");
while (!decoder.eof()) {
ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue");
ENSURE_OBJECT_KIND(ObjectIdentifier, "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::type");
if (auto type_identifier_or_error = decoder.read<Vector<int>>(); !type_identifier_or_error.is_error()) {
// Figure out what type of identifier this is
auto& identifier = type_identifier_or_error.value();
if (identifier == common_name_oid) {
READ_OBJECT_OR_FAIL(PrintableString, StringView, name,
"Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::Value");
name_struct.subject = name;
} else if (identifier == country_name_oid) {
READ_OBJECT_OR_FAIL(PrintableString, StringView, name,
"Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::Value");
name_struct.country = name;
} else if (identifier == locality_name_oid) {
READ_OBJECT_OR_FAIL(PrintableString, StringView, name,
"Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::Value");
name_struct.location = name;
} else if (identifier == organization_name_oid) {
READ_OBJECT_OR_FAIL(PrintableString, StringView, name,
"Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::Value");
name_struct.entity = name;
} else if (identifier == organizational_unit_name_oid) {
READ_OBJECT_OR_FAIL(PrintableString, StringView, name,
"Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::Value");
name_struct.unit = name;
}
} else {
dbgln_if(TLS_DEBUG, "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::type data was invalid: {}", type_identifier_or_error.error());
return {};
}
EXIT_SCOPE("Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue");
}
EXIT_SCOPE("Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName");
}
EXIT_SCOPE("Certificate::TBSCertificate::issuer/subject");
return true;
};
// issuer
{
if (!parse_name(certificate.issuer).has_value())
return {};
}
// validity
{
ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::Validity");
auto parse_time = [&](Core::DateTime& datetime) -> Optional<bool> {
// Time ::= Choice {
// utc_time UTCTime,
// general_time GeneralizedTime
// }
auto tag = decoder.peek();
if (tag.is_error()) {
dbgln_if(1, "Certificate::TBSCertificate::Validity::$::Time failed to read tag: {}", tag.error());
return {};
};
if (tag.value().kind == Crypto::ASN1::Kind::UTCTime) {
READ_OBJECT_OR_FAIL(UTCTime, StringView, time, "Certificate::TBSCertificate::Validity::$");
auto result = Crypto::ASN1::parse_utc_time(time);
if (!result.has_value()) {
dbgln_if(1, "Certificate::TBSCertificate::Validity::$::Time Invalid UTC Time: {}", time);
return {};
}
datetime = result.release_value();
return true;
}
if (tag.value().kind == Crypto::ASN1::Kind::GeneralizedTime) {
READ_OBJECT_OR_FAIL(UTCTime, StringView, time, "Certificate::TBSCertificate::Validity::$");
auto result = Crypto::ASN1::parse_generalized_time(time);
if (!result.has_value()) {
dbgln_if(1, "Certificate::TBSCertificate::Validity::$::Time Invalid Generalized Time: {}", time);
return {};
}
datetime = result.release_value();
return true;
}
dbgln_if(1, "Unrecognised Time format {}", Crypto::ASN1::kind_name(tag.value().kind));
return {};
};
if (!parse_time(certificate.not_before).has_value())
return {};
if (!parse_time(certificate.not_after).has_value())
return {};
EXIT_SCOPE("Certificate::TBSCertificate::Validity");
}
// subject
{
if (!parse_name(certificate.subject).has_value())
return {};
}
// subject_public_key_info
{
// SubjectPublicKeyInfo ::= Sequence {
// algorithm AlgorithmIdentifier,
// subject_public_key BitString
// }
ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::subject_public_key_info");
if (!parse_algorithm_identifier(certificate.key_algorithm).has_value())
return {};
READ_OBJECT_OR_FAIL(BitString, const BitmapView, value, "Certificate::TBSCertificate::subject_public_key_info::subject_public_key_info");
// Note: Once we support other kinds of keys, make sure to check the kind here!
auto key = Crypto::PK::RSA::parse_rsa_key({ value.data(), value.size_in_bytes() });
if (!key.public_key.length()) {
dbgln_if(TLS_DEBUG, "Certificate::TBSCertificate::subject_public_key_info::subject_public_key_info: Invalid key");
return {};
}
certificate.public_key = move(key.public_key);
EXIT_SCOPE("Certificate::TBSCertificate::subject_public_key_info");
}
auto parse_unique_identifier = [&]() -> Optional<bool> {
if (certificate.version == 0)
return true;
auto tag = decoder.peek();
if (tag.is_error()) {
dbgln_if(TLS_DEBUG, "Certificate::TBSCertificate::*::UniqueIdentifier could not read tag: {}", tag.error());
return {};
}
// The spec says to just ignore these.
if (static_cast<u8>(tag.value().kind) == 1 || static_cast<u8>(tag.value().kind) == 2)
DROP_OBJECT_OR_FAIL("UniqueIdentifier");
return true;
};
// issuer_unique_identifier
{
if (!parse_unique_identifier().has_value())
return {};
}
// subject_unique_identifier
{
if (!parse_unique_identifier().has_value())
return {};
}
// extensions
{
if (certificate.version == 2) {
auto tag = decoder.peek();
if (tag.is_error()) {
dbgln_if(TLS_DEBUG, "Certificate::TBSCertificate::*::UniqueIdentifier could not read tag: {}", tag.error());
return {};
}
if (static_cast<u8>(tag.value().kind) == 3) {
// Extensions ::= Sequence OF Extension
// Extension ::= Sequence {
// extension_id ObjectIdentifier,
// critical Boolean DEFAULT false,
// extension_value OctetString (DER-encoded)
// }
ENTER_SCOPE_WITHOUT_TYPECHECK("Certificate::TBSCertificate::Extensions(IMPLICIT)");
ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::Extensions");
while (!decoder.eof()) {
ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::Extensions::$::Extension");
READ_OBJECT_OR_FAIL(ObjectIdentifier, Vector<int>, extension_id, "Certificate::TBSCertificate::Extensions::$::Extension::extension_id");
bool is_critical = false;
if (auto tag = decoder.peek(); !tag.is_error() && tag.value().kind == Crypto::ASN1::Kind::Boolean) {
// Read the 'critical' property
READ_OBJECT_OR_FAIL(Boolean, bool, critical, "Certificate::TBSCertificate::Extensions::$::Extension::critical");
is_critical = critical;
}
READ_OBJECT_OR_FAIL(OctetString, StringView, extension_value, "Certificate::TBSCertificate::Extensions::$::Extension::extension_value");
// Figure out what this extension is.
if (extension_id == subject_alternative_name_oid) {
Crypto::ASN1::Decoder decoder { extension_value.bytes() };
// SubjectAlternativeName ::= GeneralNames
// GeneralNames ::= Sequence OF GeneralName
// GeneralName ::= CHOICE {
// other_name (0) OtherName,
// rfc_822_name (1) IA5String,
// dns_name (2) IA5String,
// x400Address (3) ORAddress,
// directory_name (4) Name,
// edi_party_name (5) EDIPartyName,
// uri (6) IA5String,
// ip_address (7) OctetString,
// registered_id (8) ObjectIdentifier,
// }
ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName");
while (!decoder.eof()) {
auto tag = decoder.peek();
if (tag.is_error()) {
dbgln_if(TLS_DEBUG, "Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$ could not read tag: {}", tag.error());
return {};
}
auto tag_value = static_cast<u8>(tag.value().kind);
switch (tag_value) {
case 0:
// OtherName
// We don't know how to use this.
DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::OtherName");
break;
case 1:
// RFC 822 name
// We don't know how to use this.
DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::RFC822Name");
break;
case 2: {
// DNS Name
READ_OBJECT_OR_FAIL(IA5String, StringView, name, "Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::DNSName");
certificate.SAN.append(name);
break;
}
case 3:
// x400Address
// We don't know how to use this.
DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::X400Adress");
break;
case 4:
// Directory name
// We don't know how to use this.
DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::DirectoryName");
break;
case 5:
// edi party name
// We don't know how to use this.
DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::EDIPartyName");
break;
case 6: {
// URI
READ_OBJECT_OR_FAIL(IA5String, StringView, name, "Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::URI");
certificate.SAN.append(name);
break;
}
case 7:
// IP Address
// We can't handle these.
DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::IPAddress");
break;
case 8:
// Registered ID
// We can't handle these.
DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::RegisteredID");
break;
default:
dbgln_if(TLS_DEBUG, "Unknown tag in SAN choice {}", tag_value);
if (is_critical)
return {};
else
DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::???");
}
}
}
EXIT_SCOPE("Certificate::TBSCertificate::Extensions::$::Extension");
}
EXIT_SCOPE("Certificate::TBSCertificate::Extensions");
EXIT_SCOPE("Certificate::TBSCertificate::Extensions(IMPLICIT)");
}
}
}
// Just ignore the rest of the data for now.
EXIT_SCOPE("Certificate::TBSCertificate");
EXIT_SCOPE("Certificate");
dbgln_if(TLS_DEBUG, "Certificate issued for {} by {}", certificate.subject.subject, certificate.issuer.subject);
return certificate;
#undef DROP_OBJECT_OR_FAIL
#undef ENSURE_OBJECT_KIND
#undef ENTER_SCOPE_OR_FAIL
#undef ENTER_SCOPE_WITHOUT_TYPECHECK
#undef EXIT_SCOPE
#undef READ_OBJECT_OR_FAIL
}
ssize_t TLSv12::handle_certificate(ReadonlyBytes buffer)
{
ssize_t res = 0;
if (buffer.size() < 3) {
dbgln_if(TLS_DEBUG, "not enough certificate header data");
return (i8)Error::NeedMoreData;
}
u32 certificate_total_length = buffer[0] * 0x10000 + buffer[1] * 0x100 + buffer[2];
dbgln_if(TLS_DEBUG, "total length: {}", certificate_total_length);
if (certificate_total_length <= 4)
return 3 * certificate_total_length;
res += 3;
if (certificate_total_length > buffer.size() - res) {
dbgln_if(TLS_DEBUG, "not enough data for claimed total cert length");
return (i8)Error::NeedMoreData;
}
size_t size = certificate_total_length;
size_t index = 0;
bool valid_certificate = false;
while (size > 0) {
++index;
if (buffer.size() - res < 3) {
dbgln_if(TLS_DEBUG, "not enough data for certificate length");
return (i8)Error::NeedMoreData;
}
size_t certificate_size = buffer[res] * 0x10000 + buffer[res + 1] * 0x100 + buffer[res + 2];
res += 3;
if (buffer.size() - res < certificate_size) {
dbgln_if(TLS_DEBUG, "not enough data for certificate body");
return (i8)Error::NeedMoreData;
}
auto res_cert = res;
auto remaining = certificate_size;
size_t certificates_in_chain = 0;
do {
if (remaining <= 3) {
dbgln("Ran out of data");
break;
}
++certificates_in_chain;
if (buffer.size() < (size_t)res_cert + 3) {
dbgln("not enough data to read cert size ({} < {})", buffer.size(), res_cert + 3);
break;
}
size_t certificate_size_specific = buffer[res_cert] * 0x10000 + buffer[res_cert + 1] * 0x100 + buffer[res_cert + 2];
res_cert += 3;
remaining -= 3;
if (certificate_size_specific > remaining) {
dbgln("invalid certificate size (expected {} but got {})", remaining, certificate_size_specific);
break;
}
remaining -= certificate_size_specific;
auto certificate = parse_asn1(buffer.slice(res_cert, certificate_size_specific), false);
if (certificate.has_value()) {
if (certificate.value().is_valid()) {
m_context.certificates.append(certificate.value());
valid_certificate = true;
}
}
res_cert += certificate_size_specific;
} while (remaining > 0);
if (remaining) {
dbgln("extraneous {} bytes left over after parsing certificates", remaining);
}
size -= certificate_size + 3;
res += certificate_size;
}
if (!valid_certificate)
return (i8)Error::UnsupportedCertificate;
if ((size_t)res != buffer.size())
dbgln("some data left unread: {} bytes out of {}", res, buffer.size());
return res;
}
void TLSv12::consume(ReadonlyBytes record)
{
if (m_context.critical_error) {
dbgln("There has been a critical error ({}), refusing to continue", (i8)m_context.critical_error);
return;
}
if (record.size() == 0) {
return;
}
dbgln_if(TLS_DEBUG, "Consuming {} bytes", record.size());
m_context.message_buffer.append(record.data(), record.size());
size_t index { 0 };
size_t buffer_length = m_context.message_buffer.size();
size_t size_offset { 3 }; // read the common record header
size_t header_size { 5 };
dbgln_if(TLS_DEBUG, "message buffer length {}", buffer_length);
while (buffer_length >= 5) {
auto length = AK::convert_between_host_and_network_endian(ByteReader::load16(m_context.message_buffer.offset_pointer(index + size_offset))) + header_size;
if (length > buffer_length) {
dbgln_if(TLS_DEBUG, "Need more data: {} > {}", length, buffer_length);
break;
}
auto consumed = handle_message(m_context.message_buffer.bytes().slice(index, length));
if constexpr (TLS_DEBUG) {
if (consumed > 0)
dbgln("consumed {} bytes", consumed);
else
dbgln("error: {}", consumed);
}
if (consumed != (i8)Error::NeedMoreData) {
if (consumed < 0) {
dbgln("Consumed an error: {}", consumed);
if (!m_context.critical_error)
m_context.critical_error = (i8)consumed;
m_context.error_code = (Error)consumed;
break;
}
} else {
continue;
}
index += length;
buffer_length -= length;
if (m_context.critical_error) {
dbgln("Broken connection");
m_context.error_code = Error::BrokenConnection;
break;
}
}
if (m_context.error_code != Error::NoError && m_context.error_code != Error::NeedMoreData) {
dbgln("consume error: {}", (i8)m_context.error_code);
m_context.message_buffer.clear();
return;
}
if (index) {
m_context.message_buffer = m_context.message_buffer.slice(index, m_context.message_buffer.size() - index);
}
}
void TLSv12::ensure_hmac(size_t digest_size, bool local)
{
if (local && m_hmac_local)
return;
if (!local && m_hmac_remote)
return;
auto hash_kind = Crypto::Hash::HashKind::None;
switch (digest_size) {
case Crypto::Hash::SHA1::DigestSize:
hash_kind = Crypto::Hash::HashKind::SHA1;
break;
case Crypto::Hash::SHA256::DigestSize:
hash_kind = Crypto::Hash::HashKind::SHA256;
break;
case Crypto::Hash::SHA512::DigestSize:
hash_kind = Crypto::Hash::HashKind::SHA512;
break;
default:
dbgln("Failed to find a suitable hash for size {}", digest_size);
break;
}
auto hmac = make<Crypto::Authentication::HMAC<Crypto::Hash::Manager>>(ReadonlyBytes { local ? m_context.crypto.local_mac : m_context.crypto.remote_mac, digest_size }, hash_kind);
if (local)
m_hmac_local = move(hmac);
else
m_hmac_remote = move(hmac);
}
bool Certificate::is_valid() const
{
auto now = Core::DateTime::now();
if (now < not_before) {
dbgln("certificate expired (not yet valid, signed for {})", not_before.to_string());
return false;
}
if (not_after < now) {
dbgln("certificate expired (expiry date {})", not_after.to_string());
return false;
}
return true;
}
void TLSv12::try_disambiguate_error() const
{
dbgln("Possible failure cause(s): ");
switch ((AlertDescription)m_context.critical_error) {
case AlertDescription::HandshakeFailure:
if (!m_context.cipher_spec_set) {
dbgln("- No cipher suite in common with {}", m_context.extensions.SNI);
} else {
dbgln("- Unknown internal issue");
}
break;
case AlertDescription::InsufficientSecurity:
dbgln("- No cipher suite in common with {} (the server is oh so secure)", m_context.extensions.SNI);
break;
case AlertDescription::ProtocolVersion:
dbgln("- The server refused to negotiate with TLS 1.2 :(");
break;
case AlertDescription::UnexpectedMessage:
dbgln("- We sent an invalid message for the state we're in.");
break;
case AlertDescription::BadRecordMAC:
dbgln("- Bad MAC record from our side.");
dbgln("- Ciphertext wasn't an even multiple of the block length.");
dbgln("- Bad block cipher padding.");
dbgln("- If both sides are compliant, the only cause is messages being corrupted in the network.");
break;
case AlertDescription::RecordOverflow:
dbgln("- Sent a ciphertext record which has a length bigger than 18432 bytes.");
dbgln("- Sent record decrypted to a compressed record that has a length bigger than 18432 bytes.");
dbgln("- If both sides are compliant, the only cause is messages being corrupted in the network.");
break;
case AlertDescription::DecompressionFailure:
dbgln("- We sent invalid input for decompression (e.g. data that would expand to excessive length)");
break;
case AlertDescription::IllegalParameter:
dbgln("- We sent a parameter in the handshake that is out of range or inconsistent with the other parameters.");
break;
case AlertDescription::DecodeError:
dbgln("- The message we sent cannot be decoded because a field was out of range or the length was incorrect.");
dbgln("- If both sides are compliant, the only cause is messages being corrupted in the network.");
break;
case AlertDescription::DecryptError:
dbgln("- A handshake crypto operation failed. This includes signature verification and validating Finished.");
break;
case AlertDescription::AccessDenied:
dbgln("- The certificate is valid, but once access control was applied, the sender decided to stop negotiation.");
break;
case AlertDescription::InternalError:
dbgln("- No one knows, but it isn't a protocol failure.");
break;
case AlertDescription::DecryptionFailed:
case AlertDescription::NoCertificate:
case AlertDescription::ExportRestriction:
dbgln("- No one knows, the server sent a non-compliant alert.");
break;
default:
dbgln("- No one knows.");
break;
}
}
void TLSv12::set_root_certificates(Vector<Certificate> certificates)
{
if (!m_context.root_ceritificates.is_empty())
dbgln("TLS warn: resetting root certificates!");
for (auto& cert : certificates) {
if (!cert.is_valid())
dbgln("Certificate for {} by {} is invalid, things may or may not work!", cert.subject.subject, cert.issuer.subject);
// FIXME: Figure out what we should do when our root certs are invalid.
}
m_context.root_ceritificates = move(certificates);
}
bool Context::verify_chain() const
{
if (!options.validate_certificates)
return true;
const Vector<Certificate>* local_chain = nullptr;
if (is_server) {
dbgln("Unsupported: Server mode");
TODO();
} else {
local_chain = &certificates;
}
// FIXME: Actually verify the signature, instead of just checking the name.
HashMap<String, String> chain;
HashTable<String> roots;
// First, walk the root certs.
for (auto& cert : root_ceritificates) {
roots.set(cert.subject.subject);
chain.set(cert.subject.subject, cert.issuer.subject);
}
// Then, walk the local certs.
for (auto& cert : *local_chain) {
auto& issuer_unique_name = cert.issuer.unit.is_empty() ? cert.issuer.subject : cert.issuer.unit;
chain.set(cert.subject.subject, issuer_unique_name);
}
// Then verify the chain.
for (auto& it : chain) {
if (it.key == it.value) { // Allow self-signed certificates.
if (!roots.contains(it.key))
dbgln("Self-signed warning: Certificate for {} is self-signed", it.key);
continue;
}
auto ref = chain.get(it.value);
if (!ref.has_value()) {
dbgln("Certificate for {} is not signed by anyone we trust ({})", it.key, it.value);
return false;
}
if (ref.value() == it.key) // Allow (but warn about) mutually recursively signed cert A <-> B.
dbgln("Co-dependency warning: Certificate for {} is issued by {}, which itself is issued by {}", ref.value(), it.key, ref.value());
}
return true;
}
static bool wildcard_matches(const StringView& host, const StringView& subject)
{
if (host.matches(subject))
return true;
if (subject.starts_with("*."))
return wildcard_matches(host, subject.substring_view(2));
return false;
}
Optional<size_t> TLSv12::verify_chain_and_get_matching_certificate(const StringView& host) const
{
if (m_context.certificates.is_empty() || !m_context.verify_chain())
return {};
if (host.is_empty())
return 0;
for (size_t i = 0; i < m_context.certificates.size(); ++i) {
auto& cert = m_context.certificates[i];
if (wildcard_matches(host, cert.subject.subject))
return i;
for (auto& san : cert.SAN) {
if (wildcard_matches(host, san))
return i;
}
}
return {};
}
TLSv12::TLSv12(Core::Object* parent, Options options)
: Core::Socket(Core::Socket::Type::TCP, parent)
{
m_context.options = move(options);
m_context.is_server = false;
m_context.tls_buffer = ByteBuffer::create_uninitialized(0);
#ifdef SOCK_NONBLOCK
int fd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
#else
int fd = socket(AF_INET, SOCK_STREAM, 0);
int option = 1;
ioctl(fd, FIONBIO, &option);
#endif
if (fd < 0) {
set_error(errno);
} else {
set_fd(fd);
set_mode(Core::OpenMode::ReadWrite);
set_error(0);
}
}
bool TLSv12::add_client_key(ReadonlyBytes certificate_pem_buffer, ReadonlyBytes rsa_key) // FIXME: This should not be bound to RSA
{
if (certificate_pem_buffer.is_empty() || rsa_key.is_empty()) {
return true;
}
auto decoded_certificate = Crypto::decode_pem(certificate_pem_buffer);
if (decoded_certificate.is_empty()) {
dbgln("Certificate not PEM");
return false;
}
auto maybe_certificate = parse_asn1(decoded_certificate);
if (!maybe_certificate.has_value()) {
dbgln("Invalid certificate");
return false;
}
Crypto::PK::RSA rsa(rsa_key);
auto certificate = maybe_certificate.value();
certificate.private_key = rsa.private_key();
return add_client_key(certificate);
}
AK::Singleton<DefaultRootCACertificates> DefaultRootCACertificates::s_the;
DefaultRootCACertificates::DefaultRootCACertificates()
{
// FIXME: This might not be the best format, find a better way to represent CA certificates.
auto config = Core::ConfigFile::get_for_system("ca_certs");
auto now = Core::DateTime::now();
auto last_year = Core::DateTime::create(now.year() - 1);
auto next_year = Core::DateTime::create(now.year() + 1);
for (auto& entity : config->groups()) {
Certificate cert;
cert.subject.subject = entity;
cert.issuer.subject = config->read_entry(entity, "issuer_subject", entity);
cert.subject.country = config->read_entry(entity, "country");
cert.not_before = Crypto::ASN1::parse_generalized_time(config->read_entry(entity, "not_before", "")).value_or(last_year);
cert.not_after = Crypto::ASN1::parse_generalized_time(config->read_entry(entity, "not_after", "")).value_or(next_year);
m_ca_certificates.append(move(cert));
}
}
}
| 44.173203 | 204 | 0.535055 | [
"object",
"vector"
] |
9cb9c799f15e6ddbdae20f77c876a3e343ffa122 | 4,760 | cpp | C++ | oink/src/rr.cpp | trolando/oink-experiments | a58937b78fd0857a26b8ec0e985552e672405862 | [
"Apache-2.0"
] | 1 | 2019-03-04T14:24:17.000Z | 2019-03-04T14:24:17.000Z | oink/src/rr.cpp | trolando/oink-experiments | a58937b78fd0857a26b8ec0e985552e672405862 | [
"Apache-2.0"
] | null | null | null | oink/src/rr.cpp | trolando/oink-experiments | a58937b78fd0857a26b8ec0e985552e672405862 | [
"Apache-2.0"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <sstream>
#include <vector>
#include <queue>
#include <cassert>
#include "rr.hpp"
namespace pg {
RRSolver::RRSolver(Oink *oink, Game *game, std::ostream &lgr) : PPSolver(oink, game, lgr)
{
}
/**
* RR: only reset the region if what remains of the region can escape or has a bad strategy
*/
bool
RRSolver::checkRegion(int p)
{
// check if the region escape is gone (thus require reset)
if (regions[p].empty()) return true; // technically good
// remove nodes that are no longer in the region (higher measure)
// check for the remaining nodes that their strategy still stays
// in the region and that losing nodes (except top nodes) cannot escape lower
// first remove nodes no longer in the region
auto &Rp = regions[p];
Rp.erase(std::remove_if(Rp.begin(), Rp.end(),
[&](const int n) {return region[n] > p;}), Rp.end());
for (auto j : Rp) {
// assert(priority[j] <= p && region[j] == p);
if (disabled[j]) {
// now disabled, requires a reset...
return false;
} else if (priority[j] == p) {
// an escape node; if its strategy leaves the region, reset it
if (strategy[j] != -1 && region[strategy[j]] != p) {
strategy[j] = -1;
}
} else if (owner[j] == (p&1)) {
// not-top winner
// check if the strategy stays in the region
// in very rare cases, strategy[j] == -1 (when fields are reset)
if (strategy[j] == -1) return false;
// requires a reset...
if (region[strategy[j]] != p) return false;
} else /*if (priority[j] != p)*/ {
// not-top loser
// check if it can escape in the subgame
for (auto to : out[j]) {
// it may be able to escape to a lower region if there have been resets
if (region[to] != -2 && region[to] < p) return false;
}
}
}
return true;
}
void
RRSolver::run()
{
// obtain highest priority and allocate arrays
int max_prio = priority[n_nodes-1];
regions = new std::vector<int>[max_prio+1];
region = new int[n_nodes];
strategy = new int[n_nodes];
inverse = new int[max_prio+1];
// initialize arrays
for (int i=0; i<n_nodes; i++) region[i] = disabled[i] ? -2 : priority[i];
for (int i=0; i<n_nodes; i++) strategy[i] = -1;
// start loop at last node (highest priority)
int i = n_nodes - 1;
/**
* Two loops: the outer (normal) loop, and the inner (promotion-chain) loop.
* The outer loop does region setup and attractor on the full region.
* The inner loop only attracts from the promoted region.
*/
while (i >= 0) {
// get current priority and skip all disabled/attracted nodes
int p = priority[i];
while (i >= 0 and priority[i] == p and (disabled[i] or region[i] > p)) i--;
if (i < 0) break;
// if empty, possibly reset and continue with next
if (priority[i] != p) {
if (!regions[p].empty()) resetRegion(p);
continue;
}
inverse[p] = i;
// RR: only reset the region if:
// - current node is promoted or attracted
// - or region is empty
// - or region does not fulfill conditions
// This is checked by checkRegion()
if (setupRegion(i, p, !checkRegion(p))) {
// region not empty, maybe promote
while (true) {
if (trace >= 2) reportRegion(p);
int res = getRegionStatus(i, p);
if (res == -2) {
// not closed, skip to next priority and break inner loop
while (i >= 0 and priority[i] == p) i--;
break;
} else if (res == -1) {
// found dominion, return
setDominion(p);
// restart algorithm and break inner loop
i = n_nodes - 1;
break;
} else {
// found promotion, promote
if (trace >= 2) printState();
promote(p, res);
if (trace >= 2) printState();
// continue inner loop with the higher priority
i = inverse[res];
p = res;
}
}
} else {
// skip to next priority
while (i >= 0 and priority[i] == p) i--;
}
}
delete[] regions;
delete[] region;
delete[] strategy;
delete[] inverse;
logger << "solved with " << promotions << " promotions." << std::endl;
}
}
| 32.60274 | 91 | 0.519748 | [
"vector"
] |
9cbbff3dd9ff3d6c1edfe65361fd573a824b2da1 | 23,319 | cpp | C++ | src/backends/cl/workloads/ClLstmFloatWorkload.cpp | sahilbandar/armnn | 249950645b7bc0593582182097c7e2f1d6d97442 | [
"MIT"
] | 1 | 2022-02-10T11:06:30.000Z | 2022-02-10T11:06:30.000Z | src/backends/cl/workloads/ClLstmFloatWorkload.cpp | sahilbandar/armnn | 249950645b7bc0593582182097c7e2f1d6d97442 | [
"MIT"
] | null | null | null | src/backends/cl/workloads/ClLstmFloatWorkload.cpp | sahilbandar/armnn | 249950645b7bc0593582182097c7e2f1d6d97442 | [
"MIT"
] | null | null | null | //
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#include "ClLstmFloatWorkload.hpp"
#include <cl/ClTensorHandle.hpp>
#include <backendsCommon/TensorHandle.hpp>
#include <cl/ClLayerSupport.hpp>
#include <aclCommon/ArmComputeTensorUtils.hpp>
#include <armnn/utility/NumericCast.hpp>
#include <arm_compute/runtime/CL/functions/CLLSTMLayer.h>
#include "ClWorkloadUtils.hpp"
namespace armnn
{
using namespace armcomputetensorutils;
ClLstmFloatWorkload::ClLstmFloatWorkload(const LstmQueueDescriptor &descriptor,
const WorkloadInfo &info,
const arm_compute::CLCompileContext& clCompileContext)
: FloatWorkload<LstmQueueDescriptor>(descriptor, info)
{
// Report Profiling Details
ARMNN_REPORT_PROFILING_WORKLOAD_DESC("ClLstmFloatWorkload_Construct",
descriptor.m_Parameters,
info,
this->GetGuid());
arm_compute::LSTMParams<arm_compute::ICLTensor> lstm_param;
// Basic parameters
m_InputToForgetWeightsTensor = std::make_unique<arm_compute::CLTensor>();
BuildArmComputeTensor(*m_InputToForgetWeightsTensor, m_Data.m_InputToForgetWeights->GetTensorInfo());
m_InputToCellWeightsTensor = std::make_unique<arm_compute::CLTensor>();
BuildArmComputeTensor(*m_InputToCellWeightsTensor, m_Data.m_InputToCellWeights->GetTensorInfo());
m_InputToOutputWeightsTensor = std::make_unique<arm_compute::CLTensor>();
BuildArmComputeTensor(*m_InputToOutputWeightsTensor, m_Data.m_InputToOutputWeights->GetTensorInfo());
m_RecurrentToForgetWeightsTensor = std::make_unique<arm_compute::CLTensor>();
BuildArmComputeTensor(*m_RecurrentToForgetWeightsTensor, m_Data.m_RecurrentToForgetWeights->GetTensorInfo());
m_RecurrentToCellWeightsTensor = std::make_unique<arm_compute::CLTensor>();
BuildArmComputeTensor(*m_RecurrentToCellWeightsTensor, m_Data.m_RecurrentToCellWeights->GetTensorInfo());
m_RecurrentToOutputWeightsTensor = std::make_unique<arm_compute::CLTensor>();
BuildArmComputeTensor(*m_RecurrentToOutputWeightsTensor, m_Data.m_RecurrentToOutputWeights->GetTensorInfo());
m_ForgetGateBiasTensor = std::make_unique<arm_compute::CLTensor>();
BuildArmComputeTensor(*m_ForgetGateBiasTensor, m_Data.m_ForgetGateBias->GetTensorInfo());
m_CellBiasTensor = std::make_unique<arm_compute::CLTensor>();
BuildArmComputeTensor(*m_CellBiasTensor, m_Data.m_CellBias->GetTensorInfo());
m_OutputGateBiasTensor = std::make_unique<arm_compute::CLTensor>();
BuildArmComputeTensor(*m_OutputGateBiasTensor, m_Data.m_OutputGateBias->GetTensorInfo());
// for future reference: check the AndroidNN API for the logic here
if (!m_Data.m_Parameters.m_CifgEnabled)
{
m_InputToInputWeightsTensor = std::make_unique<arm_compute::CLTensor>();
BuildArmComputeTensor(*m_InputToInputWeightsTensor, m_Data.m_InputToInputWeights->GetTensorInfo());
m_RecurrentToInputWeightsTensor = std::make_unique<arm_compute::CLTensor>();
BuildArmComputeTensor(*m_RecurrentToInputWeightsTensor, m_Data.m_RecurrentToInputWeights->GetTensorInfo());
m_CellToInputWeightsTensor = std::make_unique<arm_compute::CLTensor>();
if (m_Data.m_CellToInputWeights != nullptr)
{
BuildArmComputeTensor(*m_CellToInputWeightsTensor, m_Data.m_CellToInputWeights->GetTensorInfo());
}
m_InputGateBiasTensor = std::make_unique<arm_compute::CLTensor>();
BuildArmComputeTensor(*m_InputGateBiasTensor, m_Data.m_InputGateBias->GetTensorInfo());
lstm_param.set_cifg_params(m_InputToInputWeightsTensor.get(),
m_RecurrentToInputWeightsTensor.get(),
m_Data.m_CellToInputWeights != nullptr ? m_CellToInputWeightsTensor.get() : nullptr,
m_InputGateBiasTensor.get());
}
if (m_Data.m_Parameters.m_ProjectionEnabled)
{
m_ProjectionWeightsTensor = std::make_unique<arm_compute::CLTensor>();
BuildArmComputeTensor(*m_ProjectionWeightsTensor, m_Data.m_ProjectionWeights->GetTensorInfo());
m_ProjectionBiasTensor = std::make_unique<arm_compute::CLTensor>();
if (m_Data.m_ProjectionBias != nullptr)
{
BuildArmComputeTensor(*m_ProjectionBiasTensor, m_Data.m_ProjectionBias->GetTensorInfo());
}
lstm_param.set_projection_params(m_ProjectionWeightsTensor.get(),
m_Data.m_ProjectionBias != nullptr ? m_ProjectionBiasTensor.get() : nullptr);
}
if (m_Data.m_Parameters.m_PeepholeEnabled)
{
m_CellToForgetWeightsTensor = std::make_unique<arm_compute::CLTensor>();
BuildArmComputeTensor(*m_CellToForgetWeightsTensor, m_Data.m_CellToForgetWeights->GetTensorInfo());
m_CellToOutputWeightsTensor = std::make_unique<arm_compute::CLTensor>();
BuildArmComputeTensor(*m_CellToOutputWeightsTensor, m_Data.m_CellToOutputWeights->GetTensorInfo());
lstm_param.set_peephole_params(m_CellToForgetWeightsTensor.get(), m_CellToOutputWeightsTensor.get());
}
if (m_Data.m_Parameters.m_LayerNormEnabled)
{
m_InputLayerNormWeightsTensor = std::make_unique<arm_compute::CLTensor>();
m_ForgetLayerNormWeightsTensor = std::make_unique<arm_compute::CLTensor>();
m_CellLayerNormWeightsTensor = std::make_unique<arm_compute::CLTensor>();
m_OutputLayerNormWeightsTensor = std::make_unique<arm_compute::CLTensor>();
if (!m_Data.m_Parameters.m_CifgEnabled)
{
BuildArmComputeTensor(*m_InputLayerNormWeightsTensor, m_Data.m_InputLayerNormWeights->GetTensorInfo());
}
BuildArmComputeTensor(*m_ForgetLayerNormWeightsTensor, m_Data.m_ForgetLayerNormWeights->GetTensorInfo());
BuildArmComputeTensor(*m_CellLayerNormWeightsTensor, m_Data.m_CellLayerNormWeights->GetTensorInfo());
BuildArmComputeTensor(*m_OutputLayerNormWeightsTensor, m_Data.m_OutputLayerNormWeights->GetTensorInfo());
lstm_param.set_layer_normalization_params(m_Data.m_Parameters.m_CifgEnabled ? nullptr :
m_InputLayerNormWeightsTensor.get(),
m_ForgetLayerNormWeightsTensor.get(),
m_CellLayerNormWeightsTensor.get(),
m_OutputLayerNormWeightsTensor.get());
}
const arm_compute::ICLTensor& input = static_cast<IClTensorHandle*>(m_Data.m_Inputs[0])->GetTensor();
const arm_compute::ICLTensor& output_state_in = static_cast<IClTensorHandle*>(m_Data.m_Inputs[1])->GetTensor();
arm_compute::ICLTensor& cell_state_in = static_cast<IClTensorHandle*>(m_Data.m_Inputs[2])->GetTensor();
arm_compute::ICLTensor& output_state_out = static_cast<IClTensorHandle*>(m_Data.m_Outputs[1])->GetTensor();
arm_compute::ICLTensor& cell_state_out = static_cast<IClTensorHandle*>(m_Data.m_Outputs[2])->GetTensor();
arm_compute::ICLTensor& output = static_cast<IClTensorHandle*>(m_Data.m_Outputs[3])->GetTensor();
// Get the batch_size and the num_units from the cellStateIn dimensions
const TensorInfo& inputTensorInfo = info.m_InputTensorInfos[2];
const unsigned int batch_size = armnn::numeric_cast<unsigned int>(inputTensorInfo.GetShape()[0]);
const unsigned int num_units = armnn::numeric_cast<unsigned int>(inputTensorInfo.GetShape()[1]);
m_ScratchBuffer = std::make_unique<arm_compute::CLTensor>();
if (m_Data.m_Parameters.m_CifgEnabled)
{
// 2D tensor with dimensions [num_units * 3, batch_size] with CIFG
armnn::TensorInfo scratchBuffer1({ batch_size, num_units * 3 }, DataType::Float32);
BuildArmComputeTensor(*m_ScratchBuffer, scratchBuffer1);
}
else
{
// scratch_buffer [num_units * 4, batch_size] without CIFG
armnn::TensorInfo scratchBuffer2({ batch_size, num_units * 4 }, DataType::Float32);
BuildArmComputeTensor(*m_ScratchBuffer, scratchBuffer2);
}
float cell_threshold = m_Data.m_Parameters.m_ClippingThresCell;
float projection_threshold = m_Data.m_Parameters.m_ClippingThresProj;
// for preparing the object for the class ActivationLayerInfo, we need to consider 5 situations
arm_compute::ActivationLayerInfo activationLayerInfo;
if (m_Data.m_Parameters.m_ActivationFunc == 0)
{
// no activation, do nothing
}
else if (m_Data.m_Parameters.m_ActivationFunc == 1)
{
activationLayerInfo = arm_compute::ActivationLayerInfo(
arm_compute::ActivationLayerInfo::ActivationFunction::RELU);
}
else if (m_Data.m_Parameters.m_ActivationFunc == 3)
{
activationLayerInfo = arm_compute::ActivationLayerInfo(
arm_compute::ActivationLayerInfo::ActivationFunction::BOUNDED_RELU, 6.0);
}
else if (m_Data.m_Parameters.m_ActivationFunc == 4)
{
activationLayerInfo = arm_compute::ActivationLayerInfo(
arm_compute::ActivationLayerInfo::ActivationFunction::TANH, 1.0, 1.0);
}
else if (m_Data.m_Parameters.m_ActivationFunc == 6)
{
activationLayerInfo = arm_compute::ActivationLayerInfo(
arm_compute::ActivationLayerInfo::ActivationFunction::LOGISTIC);
}
else
{
throw armnn::Exception("Wrong Type of Activation Function!");
}
{
ARMNN_SCOPED_PROFILING_EVENT(Compute::Undefined, "ClLstmFloatWorkload_configure");
m_LstmLayer.configure(clCompileContext, &input, m_InputToForgetWeightsTensor.get(),
m_InputToCellWeightsTensor.get(), m_InputToOutputWeightsTensor.get(),
m_RecurrentToForgetWeightsTensor.get(), m_RecurrentToCellWeightsTensor.get(),
m_RecurrentToOutputWeightsTensor.get(), m_ForgetGateBiasTensor.get(),
m_CellBiasTensor.get(), m_OutputGateBiasTensor.get(), &output_state_in,
&cell_state_in, m_ScratchBuffer.get(), &output_state_out,
&cell_state_out, &output, lstm_param, activationLayerInfo,
cell_threshold, projection_threshold);
}
armcomputetensorutils::InitialiseArmComputeTensorEmpty(*m_ScratchBuffer);
InitializeArmComputeClTensorData(*m_InputToForgetWeightsTensor, m_Data.m_InputToForgetWeights);
InitializeArmComputeClTensorData(*m_InputToCellWeightsTensor, m_Data.m_InputToCellWeights);
InitializeArmComputeClTensorData(*m_InputToOutputWeightsTensor, m_Data.m_InputToOutputWeights);
InitializeArmComputeClTensorData(*m_RecurrentToForgetWeightsTensor, m_Data.m_RecurrentToForgetWeights);
InitializeArmComputeClTensorData(*m_RecurrentToCellWeightsTensor, m_Data.m_RecurrentToCellWeights);
InitializeArmComputeClTensorData(*m_RecurrentToOutputWeightsTensor, m_Data.m_RecurrentToOutputWeights);
InitializeArmComputeClTensorData(*m_ForgetGateBiasTensor, m_Data.m_ForgetGateBias);
InitializeArmComputeClTensorData(*m_CellBiasTensor, m_Data.m_CellBias);
InitializeArmComputeClTensorData(*m_OutputGateBiasTensor, m_Data.m_OutputGateBias);
if (!m_Data.m_Parameters.m_CifgEnabled)
{
InitializeArmComputeClTensorData(*m_InputToInputWeightsTensor, m_Data.m_InputToInputWeights);
InitializeArmComputeClTensorData(*m_RecurrentToInputWeightsTensor, m_Data.m_RecurrentToInputWeights);
if (m_Data.m_CellToInputWeights != nullptr)
{
InitializeArmComputeClTensorData(*m_CellToInputWeightsTensor, m_Data.m_CellToInputWeights);
}
InitializeArmComputeClTensorData(*m_InputGateBiasTensor, m_Data.m_InputGateBias);
}
if (m_Data.m_Parameters.m_ProjectionEnabled)
{
InitializeArmComputeClTensorData(*m_ProjectionWeightsTensor, m_Data.m_ProjectionWeights);
if (m_Data.m_ProjectionBias != nullptr)
{
InitializeArmComputeClTensorData(*m_ProjectionBiasTensor, m_Data.m_ProjectionBias);
}
}
if (m_Data.m_Parameters.m_PeepholeEnabled)
{
InitializeArmComputeClTensorData(*m_CellToForgetWeightsTensor, m_Data.m_CellToForgetWeights);
InitializeArmComputeClTensorData(*m_CellToOutputWeightsTensor, m_Data.m_CellToOutputWeights);
}
if (m_Data.m_Parameters.m_LayerNormEnabled)
{
if (!m_Data.m_Parameters.m_CifgEnabled)
{
InitializeArmComputeClTensorData(*m_InputLayerNormWeightsTensor, m_Data.m_InputLayerNormWeights);
}
InitializeArmComputeClTensorData(*m_ForgetLayerNormWeightsTensor, m_Data.m_ForgetLayerNormWeights);
InitializeArmComputeClTensorData(*m_CellLayerNormWeightsTensor, m_Data.m_CellLayerNormWeights);
InitializeArmComputeClTensorData(*m_OutputLayerNormWeightsTensor, m_Data.m_OutputLayerNormWeights);
}
// Force Compute Library to perform the necessary copying and reshaping, after which
// delete all the input tensors that will no longer be needed
m_LstmLayer.prepare();
FreeUnusedTensors();
}
void ClLstmFloatWorkload::Execute() const
{
ARMNN_SCOPED_PROFILING_EVENT_CL_GUID("ClLstmFloatWorkload_Execute", this->GetGuid());
RunClFunction(m_LstmLayer, CHECK_LOCATION());
}
arm_compute::Status ClLstmFloatWorkloadValidate(const TensorInfo& input, const TensorInfo& outputStateIn,
const TensorInfo& cellStateIn, const TensorInfo& scratchBuffer,
const TensorInfo& outputStateOut, const TensorInfo& cellStateOut,
const TensorInfo& output, const LstmDescriptor& descriptor,
const LstmInputParamsInfo& paramsInfo)
{
arm_compute::LSTMParams<arm_compute::ITensorInfo> lstm_params_info;
// The inputs and the outputs
const arm_compute::TensorInfo aclInputInfo = BuildArmComputeTensorInfo(input);
const arm_compute::TensorInfo aclOutputStateInInfo = BuildArmComputeTensorInfo(outputStateIn);
const arm_compute::TensorInfo aclCellStateInInfo = BuildArmComputeTensorInfo(cellStateIn);
const arm_compute::TensorInfo aclScratchBufferInfo = BuildArmComputeTensorInfo(scratchBuffer);
const arm_compute::TensorInfo aclOutputStateOutInfo = BuildArmComputeTensorInfo(outputStateOut);
const arm_compute::TensorInfo aclCellStateOutInfo = BuildArmComputeTensorInfo(cellStateOut);
const arm_compute::TensorInfo aclOutputInfo = BuildArmComputeTensorInfo(output);
// Basic parameters
const arm_compute::TensorInfo aclInputToForgetWeightsInfo
= BuildArmComputeTensorInfo(paramsInfo.GetInputToForgetWeights());
const arm_compute::TensorInfo aclInputToCellWeightsInfo
= BuildArmComputeTensorInfo(paramsInfo.GetInputToCellWeights());
const arm_compute::TensorInfo aclInputToOutputWeightsInfo
= BuildArmComputeTensorInfo(paramsInfo.GetInputToOutputWeights());
const arm_compute::TensorInfo aclRecurrentToForgetWeightsInfo
= BuildArmComputeTensorInfo(paramsInfo.GetRecurrentToForgetWeights());
const arm_compute::TensorInfo aclRecurrentToCellWeightsInfo
= BuildArmComputeTensorInfo(paramsInfo.GetRecurrentToCellWeights());
const arm_compute::TensorInfo aclRecurrentToOutputWeightsInfo
= BuildArmComputeTensorInfo(paramsInfo.GetRecurrentToOutputWeights());
const arm_compute::TensorInfo aclForgetGateBiasInfo = BuildArmComputeTensorInfo(paramsInfo.GetForgetGateBias());
const arm_compute::TensorInfo aclCellBiasInfo = BuildArmComputeTensorInfo(paramsInfo.GetCellBias());
const arm_compute::TensorInfo aclOutputGateBiasInfo = BuildArmComputeTensorInfo(paramsInfo.GetOutputGateBias());
arm_compute::TensorInfo aclInputToInputWeightsInfo;
arm_compute::TensorInfo aclRecurrentToInputWeightsInfo;
arm_compute::TensorInfo aclCellToInputWeightsInfo;
arm_compute::TensorInfo aclInputGateBiasInfo;
arm_compute::TensorInfo aclProjectionWeightsInfo;
arm_compute::TensorInfo aclProjectionBiasInfo;
arm_compute::TensorInfo aclCellToForgetWeightsInfo;
arm_compute::TensorInfo aclCellToOutputWeightsInfo;
arm_compute::TensorInfo aclInputLayerNormWeightsInfo;
arm_compute::TensorInfo aclForgetLayerNormWeightsInfo;
arm_compute::TensorInfo aclCellLayerNormWeightsInfo;
arm_compute::TensorInfo aclOutputLayerNormWeightsInfo;
if (!descriptor.m_CifgEnabled)
{
aclInputToInputWeightsInfo = BuildArmComputeTensorInfo(paramsInfo.GetInputToInputWeights());
aclRecurrentToInputWeightsInfo = BuildArmComputeTensorInfo(paramsInfo.GetRecurrentToInputWeights());
if (paramsInfo.m_CellToInputWeights != nullptr)
{
aclCellToInputWeightsInfo = BuildArmComputeTensorInfo(paramsInfo.GetCellToInputWeights());
}
aclInputGateBiasInfo = BuildArmComputeTensorInfo(paramsInfo.GetInputGateBias());
lstm_params_info.set_cifg_params(&aclInputToInputWeightsInfo, &aclRecurrentToInputWeightsInfo,
paramsInfo.m_CellToInputWeights != nullptr ?
&aclCellToInputWeightsInfo: nullptr,
&aclInputGateBiasInfo);
}
if (descriptor.m_ProjectionEnabled)
{
aclProjectionWeightsInfo = BuildArmComputeTensorInfo(paramsInfo.GetProjectionWeights());
if (paramsInfo.m_ProjectionBias != nullptr)
{
aclProjectionBiasInfo = BuildArmComputeTensorInfo(paramsInfo.GetInputGateBias());
}
lstm_params_info.set_projection_params(&aclProjectionWeightsInfo,
paramsInfo.m_ProjectionBias != nullptr ?
&aclProjectionBiasInfo: nullptr);
}
if (descriptor.m_PeepholeEnabled)
{
aclCellToForgetWeightsInfo = BuildArmComputeTensorInfo(paramsInfo.GetCellToForgetWeights());
aclCellToOutputWeightsInfo = BuildArmComputeTensorInfo(paramsInfo.GetCellToOutputWeights());
lstm_params_info.set_peephole_params(&aclCellToForgetWeightsInfo, &aclCellToOutputWeightsInfo);
}
float cell_threshold = descriptor.m_ClippingThresCell;
float projection_threshold = descriptor.m_ClippingThresProj;
// for preparing the object for the class ActivationLayerInfo, we need to consider 5 situations
arm_compute::ActivationLayerInfo activationLayerInfo;
if (descriptor.m_ActivationFunc == 0)
{
// no activation, do nothing
}
else if (descriptor.m_ActivationFunc == 1)
{
activationLayerInfo = arm_compute::ActivationLayerInfo(
arm_compute::ActivationLayerInfo::ActivationFunction::RELU);
}
else if (descriptor.m_ActivationFunc == 3)
{
activationLayerInfo = arm_compute::ActivationLayerInfo(
arm_compute::ActivationLayerInfo::ActivationFunction::BOUNDED_RELU, 6.0);
}
else if (descriptor.m_ActivationFunc == 4)
{
activationLayerInfo = arm_compute::ActivationLayerInfo(
arm_compute::ActivationLayerInfo::ActivationFunction::TANH, 1.0, 1.0);
}
else if (descriptor.m_ActivationFunc == 6)
{
activationLayerInfo = arm_compute::ActivationLayerInfo(
arm_compute::ActivationLayerInfo::ActivationFunction::LOGISTIC);
}
else
{
throw armnn::Exception("Wrong Type of Activation Function!");
}
if (descriptor.m_LayerNormEnabled)
{
if (!descriptor.m_CifgEnabled)
{
aclInputLayerNormWeightsInfo = BuildArmComputeTensorInfo(paramsInfo.GetInputLayerNormWeights());
}
aclForgetLayerNormWeightsInfo = BuildArmComputeTensorInfo(paramsInfo.GetForgetLayerNormWeights());
aclCellLayerNormWeightsInfo = BuildArmComputeTensorInfo(paramsInfo.GetCellLayerNormWeights());
aclOutputLayerNormWeightsInfo = BuildArmComputeTensorInfo(paramsInfo.GetOutputLayerNormWeights());
lstm_params_info.set_layer_normalization_params(descriptor.m_CifgEnabled ?
nullptr : &aclInputLayerNormWeightsInfo,
&aclForgetLayerNormWeightsInfo,
&aclCellLayerNormWeightsInfo,
&aclOutputLayerNormWeightsInfo);
}
return arm_compute::CLLSTMLayer::validate(&aclInputInfo, &aclInputToForgetWeightsInfo,
&aclInputToCellWeightsInfo,
&aclInputToOutputWeightsInfo,
&aclRecurrentToForgetWeightsInfo,
&aclRecurrentToCellWeightsInfo,
&aclRecurrentToOutputWeightsInfo,
&aclForgetGateBiasInfo,
&aclCellBiasInfo,
&aclOutputGateBiasInfo,
&aclOutputStateInInfo, &aclCellStateInInfo,
&aclScratchBufferInfo, &aclOutputStateOutInfo,
&aclCellStateOutInfo, &aclOutputInfo,
lstm_params_info, activationLayerInfo,
cell_threshold, projection_threshold);
}
void ClLstmFloatWorkload::FreeUnusedTensors()
{
FreeTensorIfUnused(m_InputToInputWeightsTensor);
FreeTensorIfUnused(m_InputToForgetWeightsTensor);
FreeTensorIfUnused(m_InputToCellWeightsTensor);
FreeTensorIfUnused(m_InputToOutputWeightsTensor);
FreeTensorIfUnused(m_RecurrentToInputWeightsTensor);
FreeTensorIfUnused(m_RecurrentToForgetWeightsTensor);
FreeTensorIfUnused(m_RecurrentToCellWeightsTensor);
FreeTensorIfUnused(m_RecurrentToOutputWeightsTensor);
FreeTensorIfUnused(m_CellToInputWeightsTensor);
FreeTensorIfUnused(m_CellToForgetWeightsTensor);
FreeTensorIfUnused(m_CellToOutputWeightsTensor);
FreeTensorIfUnused(m_InputGateBiasTensor);
FreeTensorIfUnused(m_ForgetGateBiasTensor);
FreeTensorIfUnused(m_CellBiasTensor);
FreeTensorIfUnused(m_OutputGateBiasTensor);
FreeTensorIfUnused(m_ProjectionWeightsTensor);
FreeTensorIfUnused(m_ProjectionBiasTensor);
FreeTensorIfUnused(m_ScratchBuffer);
FreeTensorIfUnused(m_InputLayerNormWeightsTensor);
FreeTensorIfUnused(m_ForgetLayerNormWeightsTensor);
FreeTensorIfUnused(m_CellLayerNormWeightsTensor);
FreeTensorIfUnused(m_OutputLayerNormWeightsTensor);
}
} //namespace armnn
| 51.82 | 119 | 0.70256 | [
"object"
] |
9cbc6fdae36d4bac24af6e7ad0ab6bbffd9dfbe2 | 28,548 | cpp | C++ | src/implements/objects_impl.cpp | philip1337/samp-plugin-streamer | 54b08afd5e73bd5f68f67f9cf8cc78189bf6ef8a | [
"Apache-2.0"
] | 2 | 2017-07-23T23:27:03.000Z | 2017-07-24T06:18:13.000Z | src/implements/objects_impl.cpp | Sphinxila/samp-plugin-streamer | 54b08afd5e73bd5f68f67f9cf8cc78189bf6ef8a | [
"Apache-2.0"
] | null | null | null | src/implements/objects_impl.cpp | Sphinxila/samp-plugin-streamer | 54b08afd5e73bd5f68f67f9cf8cc78189bf6ef8a | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2017 Incognito (Edited by ProMetheus)
*
* 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 <streamer/config.hpp>
#include "../natives.h"
#include "../core.h"
#include "../utility.h"
#include <streamer/objects.hpp>
#include <boost/chrono.hpp>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/geometries.hpp>
#include <boost/intrusive_ptr.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/unordered_map.hpp>
#include <Eigen/Core>
#include <limits>
#include <string>
#include <a_objects.h>
#include <a_players.h>
#include <a_actor.h>
#include <sampgdk/interop.h>
STREAMER_BEGIN_NS
int CreateDynamicObject( int modelid, float x, float y, float z,
float rx, float ry, float rz, int worldid, int interiorid, int playerid,
float streamDistance, float drawDistance, int areaid, int priority) {
if (core->getData()->getGlobalMaxItems(STREAMER_TYPE_OBJECT) == core->getData()->objects.size()) {
return 0;
}
int objectId = Item::Object::identifier.get();
Item::SharedObject object(new Item::Object);
//object->amx = amx;
object->objectId = objectId;
object->inverseAreaChecking = false;
object->noCameraCollision = false;
object->inverseAreaChecking = false;
object->originalComparableStreamDistance = -1.0f;
object->positionOffset = Eigen::Vector3f::Zero();
object->streamCallbacks = false;
object->modelId = modelid;
object->position = Eigen::Vector3f(x, y, z);
object->rotation = Eigen::Vector3f(rx, ry, rz);
Utility::addToContainer(object->worlds, worldid);
Utility::addToContainer(object->interiors, interiorid);
Utility::addToContainer(object->players, playerid);
object->comparableStreamDistance = streamDistance < STREAMER_STATIC_DISTANCE_CUTOFF ? streamDistance : streamDistance * streamDistance;
object->streamDistance = streamDistance;
object->drawDistance = drawDistance;
Utility::addToContainer(object->areas, areaid);
object->priority = priority;
core->getGrid()->addObject(object);
core->getData()->objects.insert(std::make_pair(objectId, object));
return objectId;
}
int DestroyDynamicObject(int id) {
boost::unordered_map<int, Item::SharedObject>::iterator o = core->getData()->objects.find(id);
if (o != core->getData()->objects.end()) {
Utility::destroyObject(o);
return 1;
}
return 0;
}
int IsValidDynamicObject(int id) {
boost::unordered_map<int, Item::SharedObject>::iterator o = core->getData()->objects.find(id);
if (o != core->getData()->objects.end()) {
return 1;
}
return 0;
}
int SetDynamicObjectPos(int id, float x, float y, float z) {
boost::unordered_map<int, Item::SharedObject>::iterator o = core->getData()->objects.find(id);
if (o != core->getData()->objects.end()) {
Eigen::Vector3f position = o->second->position;
o->second->position = Eigen::Vector3f(x, y, z);
for (boost::unordered_map<int, Player>::iterator p = core->getData()->players.begin(); p != core->getData()->players.end(); ++p) {
boost::unordered_map<int, int>::iterator i = p->second.internalObjects.find(o->first);
if (i != p->second.internalObjects.end())
{
sampgdk::SetPlayerObjectPos(p->first, i->second, o->second->position[0], o->second->position[1], o->second->position[2]);
}
}
if (position[0] != o->second->position[0] || position[1] != o->second->position[1]) {
if (o->second->cell)
{
core->getGrid()->removeObject(o->second, true);
}
}
if (o->second->move) {
o->second->move->duration = static_cast<int>((static_cast<float>(boost::geometry::distance(o->second->move->position.get<0>(), o->second->position) / o->second->move->speed) * 1000.0f));
o->second->move->position.get<1>() = o->second->position;
o->second->move->position.get<2>() = (o->second->move->position.get<0>() - o->second->position) / static_cast<float>(o->second->move->duration);
if ((o->second->move->rotation.get<0>().maxCoeff() + 1000.0f) > std::numeric_limits<float>::epsilon())
{
o->second->move->rotation.get<1>() = o->second->rotation;
o->second->move->rotation.get<2>() = (o->second->move->rotation.get<0>() - o->second->rotation) / static_cast<float>(o->second->move->duration);
}
o->second->move->time = boost::chrono::steady_clock::now();
}
return 1;
}
return 0;
}
/*int GetDynamicObjectPos(int id, float &x, float &y, float &z) {
boost::unordered_map<int, Item::SharedObject>::iterator o = core->getData()->objects.find(id);
if (o != core->getData()->objects.end()) {
if (o->second->move) {
core->getStreamer()->processActiveItems();
}
x = o->second->position[0];
y = o->second->position[1];
z = o->second->position[2];
return 1;
}
return 0;
}*/
int SetDynamicObjectRot(int id, float rx, float ry, float rz) {
boost::unordered_map<int, Item::SharedObject>::iterator o = core->getData()->objects.find(id);
if (o != core->getData()->objects.end()) {
o->second->rotation = Eigen::Vector3f(rx, ry, rz);
for (boost::unordered_map<int, Player>::iterator p = core->getData()->players.begin(); p != core->getData()->players.end(); ++p) {
boost::unordered_map<int, int>::iterator i = p->second.internalObjects.find(o->first);
if (i != p->second.internalObjects.end())
{
sampgdk::SetPlayerObjectRot(p->first, i->second, o->second->rotation[0], o->second->rotation[1], o->second->rotation[2]);
}
}
if (o->second->move) {
if ((o->second->move->rotation.get<0>().maxCoeff() + 1000.0f) > std::numeric_limits<float>::epsilon()) {
o->second->move->rotation.get<1>() = o->second->rotation;
o->second->move->rotation.get<2>() = (o->second->move->rotation.get<0>() - o->second->rotation) / static_cast<float>(o->second->move->duration);
}
}
return 1;
}
return 0;
}
/*int GetDynamicObjectRot(int id, float &rx, float &ry, float &rz) {
boost::unordered_map<int, Item::SharedObject>::iterator o = core->getData()->objects.find(id);
if (o != core->getData()->objects.end()) {
if (o->second->move) {
core->getStreamer()->processActiveItems();
}
rx = o->second->rotation[0];
ry = o->second->rotation[1];
rz = o->second->rotation[2];
return 1;
}
return 0;
}*/
int SetDynamicObjectNoCameraCol(int id) {
boost::unordered_map<int, Item::SharedObject>::iterator o = core->getData()->objects.find(id);
if (o != core->getData()->objects.end()) {
o->second->noCameraCollision = true;
for (boost::unordered_map<int, Player>::iterator p = core->getData()->players.begin(); p != core->getData()->players.end(); ++p) {
boost::unordered_map<int, int>::iterator i = p->second.internalObjects.find(o->first);
if (i != p->second.internalObjects.end()) {
sampgdk::SetPlayerObjectNoCameraCol(p->first, i->second);
}
}
return 1;
}
return 0;
}
int GetDynamicObjectNoCameraCol(int id) {
boost::unordered_map<int, Item::SharedObject>::iterator o = core->getData()->objects.find(id);
if (o != core->getData()->objects.end()) {
return o->second->noCameraCollision != 0;
}
return 0;
}
int MoveDynamicObject(int id, float x, float y, float z, float speed, float rx, float ry, float rz) {
if (!rx) {
return 0;
}
boost::unordered_map<int, Item::SharedObject>::iterator o = core->getData()->objects.find(id);
if (o != core->getData()->objects.end()) {
if (o->second->attach) {
Utility::logError("MoveDynamicObject: Object is currently attached and cannot be moved.");
return 0;
}
Eigen::Vector3f position(x, y, z);
Eigen::Vector3f rotation(rx, ry, rz);
o->second->move = boost::intrusive_ptr<Item::Object::Move>(new Item::Object::Move);
o->second->move->duration = static_cast<int>((static_cast<float>(boost::geometry::distance(position, o->second->position) / speed * 1000.0f)));
o->second->move->position.get<0>() = position;
o->second->move->position.get<1>() = o->second->position;
o->second->move->position.get<2>() = (position - o->second->position) / static_cast<float>(o->second->move->duration);
o->second->move->rotation.get<0>() = rotation;
if ((o->second->move->rotation.get<0>().maxCoeff() + 1000.0f) > std::numeric_limits<float>::epsilon())
{
o->second->move->rotation.get<1>() = o->second->rotation;
o->second->move->rotation.get<2>() = (rotation - o->second->rotation) / static_cast<float>(o->second->move->duration);
}
o->second->move->speed = speed;
o->second->move->time = boost::chrono::steady_clock::now();
for (boost::unordered_map<int, Player>::iterator p = core->getData()->players.begin(); p != core->getData()->players.end(); ++p)
{
boost::unordered_map<int, int>::iterator i = p->second.internalObjects.find(o->first);
if (i != p->second.internalObjects.end())
{
sampgdk::StopPlayerObject(p->first, i->second);
sampgdk::MovePlayerObject(p->first, i->second, o->second->move->position.get<0>()[0], o->second->move->position.get<0>()[1], o->second->move->position.get<0>()[2], o->second->move->speed, o->second->move->rotation.get<0>()[0], o->second->move->rotation.get<0>()[1], o->second->move->rotation.get<0>()[2]);
}
}
core->getStreamer()->movingObjects.insert(o->second);
return static_cast<cell>(o->second->move->duration);
}
return 0;
}
int StopDynamicObject(int id) {
boost::unordered_map<int, Item::SharedObject>::iterator o = core->getData()->objects.find(id);
if (o != core->getData()->objects.end()) {
if (o->second->move) {
for (boost::unordered_map<int, Player>::iterator p = core->getData()->players.begin(); p != core->getData()->players.end(); ++p) {
boost::unordered_map<int, int>::iterator i = p->second.internalObjects.find(o->first);
if (i != p->second.internalObjects.end()) {
sampgdk::StopPlayerObject(p->first, i->second);
}
}
o->second->move.reset();
core->getStreamer()->movingObjects.erase(o->second);
return 1;
}
}
return 0;
}
int IsDynamicObjectMoving(int id) {
boost::unordered_map<int, Item::SharedObject>::iterator o = core->getData()->objects.find(id);
if (o != core->getData()->objects.end()) {
if (o->second->move) {
return 1;
}
}
return 0;
}
int AttachCameraToDynamicObject(int playerid, int objectid) {
boost::unordered_map<int, Player>::iterator p = core->getData()->players.find(playerid);
if (p != core->getData()->players.end()) {
int internalID = INVALID_OBJECT_ID;
boost::unordered_map<int, int>::iterator i = p->second.internalObjects.find(objectid);
if (i == p->second.internalObjects.end()) {
boost::unordered_map<int, Item::SharedObject>::iterator o = core->getData()->objects.find(objectid);
if (o != core->getData()->objects.end())
{
p->second.position = Eigen::Vector3f(o->second->position[0], o->second->position[1], o->second->position[2]);
core->getStreamer()->startManualUpdate(p->second, STREAMER_TYPE_OBJECT);
}
boost::unordered_map<int, int>::iterator j = p->second.internalObjects.find(objectid);
if (j != p->second.internalObjects.end())
{
internalID = j->second;
}
} else {
internalID = i->second;
}
if (internalID != INVALID_OBJECT_ID) {
sampgdk::AttachCameraToPlayerObject(p->first, internalID);
return 1;
}
}
return 0;
}
int AttachDynamicObjectToObject(int objectid, int attachtoid, float x, float y, float z, float rx, float ry, float rz, bool sync) {
if (sampgdk::FindNative("SetPlayerGravity") == NULL) {
Utility::logError("AttachDynamicObjectToObject: YSF plugin must be loaded to attach objects to objects.");
return 0;
}
boost::unordered_map<int, Item::SharedObject>::iterator o = core->getData()->objects.find(objectid);
if (o != core->getData()->objects.end()) {
if (o->second->move) {
Utility::logError("AttachDynamicObjectToObject: Object is currently moving and must be stopped first.");
return 0;
}
o->second->attach = boost::intrusive_ptr<Item::Object::Attach>(new Item::Object::Attach);
o->second->attach->player = INVALID_OBJECT_ID;
o->second->attach->vehicle = INVALID_OBJECT_ID;
o->second->attach->object = attachtoid;
o->second->attach->positionOffset = Eigen::Vector3f(x, y, z);
o->second->attach->rotation = Eigen::Vector3f(rx, ry, rz);
o->second->attach->syncRotation = sync;
for (boost::unordered_map<int, Player>::iterator p = core->getData()->players.begin(); p != core->getData()->players.end(); ++p) {
boost::unordered_map<int, int>::iterator i = p->second.internalObjects.find(o->first);
if (i != p->second.internalObjects.end()) {
boost::unordered_map<int, int>::iterator j = p->second.internalObjects.find(o->second->attach->object);
if (j != p->second.internalObjects.end()) {
AMX_NATIVE native = sampgdk::FindNative("AttachPlayerObjectToObject");
if (native != NULL) {
sampgdk::InvokeNative(native, "dddffffffb", p->first, i->second, j->second, o->second->attach->positionOffset[0], o->second->attach->positionOffset[1], o->second->attach->positionOffset[2], o->second->attach->rotation[0], o->second->attach->rotation[1], o->second->attach->rotation[2], o->second->attach->syncRotation);
}
for (boost::unordered_map<int, Item::Object::Material>::iterator m = o->second->materials.begin(); m != o->second->materials.end(); ++m) {
if (m->second.main) {
sampgdk::SetPlayerObjectMaterial(p->first, i->second, m->first, m->second.main->modelId, m->second.main->txdFileName.c_str(), m->second.main->textureName.c_str(), m->second.main->materialColor);
} else if (m->second.text) {
sampgdk::SetPlayerObjectMaterialText(p->first, i->second, m->second.text->materialText.c_str(), m->first, m->second.text->materialSize, m->second.text->fontFace.c_str(), m->second.text->fontSize, m->second.text->bold, m->second.text->fontColor, m->second.text->backColor, m->second.text->textAlignment);
}
}
}
}
}
if (attachtoid != INVALID_STREAMER_ID) {
boost::unordered_map<int, Item::SharedObject>::iterator p = core->getData()->objects.find(attachtoid);
if (p != core->getData()->objects.end())
{
if (o->second->comparableStreamDistance > STREAMER_STATIC_DISTANCE_CUTOFF && p->second->comparableStreamDistance > STREAMER_STATIC_DISTANCE_CUTOFF)
{
o->second->originalComparableStreamDistance = o->second->comparableStreamDistance;
o->second->comparableStreamDistance = p->second->comparableStreamDistance + static_cast<float>(boost::geometry::comparable_distance(o->second->position, p->second->position));
}
}
core->getStreamer()->attachedObjects.insert(o->second);
} else {
if (o->second->originalComparableStreamDistance > STREAMER_STATIC_DISTANCE_CUTOFF && o->second->comparableStreamDistance > STREAMER_STATIC_DISTANCE_CUTOFF) {
o->second->comparableStreamDistance = o->second->originalComparableStreamDistance;
}
o->second->attach.reset();
core->getStreamer()->attachedObjects.erase(o->second);
core->getGrid()->removeObject(o->second, true);
}
return 1;
}
return 0;
}
int AttachDynamicObjectToPlayer(int objectid, int playerid, float x, float y, float z, float rx, float ry, float rz) {
if (sampgdk::FindNative("SetPlayerGravity") == NULL) {
Utility::logError("AttachDynamicObjectToPlayer: YSF plugin must be loaded to attach objects to players.");
return 0;
}
boost::unordered_map<int, Item::SharedObject>::iterator o = core->getData()->objects.find(objectid);
if (o != core->getData()->objects.end()) {
if (o->second->move) {
Utility::logError("AttachDynamicObjectToPlayer: Object is currently moving and must be stopped first.");
return 0;
}
o->second->attach = boost::intrusive_ptr<Item::Object::Attach>(new Item::Object::Attach);
o->second->attach->object = INVALID_STREAMER_ID;
o->second->attach->vehicle = INVALID_OBJECT_ID;
o->second->attach->player = playerid;
o->second->attach->positionOffset = Eigen::Vector3f(x,y,z);
o->second->attach->rotation = Eigen::Vector3f(rx,ry,rz);
for (boost::unordered_map<int, Player>::iterator p = core->getData()->players.begin(); p != core->getData()->players.end(); ++p) {
boost::unordered_map<int, int>::iterator i = p->second.internalObjects.find(o->first);
if (i != p->second.internalObjects.end()) {
AMX_NATIVE native = sampgdk::FindNative("AttachPlayerObjectToPlayer");
if (native != NULL) {
sampgdk::InvokeNative(native, "dddffffffd", p->first, i->second, o->second->attach->player, o->second->attach->positionOffset[0], o->second->attach->positionOffset[1], o->second->attach->positionOffset[2], o->second->attach->rotation[0], o->second->attach->rotation[1], o->second->attach->rotation[2], 0);
}
for (boost::unordered_map<int, Item::Object::Material>::iterator m = o->second->materials.begin(); m != o->second->materials.end(); ++m) {
if (m->second.main) {
sampgdk::SetPlayerObjectMaterial(p->first, i->second, m->first, m->second.main->modelId, m->second.main->txdFileName.c_str(), m->second.main->textureName.c_str(), m->second.main->materialColor);
} else if (m->second.text) {
sampgdk::SetPlayerObjectMaterialText(p->first, i->second, m->second.text->materialText.c_str(), m->first, m->second.text->materialSize, m->second.text->fontFace.c_str(), m->second.text->fontSize, m->second.text->bold, m->second.text->fontColor, m->second.text->backColor, m->second.text->textAlignment);
}
}
}
}
if (playerid != INVALID_OBJECT_ID) {
core->getStreamer()->attachedObjects.insert(o->second);
} else {
o->second->attach.reset();
core->getStreamer()->attachedObjects.erase(o->second);
core->getGrid()->removeObject(o->second, true);
}
return 1;
}
return 0;
}
int AttachDynamicObjectToVehicle(int objectid, int vehicleid, float x, float y, float z, float rx, float ry, float rz) {
boost::unordered_map<int, Item::SharedObject>::iterator o = core->getData()->objects.find(objectid);
if (o != core->getData()->objects.end()) {
if (o->second->move) {
Utility::logError("AttachDynamicObjectToVehicle: Object is currently moving and must be stopped first.");
return 0;
}
o->second->attach = boost::intrusive_ptr<Item::Object::Attach>(new Item::Object::Attach);
o->second->attach->object = INVALID_STREAMER_ID;
o->second->attach->player = INVALID_OBJECT_ID;
o->second->attach->vehicle = vehicleid;
o->second->attach->positionOffset = Eigen::Vector3f(x, y, z);
o->second->attach->rotation = Eigen::Vector3f(rx, ry, rz);
for (boost::unordered_map<int, Player>::iterator p = core->getData()->players.begin(); p != core->getData()->players.end(); ++p) {
boost::unordered_map<int, int>::iterator i = p->second.internalObjects.find(o->first);
if (i != p->second.internalObjects.end()) {
sampgdk::AttachPlayerObjectToVehicle(p->first, i->second, o->second->attach->vehicle, o->second->attach->positionOffset[0], o->second->attach->positionOffset[1], o->second->attach->positionOffset[2], o->second->attach->rotation[0], o->second->attach->rotation[1], o->second->attach->rotation[2]);
for (boost::unordered_map<int, Item::Object::Material>::iterator m = o->second->materials.begin(); m != o->second->materials.end(); ++m) {
if (m->second.main) {
sampgdk::SetPlayerObjectMaterial(p->first, i->second, m->first, m->second.main->modelId, m->second.main->txdFileName.c_str(), m->second.main->textureName.c_str(), m->second.main->materialColor);
} else if (m->second.text) {
sampgdk::SetPlayerObjectMaterialText(p->first, i->second, m->second.text->materialText.c_str(), m->first, m->second.text->materialSize, m->second.text->fontFace.c_str(), m->second.text->fontSize, m->second.text->bold, m->second.text->fontColor, m->second.text->backColor, m->second.text->textAlignment);
}
}
}
}
if (vehicleid != INVALID_OBJECT_ID) {
core->getStreamer()->attachedObjects.insert(o->second);
} else {
o->second->attach.reset();
core->getStreamer()->attachedObjects.erase(o->second);
core->getGrid()->removeObject(o->second, true);
}
return 1;
}
return 0;
}
int EditDynamicObject(int playerid, int objectid) {
boost::unordered_map<int, Player>::iterator p = core->getData()->players.find(playerid);
if (p != core->getData()->players.end()) {
int internalID = INVALID_OBJECT_ID;
boost::unordered_map<int, int>::iterator i = p->second.internalObjects.find(objectid);
if (i == p->second.internalObjects.end()) {
boost::unordered_map<int, Item::SharedObject>::iterator o = core->getData()->objects.find(objectid);
if (o != core->getData()->objects.end()) {
if (o->second->comparableStreamDistance > STREAMER_STATIC_DISTANCE_CUTOFF && o->second->originalComparableStreamDistance < STREAMER_STATIC_DISTANCE_CUTOFF) {
o->second->originalComparableStreamDistance = o->second->comparableStreamDistance;
o->second->comparableStreamDistance = -1.0f;
}
p->second.position = Eigen::Vector3f(o->second->position[0], o->second->position[1], o->second->position[2]);
core->getStreamer()->startManualUpdate(p->second, STREAMER_TYPE_OBJECT);
}
boost::unordered_map<int, int>::iterator j = p->second.internalObjects.find(objectid);
if (j != p->second.internalObjects.end()) {
internalID = j->second;
}
} else {
internalID = i->second;
}
if (internalID != INVALID_OBJECT_ID) {
sampgdk::EditPlayerObject(p->first, internalID);
return 1;
}
}
return 0;
}
int IsDynamicObjectMaterialUsed(int objectid, int materialindex) {
boost::unordered_map<int, Item::SharedObject>::iterator o = core->getData()->objects.find(objectid);
if (o != core->getData()->objects.end()) {
boost::unordered_map<int, Item::Object::Material>::iterator m = o->second->materials.find(materialindex);
if (m != o->second->materials.end()) {
if (m->second.main) {
return 1;
}
}
}
return 0;
}
int GetDynamicObjectMaterial(int objectid, int materialindex, int &modelid, std::string &txdname, std::string &texturename, int &materialcolor) {
boost::unordered_map<int, Item::SharedObject>::iterator o = core->getData()->objects.find(objectid);
if (o != core->getData()->objects.end()) {
boost::unordered_map<int, Item::Object::Material>::iterator m = o->second->materials.find(materialindex);
if (m != o->second->materials.end()) {
if (m->second.main) {
modelid = m->second.main->modelId;
txdname = m->second.main->txdFileName;
texturename = m->second.main->textureName;
materialcolor = m->second.main->materialColor;
return 1;
}
}
}
return 0;
}
int SetDynamicObjectMaterial(int id, int materialindex, int modelid, std::string txdname, std::string texturename, int materialcolor) {
boost::unordered_map<int, Item::SharedObject>::iterator o = core->getData()->objects.find(id);
if (o != core->getData()->objects.end()) {
int index = materialindex;
o->second->materials[index].main = boost::intrusive_ptr<Item::Object::Material::Main>(new Item::Object::Material::Main);
o->second->materials[index].main->modelId = modelid;
o->second->materials[index].main->txdFileName = txdname;
o->second->materials[index].main->textureName = texturename;
o->second->materials[index].main->materialColor = materialcolor;
for (boost::unordered_map<int, Player>::iterator p = core->getData()->players.begin(); p != core->getData()->players.end(); ++p)
{
boost::unordered_map<int, int>::iterator i = p->second.internalObjects.find(o->first);
if (i != p->second.internalObjects.end())
{
sampgdk::SetPlayerObjectMaterial(p->first, i->second, index, o->second->materials[index].main->modelId, o->second->materials[index].main->txdFileName.c_str(), o->second->materials[index].main->textureName.c_str(), o->second->materials[index].main->materialColor);
}
}
o->second->materials[index].text.reset();
return 1;
}
return 0;
}
int IsDynamicObjectMaterialTextUsed(int id, int materialindex) {
boost::unordered_map<int, Item::SharedObject>::iterator o = core->getData()->objects.find(id);
if (o != core->getData()->objects.end()) {
boost::unordered_map<int, Item::Object::Material>::iterator m = o->second->materials.find(materialindex);
if (m != o->second->materials.end()) {
if (m->second.text) {
return 1;
}
}
}
return 0;
}
int GetDynamicObjectMaterialText(int id, int materialindex, std::string &text, int &materialSize, std::string &fontface, int &fontsize, bool &bold, int &fontcolor, int &backcolor, int &textalignment) {
boost::unordered_map<int, Item::SharedObject>::iterator o = core->getData()->objects.find(id);
if (o != core->getData()->objects.end()) {
boost::unordered_map<int, Item::Object::Material>::iterator m = o->second->materials.find(materialindex);
if (m != o->second->materials.end()) {
if (m->second.text) {
text = m->second.text->materialText;
materialSize = m->second.text->materialSize;
fontface = m->second.text->fontFace;
fontsize = m->second.text->fontSize;
bold = m->second.text->bold;
fontcolor = m->second.text->fontColor;
backcolor = m->second.text->backColor;
textalignment = m->second.text->textAlignment;
return 1;
}
}
}
return 0;
}
int SetDynamicObjectMaterialText(int id, int materialindex, std::string text, int materialsize, std::string fontface, int fontsize, bool bold, int fontcolor, int backcolor, int textalignment) {
boost::unordered_map<int, Item::SharedObject>::iterator o = core->getData()->objects.find(id);
if (o != core->getData()->objects.end()) {
int index = materialindex;
o->second->materials[index].text = boost::intrusive_ptr<Item::Object::Material::Text>(new Item::Object::Material::Text);
o->second->materials[index].text->materialText = text;
o->second->materials[index].text->materialSize = materialsize;
o->second->materials[index].text->fontFace = fontface;
o->second->materials[index].text->fontSize = fontsize;
o->second->materials[index].text->bold = bold;
o->second->materials[index].text->fontColor = fontcolor;
o->second->materials[index].text->backColor = backcolor;
o->second->materials[index].text->textAlignment = textalignment;
for (boost::unordered_map<int, Player>::iterator p = core->getData()->players.begin(); p != core->getData()->players.end(); ++p) {
boost::unordered_map<int, int>::iterator i = p->second.internalObjects.find(o->first);
if (i != p->second.internalObjects.end()) {
sampgdk::SetPlayerObjectMaterialText(p->first, i->second, o->second->materials[index].text->materialText.c_str(), index, o->second->materials[index].text->materialSize, o->second->materials[index].text->fontFace.c_str(), o->second->materials[index].text->fontSize, o->second->materials[index].text->bold, o->second->materials[index].text->fontColor, o->second->materials[index].text->backColor, o->second->materials[index].text->textAlignment);
}
}
o->second->materials[index].main.reset();
return 1;
}
return 0;
}
int GetPlayerCameraTargetDynObject(int playerrid) {
boost::unordered_map<int, Player>::iterator p = core->getData()->players.find(playerrid);
if (p != core->getData()->players.end()) {
int objectid = sampgdk::GetPlayerCameraTargetObject(p->second.playerId);
if (objectid != INVALID_OBJECT_ID) {
for (boost::unordered_map<int, int>::iterator i = p->second.internalObjects.begin(); i != p->second.internalObjects.end(); ++i) {
if (i->second == objectid) {
return i->first;
}
}
}
}
return 0;
}
int GetDynamicObjectPos(int objectid, float &x, float &y, float &z) {
boost::unordered_map<int, Item::SharedObject>::iterator o = core->getData()->objects.find(objectid);
if (o != core->getData()->objects.end()) {
if (o->second->move) {
core->getStreamer()->processActiveItems();
}
x = o->second->position[0];
y = o->second->position[1];
z = o->second->position[2];
return 1;
}
return 0;
}
int GetDynamicObjectRot(int objectid, float &rx, float &ry, float &rz) {
boost::unordered_map<int, Item::SharedObject>::iterator o = core->getData()->objects.find(objectid);
if (o != core->getData()->objects.end()) {
if (o->second->move) {
core->getStreamer()->processActiveItems();
}
rx = o->second->rotation[0];
ry = o->second->rotation[1];
rz = o->second->rotation[2];
return 1;
}
return 0;
}
STREAMER_END_NS | 45.170886 | 448 | 0.684111 | [
"geometry",
"object"
] |
9cbd2eb53c74a1f228c2c03b0df25979d0c49fad | 7,858 | cpp | C++ | src/server/main.cpp | ondra-novak/loginserver | d59a87f04f9c1543e206e0e78a23d8f1fe2cc2ae | [
"MIT"
] | 1 | 2018-04-05T13:15:01.000Z | 2018-04-05T13:15:01.000Z | src/server/main.cpp | ondra-novak/loginserver | d59a87f04f9c1543e206e0e78a23d8f1fe2cc2ae | [
"MIT"
] | null | null | null | src/server/main.cpp | ondra-novak/loginserver | d59a87f04f9c1543e206e0e78a23d8f1fe2cc2ae | [
"MIT"
] | null | null | null | /*
* main.cpp
*
* Created on: 11. 7. 2017
* Author: ondra
*/
#include <thread>
#include <couchit/changes.h>
#include <imtjson/rpc.h>
#include <rpc/rpcServer.h>
#include <shared/stdLogFile.h>
#include <simpleServer/address.h>
#include <simpleServer/http_server.h>
#include <simpleServer/abstractService.h>
#include <simpleServer/http_filemapper.h>
#include <simpleServer/logOutput.h>
#include <shared/ini_config.h>
#include <token/usertoken.h>
#include "rpcinterface.h"
#include "user_services.h"
using ondra_shared::StdLogFile;
using ondra_shared::IniConfig;
using ondra_shared::StrViewA;
using namespace couchit;
using namespace json;
using namespace simpleServer;
using namespace loginsrv;
static Value customRules = json::Value::fromString(R"json(
{
"Email":["explode","@",[[2],"Username","Domain"]],
"Username":"[a-z-A-Z.0-9_+\"]",
"Domain":["explode",".",[[2],"DomainPart","DomainPart","DomainPart"]],
"DomainPart":"[a-z-0-9]",
"Token":["explode",".",[[2],"base64url","base64url"]],
"Code":["explode","-",[[2],"digits","digits","digits"]],
"Password":["all","string",["minsize",8]],
"PurposeItem":["all","[a-zA-Z0-9_]",["!","Refresh"]],
"PurposeList":[[],"PurposeItem"],
"Purpose":["Refresh","PurposeItem","PurposeList",[[2],"Refresh","PurposeList"]],
"Refresh":"'refresh"
}
)json");
static Value readUserConfig(const std::string &name) {
std::ifstream inf(name, std::ios::in);
if (!inf) {
std::string error = "Can't read user config: " + name;
throw std::runtime_error(error);
}
try {
return Value::fromStream(inf);
} catch (std::exception &e) {
std::string error("Failed to read user config: ");
error.append(e.what());
throw std::runtime_error(error);
}
}
class Svcs: public RpcInterface::IServices {
public:
Svcs(
const std::string &templatePrefix,
const std::string &sendCmd,
const std::string &captchaCmd,
const std::string &otpissuer,
const std::string &reportCmd,
const Value &usercfg
):templatePrefix(templatePrefix)
,sendCmd(sendCmd)
,captchaCmd(captchaCmd)
,otpissuer(otpissuer)
,reportCmd(reportCmd)
,usercfg(usercfg)
,reportF(nullptr) {}
~Svcs() {
if (reportF) pclose(reportF);
}
virtual void sendMail(const StrViewA email,
const StrViewA templateName,
const Value &templateData) override;
virtual bool verifyCaptcha(const StrViewA response)override;
virtual String getOTPLabel(const UserProfile &profile)override;
virtual Value getUserConfig(const StrViewA key) override;
virtual void report(const Value userId, const StrViewA &action, Value data) override;
protected:
std::string templatePrefix;
std::string sendCmd;
std::string captchaCmd;
std::string otpissuer;
std::string reportCmd;
Value usercfg;
std::mutex lock;
FILE *reportF;
};
void Svcs::sendMail(const StrViewA email,
const StrViewA templateName,
const Value &templateData) {
if (email.empty()) return;
Value req = Object("template",String({templatePrefix,templateName}))
("recepient", email)
("data", templateData);
ondra_shared::logDebug("Send mail: $1 - $2", sendCmd, req.toString());
if (!sendCmd.empty()) {
FILE *f = popen(sendCmd.c_str(),"w");
if (f == nullptr) {
ondra_shared::logError("Cannot execute command: $1",sendCmd);
} else {
req.toFile(f);
fputs("\n",f);
int res = pclose(f);
if (res) ondra_shared::logError("Unexpected exit status for command: $1 - exit $2",sendCmd, res);
}
}
}
bool Svcs::verifyCaptcha(const StrViewA response) {
ondra_shared::logDebug("Check captcha: $1 - $2", captchaCmd, response);
if (!captchaCmd.empty()) {
FILE *f = popen(captchaCmd.c_str(),"w");
if (f == nullptr) {
ondra_shared::logError("Cannot execute command: $1",captchaCmd);
return false;
} else {
fwrite(response.data,response.length,1,f);
fputs("\n",f);
int res = pclose(f);
return res == 0;
}
}
return true;
}
String Svcs::getOTPLabel(const UserProfile &profile) {
return String(StrViewA(otpissuer));
}
Value Svcs::getUserConfig(const StrViewA key) {
Value c = usercfg[key];
if (c.defined()) return c;
return usercfg[""];
}
void Svcs::report(const Value userId, const StrViewA &action, Value data) {
Object repObj;
time_t now;
time(&now);
repObj("time", std::size_t(now))
("user", userId)
("event", action)
("data", data);
std::lock_guard<std::mutex> _(lock);
if (reportF == nullptr) {
reportF = popen(reportCmd.c_str(),"w");
if (reportF == nullptr) {
logError("Can't initialize report stream. Cmd: $1 - error $2", reportCmd, errno);
return;
}
}
Value(repObj).toFile(reportF);
if (fputs("\n",reportF) < 0 || fflush(reportF) < 0) {
unsigned int res = pclose(reportF);
logError("The report process (cmd: $1) has died with exit code: $2", reportCmd, res);
reportF = nullptr;
}
}
int main(int argc, char **argv) {
(new StdLogProviderFactory())->setDefault();
return
simpleServer::ServiceControl::create(argc, argv, "loginsrv",
[&](simpleServer::ServiceControl svc, StrViewA, simpleServer::ArgList lst) {
if (lst.length != 1) {
std::cerr << "need path to config";
return 1;
}
IniConfig config;
config.load(lst[0]);
couchit::Config couchcfg;
auto dbCfg = config["database"];
couchcfg.authInfo.username = dbCfg.mandatory["user"].getString();
couchcfg.authInfo.password = dbCfg.mandatory["password"].getString();
couchcfg.baseUrl =dbCfg.mandatory["url"].getString();
couchcfg.databaseName = dbCfg.mandatory["name"].getString();
CouchDB couchdb(couchcfg);
auto serverCfg = config["server"];
LogLevelToStrTable levelToStr;
(new StdLogFile(serverCfg["log_file"].getPath(), levelToStr.fromString(serverCfg["log_level"].getString(), LogLevel::info)))->setDefault();
StrViewA hostMapping = serverCfg.mandatory["map_hosts"].getString();
StrViewA straddr = serverCfg.mandatory["bind"].getString();
unsigned int threads = serverCfg.mandatory["threads"].getUInt();
unsigned int dispatchers = serverCfg.mandatory["dispatchers"].getUInt();
simpleServer::NetAddr addr = simpleServer::NetAddr::create(straddr,52123);
RpcHttpServer server(addr, threads, dispatchers);
server.setHostMapping(String(hostMapping));
svc.changeUser(serverCfg["user"].getString());
svc.enableRestart();
RpcHttpServer::Config cfg;
cfg.enableConsole = serverCfg.mandatory["rpc_enableConsole"].getUInt() != 0;
cfg.maxReqSize = serverCfg.mandatory["rpc_maxReqSize"].getUInt();
server.addRPCPath("/RPC", cfg);
server.add_listMethods("methods");
server.add_ping("ping");
auto loginCfg = config["login"];
Value privateKey = loginCfg.mandatory["private_key"].getString();
std::string userConfig = loginCfg.mandatory["user_config"].getPath();
std::string sendCmd = loginCfg.mandatory["mail_svc"].getPath();
std::string templatePrefix = loginCfg["mail_template_prefix"].getString();
std::string captcha = loginCfg["captcha_svc"].getPath();
std::string otpIssuer = loginCfg.mandatory["otp_issuer"].getString();
std::string reportSvc = loginCfg.mandatory["report_svc"].getPath();
Value userConfigJson = readUserConfig(userConfig);
UserToken tok(Token::privateKey, String(privateKey));
RpcInterface::Config ifccfg;
ifccfg.mailCodeExpiration_sec = loginCfg.mandatory["mail_code_expires"].getUInt();
ifccfg.refreshTokenExpiration_sec = loginCfg.mandatory["refresh_token_expires"].getUInt();
ifccfg.rootTokenExpiration_sec = loginCfg.mandatory["token_expires"].getUInt();
ifccfg.userLockWait = loginCfg.mandatory["login_failure_lock_time"].getUInt();
UserServices us(couchdb);
Svcs ifcsvc(templatePrefix,sendCmd,captcha,otpIssuer,reportSvc,userConfigJson);
RpcInterface ifc(us, tok, ifcsvc, ifccfg);
server.setCustomValidationRules(customRules);
ifc.registerMethods(server);
server.addPath("/web",HttpFileMapper("web/","index.html"));
server.start();
svc.dispatch();
return 0;
});
}
| 25.185897 | 140 | 0.706159 | [
"object"
] |
9cc339db94c913675a1093566455771937fc9b8e | 131,136 | cpp | C++ | mysql-server/storage/ndb/test/ndbapi/testBasic.cpp | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | mysql-server/storage/ndb/test/ndbapi/testBasic.cpp | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | mysql-server/storage/ndb/test/ndbapi/testBasic.cpp | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | /*
Copyright (c) 2003, 2020 Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is also distributed with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have included with MySQL.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <NDBT_Test.hpp>
#include <NDBT_ReturnCodes.h>
#include <HugoTransactions.hpp>
#include <UtilTransactions.hpp>
#include <NdbRestarter.hpp>
#include <signaldata/DictTabInfo.hpp>
#include <Bitmask.hpp>
#include <random.h>
#include <signaldata/DumpStateOrd.hpp>
#include <NdbConfig.hpp>
#include <BlockNumbers.h>
#include <NdbHost.h>
#include <NdbMgmd.hpp>
#define CHK1(b) \
if (!(b)) { \
g_err << "ERR: " << #b << " failed at line " << __LINE__; \
result = NDBT_FAILED; \
break; \
}
#define CHK2(b, e) \
if (!(b)) { \
g_err << "ERR: " << #b << " failed at line " << __LINE__ \
<< ": " << e << endl; \
result = NDBT_FAILED; \
break; \
}
#define CHECK3(b) if (!(b)) { \
ndbout << "ERR: "<< step->getName() \
<< " failed on line " << __LINE__ << endl; \
return NDBT_FAILED; }
/**
* TODO
* dirtyWrite, write, dirtyUpdate
* delete should be visible to same transaction
*
*/
int runLoadTable2(NDBT_Context* ctx, NDBT_Step* step)
{
int records = ctx->getNumRecords();
HugoTransactions hugoTrans(*ctx->getTab());
if (hugoTrans.loadTable(GETNDB(step), records, 512, false, 0, true) != 0){
return NDBT_FAILED;
}
return NDBT_OK;
}
int runLoadTable(NDBT_Context* ctx, NDBT_Step* step)
{
int num_records = ctx->getProperty("Records", Uint32(0));
int records = ctx->getNumRecords();
if (num_records != 0)
{
records = num_records;
}
HugoTransactions hugoTrans(*ctx->getTab());
if (hugoTrans.loadTable(GETNDB(step), records) != 0){
return NDBT_FAILED;
}
return NDBT_OK;
}
int runInsert(NDBT_Context* ctx, NDBT_Step* step){
int records = ctx->getNumRecords();
HugoTransactions hugoTrans(*ctx->getTab());
// Insert records, dont allow any
// errors(except temporary) while inserting
if (hugoTrans.loadTable(GETNDB(step), records, 1, false) != 0){
return NDBT_FAILED;
}
return NDBT_OK;
}
int runInsertTwice(NDBT_Context* ctx, NDBT_Step* step){
int records = ctx->getNumRecords();
HugoTransactions hugoTrans(*ctx->getTab());
// Insert records, expect primary key violation 630
if (hugoTrans.loadTable(GETNDB(step), records, 1, false) != 630){
return NDBT_FAILED;
}
return NDBT_OK;
}
int runVerifyInsert(NDBT_Context* ctx, NDBT_Step* step){
int records = ctx->getNumRecords();
HugoTransactions hugoTrans(*ctx->getTab());
if (hugoTrans.pkDelRecords(GETNDB(step), records, 1, false) != 0){
return NDBT_FAILED;
}
return NDBT_OK;
}
int runInsertUntilStopped(NDBT_Context* ctx, NDBT_Step* step){
int records = ctx->getNumRecords();
int i = 0;
HugoTransactions hugoTrans(*ctx->getTab());
while (ctx->isTestStopped() == false) {
g_info << i << ": ";
if (hugoTrans.loadTable(GETNDB(step), records) != 0){
g_info << endl;
return NDBT_FAILED;
}
i++;
}
g_info << endl;
return NDBT_OK;
}
int runClearTable(NDBT_Context* ctx, NDBT_Step* step){
int num_records = ctx->getProperty("Records", Uint32(0));
int records = ctx->getNumRecords();
int batchSize = ctx->getProperty("BatchSize", 1);
if (num_records != 0)
{
records = num_records;
}
HugoTransactions hugoTrans(*ctx->getTab());
if (hugoTrans.pkDelRecords(GETNDB(step), records, batchSize) != 0){
return NDBT_FAILED;
}
return NDBT_OK;
}
int runPkDelete(NDBT_Context* ctx, NDBT_Step* step){
int loops = ctx->getNumLoops();
int records = ctx->getNumRecords();
int i = 0;
HugoTransactions hugoTrans(*ctx->getTab());
while (i<loops) {
g_info << i << ": ";
if (hugoTrans.pkDelRecords(GETNDB(step), records) != 0){
g_info << endl;
return NDBT_FAILED;
}
// Load table, don't allow any primary key violations
if (hugoTrans.loadTable(GETNDB(step), records, 512, false) != 0){
g_info << endl;
return NDBT_FAILED;
}
i++;
}
g_info << endl;
return NDBT_OK;
}
int runPkRead(NDBT_Context* ctx, NDBT_Step* step){
int loops = ctx->getNumLoops();
int records = ctx->getNumRecords();
int batchSize = ctx->getProperty("BatchSize", 1);
int lm = ctx->getProperty("LockMode", NdbOperation::LM_Read);
int i = 0;
HugoTransactions hugoTrans(*ctx->getTab());
while (i<loops) {
g_info << i << ": ";
if (hugoTrans.pkReadRecords(GETNDB(step), records, batchSize,
(NdbOperation::LockMode)lm) != NDBT_OK){
g_info << endl;
return NDBT_FAILED;
}
i++;
}
g_info << endl;
return NDBT_OK;
}
int runTimer(NDBT_Context* ctx, NDBT_Step* step)
{
sleep(120);
ctx->stopTest();
return NDBT_OK;
}
int runPkDirtyReadUntilStopped(NDBT_Context* ctx, NDBT_Step* step)
{
int num_records = ctx->getProperty("Records", Uint32(0));
int records = ctx->getNumRecords();
int batchSize = ctx->getProperty("BatchSize", 2);
int lm = ctx->getProperty("LockMode", NdbOperation::LM_CommittedRead);
int i = 0;
if (num_records != 0)
{
records = num_records;
}
HugoTransactions hugoTrans(*ctx->getTab());
while (ctx->isTestStopped() == false) {
g_info << i << ": ";
if (hugoTrans.pkReadRecords(GETNDB(step),
records,
batchSize,
(NdbOperation::LockMode)lm) != 0){
g_info << endl;
return NDBT_FAILED;
}
i++;
}
g_info << endl;
return NDBT_OK;
}
int runPkReadUntilStopped(NDBT_Context* ctx, NDBT_Step* step){
int records = ctx->getNumRecords();
int batchSize = ctx->getProperty("BatchSize", 1);
int i = 0;
HugoTransactions hugoTrans(*ctx->getTab());
while (ctx->isTestStopped() == false) {
g_info << i << ": ";
if (hugoTrans.pkReadRecords(GETNDB(step), records, batchSize) != 0){
g_info << endl;
return NDBT_FAILED;
}
i++;
}
g_info << endl;
return NDBT_OK;
}
int runPkUpdate(NDBT_Context* ctx, NDBT_Step* step){
int loops = ctx->getNumLoops();
int records = ctx->getNumRecords();
int batchSize = ctx->getProperty("BatchSize", 1);
int i = 0;
HugoTransactions hugoTrans(*ctx->getTab());
while (i<loops) {
g_info << "|- " << i << ": ";
if (hugoTrans.pkUpdateRecords(GETNDB(step), records, batchSize) != 0){
g_info << endl;
return NDBT_FAILED;
}
i++;
}
g_info << endl;
return NDBT_OK;
}
int runPkUpdateUntilStopped(NDBT_Context* ctx, NDBT_Step* step)
{
int num_records = ctx->getProperty("Records", Uint32(0));
int records = ctx->getNumRecords();
int batchSize = ctx->getProperty("BatchSize", 1);
int i = 0;
if (num_records != 0)
{
records = num_records;
}
HugoTransactions hugoTrans(*ctx->getTab());
while (ctx->isTestStopped()) {
g_info << i << ": ";
if (hugoTrans.pkUpdateRecords(GETNDB(step), records, batchSize) != 0){
g_info << endl;
return NDBT_FAILED;
}
i++;
}
g_info << endl;
return NDBT_OK;
}
int runLocker(NDBT_Context* ctx, NDBT_Step* step){
int result = NDBT_OK;
int records = ctx->getNumRecords();
HugoTransactions hugoTrans(*ctx->getTab());
if (hugoTrans.lockRecords(GETNDB(step), records, 10, 500) != 0){
result = NDBT_FAILED;
}
ctx->stopTest();
return result;
}
int
runInsertOne(NDBT_Context* ctx, NDBT_Step* step){
if(ctx->getProperty("InsertCommitted", (Uint32)0) != 0){
abort();
}
while(ctx->getProperty("Read1Performed", (Uint32)0) == 0){
NdbSleep_MilliSleep(20);
}
HugoTransactions hugoTrans(*ctx->getTab());
if (hugoTrans.loadTable(GETNDB(step), 1, 1) != 0){
return NDBT_FAILED;
}
ctx->setProperty("InsertCommitted", 1);
NdbSleep_SecSleep(2);
return NDBT_OK;
}
/**
* Insert error 5083 in DBLQH that puts operation into LOG_QUEUED state and puts
* the operation in the REDO log queue. After a while it will be timed out and
* the abort code will handle it, the runLoadTableFail method will then abort and
* be assumed to be ok, so as long as the node doesn't crash we're passing the
* test case and also the operation should be aborted.
*
* If this test case is run on 7.2 it will simply be the same as Fill since we
* don't queue REDO log operations but rather abort it immediately. So it will
* pass as well but won't test the desired functionality.
*/
int runLoadTableFail(NDBT_Context* ctx, NDBT_Step* step)
{
int records = 16;
int res;
HugoTransactions hugoTrans(*ctx->getTab());
res = hugoTrans.loadTable(GETNDB(step), records, 64, true, 0, true, true);
if (res == 266 || /* Timeout when REDO logging queueing active (or not) */
res == 0) /* No error when not REDO logging active and no error insert */
{
ndbout << "res = " << res << endl;
return NDBT_OK;
}
/* All other error variants are errors in this case */
return NDBT_FAILED;
}
int
insertError5083(NDBT_Context* ctx, NDBT_Step* step)
{
NdbRestarter restarter;
restarter.insertErrorInAllNodes(5083);
return 0;
}
int
clearError5083(NDBT_Context* ctx, NDBT_Step* step)
{
NdbRestarter restarter;
restarter.insertErrorInAllNodes(0);
return 0;
}
static
int
readOneNoCommit(Ndb* pNdb, NdbConnection* pTrans,
const NdbDictionary::Table* tab,NDBT_ResultRow * row){
int a;
NdbOperation * pOp = pTrans->getNdbOperation(tab->getName());
if (pOp == NULL){
NDB_ERR(pTrans->getNdbError());
return NDBT_FAILED;
}
HugoTransactions tmp(*tab);
int check = pOp->readTuple();
if( check == -1 ) {
NDB_ERR(pTrans->getNdbError());
return NDBT_FAILED;
}
// Define primary keys
for(a = 0; a<tab->getNoOfColumns(); a++){
if (tab->getColumn(a)->getPrimaryKey() == true){
if(tmp.equalForAttr(pOp, a, 0) != 0){
NDB_ERR(pTrans->getNdbError());
return NDBT_FAILED;
}
}
}
// Define attributes to read
for(a = 0; a<tab->getNoOfColumns(); a++){
if((row->attributeStore(a) =
pOp->getValue(tab->getColumn(a)->getName())) == 0) {
NDB_ERR(pTrans->getNdbError());
return NDBT_FAILED;
}
}
check = pTrans->execute(NoCommit);
if( check == -1 ) {
const NdbError err = pTrans->getNdbError();
NDB_ERR(err);
return err.code;
}
return NDBT_OK;
}
int
runReadOne(NDBT_Context* ctx, NDBT_Step* step){
Ndb* pNdb = GETNDB(step);
const NdbDictionary::Table* tab = ctx->getTab();
NDBT_ResultRow row1(*tab);
NDBT_ResultRow row2(*tab);
if(ctx->getProperty("Read1Performed", (Uint32)0) != 0){
abort();
}
if(ctx->getProperty("InsertCommitted", (Uint32)0) != 0){
abort();
}
NdbConnection * pTrans = pNdb->startTransaction();
if (pTrans == NULL) {
abort();
}
// Read a record with NoCommit
// Since the record isn't inserted yet it wil return 626
const int res1 = readOneNoCommit(pNdb, pTrans, tab, &row1);
g_info << "|- res1 = " << res1 << endl;
ctx->setProperty("Read1Performed", 1);
while(ctx->getProperty("InsertCommitted", (Uint32)0) == 0 &&
!ctx->isTestStopped()){
g_info << "|- Waiting for insert" << endl;
NdbSleep_MilliSleep(20);
}
if(ctx->isTestStopped()){
abort();
}
// Now the record should have been inserted
// Read it once again in the same transaction
// Should also reutrn 626 if reads are consistent
// NOTE! Currently it's not possible to start a new operation
// on a transaction that has returned an error code
// This is wat fail in this test
// MASV 20030624
const int res2 = readOneNoCommit(pNdb, pTrans, tab, &row2);
pTrans->execute(Commit);
pNdb->closeTransaction(pTrans);
g_info << "|- res2 = " << res2 << endl;
if (res2 == 626 && res1 == res2)
return NDBT_OK;
else
return NDBT_FAILED;
}
int runFillTable(NDBT_Context* ctx, NDBT_Step* step){
int batch = 512; //4096;
HugoTransactions hugoTrans(*ctx->getTab());
if (hugoTrans.fillTable(GETNDB(step), batch ) != 0){
return NDBT_FAILED;
}
return NDBT_OK;
}
int runClearTable2(NDBT_Context* ctx, NDBT_Step* step){
int records = ctx->getNumRecords();
UtilTransactions utilTrans(*ctx->getTab());
if (utilTrans.clearTable2(GETNDB(step), records, 240) != 0){
return NDBT_FAILED;
}
return NDBT_OK;
}
#define CHECK(b) if (!(b)) { \
ndbout << "ERR: "<< step->getName() \
<< " failed on line " << __LINE__ << endl; \
result = NDBT_FAILED; \
break; }
#define CHECK2(b) if (!(b)) { \
ndbout << "ERR: "<< step->getName() \
<< " failed on line " << __LINE__ << endl; \
result = NDBT_FAILED; }
int runNoCommitSleep(NDBT_Context* ctx, NDBT_Step* step){
int result = NDBT_OK;
HugoOperations hugoOps(*ctx->getTab());
Ndb* pNdb = GETNDB(step);
int sleepTime = 100; // ms
for (int i = 2; i < 8; i++){
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 1, 1, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.execute_NoCommit(pNdb) == 0);
ndbout << i <<": Sleeping for " << sleepTime << " ms" << endl;
NdbSleep_MilliSleep(sleepTime);
// Dont care about result of these ops
hugoOps.pkReadRecord(pNdb, 1, 1, NdbOperation::LM_Exclusive);
hugoOps.closeTransaction(pNdb);
sleepTime = sleepTime *i;
}
hugoOps.closeTransaction(pNdb);
return result;
}
int runCommit626(NDBT_Context* ctx, NDBT_Step* step){
int result = NDBT_OK;
HugoOperations hugoOps(*ctx->getTab());
Ndb* pNdb = GETNDB(step);
do{
// Commit transaction
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 1, 1, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.execute_Commit(pNdb) == 626);
CHECK(hugoOps.closeTransaction(pNdb) == 0);
// Commit transaction
// Multiple operations
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 1, 1, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 2, 1, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 3, 1, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.execute_Commit(pNdb) == 626);
}while(false);
hugoOps.closeTransaction(pNdb);
return result;
}
int runCommit630(NDBT_Context* ctx, NDBT_Step* step){
int result = NDBT_OK;
HugoOperations hugoOps(*ctx->getTab());
Ndb* pNdb = GETNDB(step);
do{
// Commit transaction
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkInsertRecord(pNdb, 1) == 0);
CHECK(hugoOps.execute_Commit(pNdb) == 630);
}while(false);
hugoOps.closeTransaction(pNdb);
return result;
}
int runCommit_TryCommit626(NDBT_Context* ctx, NDBT_Step* step){
int result = NDBT_OK;
HugoOperations hugoOps(*ctx->getTab());
Ndb* pNdb = GETNDB(step);
do{
// Commit transaction, TryCommit
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 1, 1, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.execute_Commit(pNdb, TryCommit) == 626);
CHECK(hugoOps.closeTransaction(pNdb) == 0);
// Commit transaction, TryCommit
// Several operations in one transaction
// The insert is OK
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 1, 1, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 2, 1, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 3, 1, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.pkInsertRecord(pNdb, 1) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 4, 1, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.execute_Commit(pNdb, TryCommit) == 626);
}while(false);
hugoOps.closeTransaction(pNdb);
return result;
}
int runCommit_TryCommit630(NDBT_Context* ctx, NDBT_Step* step){
int result = NDBT_OK;
HugoOperations hugoOps(*ctx->getTab());
Ndb* pNdb = GETNDB(step);
do{
// Commit transaction, TryCommit
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkInsertRecord(pNdb, 1) == 0);
CHECK(hugoOps.execute_Commit(pNdb, TryCommit) == 630);
}while(false);
hugoOps.closeTransaction(pNdb);
return result;
}
int runCommit_CommitAsMuchAsPossible626(NDBT_Context* ctx, NDBT_Step* step){
int result = NDBT_OK;
HugoOperations hugoOps(*ctx->getTab());
Ndb* pNdb = GETNDB(step);
do{
// Commit transaction, CommitAsMuchAsPossible
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 1, 1, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.execute_Commit(pNdb, CommitAsMuchAsPossible) == 626);
CHECK(hugoOps.closeTransaction(pNdb) == 0);
// Commit transaction, CommitAsMuchAsPossible
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 2, 1, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 3, 1, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.pkInsertRecord(pNdb, 1) == 0);
CHECK(hugoOps.execute_Commit(pNdb, CommitAsMuchAsPossible) == 626);
CHECK(hugoOps.closeTransaction(pNdb) == 0);
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 1) == 0);
CHECK(hugoOps.execute_Commit(pNdb) == 0);
CHECK(hugoOps.closeTransaction(pNdb) == 0);
} while(false);
hugoOps.closeTransaction(pNdb);
return result;
}
int runCommit_CommitAsMuchAsPossible630(NDBT_Context* ctx, NDBT_Step* step){
int result = NDBT_OK;
HugoOperations hugoOps(*ctx->getTab());
Ndb* pNdb = GETNDB(step);
do{
// Commit transaction, CommitAsMuchAsPossible
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkInsertRecord(pNdb, 1) == 0);
CHECK(hugoOps.pkDeleteRecord(pNdb, 2) == 0);
CHECK(hugoOps.execute_Commit(pNdb, CommitAsMuchAsPossible) == 630);
CHECK(hugoOps.closeTransaction(pNdb) == 0);
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 2) == 0);
CHECK(hugoOps.execute_Commit(pNdb) == 626);
} while(false);
hugoOps.closeTransaction(pNdb);
return result;
}
int runNoCommit626(NDBT_Context* ctx, NDBT_Step* step){
int result = NDBT_OK;
HugoOperations hugoOps(*ctx->getTab());
Ndb* pNdb = GETNDB(step);
do{
// No commit transaction, readTuple
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 1, 1, NdbOperation::LM_Read) == 0);
CHECK(hugoOps.execute_NoCommit(pNdb) == 626);
CHECK(hugoOps.closeTransaction(pNdb) == 0);
// No commit transaction, readTupleExcluive
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 1, 1, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.execute_NoCommit(pNdb) == 626);
}while(false);
hugoOps.closeTransaction(pNdb);
return result;
}
int runNoCommit630(NDBT_Context* ctx, NDBT_Step* step){
int result = NDBT_OK;
HugoOperations hugoOps(*ctx->getTab());
Ndb* pNdb = GETNDB(step);
do{
// No commit transaction
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkInsertRecord(pNdb, 1) == 0);
CHECK(hugoOps.execute_NoCommit(pNdb) == 630);
}while(false);
hugoOps.closeTransaction(pNdb);
return result;
}
int runNoCommitRollback626(NDBT_Context* ctx, NDBT_Step* step){
int result = NDBT_OK;
HugoOperations hugoOps(*ctx->getTab());
Ndb* pNdb = GETNDB(step);
do{
// No commit transaction, rollback
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 1, 1, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.execute_NoCommit(pNdb) == 626);
CHECK(hugoOps.execute_Rollback(pNdb) == 0);
CHECK(hugoOps.closeTransaction(pNdb) == 0);
// No commit transaction, rollback
// Multiple operations
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 1, 1, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 2, 1, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 3, 1, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 4, 1, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.execute_NoCommit(pNdb) == 626);
CHECK(hugoOps.execute_Rollback(pNdb) == 0);
}while(false);
hugoOps.closeTransaction(pNdb);
return result;
}
int runNoCommitRollback630(NDBT_Context* ctx, NDBT_Step* step){
int result = NDBT_OK;
HugoOperations hugoOps(*ctx->getTab());
Ndb* pNdb = GETNDB(step);
do{
// No commit transaction, rollback
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkInsertRecord(pNdb, 1) == 0);
CHECK(hugoOps.execute_NoCommit(pNdb) == 630);
CHECK(hugoOps.execute_Rollback(pNdb) == 0);
}while(false);
hugoOps.closeTransaction(pNdb);
return result;
}
int runNoCommitAndClose(NDBT_Context* ctx, NDBT_Step* step){
int i, result = NDBT_OK;
HugoOperations hugoOps(*ctx->getTab());
Ndb* pNdb = GETNDB(step);
do{
// Read
CHECK(hugoOps.startTransaction(pNdb) == 0);
for (i = 0; i < 10; i++)
CHECK(hugoOps.pkReadRecord(pNdb, i, 1, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.execute_NoCommit(pNdb) == 0);
CHECK(hugoOps.closeTransaction(pNdb) == 0);
// Update
CHECK(hugoOps.startTransaction(pNdb) == 0);
for (i = 0; i < 10; i++)
CHECK(hugoOps.pkUpdateRecord(pNdb, i) == 0);
CHECK(hugoOps.execute_NoCommit(pNdb) == 0);
CHECK(hugoOps.closeTransaction(pNdb) == 0);
// Delete
CHECK(hugoOps.startTransaction(pNdb) == 0);
for (i = 0; i < 10; i++)
CHECK(hugoOps.pkDeleteRecord(pNdb, i) == 0);
CHECK(hugoOps.execute_NoCommit(pNdb) == 0);
CHECK(hugoOps.closeTransaction(pNdb) == 0);
// Try to insert, record should already exist
CHECK(hugoOps.startTransaction(pNdb) == 0);
for (i = 0; i < 10; i++)
CHECK(hugoOps.pkInsertRecord(pNdb, i) == 0);
CHECK(hugoOps.execute_Commit(pNdb) == 630);
CHECK(hugoOps.closeTransaction(pNdb) == 0);
}while(false);
hugoOps.closeTransaction(pNdb);
return result;
}
int runCheckRollbackDelete(NDBT_Context* ctx, NDBT_Step* step){
int result = NDBT_OK;
HugoOperations hugoOps(*ctx->getTab());
Ndb* pNdb = GETNDB(step);
do{
// Read value and save it for later
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 5) == 0);
CHECK(hugoOps.execute_Commit(pNdb) == 0);
CHECK(hugoOps.saveCopyOfRecord() == NDBT_OK);
CHECK(hugoOps.closeTransaction(pNdb) == 0);
// Delete record 5
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkDeleteRecord(pNdb, 5) == 0);
CHECK(hugoOps.execute_NoCommit(pNdb) == 0);
// Check record is deleted
CHECK(hugoOps.pkReadRecord(pNdb, 5, 1, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.execute_NoCommit(pNdb) == 626);
CHECK(hugoOps.execute_Rollback(pNdb) == 0);
CHECK(hugoOps.closeTransaction(pNdb) == 0);
// Check record is not deleted
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 5, 1, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.execute_Commit(pNdb) == 0);
CHECK(hugoOps.closeTransaction(pNdb) == 0);
// Check record is back to original value
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 5, 1, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.execute_Commit(pNdb) == 0);
CHECK(hugoOps.compareRecordToCopy() == NDBT_OK);
}while(false);
hugoOps.closeTransaction(pNdb);
return result;
}
int runCheckRollbackUpdate(NDBT_Context* ctx, NDBT_Step* step){
int result = NDBT_OK;
HugoOperations hugoOps(*ctx->getTab());
Ndb* pNdb = GETNDB(step);
int numRecords = 5;
do{
// Read value and save it for later
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 1, numRecords) == 0);
CHECK(hugoOps.execute_Commit(pNdb) == 0);
CHECK(hugoOps.verifyUpdatesValue(0) == NDBT_OK); // Update value 0
CHECK(hugoOps.closeTransaction(pNdb) == 0);
// Update record 5
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkUpdateRecord(pNdb, 1, numRecords, 5) == 0);// Updates value 5
CHECK(hugoOps.execute_NoCommit(pNdb) == 0);
// Check record is updated
CHECK(hugoOps.pkReadRecord(pNdb, 1, numRecords, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.execute_NoCommit(pNdb) == 0);
CHECK(hugoOps.verifyUpdatesValue(5) == NDBT_OK); // Updates value 5
CHECK(hugoOps.execute_Rollback(pNdb) == 0);
CHECK(hugoOps.closeTransaction(pNdb) == 0);
// Check record is back to original value
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 1, numRecords, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.execute_Commit(pNdb) == 0);
CHECK(hugoOps.verifyUpdatesValue(0) == NDBT_OK); // Updates value 0
}while(false);
hugoOps.closeTransaction(pNdb);
return result;
}
int runCheckRollbackDeleteMultiple(NDBT_Context* ctx, NDBT_Step* step){
int result = NDBT_OK;
HugoOperations hugoOps(*ctx->getTab());
Ndb* pNdb = GETNDB(step);
do{
// Read value and save it for later
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 5, 10) == 0);
CHECK(hugoOps.execute_Commit(pNdb) == 0);
CHECK(hugoOps.verifyUpdatesValue(0) == NDBT_OK);
CHECK(hugoOps.closeTransaction(pNdb) == 0);
Uint32 updatesValue = 0;
Uint32 j;
for(Uint32 i = 0; i<1; i++){
// Read record 5 - 10
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 5, 10, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.execute_NoCommit(pNdb) == 0);
for(j = 0; j<10; j++){
// Update record 5 - 10
updatesValue++;
CHECK(hugoOps.pkUpdateRecord(pNdb, 5, 10, updatesValue) == 0);
CHECK(hugoOps.execute_NoCommit(pNdb) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 5, 10, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.execute_NoCommit(pNdb) == 0);
CHECK(hugoOps.verifyUpdatesValue(updatesValue) == 0);
}
for(j = 0; j<10; j++){
// Delete record 5 - 10 times
CHECK(hugoOps.pkDeleteRecord(pNdb, 5, 10) == 0);
CHECK(hugoOps.execute_NoCommit(pNdb) == 0);
#if 0
// Check records are deleted
CHECK(hugoOps.pkReadRecord(pNdb, 5, 10, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.execute_NoCommit(pNdb) == 626);
#endif
updatesValue++;
CHECK(hugoOps.pkInsertRecord(pNdb, 5, 10, updatesValue) == 0);
CHECK(hugoOps.execute_NoCommit(pNdb) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 5, 10, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.execute_NoCommit(pNdb) == 0);
CHECK(hugoOps.verifyUpdatesValue(updatesValue) == 0);
}
CHECK(hugoOps.pkDeleteRecord(pNdb, 5, 10) == 0);
CHECK(hugoOps.execute_NoCommit(pNdb) == 0);
// Check records are deleted
CHECK(hugoOps.pkReadRecord(pNdb, 5, 10, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.execute_NoCommit(pNdb) == 626);
CHECK(hugoOps.execute_Rollback(pNdb) == 0);
CHECK(hugoOps.closeTransaction(pNdb) == 0);
}
// Check records are not deleted
// after rollback
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 5, 10, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.execute_Commit(pNdb) == 0);
CHECK(hugoOps.verifyUpdatesValue(0) == NDBT_OK);
}while(false);
hugoOps.closeTransaction(pNdb);
return result;
}
int runCheckImplicitRollbackDelete(NDBT_Context* ctx, NDBT_Step* step){
int result = NDBT_OK;
HugoOperations hugoOps(*ctx->getTab());
Ndb* pNdb = GETNDB(step);
do{
// Read record 5
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 5, 1, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.execute_NoCommit(pNdb) == 0);
CHECK(hugoOps.closeTransaction(pNdb) == 0);
// Update record 5
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkUpdateRecord(pNdb, 5) == 0);
CHECK(hugoOps.execute_NoCommit(pNdb) == 0);
CHECK(hugoOps.closeTransaction(pNdb) == 0);
// Delete record 5
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkDeleteRecord(pNdb, 5) == 0);
CHECK(hugoOps.execute_NoCommit(pNdb) == 0);
CHECK(hugoOps.closeTransaction(pNdb) == 0);
// Check record is not deleted
// Close transaction should have rollbacked
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 5, 1, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.execute_Commit(pNdb) == 0);
}while(false);
hugoOps.closeTransaction(pNdb);
return result;
}
int runCheckCommitDelete(NDBT_Context* ctx, NDBT_Step* step){
int result = NDBT_OK;
HugoOperations hugoOps(*ctx->getTab());
Ndb* pNdb = GETNDB(step);
do{
// Read 10 records
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 5, 10, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.execute_NoCommit(pNdb) == 0);
// Update 10 records
CHECK(hugoOps.pkUpdateRecord(pNdb, 5, 10) == 0);
CHECK(hugoOps.execute_NoCommit(pNdb) == 0);
// Delete 10 records
CHECK(hugoOps.pkDeleteRecord(pNdb, 5, 10) == 0);
CHECK(hugoOps.execute_NoCommit(pNdb) == 0);
CHECK(hugoOps.execute_Commit(pNdb) == 0);
CHECK(hugoOps.closeTransaction(pNdb) == 0);
// Check record's are deleted
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 5, 10, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.execute_Commit(pNdb) == 626);
}while(false);
hugoOps.closeTransaction(pNdb);
return result;
}
int runRollbackNothing(NDBT_Context* ctx, NDBT_Step* step){
int result = NDBT_OK;
HugoOperations hugoOps(*ctx->getTab());
Ndb* pNdb = GETNDB(step);
do{
// Delete record 5 - 15
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkDeleteRecord(pNdb, 5, 10) == 0);
// Rollback
CHECK(hugoOps.execute_Rollback(pNdb) == 0);
CHECK(hugoOps.closeTransaction(pNdb) == 0);
// Check records are not deleted
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.pkReadRecord(pNdb, 5, 10, NdbOperation::LM_Exclusive) == 0);
CHECK(hugoOps.execute_Commit(pNdb) == 0);
CHECK(hugoOps.closeTransaction(pNdb) == 0);
CHECK(hugoOps.startTransaction(pNdb) == 0);
CHECK(hugoOps.execute_Rollback(pNdb) == 0);
}while(false);
hugoOps.closeTransaction(pNdb);
return result;
}
int runMassiveRollback(NDBT_Context* ctx, NDBT_Step* step){
NdbRestarter restarter;
const int records = 4 * restarter.getNumDbNodes();
HugoTransactions hugoTrans(*ctx->getTab());
if (hugoTrans.loadTable(GETNDB(step), records) != 0){
return NDBT_FAILED;
}
int result = NDBT_OK;
HugoOperations hugoOps(*ctx->getTab());
Ndb* pNdb = GETNDB(step);
const Uint32 OPS_PER_TRANS = 256;
const Uint32 OPS_TOTAL = 4096;
for(int row = 0; row < records; row++){
int res;
CHECK(hugoOps.startTransaction(pNdb) == 0);
for(Uint32 i = 0; i<OPS_TOTAL; i += OPS_PER_TRANS){
for(Uint32 j = 0; j<OPS_PER_TRANS; j++){
CHECK(hugoOps.pkUpdateRecord(pNdb, row, 1, i) == 0);
}
g_info << "Performed " << (i+OPS_PER_TRANS) << " updates on row: " << row
<< endl;
if(result != NDBT_OK){
break;
}
res = hugoOps.execute_NoCommit(pNdb);
if(res != 0){
NdbError err = pNdb->getNdbError(res);
CHECK(err.classification == NdbError::TimeoutExpired);
break;
}
}
if(result != NDBT_OK){
break;
}
g_info << "executeRollback" << endl;
CHECK(hugoOps.execute_Rollback(pNdb) == 0);
CHECK(hugoOps.closeTransaction(pNdb) == 0);
}
hugoOps.closeTransaction(pNdb);
return result;
}
int
runMassiveRollback2(NDBT_Context* ctx, NDBT_Step* step){
HugoTransactions hugoTrans(*ctx->getTab());
if (hugoTrans.loadTable(GETNDB(step), 1) != 0){
return NDBT_FAILED;
}
int result = NDBT_OK;
HugoOperations hugoOps(*ctx->getTab());
Ndb* pNdb = GETNDB(step);
const Uint32 OPS_TOTAL = 4096;
const Uint32 LOOPS = 10;
for(Uint32 loop = 0; loop<LOOPS; loop++){
CHECK(hugoOps.startTransaction(pNdb) == 0);
for(Uint32 i = 0; i<OPS_TOTAL-1; i ++){
if((i & 1) == 0){
CHECK(hugoOps.pkUpdateRecord(pNdb, 0, 1, loop) == 0);
} else {
CHECK(hugoOps.pkUpdateRecord(pNdb, 1, 1, loop) == 0);
}
}
CHECK(hugoOps.execute_Commit(pNdb) == 626);
CHECK(hugoOps.execute_Rollback(pNdb) == 0);
CHECK(hugoOps.closeTransaction(pNdb) == 0);
}
hugoOps.closeTransaction(pNdb);
return result;
}
int
runMassiveRollback3(NDBT_Context* ctx, NDBT_Step* step){
int result = NDBT_OK;
HugoOperations hugoOps(*ctx->getTab());
Ndb* pNdb = GETNDB(step);
const Uint32 BATCH = 10;
const Uint32 OPS_TOTAL = 50;
const Uint32 LOOPS = 100;
for(Uint32 loop = 0; loop<LOOPS; loop++)
{
CHECK(hugoOps.startTransaction(pNdb) == 0);
bool ok = true;
for (Uint32 i = 0; i<OPS_TOTAL; i+= BATCH)
{
CHECK(hugoOps.pkInsertRecord(pNdb, i, BATCH, 0) == 0);
if (hugoOps.execute_NoCommit(pNdb) != 0)
{
ok = false;
break;
}
}
hugoOps.execute_Rollback(pNdb);
CHECK(hugoOps.closeTransaction(pNdb) == 0);
}
hugoOps.closeTransaction(pNdb);
return result;
}
int
runMassiveRollback4(NDBT_Context* ctx, NDBT_Step* step){
int result = NDBT_OK;
HugoOperations hugoOps(*ctx->getTab());
Ndb* pNdb = GETNDB(step);
const Uint32 BATCH = 10;
const Uint32 OPS_TOTAL = 20;
const Uint32 LOOPS = 100;
for(Uint32 loop = 0; loop<LOOPS; loop++)
{
CHECK(hugoOps.startTransaction(pNdb) == 0);
bool ok = true;
for (Uint32 i = 0; i<OPS_TOTAL; i+= BATCH)
{
CHECK(hugoOps.pkInsertRecord(pNdb, i, BATCH, 0) == 0);
CHECK(hugoOps.pkDeleteRecord(pNdb, i, BATCH) == 0);
if (hugoOps.execute_NoCommit(pNdb) != 0)
{
ok = false;
break;
}
}
hugoOps.execute_Rollback(pNdb);
CHECK(hugoOps.closeTransaction(pNdb) == 0);
}
hugoOps.closeTransaction(pNdb);
return result;
}
/**
* TUP errors
*/
struct TupError
{
enum Bits {
TE_VARSIZE = 0x1,
TE_MULTI_OP = 0x2,
TE_DISK = 0x4,
TE_REPLICA = 0x8,
TE_OI = 0x10, // Ordered index
TE_UI = 0x20 // Unique hash index
};
int op;
int error;
int bits;
};
static
TupError
f_tup_errors[] =
{
{ NdbOperation::InsertRequest, 4014, 0 }, // Out of undo buffer
{ NdbOperation::InsertRequest, 4015, TupError::TE_DISK }, // Out of log space
{ NdbOperation::InsertRequest, 4016, 0 }, // AI Inconsistency
{ NdbOperation::InsertRequest, 4017, 0 }, // Out of memory
{ NdbOperation::InsertRequest, 4018, 0 }, // Null check error
{ NdbOperation::InsertRequest, 4019, TupError::TE_REPLICA }, //Alloc rowid error
{ NdbOperation::InsertRequest, 4020, TupError::TE_MULTI_OP }, // Size change error
{ NdbOperation::InsertRequest, 4021, TupError::TE_DISK }, // Out of disk space
{ NdbOperation::InsertRequest, 4022, TupError::TE_OI }, // Tux add error first
{ NdbOperation::InsertRequest, 4023, TupError::TE_OI }, // Tux add error last
{ NdbOperation::InsertRequest, 4030, TupError::TE_UI },
{ NdbOperation::UpdateRequest, 4030, TupError::TE_UI }, // UI trig error
{ -1, 0, 0 }
};
static
int
compare(unsigned block,
struct ndb_mgm_events * time0,
struct ndb_mgm_events * time1)
{
int diff = 0;
for (int i = 0; i < time0->no_of_events; i++)
{
if (time0->events[i].MemoryUsage.block != block)
continue;
unsigned node = time0->events[i].source_nodeid;
for (int j = 0; j < time1->no_of_events; j++)
{
if (time1->events[j].MemoryUsage.block != block)
continue;
if (time1->events[j].source_nodeid != node)
continue;
int difference =
time1->events[j].MemoryUsage.pages_used -
time0->events[i].MemoryUsage.pages_used;
if (difference > 0 || difference < 0)
{
diff = 1;
ndbout_c("i: %u, j: %u, before: %u, after: %u",
i, j,
time0->events[i].MemoryUsage.pages_used,
time1->events[j].MemoryUsage.pages_used);
}
}
}
return diff;
}
int
runTupErrors(NDBT_Context* ctx, NDBT_Step* step){
NdbRestarter restarter;
Ndb* pNdb = GETNDB(step);
NdbDictionary::Dictionary* pDict = pNdb->getDictionary();
const NdbDictionary::Table * tab = ctx->getTab();
int i;
int bits = TupError::TE_MULTI_OP;
for(i = 0; i<tab->getNoOfColumns(); i++)
{
if (tab->getColumn(i)->getArrayType() != NdbDictionary::Column::ArrayTypeFixed)
bits |= TupError::TE_VARSIZE;
if (tab->getColumn(i)->getStorageType()!= NdbDictionary::Column::StorageTypeMemory)
bits |= TupError::TE_DISK;
}
if (restarter.getNumDbNodes() >= 2)
{
bits |= TupError::TE_REPLICA;
}
NdbDictionary::Dictionary::List l;
pNdb->getDictionary()->listIndexes(l, tab->getName());
for (i = 0; i<(int)l.count; i++)
{
if (DictTabInfo::isOrderedIndex(l.elements[i].type))
bits |= TupError::TE_OI;
if (DictTabInfo::isUniqueIndex(l.elements[i].type))
bits |= TupError::TE_UI;
}
/**
* Insert
*/
for(i = 0; f_tup_errors[i].op != -1; i++)
{
if (f_tup_errors[i].op != NdbOperation::InsertRequest)
{
continue;
}
if ((f_tup_errors[i].bits & bits) != f_tup_errors[i].bits)
{
g_err << "Skipping " << f_tup_errors[i].error
<< " - req bits: " << hex << f_tup_errors[i].bits
<< " bits: " << hex << bits << endl;
continue;
}
NdbDictionary::Table copy = *tab;
BaseString name;
name.assfmt("%s_COPY", copy.getName());
copy.setName(name.c_str());
pDict->createTable(copy);
const NdbDictionary::Table * copyTab = pDict->getTable(copy.getName());
HugoTransactions hugoTrans(*copyTab);
HugoOperations hugoOps(*copyTab);
g_err << "Testing error insert: " << f_tup_errors[i].error << endl;
restarter.insertErrorInAllNodes(f_tup_errors[i].error);
struct ndb_mgm_events * before =
ndb_mgm_dump_events(restarter.handle, NDB_LE_MemoryUsage, 0, 0);
if (before == 0)
{
ndbout_c("ERROR: failed to fetch report!");
return NDBT_FAILED;;
}
if (f_tup_errors[i].bits & TupError::TE_MULTI_OP)
{
}
else
{
hugoTrans.loadTable(pNdb, 5);
}
restarter.insertErrorInAllNodes(0);
if (hugoTrans.clearTable(pNdb, 5) != 0)
{
return NDBT_FAILED;
}
pDict->dropTable(copy.getName());
sleep(2);
struct ndb_mgm_events * after =
ndb_mgm_dump_events(restarter.handle, NDB_LE_MemoryUsage, 0, 0);
if (after == 0)
{
ndbout_c("ERROR: failed to fetch report!");
return NDBT_FAILED;;
}
/**
* check memory leak
*/
if (compare(DBTUP, before, after) != 0)
{
ndbout_c("memleak detected!!");
return NDBT_FAILED;;
}
free(before);
free(after);
}
/**
* update
*/
{
NdbDictionary::Table copy = *tab;
BaseString name;
name.assfmt("%s_COPY", copy.getName());
copy.setName(name.c_str());
pDict->createTable(copy);
const NdbDictionary::Table * copyTab = pDict->getTable(copy.getName());
HugoTransactions hugoTrans(*copyTab);
HugoOperations hugoOps(*copyTab);
struct ndb_mgm_events * before =
ndb_mgm_dump_events(restarter.handle, NDB_LE_MemoryUsage, 0, 0);
hugoTrans.loadTable(pNdb, 5);
for(i = 0; f_tup_errors[i].op != -1; i++)
{
if (f_tup_errors[i].op != NdbOperation::UpdateRequest)
{
continue;
}
if ((f_tup_errors[i].bits & bits) != f_tup_errors[i].bits)
{
g_err << "Skipping " << f_tup_errors[i].error
<< " - req bits: " << hex << f_tup_errors[i].bits
<< " bits: " << hex << bits << endl;
continue;
}
g_err << "Testing error insert: " << f_tup_errors[i].error << endl;
restarter.insertErrorInAllNodes(f_tup_errors[i].error);
if (f_tup_errors[i].bits & TupError::TE_MULTI_OP)
{
}
else
{
hugoTrans.scanUpdateRecords(pNdb, 5);
}
restarter.insertErrorInAllNodes(0);
if (hugoTrans.scanUpdateRecords(pNdb, 5) != 0)
{
return NDBT_FAILED;
}
}
if (hugoTrans.clearTable(pNdb) != 0)
{
return NDBT_FAILED;
}
pDict->dropTable(copy.getName());
sleep(2);
struct ndb_mgm_events * after =
ndb_mgm_dump_events(restarter.handle, NDB_LE_MemoryUsage, 0, 0);
int diff = compare(DBTUP, before, after);
free(before);
free(after);
if (diff != 0)
{
ndbout_c("2:memleak detected!!");
return NDBT_FAILED;;
}
}
return NDBT_OK;
}
int
runInsertError(NDBT_Context* ctx, NDBT_Step* step){
int result = NDBT_OK;
HugoOperations hugoOp1(*ctx->getTab());
HugoOperations hugoOp2(*ctx->getTab());
Ndb* pNdb = GETNDB(step);
NdbRestarter restarter;
restarter.insertErrorInAllNodes(4017);
const Uint32 LOOPS = 10;
for (Uint32 i = 0; i<LOOPS; i++)
{
CHECK(hugoOp1.startTransaction(pNdb) == 0);
CHECK(hugoOp1.pkInsertRecord(pNdb, 1) == 0);
CHECK(hugoOp2.startTransaction(pNdb) == 0);
CHECK(hugoOp2.pkReadRecord(pNdb, 1, 1) == 0);
CHECK(hugoOp1.execute_async_prepare(pNdb, NdbTransaction::Commit) == 0);
CHECK(hugoOp2.execute_async_prepare(pNdb, NdbTransaction::Commit) == 0);
hugoOp1.wait_async(pNdb);
hugoOp2.wait_async(pNdb);
CHECK(hugoOp1.closeTransaction(pNdb) == 0);
CHECK(hugoOp2.closeTransaction(pNdb) == 0);
}
restarter.insertErrorInAllNodes(0);
return result;
}
int
runInsertError2(NDBT_Context* ctx, NDBT_Step* step){
int result = NDBT_OK;
HugoOperations hugoOp1(*ctx->getTab());
Ndb* pNdb = GETNDB(step);
NdbRestarter restarter;
restarter.insertErrorInAllNodes(4017);
const Uint32 LOOPS = 1;
for (Uint32 i = 0; i<LOOPS; i++)
{
CHECK(hugoOp1.startTransaction(pNdb) == 0);
CHECK(hugoOp1.pkInsertRecord(pNdb, 1) == 0);
CHECK(hugoOp1.pkDeleteRecord(pNdb, 1) == 0);
hugoOp1.execute_NoCommit(pNdb);
CHECK(hugoOp1.closeTransaction(pNdb) == 0);
}
restarter.insertErrorInAllNodes(0);
return NDBT_OK;
}
int
runBug25090(NDBT_Context* ctx, NDBT_Step* step){
Ndb* pNdb = GETNDB(step);
//NdbDictionary::Dictionary * dict = pNdb->getDictionary();
HugoOperations ops(*ctx->getTab());
int loops = ctx->getNumLoops();
//const int rows = ctx->getNumRecords();
while (loops--)
{
ops.startTransaction(pNdb);
ops.pkReadRecord(pNdb, 1, 1);
ops.execute_Commit(pNdb, AO_IgnoreError);
sleep(10);
ops.closeTransaction(pNdb);
}
return NDBT_OK;
}
int
runDeleteRead(NDBT_Context* ctx, NDBT_Step* step){
Ndb* pNdb = GETNDB(step);
const NdbDictionary::Table* tab = ctx->getTab();
NDBT_ResultRow row(*ctx->getTab());
HugoTransactions tmp(*ctx->getTab());
int a;
int loops = ctx->getNumLoops();
//const int rows = ctx->getNumRecords();
while (loops--)
{
NdbTransaction* pTrans = pNdb->startTransaction();
NdbOperation* pOp = pTrans->getNdbOperation(tab->getName());
pOp->deleteTuple();
tmp.equalForRow(pOp, loops);
// Define attributes to read
for(a = 0; a<tab->getNoOfColumns(); a++)
{
if((row.attributeStore(a) = pOp->getValue(tab->getColumn(a)->getName())) == 0) {
NDB_ERR(pTrans->getNdbError());
return NDBT_FAILED;
}
}
pTrans->execute(Commit);
pTrans->close();
pTrans = pNdb->startTransaction();
pOp = pTrans->getNdbOperation(tab->getName());
pOp->insertTuple();
tmp.setValues(pOp, loops, 0);
pOp = pTrans->getNdbOperation(tab->getName());
pOp->deleteTuple();
tmp.equalForRow(pOp, loops);
for(a = 0; a<tab->getNoOfColumns(); a++)
{
if((row.attributeStore(a) = pOp->getValue(tab->getColumn(a)->getName())) == 0)
{
NDB_ERR(pTrans->getNdbError());
return NDBT_FAILED;
}
}
if (pTrans->execute(Commit) != 0)
{
NDB_ERR(pTrans->getNdbError());
return NDBT_FAILED;
}
pTrans->close();
}
return NDBT_OK;
}
int
runBug27756(NDBT_Context* ctx, NDBT_Step* step)
{
Ndb* pNdb = GETNDB(step);
//NdbDictionary::Dictionary * dict = pNdb->getDictionary();
HugoOperations ops(*ctx->getTab());
int loops = ctx->getNumLoops();
//const int rows = ctx->getNumRecords();
Vector<Uint64> copies;
while (loops--)
{
ops.startTransaction(pNdb);
ops.pkInsertRecord(pNdb, 1, 1);
ops.execute_NoCommit(pNdb);
NdbTransaction* pTrans = ops.getTransaction();
NdbOperation* op = pTrans->getNdbOperation(ctx->getTab()->getName());
op->interpretedUpdateTuple();
ops.equalForRow(op, 1);
NdbRecAttr* attr = op->getValue(NdbDictionary::Column::COPY_ROWID);
ops.execute_NoCommit(pNdb);
copies.push_back(attr->u_64_value());
ndbout_c("copy at: %llx", copies.back());
ops.execute_NoCommit(pNdb);
ops.pkDeleteRecord(pNdb, 1, 1);
ops.execute_NoCommit(pNdb);
if (loops & 1)
{
ops.execute_Rollback(pNdb);
ops.closeTransaction(pNdb);
}
else
{
ops.execute_Commit(pNdb);
ops.closeTransaction(pNdb);
ops.clearTable(pNdb, 100);
}
}
for (Uint32 i = 0; i<copies.size(); i++)
if (copies[i] != copies.back())
{
ndbout_c("Memleak detected");
return NDBT_FAILED;
}
return NDBT_OK;
}
int
runBug28073(NDBT_Context *ctx, NDBT_Step* step)
{
int result = NDBT_OK;
const NdbDictionary::Table *table= ctx->getTab();
HugoOperations hugoOp1(*table);
HugoOperations hugoOp2(*table);
Ndb* pNdb = GETNDB(step);
int loops = ctx->getNumLoops();
bool inserted= false;
while (loops--)
{
if (!inserted)
{
CHECK(hugoOp1.startTransaction(pNdb) == 0);
CHECK(hugoOp1.pkInsertRecord(pNdb, 1, 1) == 0);
CHECK(hugoOp1.execute_Commit(pNdb) == 0);
CHECK(hugoOp1.closeTransaction(pNdb) == 0);
inserted= 1;
}
// Use TC hint to hit the same node in both transactions.
Uint32 key_val= 0;
const char *key= (const char *)(&key_val);
CHECK(hugoOp1.startTransaction(pNdb, table, key, 4) == 0);
CHECK(hugoOp2.startTransaction(pNdb, table, key, 4) == 0);
// First take 2*read lock on the tuple in transaction 1.
for (Uint32 i= 0; i < 2; i++)
{
CHECK(hugoOp1.pkReadRecord(pNdb, 1, 1, NdbOperation::LM_Read) == 0);
CHECK(hugoOp1.pkReadRecord(pNdb, 1, 1, NdbOperation::LM_Read) == 0);
}
CHECK(hugoOp1.execute_NoCommit(pNdb) == 0);
// Now send ops in two transactions, one batch.
// First 2*read in transaction 2.
for (Uint32 i= 0; i < 2; i++)
{
CHECK(hugoOp2.pkReadRecord(pNdb, 1, 1, NdbOperation::LM_Read) == 0);
CHECK(hugoOp2.pkReadRecord(pNdb, 1, 1, NdbOperation::LM_Read) == 0);
}
CHECK(hugoOp2.execute_async_prepare(pNdb, NdbTransaction::NoCommit) == 0);
// Second op an update in transaction 1.
CHECK(hugoOp1.pkUpdateRecord(pNdb, 1, 1) == 0);
CHECK(hugoOp1.execute_async_prepare(pNdb, NdbTransaction::Commit) == 0);
// Transaction 1 will now hang waiting on transaction 2 to commit before it
// can upgrade its read lock to a write lock.
// With the bug, we get a node failure due to watchdog timeout here.
CHECK(hugoOp2.wait_async(pNdb) == 0);
// Now commit transaction 2, we should see transaction 1 finish with the
// update.
CHECK(hugoOp2.execute_async_prepare(pNdb, NdbTransaction::Commit) == 0);
CHECK(hugoOp2.wait_async(pNdb) == 0);
// No error check, as transaction 1 may have terminated already.
hugoOp1.wait_async(pNdb);
CHECK(hugoOp1.closeTransaction(pNdb) == 0);
CHECK(hugoOp2.closeTransaction(pNdb) == 0);
}
return result;
}
int
runBug20535(NDBT_Context* ctx, NDBT_Step* step)
{
Ndb* pNdb = GETNDB(step);
const NdbDictionary::Table * tab = ctx->getTab();
bool hasDefault = false;
for (Uint32 i = 0; i<(Uint32)tab->getNoOfColumns(); i++)
{
if (tab->getColumn(i)->getNullable() ||
tab->getColumn(i)->getDefaultValue())
{
hasDefault = true;
break;
}
}
if (!hasDefault)
return NDBT_OK;
HugoTransactions hugoTrans(* tab);
hugoTrans.loadTable(pNdb, 1);
NdbTransaction* pTrans = pNdb->startTransaction();
NdbOperation* pOp = pTrans->getNdbOperation(tab->getName());
pOp->deleteTuple();
hugoTrans.equalForRow(pOp, 0);
if (pTrans->execute(NoCommit) != 0)
return NDBT_FAILED;
pOp = pTrans->getNdbOperation(tab->getName());
pOp->insertTuple();
hugoTrans.equalForRow(pOp, 0);
for (Uint32 i = 0; i<(Uint32)tab->getNoOfColumns(); i++)
{
if (!tab->getColumn(i)->getPrimaryKey() &&
!tab->getColumn(i)->getNullable() &&
!tab->getColumn(i)->getDefaultValue())
{
hugoTrans.setValueForAttr(pOp, i, 0, 1);
}
}
if (pTrans->execute(Commit) != 0)
return NDBT_FAILED;
pTrans->close();
pTrans = pNdb->startTransaction();
pOp = pTrans->getNdbOperation(tab->getName());
pOp->readTuple();
hugoTrans.equalForRow(pOp, 0);
Vector<NdbRecAttr*> values;
for (Uint32 i = 0; i<(Uint32)tab->getNoOfColumns(); i++)
{
if (!tab->getColumn(i)->getPrimaryKey() &&
(tab->getColumn(i)->getNullable() ||
tab->getColumn(i)->getDefaultValue()))
{
values.push_back(pOp->getValue(i));
}
}
if (pTrans->execute(Commit) != 0)
return NDBT_FAILED;
bool defaultOk = true;
for (unsigned int i = 0; i<values.size(); i++)
{
const NdbRecAttr* recAttr = values[i];
const NdbDictionary::Column* col = recAttr->getColumn();
unsigned int defaultLen = 0;
const char* def = (const char*) col->getDefaultValue(&defaultLen);
if (def)
{
/* Column has a native default, check that it was set */
if (!recAttr->isNULL())
{
if (memcmp(def, recAttr->aRef(), defaultLen) != 0)
{
defaultOk = false;
ndbout_c("column %s does not have correct default value",
recAttr->getColumn()->getName());
}
}
else
{
defaultOk = false;
ndbout_c("column %s is null, should have default value",
recAttr->getColumn()->getName());
}
}
else
{
/* Column has Null as its default */
if (!recAttr->isNULL())
{
defaultOk = false;
ndbout_c("column %s is not NULL", recAttr->getColumn()->getName());
}
}
}
pTrans->close();
if (defaultOk)
return NDBT_OK;
else
return NDBT_FAILED;
}
int
runDDInsertFailUpdateBatch(NDBT_Context* ctx, NDBT_Step* step)
{
Ndb* pNdb = GETNDB(step);
NdbRestarter restarter;
const NdbDictionary::Table * tab = ctx->getTab();
int errCode = 0;
int expectedError = 0;
{
bool tabHasDD = false;
for(int i = 0; i<tab->getNoOfColumns(); i++)
{
tabHasDD |= (tab->getColumn(i)->getStorageType() ==
NdbDictionary::Column::StorageTypeDisk);
}
if (tabHasDD)
{
errCode = 4021;
expectedError = 1601;
}
else
{
NdbDictionary::Dictionary::List l;
pNdb->getDictionary()->listIndexes(l, tab->getName());
for (Uint32 i = 0; i<l.count; i++)
{
if (DictTabInfo::isOrderedIndex(l.elements[i].type))
{
errCode = 4023;
expectedError = 9999;
break;
}
}
}
if (errCode == 0)
{
ndbout_c("Table %s has no disk attributes or ordered indexes, skipping",
tab->getName());
return NDBT_OK;
}
}
HugoOperations hugoOps(*ctx->getTab());
int result = NDBT_OK;
for (Uint32 loop = 0; loop < 100; loop ++)
{
restarter.insertErrorInAllNodes(errCode);
CHECK(hugoOps.startTransaction(pNdb) == 0);
/* Create batch with insert op (which will fail due to disk allocation issue)
* followed by update op on same pk
* Transaction will abort due to insert failure, and reason should be
* disk space exhaustion, not any issue with the update.
*/
CHECK(hugoOps.pkInsertRecord(pNdb, loop, 1, 0) == 0);
/* Add up to 16 updates after the insert */
Uint32 numUpdates = 1 + (loop % 15);
for (Uint32 updateCnt = 0; updateCnt < numUpdates; updateCnt++)
CHECK(hugoOps.pkUpdateRecord(pNdb, loop, 1, 1+updateCnt) == 0);
CHECK(hugoOps.execute_Commit(pNdb) != 0); /* Expect failure */
NdbError err= hugoOps.getTransaction()->getNdbError();
CHECK(err.code == expectedError);
hugoOps.closeTransaction(pNdb);
}
restarter.insertErrorInAllNodes(0);
return result;
}
// Bug34348
#define chk1(b) \
if (!(b)) { g_err << "ERR: " << step->getName() << " failed on line " << __LINE__ << endl; result = NDBT_FAILED; continue; }
#define chk2(b, e) \
if (!(b)) { g_err << "ERR: " << step->getName() << " failed on line " << __LINE__ << ": " << e << endl; result = NDBT_FAILED; continue; }
const char* tabname_bug34348 = "TBug34348";
int
runBug34348insert(NDBT_Context* ctx, NDBT_Step* step,
HugoOperations& ops, int i, bool* rangeFull)
{
const int rangeFullError = 633;
Ndb* pNdb = GETNDB(step);
int result = NDBT_OK;
while (result == NDBT_OK)
{
int code = 0;
chk2(ops.startTransaction(pNdb) == 0, ops.getNdbError());
chk2(ops.pkInsertRecord(pNdb, i, 1) == 0, ops.getNdbError());
chk2(ops.execute_Commit(pNdb) == 0 || (code = ops.getNdbError().code) == rangeFullError, ops.getNdbError());
ops.closeTransaction(pNdb);
*rangeFull = (code == rangeFullError);
break;
}
return result;
}
int
runBug34348delete(NDBT_Context* ctx, NDBT_Step* step,
HugoOperations& ops, int i)
{
Ndb* pNdb = GETNDB(step);
int result = NDBT_OK;
while (result == NDBT_OK)
{
chk2(ops.startTransaction(pNdb) == 0, ops.getNdbError());
chk2(ops.pkDeleteRecord(pNdb, i, 1) == 0, ops.getNdbError());
chk2(ops.execute_Commit(pNdb) == 0, ops.getNdbError());
ops.closeTransaction(pNdb);
break;
}
return result;
}
int
runBug34348(NDBT_Context* ctx, NDBT_Step* step)
{
myRandom48Init((long)NdbTick_CurrentMillisecond());
Ndb* pNdb = GETNDB(step);
NdbDictionary::Dictionary* pDict = pNdb->getDictionary();
NdbRestarter restarter;
int result = NDBT_OK;
const int loops = ctx->getNumLoops();
const int errInsDBACC = 3002;
const int errInsCLEAR = 0;
Uint32* rowmask = 0;
while (result == NDBT_OK)
{
chk1(restarter.insertErrorInAllNodes(errInsDBACC) == 0);
ndbout << "error insert " << errInsDBACC << " done" << endl;
const NdbDictionary::Table* pTab = 0;
while (result == NDBT_OK)
{
(void)pDict->dropTable(tabname_bug34348);
NdbDictionary::Table tab(tabname_bug34348);
{
NdbDictionary::Column col("a");
col.setType(NdbDictionary::Column::Unsigned);
col.setPrimaryKey(true);
tab.addColumn(col);
}
{
NdbDictionary::Column col("b");
col.setType(NdbDictionary::Column::Unsigned);
col.setNullable(false);
tab.addColumn(col);
}
chk2(pDict->createTable(tab) == 0, pDict->getNdbError());
chk2((pTab = pDict->getTable(tabname_bug34348)) != 0, pDict->getNdbError());
break;
}
HugoOperations ops(*pTab);
ops.setQuiet();
int rowmaxprev = 0;
int loop = 0;
while (result == NDBT_OK && loop < loops)
{
ndbout << "loop:" << loop << endl;
int rowcnt = 0;
// fill up
while (result == NDBT_OK)
{
bool rangeFull;
chk1(runBug34348insert(ctx, step, ops, rowcnt, &rangeFull) == NDBT_OK);
if (rangeFull)
{
// 360449 (1 fragment)
ndbout << "dir range full at " << rowcnt << endl;
break;
}
rowcnt++;
}
chk1(result == NDBT_OK);
const int rowmax = rowcnt;
if (loop == 0)
rowmaxprev = rowmax;
else
chk2(rowmaxprev == rowmax, "rowmaxprev:" << rowmaxprev << " rowmax:" << rowmax);
const int sz = (rowmax + 31) / 32;
delete [] rowmask;
rowmask = new Uint32 [sz];
BitmaskImpl::clear(sz, rowmask);
{
int i;
for (i = 0; i < rowmax; i++)
BitmaskImpl::set(sz, rowmask, i);
}
// random delete until insert succeeds
while (result == NDBT_OK)
{
int i = myRandom48(rowmax);
if (!BitmaskImpl::get(sz, rowmask, i))
continue;
chk1(runBug34348delete(ctx, step, ops, i) == NDBT_OK);
BitmaskImpl::clear(sz, rowmask, i);
rowcnt--;
bool rangeFull;
chk1(runBug34348insert(ctx, step, ops, rowmax, &rangeFull) == NDBT_OK);
if (!rangeFull)
{
chk1(runBug34348delete(ctx, step, ops, rowmax) == NDBT_OK);
// 344063 (1 fragment)
ndbout << "dir range released at " << rowcnt << endl;
break;
}
}
chk1(result == NDBT_OK);
require(BitmaskImpl::count(sz, rowmask)== (Uint32)rowcnt);
// delete about 1/2 remaining
while (result == NDBT_OK)
{
int i;
for (i = 0; result == NDBT_OK && i < rowmax; i++)
{
if (!BitmaskImpl::get(sz, rowmask, i))
continue;
if (myRandom48(100) < 50)
continue;
chk1(runBug34348delete(ctx, step, ops, i) == NDBT_OK);
BitmaskImpl::clear(sz, rowmask, i);
rowcnt--;
}
ndbout << "deleted down to " << rowcnt << endl;
break;
}
chk1(result == NDBT_OK);
require(BitmaskImpl::count(sz, rowmask)== (Uint32)rowcnt);
// insert until full again
while (result == NDBT_OK)
{
int i;
for (i = 0; result == NDBT_OK && i < rowmax; i++)
{
if (BitmaskImpl::get(sz, rowmask, i))
continue;
bool rangeFull;
chk1(runBug34348insert(ctx, step, ops, i, &rangeFull) == NDBT_OK);
// assume all can be inserted back
chk2(!rangeFull, "dir range full too early at " << rowcnt);
BitmaskImpl::set(sz, rowmask, i);
rowcnt++;
}
chk1(result == NDBT_OK);
ndbout << "inserted all back to " << rowcnt << endl;
break;
}
chk1(result == NDBT_OK);
require(BitmaskImpl::count(sz, rowmask)== (Uint32)rowcnt);
// delete all
while (result == NDBT_OK)
{
int i;
for (i = 0; result == NDBT_OK && i < rowmax; i++)
{
if (!BitmaskImpl::get(sz, rowmask, i))
continue;
chk1(runBug34348delete(ctx, step, ops, i) == NDBT_OK);
BitmaskImpl::clear(sz, rowmask, i);
rowcnt--;
}
ndbout << "deleted all" << endl;
break;
}
chk1(result == NDBT_OK);
require(BitmaskImpl::count(sz, rowmask)== (Uint32)rowcnt);
require(rowcnt == 0);
loop++;
}
chk2(pDict->dropTable(tabname_bug34348) == 0, pDict->getNdbError());
chk1(restarter.insertErrorInAllNodes(errInsCLEAR) == 0);
ndbout << "error insert clear done" << endl;
break;
}
if (result != NDBT_OK && restarter.insertErrorInAllNodes(errInsCLEAR) != 0)
g_err << "error insert clear failed" << endl;
delete [] rowmask;
rowmask = 0;
return result;
}
#define check(b, e) \
if (!(b)) { g_err << "ERR: " << step->getName() << " failed on line " << __LINE__ << ": " << e.getNdbError() << endl; return NDBT_FAILED; }
int runUnlocker(NDBT_Context* ctx, NDBT_Step* step){
int loops = ctx->getNumLoops();
int records = ctx->getNumRecords();
int batchSize = ctx->getProperty("Batchsize", 1);
int doubleUnlock = ctx->getProperty("DoubleUnlock", (Uint32)0);
int lm = ctx->getProperty("LockMode", NdbOperation::LM_Read);
int i = 0;
HugoOperations hugoOps(*ctx->getTab());
Ndb* ndb = GETNDB(step);
g_err << "Unlocker : ";
g_err << "Loops = " << loops << " Records = " << records << " Batchsize = "
<< batchSize << endl;
while(i++ < loops)
{
g_err << i << " ";
check(hugoOps.startTransaction(ndb) == 0, (*ndb));
const int maxRetries = 10;
int retryAttempt = 0;
int r = records;
Vector<const NdbLockHandle*> lockHandles;
while(r > 0)
{
int batchContents = MIN(r, batchSize);
check(hugoOps.pkReadRecordLockHandle(ndb,
lockHandles,
records - r,
batchContents,
(NdbOperation::LockMode)lm) == 0,
hugoOps);
r-= batchContents;
if (hugoOps.execute_NoCommit(ndb) != 0)
{
NdbError err = hugoOps.getNdbError();
if ((err.status == NdbError::TemporaryError) &&
retryAttempt < maxRetries){
NDB_ERR(err);
NdbSleep_MilliSleep(50);
retryAttempt++;
lockHandles.clear();
check(hugoOps.closeTransaction(ndb) == 0,
hugoOps);
check(hugoOps.startTransaction(ndb) == 0, (*ndb));
continue;
}
NDB_ERR(err);
return NDBT_FAILED;
}
check(hugoOps.pkUnlockRecord(ndb,
lockHandles) == 0,
hugoOps);
check(hugoOps.execute_NoCommit(ndb) == 0,
hugoOps);
if (doubleUnlock)
{
NdbOperation::AbortOption ao;
switch(rand() % 2)
{
case 0:
ao = NdbOperation::AbortOnError;
break;
case 1:
default:
ao = NdbOperation::AO_IgnoreError;
break;
}
g_err << "Double unlock, abort option is "
<< ao << endl;
/* Failure scenario */
check(hugoOps.pkUnlockRecord(ndb,
lockHandles,
0, // offset
~(0), // NumRecords
ao) == 0,
hugoOps);
check(hugoOps.execute_NoCommit(ndb,
DefaultAbortOption) != 0,
hugoOps);
/* 417 = Bad operation reference */
check(hugoOps.getNdbError().code == 417,
hugoOps);
if (ao == NdbOperation::AbortOnError)
{
/* Restart transaction and continue with next loop iteration */
r = 0;
lockHandles.clear();
check(hugoOps.closeTransaction(ndb) == 0,
hugoOps);
check(hugoOps.startTransaction(ndb) == 0, (*ndb));
continue;
}
/* Otherwise, IgnoreError, so let's attempt to
* continue
*/
}
check(hugoOps.releaseLockHandles(ndb,
lockHandles) == 0,
hugoOps);
lockHandles.clear();
}
switch(rand() % 3)
{
case 0:
check(hugoOps.execute_Commit(ndb) == 0,
hugoOps);
break;
case 1:
check(hugoOps.execute_Rollback(ndb) == 0,
hugoOps);
break;
default:
/* Do nothing, just close */
break;
}
check(hugoOps.closeTransaction(ndb) == 0,
hugoOps);
}
g_err << endl;
return NDBT_OK;
}
template class Vector<NdbRecAttr*>;
int
runBug54986(NDBT_Context* ctx, NDBT_Step* step)
{
NdbRestarter restarter;
Ndb* pNdb = GETNDB(step);
NdbDictionary::Dictionary* pDict = pNdb->getDictionary();
const NdbDictionary::Table * pTab = ctx->getTab();
NdbDictionary::Table copy = *pTab;
int result = NDBT_OK;
BaseString name;
name.assfmt("%s_COPY", copy.getName());
copy.setName(name.c_str());
pDict->createTable(copy);
const NdbDictionary::Table * copyTab = pDict->getTable(copy.getName());
HugoTransactions hugoTrans(*pTab);
hugoTrans.loadTable(pNdb, 20);
hugoTrans.clearTable(pNdb);
const Uint32 rows = 5000;
HugoTransactions hugoTransCopy(*copyTab);
hugoTransCopy.loadTable(pNdb, rows);
ndbout << "Waiting for 3 LCPs" << endl;
{
restarter.getNumDbNodes(); // connect
int filter[] = { 15, NDB_MGM_EVENT_CATEGORY_CHECKPOINT, 0 };
NdbLogEventHandle handle =
ndb_mgm_create_logevent_handle(restarter.handle, filter);
for (Uint32 i = 0; i<3; i++)
{
int dump[] = { DumpStateOrd::DihStartLcpImmediately };
struct ndb_logevent event;
restarter.dumpStateAllNodes(dump, 1);
while(ndb_logevent_get_next(handle, &event, 0) >= 0 &&
event.type != NDB_LE_LocalCheckpointStarted);
while(ndb_logevent_get_next(handle, &event, 0) >= 0 &&
event.type != NDB_LE_LocalCheckpointCompleted);
ndbout << "LCP" << i << endl;
}
ndb_mgm_destroy_logevent_handle(&handle);
}
for (int i = 0; i<5; i++)
{
ndbout << "loop: " << i << endl;
int val1 = DumpStateOrd::DihMaxTimeBetweenLCP;
int val2 = DumpStateOrd::DihStartLcpImmediately; // Force start
ndbout << " ... dumpState set 'MaxTimeBetweenLCP'" << endl;
CHK1(restarter.dumpStateAllNodes(&val1, 1) == 0);
int val[] = { DumpStateOrd::CmvmiSetRestartOnErrorInsert, 1 };
ndbout << " ... dumpState set 'RestartOnErrorInsert = NoStart'" << endl;
CHK1(restarter.dumpStateAllNodes(val, 2) == 0);
ndbout << " ... insert error 932" << endl;
CHK1(restarter.insertErrorInAllNodes(932) ==0); // prevent arbit shutdown
HugoTransactions hugoTrans(*pTab);
ndbout << " ... loadTable" << endl;
CHK1(hugoTrans.loadTable(pNdb, 20) == 0);
ndbout << " ... dumpState set 'StartLcpImmediately'" << endl;
CHK1(restarter.dumpStateAllNodes(&val2, 1) == 0);
ndbout << " ... sleep for 15 sec" << endl;
NdbSleep_SecSleep(15);
ndbout << " ... clearTable" << endl;
CHK1(hugoTrans.clearTable(pNdb) == 0);
ndbout << " ... Hugo txn" << endl;
CHK1(hugoTransCopy.pkReadRecords(pNdb, rows) == 0);
HugoOperations hugoOps(*pTab);
CHK1(hugoOps.startTransaction(pNdb) == 0);
CHK1(hugoOps.pkInsertRecord(pNdb, 1) == 0);
CHK1(hugoOps.execute_NoCommit(pNdb) == 0);
ndbout << " ... insert error 5056 (Crash on LCP_COMPLETE_REP)" << endl;
CHK1(restarter.insertErrorInAllNodes(5056) == 0);
ndbout << " ... dumpState set 'StartLcpImmediately'" << endl;
CHK1(restarter.dumpStateAllNodes(&val2, 1) == 0);
ndbout << " ... waitClusterNoStart" << endl;
CHK1(restarter.waitClusterNoStart() == 0);
int vall = 11009;
CHK1(restarter.dumpStateAllNodes(&vall, 1) == 0);
CHK1(restarter.startAll() == 0);
CHK1(restarter.waitClusterStarted() == 0);
CHK1(pNdb->waitUntilReady() == 0);
CHK1(hugoOps.closeTransaction(pNdb) == 0);
}
pDict->dropTable(copy.getName());
// remove 25-page pgman
restarter.restartAll(false, true, true);
restarter.waitClusterNoStart();
restarter.startAll();
restarter.waitClusterStarted();
pNdb->waitUntilReady();
return result;
}
int
runBug54944(NDBT_Context* ctx, NDBT_Step* step)
{
Ndb* pNdb = GETNDB(step);
const NdbDictionary::Table * pTab = ctx->getTab();
NdbRestarter res;
int databuffer = ctx->getProperty("DATABUFFER");
for (Uint32 i = 0; i<5; i++)
{
Uint32 rows = 5000 + i * 2000;
HugoOperations hugoOps(*pTab);
hugoOps.startTransaction(pNdb);
for (Uint32 r = 0; r < rows; r++)
{
for (Uint32 b = 0; b<100; b++, r++)
{
hugoOps.pkInsertRecord(pNdb, r);
}
hugoOps.execute_NoCommit(pNdb);
}
if (!databuffer)
res.insertErrorInAllNodes(8087);
else
res.insertErrorInAllNodes(8096);
HugoTransactions hugoTrans(*pTab);
hugoTrans.loadTableStartFrom(pNdb, 50000, 100);
hugoOps.execute_Rollback(pNdb);
hugoTrans.clearTable(pNdb);
res.insertErrorInAllNodes(0);
}
return NDBT_OK;
}
int
runBug59496_scan(NDBT_Context* ctx, NDBT_Step* step)
{
Ndb* pNdb = GETNDB(step);
const NdbDictionary::Table * pTab = ctx->getTab();
NdbRestarter res;
int rowcount = ctx->getProperty("CHECK_ROWCOUNT", Uint32(0));
int records = ctx->getNumRecords();
if (rowcount == 0)
records = 0;
HugoTransactions hugoTrans(*pTab);
while (!ctx->isTestStopped())
{
if (hugoTrans.scanReadRecords(pNdb,
records, 0, 0,
NdbOperation::LM_CommittedRead,
(int)NdbScanOperation::SF_TupScan) != NDBT_OK)
return NDBT_FAILED;
}
return NDBT_OK;
}
int
runBug59496_case1(NDBT_Context* ctx, NDBT_Step* step)
{
Ndb* pNdb = GETNDB(step);
NdbRestarter res;
int loops = ctx->getNumLoops();
int records = ctx->getNumRecords();
HugoOperations hugoOps(*ctx->getTab());
for (int i = 0; i < loops; i++)
{
hugoOps.startTransaction(pNdb);
hugoOps.pkInsertRecord(pNdb, 0, records, 0);
hugoOps.execute_NoCommit(pNdb);
hugoOps.pkUpdateRecord(pNdb, 0, records, rand());
hugoOps.execute_NoCommit(pNdb);
hugoOps.pkUpdateRecord(pNdb, 0, records, rand());
hugoOps.execute_NoCommit(pNdb);
res.insertErrorInAllNodes(8089);
hugoOps.execute_Commit(pNdb);
res.insertErrorInAllNodes(0);
hugoOps.closeTransaction(pNdb);
hugoOps.clearTable(pNdb);
}
ctx->stopTest();
return NDBT_OK;
}
int
runBug59496_case2(NDBT_Context* ctx, NDBT_Step* step)
{
Ndb* pNdb = GETNDB(step);
NdbRestarter res;
int loops = ctx->getNumLoops();
int records = ctx->getNumRecords();
HugoOperations hugoOps(*ctx->getTab());
for (int i = 0; i < loops; i++)
{
hugoOps.startTransaction(pNdb);
hugoOps.pkDeleteRecord(pNdb, 0, records);
hugoOps.execute_NoCommit(pNdb);
hugoOps.pkInsertRecord(pNdb, 0, records, 0);
hugoOps.execute_NoCommit(pNdb);
res.insertErrorInAllNodes(8089);
hugoOps.execute_Rollback(pNdb);
res.insertErrorInAllNodes(0);
hugoOps.closeTransaction(pNdb);
}
ctx->stopTest();
return NDBT_OK;
}
#define CHK_RET_FAILED(x) if (!(x)) { ndbout_c("Failed on line: %u", __LINE__); return NDBT_FAILED; }
int
runTest899(NDBT_Context* ctx, NDBT_Step* step)
{
Ndb* pNdb = GETNDB(step);
const NdbDictionary::Table* pTab = ctx->getTab();
const int rows = ctx->getNumRecords();
const int loops = ctx->getNumLoops();
const int batch = ctx->getProperty("Batch", Uint32(50));
const int until_stopped = ctx->getProperty("UntilStopped");
const NdbRecord * pRowRecord = pTab->getDefaultRecord();
CHK_RET_FAILED(pRowRecord != 0);
const Uint32 len = NdbDictionary::getRecordRowLength(pRowRecord);
Uint8 * pRow = new Uint8[len];
int count_ok = 0;
int count_failed = 0;
int count_899 = 0;
for (int i = 0; i < loops || (until_stopped && !ctx->isTestStopped()); i++)
{
ndbout_c("loop: %d",i);
int result = 0;
for (int rowNo = 0; rowNo < rows;)
{
NdbTransaction* pTrans = pNdb->startTransaction();
CHK_RET_FAILED(pTrans != 0);
for (int b = 0; rowNo < rows && b < batch; rowNo++, b++)
{
bzero(pRow, len);
HugoCalculator calc(* pTab);
NdbOperation::OperationOptions opts;
bzero(&opts, sizeof(opts));
const NdbOperation* pOp = 0;
switch(i % 2){
case 0:
calc.setValues(pRow, pRowRecord, rowNo, rand());
pOp = pTrans->writeTuple(pRowRecord, (char*)pRow,
pRowRecord, (char*)pRow,
0,
&opts,
sizeof(opts));
result = pTrans->execute(NoCommit);
break;
case 1:
calc.setValues(pRow, pRowRecord, rowNo, rand());
pOp = pTrans->deleteTuple(pRowRecord, (char*)pRow,
pRowRecord, (char*)pRow,
0,
&opts,
sizeof(opts));
result = pTrans->execute(NoCommit, AO_IgnoreError);
break;
}
CHK_RET_FAILED(pOp != 0);
if (result != 0)
{
goto found_error;
}
}
result = pTrans->execute(Commit);
if (result != 0)
{
found_error:
count_failed++;
NdbError err = pTrans->getNdbError();
if (! (err.status == NdbError::TemporaryError ||
err.classification == NdbError::NoDataFound ||
err.classification == NdbError::ConstraintViolation))
{
ndbout << err << endl;
}
CHK_RET_FAILED(err.status == NdbError::TemporaryError ||
err.classification == NdbError::NoDataFound ||
err.classification == NdbError::ConstraintViolation);
if (err.code == 899)
{
count_899++;
ndbout << err << endl;
}
}
else
{
count_ok++;
}
pTrans->close();
}
}
ndbout_c("count_ok: %d count_failed: %d (899: %d)",
count_ok, count_failed, count_899);
delete [] pRow;
return count_899 == 0 ? NDBT_OK : NDBT_FAILED;
}
int
runInit899(NDBT_Context* ctx, NDBT_Step* step)
{
NdbRestarter restarter;
int val = DumpStateOrd::DihMinTimeBetweenLCP;
restarter.dumpStateAllNodes(&val, 1);
Ndb* pNdb = GETNDB(step);
const NdbDictionary::Table* pTab = ctx->getTab();
const NdbDictionary::Table * pTab2 = pNdb->getDictionary()->
getTable(pTab->getName());
int tableId = pTab2->getObjectId();
int val2[] = { DumpStateOrd::BackupErrorInsert, 10042, tableId };
for (int i = 0; i < restarter.getNumDbNodes(); i++)
{
if (i & 1)
{
int nodeId = restarter.getDbNodeId(i);
ndbout_c("Setting slow LCP of table %d on node %d",
tableId, nodeId);
restarter.dumpStateOneNode(nodeId, val2, 3);
}
}
return NDBT_OK;
}
int
runEnd899(NDBT_Context* ctx, NDBT_Step* step)
{
// reset LCP speed
NdbRestarter restarter;
int val[] = { DumpStateOrd::DihMinTimeBetweenLCP, 0 };
restarter.dumpStateAllNodes(val, 2);
restarter.insertErrorInAllNodes(0);
return NDBT_OK;
}
int initSubscription(NDBT_Context* ctx, NDBT_Step* step){
/* Subscribe to events on the table, and put access
* to the subscription somewhere handy
*/
Ndb* pNdb = GETNDB(step);
const NdbDictionary::Table& tab = *ctx->getTab();
bool merge_events = false;
bool report = false;
char eventName[1024];
sprintf(eventName,"%s_EVENT",tab.getName());
NdbDictionary::Dictionary *myDict = pNdb->getDictionary();
if (!myDict) {
g_err << "Dictionary not found "
<< pNdb->getNdbError().code << " "
<< pNdb->getNdbError().message << endl;
return NDBT_FAILED;
}
myDict->dropEvent(eventName);
NdbDictionary::Event myEvent(eventName);
myEvent.setTable(tab.getName());
myEvent.addTableEvent(NdbDictionary::Event::TE_ALL);
for(int a = 0; a < tab.getNoOfColumns(); a++){
myEvent.addEventColumn(a);
}
myEvent.mergeEvents(merge_events);
if (report)
myEvent.setReport(NdbDictionary::Event::ER_SUBSCRIBE);
int res = myDict->createEvent(myEvent); // Add event to database
if (res == 0)
myEvent.print();
else if (myDict->getNdbError().classification ==
NdbError::SchemaObjectExists)
{
g_info << "Event creation failed event exists\n";
res = myDict->dropEvent(eventName);
if (res) {
g_err << "Failed to drop event: "
<< myDict->getNdbError().code << " : "
<< myDict->getNdbError().message << endl;
return NDBT_FAILED;
}
// try again
res = myDict->createEvent(myEvent); // Add event to database
if (res) {
g_err << "Failed to create event (1): "
<< myDict->getNdbError().code << " : "
<< myDict->getNdbError().message << endl;
return NDBT_FAILED;
}
}
else
{
g_err << "Failed to create event (2): "
<< myDict->getNdbError().code << " : "
<< myDict->getNdbError().message << endl;
return NDBT_FAILED;
}
return NDBT_OK;
}
int removeSubscription(NDBT_Context* ctx, NDBT_Step* step){
/* Remove subscription created above */
Ndb* pNdb = GETNDB(step);
const NdbDictionary::Table& tab = *ctx->getTab();
char eventName[1024];
sprintf(eventName,"%s_EVENT",tab.getName());
NdbDictionary::Dictionary *myDict = pNdb->getDictionary();
if (!myDict) {
g_err << "Dictionary not found "
<< pNdb->getNdbError().code << " "
<< pNdb->getNdbError().message << endl;
return NDBT_FAILED;
}
myDict->dropEvent(eventName);
return NDBT_OK;
}
int runVerifyRowCount(NDBT_Context* ctx, NDBT_Step* step)
{
Ndb* ndb = GETNDB(step);
/* Check that number of results returned by a normal scan
* and per-fragment rowcount sum are equal
*/
Uint32 rowCountSum = 0;
Uint32 rowScanCount = 0;
int result = NDBT_OK;
do
{
NdbTransaction* trans = ndb->startTransaction();
CHECK(trans != NULL);
NdbScanOperation* scan = trans->getNdbScanOperation(ctx->getTab());
CHECK(scan != NULL);
CHECK(scan->readTuples(NdbScanOperation::LM_CommittedRead) == 0);
NdbInterpretedCode code;
CHECK(code.interpret_exit_last_row() == 0);
CHECK(code.finalise() == 0);
NdbRecAttr* rowCountRA = scan->getValue(NdbDictionary::Column::ROW_COUNT);
CHECK(rowCountRA != NULL);
CHECK(scan->setInterpretedCode(&code) == 0);
CHECK(trans->execute(NoCommit) == 0);
while (scan->nextResult() == 0)
rowCountSum+= rowCountRA->u_32_value();
trans->close();
trans = ndb->startTransaction();
CHECK(trans != NULL);
scan = trans->getNdbScanOperation(ctx->getTab());
CHECK(scan != NULL);
CHECK(scan->readTuples(NdbScanOperation::LM_CommittedRead) == 0);
rowCountRA = scan->getValue(NdbDictionary::Column::ROW_COUNT);
CHECK(rowCountRA != NULL);
CHECK(trans->execute(NoCommit) == 0);
while (scan->nextResult() == 0)
rowScanCount++;
trans->close();
}
while(0);
if (result == NDBT_OK)
{
ndbout_c("Sum of fragment row counts : %u Number rows scanned : %u",
rowCountSum,
rowScanCount);
if (rowCountSum != rowScanCount)
{
ndbout_c("MISMATCH");
result = NDBT_FAILED;
}
}
return result;
}
enum ApiEventType { Insert, Update, Delete };
template class Vector<ApiEventType>;
struct EventInfo
{
ApiEventType type;
int id;
Uint64 gci;
};
template class Vector<EventInfo>;
int collectEvents(Ndb* ndb,
HugoCalculator& calc,
const NdbDictionary::Table& tab,
Vector<EventInfo>& receivedEvents,
int idCol,
int updateCol,
Vector<NdbRecAttr*>* beforeAttrs,
Vector<NdbRecAttr*>* afterAttrs)
{
int MaxTimeouts = 5;
int MaxEmptyPollsAfterData = 10;
bool some_event_data_received = false;
while (true)
{
NdbEventOperation* pOp = NULL;
int res = ndb->pollEvents(1000);
if (res <= 0)
{
if (--MaxTimeouts == 0)
break;
}
else
{
assert(res == 1);
pOp = ndb->nextEvent();
if (!pOp)
{
/* pollEvents returning 1 and nextEvent returning 0 means
* empty epochs found in the event queue. After we receive
* some event data, we wait some empty epoch poll rounds
* to make sure that no more event data arrives.
*/
if (some_event_data_received && --MaxEmptyPollsAfterData == 0)
break;
}
}
{
while (pOp)
{
bool isDelete = (pOp->getEventType() == NdbDictionary::Event::TE_DELETE);
Vector<NdbRecAttr*>* whichVersion =
isDelete?
beforeAttrs :
afterAttrs;
int id = (*whichVersion)[idCol]->u_32_value();
Uint64 gci = pOp->getGCI();
Uint32 anyValue = pOp->getAnyValue();
Uint32 scenario = ((anyValue >> 24) & 0xff) -1;
Uint32 optype = ((anyValue >> 16) & 0xff);
Uint32 recNum = (anyValue & 0xffff);
g_err << "# " << receivedEvents.size()
<< " GCI : " << (gci >> 32)
<< "/"
<< (gci & 0xffffffff)
<< " id : "
<< id
<< " scenario : " << scenario
<< " optype : " << optype
<< " record : " << recNum
<< " ";
/* Check event has self-consistent data */
int updatesValue = (*whichVersion)[updateCol]->u_32_value();
if ((*whichVersion)[updateCol]->isNULL() ||
(*whichVersion)[idCol]->isNULL())
{
g_err << "Null update/id cols : REFRESH of !EXISTS ";
}
g_err << "(Updates val = " << updatesValue << ")";
for (int i=0; i < (int) whichVersion->size(); i++)
{
/* Check PK columns and also other columns for non-delete */
if (!isDelete ||
tab.getColumn(i)->getPrimaryKey())
{
NdbRecAttr* ra = (*whichVersion)[i];
if (calc.verifyRecAttr(recNum, updatesValue, ra) != 0)
{
g_err << "Verify failed on recNum : " << recNum << " with updates value "
<< updatesValue << " for column " << ra->getColumn()->getAttrId()
<< endl;
return NDBT_FAILED;
}
}
}
EventInfo ei;
switch (pOp->getEventType())
{
case NdbDictionary::Event::TE_INSERT:
g_err << " Insert event" << endl;
ei.type = Insert;
break;
case NdbDictionary::Event::TE_DELETE:
ei.type = Delete;
g_err << " Delete event" << endl;
break;
case NdbDictionary::Event::TE_UPDATE:
ei.type = Update;
g_err << " Update event" << endl;
break;
default:
g_err << " Event type : " << pOp->getEventType() << endl;
abort();
break;
}
ei.id = recNum;
ei.gci = gci;
receivedEvents.push_back(ei);
some_event_data_received = true;
pOp = ndb->nextEvent();
}
}
}
return NDBT_OK;
}
int verifyEvents(const Vector<EventInfo>& receivedEvents,
const Vector<ApiEventType>& expectedEvents,
int records)
{
/* Now verify received events against expected
* This is messy as events occurring in the same epoch are unordered
* except via id, so we use id-duplicates to determine which event
* sequence we're looking at.
*/
g_err << "Received total of " << receivedEvents.size() << " events" << endl;
Vector<Uint32> keys;
Vector<Uint64> gcis;
Uint32 z = 0;
Uint64 z2 = 0;
keys.fill(records, z);
gcis.fill(records, z2);
Uint64 currGci = 0;
for (Uint32 e=0; e < receivedEvents.size(); e++)
{
EventInfo ei = receivedEvents[e];
if (ei.gci != currGci)
{
if (ei.gci < currGci)
abort();
/* Epoch boundary */
/* At this point, all id counts must be equal */
for (int i=0; i < records; i++)
{
if (keys[i] != keys[0])
{
g_err << "Count for id " << i
<< " is " << keys[i]
<< " but should be " << keys[0] << endl;
return NDBT_OK;
}
}
currGci = ei.gci;
}
Uint32 eventIndex = keys[ei.id];
keys[ei.id]++;
ApiEventType et = expectedEvents[eventIndex];
if (ei.type != et)
{
g_err << "Expected event of type " << et
<< " but found " << ei.type
<< " at expectedEvent " << eventIndex
<< " and event num " << e << endl;
return NDBT_FAILED;
}
}
return NDBT_OK;
}
int runRefreshTuple(NDBT_Context* ctx, NDBT_Step* step){
int records = ctx->getNumRecords();
Ndb* ndb = GETNDB(step);
/* Now attempt to create EventOperation */
NdbEventOperation* pOp;
const NdbDictionary::Table& tab = *ctx->getTab();
char eventName[1024];
sprintf(eventName,"%s_EVENT",tab.getName());
pOp = ndb->createEventOperation(eventName);
if (pOp == NULL)
{
g_err << "Failed to create event operation\n";
return NDBT_FAILED;
}
HugoCalculator calc(tab);
Vector<NdbRecAttr*> eventAfterRecAttr;
Vector<NdbRecAttr*> eventBeforeRecAttr;
int updateCol = -1;
int idCol = -1;
/* Now request all attributes */
for (int a = 0; a < tab.getNoOfColumns(); a++)
{
eventAfterRecAttr.push_back(pOp->getValue(tab.getColumn(a)->getName()));
eventBeforeRecAttr.push_back(pOp->getPreValue(tab.getColumn(a)->getName()));
if (calc.isIdCol(a))
idCol = a;
if (calc.isUpdateCol(a))
updateCol = a;
}
/* Now execute the event */
if (pOp->execute())
{
g_err << "Event operation execution failed : " << pOp->getNdbError() << endl;
return NDBT_FAILED;
}
HugoOperations hugoOps(*ctx->getTab());
int scenario = 0;
Vector<ApiEventType> expectedEvents;
for (scenario = 0; scenario < 2; scenario++)
{
g_err << "Scenario = " << scenario
<< " ( Refresh "
<< ((scenario == 0)? "before":"after")
<< " operations )" << endl;
int optype = 0;
bool done = false;
int expectedError = 0;
do
{
check(hugoOps.startTransaction(ndb) == 0, hugoOps);
if (scenario == 0)
{
g_err << "Refresh before operations" << endl;
int anyValue =
((1) << 8) |
optype;
check(hugoOps.pkRefreshRecord(ndb, 0, records, anyValue) == 0, hugoOps);
}
switch(optype)
{
case 0:
{
/* Refresh with no data present */
g_err << " Do nothing" << endl;
expectedError = 0; /* Single refresh should always be fine */
expectedEvents.push_back(Delete);
break;
}
case 1:
{
/* [Refresh] Insert [Refresh] */
g_err << " Insert" << endl;
check(hugoOps.pkInsertRecord(ndb, 0, records, 1) == 0, hugoOps);
if (scenario == 0)
{
/* Tuple already existed error when we insert after refresh */
expectedError = 630;
expectedEvents.push_back(Delete);
}
else
{
expectedError = 0;
expectedEvents.push_back(Insert);
}
/* Tuple already existed error when we insert after refresh */
break;
}
case 2:
{
/* Refresh */
g_err << " Refresh" << endl;
if (scenario == 0)
{
expectedEvents.push_back(Delete);
}
else
{
expectedEvents.push_back(Insert);
}
expectedError = 0;
break;
}
case 3:
{
/* [Refresh] Update [Refresh] */
g_err << " Update" << endl;
check(hugoOps.pkUpdateRecord(ndb, 0, records, 3) == 0, hugoOps);
if (scenario == 0)
{
expectedError = 920;
expectedEvents.push_back(Delete);
}
else
{
expectedError = 0;
expectedEvents.push_back(Insert);
}
break;
}
case 4:
{
/* [Refresh] Delete [Refresh] */
g_err << " [Refresh] Delete [Refresh]" << endl;
if (scenario == 0)
{
expectedError = 920;
expectedEvents.push_back(Delete);
}
else
{
expectedError = 0;
expectedEvents.push_back(Delete);
}
check(hugoOps.pkDeleteRecord(ndb, 0, records) == 0, hugoOps);
break;
}
case 5:
{
g_err << " Refresh" << endl;
expectedError = 0;
expectedEvents.push_back(Delete);
/* Refresh with no data present */
break;
}
case 6:
{
g_err << " Double refresh" << endl;
int anyValue =
((2) << 8) |
optype;
check(hugoOps.pkRefreshRecord(ndb, 0, records, anyValue) == 0, hugoOps);
expectedError = 920; /* Row operation defined after refreshTuple() */
expectedEvents.push_back(Delete);
}
// Fall through - done with last optype
default:
done = true;
break;
}
if (scenario == 1)
{
g_err << "Refresh after operations" << endl;
int anyValue =
((4) << 8) |
optype;
check(hugoOps.pkRefreshRecord(ndb, 0, records, anyValue) == 0, hugoOps);
}
int rc = hugoOps.execute_Commit(ndb, AO_IgnoreError);
check(rc == expectedError, hugoOps);
check(hugoOps.closeTransaction(ndb) == 0, hugoOps);
optype++;
/* Now check fragment counts vs findable row counts */
if (runVerifyRowCount(ctx, step) != NDBT_OK)
return NDBT_FAILED;
} while (!done);
} // for scenario...
/* Now check fragment counts vs findable row counts */
if (runVerifyRowCount(ctx, step) != NDBT_OK)
return NDBT_FAILED;
/* Now let's dump and check the events */
g_err << "Expecting the following sequence..." << endl;
for (Uint32 i=0; i < expectedEvents.size(); i++)
{
g_err << i << ". ";
switch(expectedEvents[i])
{
case Insert:
g_err << "Insert" << endl;
break;
case Update:
g_err << "Update" << endl;
break;
case Delete:
g_err << "Delete" << endl;
break;
default:
abort();
}
}
Vector<EventInfo> receivedEvents;
int rc = collectEvents(ndb, calc, tab, receivedEvents, idCol, updateCol,
&eventBeforeRecAttr,
&eventAfterRecAttr);
if (rc == NDBT_OK)
{
rc = verifyEvents(receivedEvents,
expectedEvents,
records);
}
if (ndb->dropEventOperation(pOp) != 0)
{
g_err << "Drop Event Operation failed : " << ndb->getNdbError() << endl;
return NDBT_FAILED;
}
return rc;
}
// Regression test for bug #14208924
static int
runLeakApiConnectObjects(NDBT_Context* ctx, NDBT_Step* step)
{
NdbRestarter restarter;
/**
* This error insert inc ombination with bug #14208924 will
* cause TC to leak ApiConnectRecord objects.
*/
restarter.insertErrorInAllNodes(8094);
Ndb* const ndb = GETNDB(step);
Uint32 maxTrans = 0;
NdbConfig conf;
require(conf.getProperty(conf.getMasterNodeId(),
NODE_TYPE_DB,
CFG_DB_NO_TRANSACTIONS,
&maxTrans));
require(maxTrans > 0);
HugoOperations hugoOps(*ctx->getTab());
// One ApiConnectRecord object is leaked for each iteration.
for (uint i = 0; i < maxTrans+1; i++)
{
require(hugoOps.startTransaction(ndb) == 0);
require(hugoOps.pkInsertRecord(ndb, i) == 0);
NdbTransaction* const trans = hugoOps.getTransaction();
/**
* The error insert causes trans->execute(Commit) to fail with error code
* 286 even if the bug is fixed. Therefore, we ignore this error code.
*/
if (trans->execute(Commit) != 0 &&
trans->getNdbError().code != 286)
{
g_err << "trans->execute() gave unexpected error : "
<< trans->getNdbError() << endl;
restarter.insertErrorInAllNodes(0);
return NDBT_FAILED;
}
require(hugoOps.closeTransaction(ndb) == 0);
}
restarter.insertErrorInAllNodes(0);
UtilTransactions utilTrans(*ctx->getTab());
if (utilTrans.clearTable(ndb) != 0){
return NDBT_FAILED;
}
return NDBT_OK;
}
enum PreRefreshOps
{
PR_NONE,
PR_INSERT,
PR_INSERTDELETE,
PR_DELETE
};
struct RefreshScenario
{
const char* name;
bool preExist;
PreRefreshOps preRefreshOps;
};
static RefreshScenario refreshTests[] = {
{ "No row, No pre-ops", false, PR_NONE },
{ "No row, Insert pre-op", false, PR_INSERT },
{ "No row, Insert-Del pre-op", false, PR_INSERTDELETE },
{ "Row exists, No pre-ops", true, PR_NONE },
{ "Row exists, Delete pre-op", true, PR_DELETE }
};
enum OpTypes
{
OP_READ_C,
OP_READ_S,
OP_READ_E,
OP_INSERT,
OP_UPDATE,
OP_WRITE,
OP_DELETE,
OP_LAST
};
const char* opTypeNames[] =
{
"READ_C",
"READ_S",
"READ_E",
"INSERT",
"UPDATE",
"WRITE",
"DELETE"
};
int
runRefreshLocking(NDBT_Context* ctx, NDBT_Step* step)
{
/* Check that refresh in various situations has the
* locks we expect it to
* Scenario combinations :
* Now row pre-existing | Row pre-existing
* Trans1 : Refresh | Insert-Refresh | Insert-Delete-Refresh
* Delete-Refresh
* Trans2 : Read [Committed|Shared|Exclusive] | Insert | Update
* Write | Delete
*
* Expectations : Read committed always non-blocking
* Read committed sees pre-existing row
* All other trans2 operations deadlock
*/
Ndb* ndb = GETNDB(step);
Uint32 numScenarios = sizeof(refreshTests) / sizeof(refreshTests[0]);
HugoTransactions hugoTrans(*ctx->getTab());
for (Uint32 s = 0; s < numScenarios; s++)
{
RefreshScenario& scenario = refreshTests[s];
if (scenario.preExist)
{
/* Create pre-existing tuple */
if (hugoTrans.loadTable(ndb, 1) != 0)
{
g_err << "Pre-exist failed : " << hugoTrans.getNdbError() << endl;
return NDBT_FAILED;
}
}
if (hugoTrans.startTransaction(ndb) != 0)
{
g_err << "Start trans failed : " << hugoTrans.getNdbError() << endl;
return NDBT_FAILED;
}
g_err << "Scenario : " << scenario.name << endl;
/* Do pre-refresh ops */
switch (scenario.preRefreshOps)
{
case PR_NONE:
break;
case PR_INSERT:
case PR_INSERTDELETE:
if (hugoTrans.pkInsertRecord(ndb, 0) != 0)
{
g_err << "Pre insert failed : " << hugoTrans.getNdbError() << endl;
return NDBT_FAILED;
}
if (scenario.preRefreshOps == PR_INSERT)
break;
// Fall through
case PR_DELETE:
if (hugoTrans.pkDeleteRecord(ndb, 0) != 0)
{
g_err << "Pre delete failed : " << hugoTrans.getNdbError() << endl;
return NDBT_FAILED;
}
break;
}
/* Then refresh */
if (hugoTrans.pkRefreshRecord(ndb, 0) != 0)
{
g_err << "Refresh failed : " << hugoTrans.getNdbError() << endl;
return NDBT_FAILED;
}
/* Now execute */
if (hugoTrans.execute_NoCommit(ndb) != 0)
{
g_err << "Execute failed : " << hugoTrans.getNdbError() << endl;
return NDBT_FAILED;
}
{
/* Now try ops from another transaction */
HugoOperations hugoOps(*ctx->getTab());
Uint32 ot = OP_READ_C;
while (ot < OP_LAST)
{
if (hugoOps.startTransaction(ndb) != 0)
{
g_err << "Start trans2 failed : " << hugoOps.getNdbError() << endl;
return NDBT_FAILED;
}
g_err << "Operation type : " << opTypeNames[ot] << endl;
int res = 0;
switch (ot)
{
case OP_READ_C:
res = hugoOps.pkReadRecord(ndb,0,1,NdbOperation::LM_CommittedRead);
break;
case OP_READ_S:
res = hugoOps.pkReadRecord(ndb,0,1,NdbOperation::LM_Read);
break;
case OP_READ_E:
res = hugoOps.pkReadRecord(ndb,0,1,NdbOperation::LM_Exclusive);
break;
case OP_INSERT:
res = hugoOps.pkInsertRecord(ndb, 0);
break;
case OP_UPDATE:
res = hugoOps.pkUpdateRecord(ndb, 0);
break;
case OP_WRITE:
res = hugoOps.pkWriteRecord(ndb, 0);
break;
case OP_DELETE:
res = hugoOps.pkDeleteRecord(ndb, 0);
break;
case OP_LAST:
abort();
}
hugoOps.execute_Commit(ndb);
if ((ot == OP_READ_C) && (scenario.preExist))
{
if (hugoOps.getNdbError().code == 0)
{
g_err << "Read committed succeeded" << endl;
}
else
{
g_err << "UNEXPECTED : Read committed failed. " << hugoOps.getNdbError() << endl;
return NDBT_FAILED;
}
}
else
{
if (hugoOps.getNdbError().code == 0)
{
g_err << opTypeNames[ot] << " succeeded, should not have" << endl;
return NDBT_FAILED;
}
}
hugoOps.closeTransaction(ndb);
ot = ot + 1;
}
}
/* Close refresh transaction */
hugoTrans.closeTransaction(ndb);
if (scenario.preExist)
{
/* Cleanup pre-existing before next iteration */
if (hugoTrans.pkDelRecords(ndb, 0) != 0)
{
g_err << "Delete pre existing failed : " << hugoTrans.getNdbError() << endl;
return NDBT_FAILED;
}
}
}
return NDBT_OK;
}
int
runBugXXX_init(NDBT_Context* ctx, NDBT_Step* step)
{
return NDBT_OK;
}
int
runBugXXX_trans(NDBT_Context* ctx, NDBT_Step* step)
{
NdbRestarter res;
while (!ctx->isTestStopped())
{
runLoadTable(ctx, step);
ctx->getPropertyWait("CREATE_INDEX", 1);
ctx->setProperty("CREATE_INDEX", Uint32(0));
res.insertErrorInAllNodes(8105); // randomly abort trigger ops with 218
runClearTable2(ctx, step);
res.insertErrorInAllNodes(0);
}
return NDBT_OK;
}
int
runBugXXX_createIndex(NDBT_Context* ctx, NDBT_Step* step)
{
NdbRestarter res;
const int loops = ctx->getNumLoops();
Ndb* pNdb = GETNDB(step);
const NdbDictionary::Table* pTab = ctx->getTab();
BaseString name;
name.assfmt("%s_PK_IDX", pTab->getName());
NdbDictionary::Index pIdx(name.c_str());
pIdx.setTable(pTab->getName());
pIdx.setType(NdbDictionary::Index::UniqueHashIndex);
for (int c = 0; c < pTab->getNoOfColumns(); c++)
{
const NdbDictionary::Column * col = pTab->getColumn(c);
if(col->getPrimaryKey())
{
pIdx.addIndexColumn(col->getName());
}
}
pIdx.setStoredIndex(false);
for (int i = 0; i < loops; i++)
{
res.insertErrorInAllNodes(18000);
ctx->setProperty("CREATE_INDEX", 1);
pNdb->getDictionary()->createIndex(pIdx);
pNdb->getDictionary()->dropIndex(name.c_str(), pTab->getName());
}
ctx->stopTest();
return NDBT_OK;
}
int
runDeleteNdbInFlight(NDBT_Context* ctx, NDBT_Step* step)
{
Ndb* pNdb = GETNDB(step);
Ndb_cluster_connection & nc = pNdb->get_ndb_cluster_connection();
const NdbDictionary::Table* tab = ctx->getTab();
BaseString name;
name.assfmt("%s", tab->getName());
int result = NDBT_OK;
int rows = 1000;
/**
* We start by filling the table with 1000 rows.
* Next we start a transaction that inserts 1000 rows
* without committing it.
* Next we delete the Ndb object that sends off a
* TCRELEASEREQ signal that should ensure the
* transaction is aborted, we will not receive
* any info on this since we disconnected.
*
* Next we perform 1000 inserts and start off
* executing those in prepare phase. Next we
* delete Ndb object that sends off TCRELEASEREQ
* signal.
*
* After receiving TCRELEASECONF we can still
* receive many more TCKEYCONF's and TRANSID_AI's
* from the LDM threads and TC threads.
* This is ok, getting rid of TRANSID_AI's from
* LDM threads is more or less impossible since
* these are no longer controlled by TC. Getting
* rid of TCKEYCONF's is possible, but dangerous,
* so we put the responsibility on the NDB API to
* filter out those old signals by looking at the
* Transaction id.
*
* Finally we test a scan that gets closed down
* in the middle of execution by a TCRELEASEREQ.
*
* This test also massages the code for API node
* fail handling that probably wasn't 100% covered
* before this test was written.
*
* Given that ongoing transactions was stopped by
* deleting Ndb object we have to set Transaction
* to NULL in HugOperations to avoid it closing
* the transaction.
*/
HugoOperations *h_op = new HugoOperations(*tab);
h_op->startTransaction(pNdb);
h_op->pkInsertRecord(pNdb, 0, rows);
h_op->execute_Commit(pNdb);
h_op->closeTransaction(pNdb);
delete h_op;
ndbout_c("Test1");
Ndb *newNdb1 = new Ndb(&nc, "TEST_DB");
newNdb1->init(1024);
const NdbDictionary::Table *tab1 =
newNdb1->getDictionary()->getTable(name.c_str());
HugoOperations *h_op1 = new HugoOperations(*tab1);
h_op1->startTransaction(newNdb1);
h_op1->pkInsertRecord(newNdb1, rows, rows);
h_op1->execute_NoCommit(newNdb1);
delete newNdb1;
ndbout_c("Test2");
Ndb *newNdb2 = new Ndb(&nc, "TEST_DB");
newNdb2->init(1024);
const NdbDictionary::Table *tab2 =
newNdb2->getDictionary()->getTable(name.c_str());
HugoOperations *h_op2 = new HugoOperations(*tab2);
h_op2->startTransaction(newNdb2);
h_op2->pkInsertRecord(newNdb2, rows, 2 * rows);
h_op2->execute_async(newNdb2, NdbTransaction::Commit);
delete newNdb2;
ndbout_c("Test3");
Ndb *newNdb3 = new Ndb(&nc, "TEST_DB");
newNdb3->init(1024);
const NdbDictionary::Table *tab3 =
newNdb3->getDictionary()->getTable(name.c_str());
HugoOperations *h_op3 = new HugoOperations(*tab3);
h_op3->startTransaction(newNdb3);
h_op3->scanReadRecords(newNdb3, NdbScanOperation::LM_Exclusive, rows);
h_op3->execute_NoCommit(newNdb1);
delete newNdb3;
h_op1->setTransaction(NULL, true);
h_op2->setTransaction(NULL, true);
h_op3->setTransaction(NULL, true);
delete h_op1;
delete h_op2;
delete h_op3;
return result;
}
int
runBug16834333(NDBT_Context* ctx, NDBT_Step* step)
{
Ndb* pNdb = GETNDB(step);
NdbDictionary::Dictionary* pDic = pNdb->getDictionary();
const int records = ctx->getNumRecords();
NdbRestarter restarter;
int result = NDBT_OK;
do
{
/*
* Drop the pre-created table before initial restart to avoid invalid
* dict cache. One symptom would be running the test twice and getting
* abort() in final dict cache release due to non-existent version.
* Also use a copy of the pre-created table struct to avoid accessing
* invalid memory.
*/
const NdbDictionary::Table tab(* ctx->getTab());
CHK2(pDic->dropTable(tab.getName()) == 0, pDic->getNdbError());
ndbout_c("restart initial");
restarter.restartAll(true, /* initial */
true, /* nostart */
true /* abort */ );
ndbout_c("wait nostart");
restarter.waitClusterNoStart();
ndbout_c("startAll");
restarter.startAll();
ndbout_c("wait started");
restarter.waitClusterStarted();
CHK_NDB_READY(pNdb);
ndbout_c("create tab");
CHK2(pDic->createTable(tab) == 0, pDic->getNdbError());
const NdbDictionary::Table* pTab = pDic->getTable(tab.getName());
CHK2(pTab != 0, pDic->getNdbError());
ndbout_c("load table");
HugoTransactions trans(* pTab);
CHK2(trans.loadTable(pNdb, records) == 0, trans.getNdbError());
int codes[] = { 5080, 5081 };
for (int i = 0, j = 0; i < restarter.getNumDbNodes(); i++, j++)
{
int code = codes[j % NDB_ARRAY_SIZE(codes)];
int nodeId = restarter.getDbNodeId(i);
ndbout_c("error %d node: %d", code, nodeId);
restarter.insertErrorInNode(nodeId, code);
}
ndbout_c("running big trans");
HugoOperations ops(* pTab);
CHK2(ops.startTransaction(pNdb) == 0, ops.getNdbError());
CHK2(ops.pkReadRecord(0, 16384) == 0, ops.getNdbError());
if (ops.execute_Commit(pNdb, AO_IgnoreError) != 0)
{
// XXX should this occur if AO_IgnoreError ?
CHK2(ops.getNdbError().code == 1223, ops.getNdbError());
g_info << ops.getNdbError() << endl;
}
ops.closeTransaction(pNdb);
}
while (0);
restarter.insertErrorInAllNodes(0);
return result;
}
// bug#19031389
int
runAccCommitOrder(NDBT_Context* ctx, NDBT_Step* step)
{
Ndb* pNdb = GETNDB(step);
const NdbDictionary::Table* pTab = ctx->getTab();
const int loops = ctx->getNumLoops();
const int records = ctx->getNumRecords();
require(records > 0);
const int opsteps = ctx->getProperty("OPSTEPS");
int result = NDBT_OK;
for (int loop = 0; loop < loops; loop++)
{
g_info << "loop " << loop << endl;
{
g_info << "load table" << endl;
HugoTransactions trans(*pTab);
CHK2(trans.loadTable(pNdb, records) == 0, trans.getNdbError());
}
g_info << "start op steps" << endl;
require(ctx->getProperty("RUNNING", (Uint32)opsteps) == 0);
ctx->setProperty("RUN", (Uint32)1);
if (ctx->getPropertyWait("RUNNING", (Uint32)opsteps))
break;
g_info << "all op steps running" << endl;
int mssleep = 10 + ndb_rand() % records;
if (mssleep > 1000)
mssleep = 1000;
NdbSleep_MilliSleep(mssleep);
g_info << "stop op steps" << endl;
require(ctx->getProperty("RUNNING", (Uint32)0) == (Uint32)opsteps);
ctx->setProperty("RUN", (Uint32)0);
if (ctx->getPropertyWait("RUNNING", (Uint32)0))
break;
g_info << "all op steps stopped" << endl;
{
g_info << "clear table" << endl;
UtilTransactions trans(*pTab);
CHK1(trans.clearTable(pNdb, records) == 0);
}
}
g_info << "stop test" << endl;
ctx->stopTest();
return result;
}
int
runAccCommitOrderOps(NDBT_Context* ctx, NDBT_Step* step)
{
const int stepNo = step->getStepNo();
Ndb* pNdb = GETNDB(step);
const NdbDictionary::Table* pTab = ctx->getTab();
const int records = ctx->getNumRecords();
int result = NDBT_OK;
unsigned seed = (unsigned)(NdbHost_GetProcessId() ^ stepNo);
ndb_srand(seed);
int loop = 0;
while (!ctx->isTestStopped())
{
if (ctx->getPropertyWait("RUN", (Uint32)1))
break;
g_info << "step " << stepNo << ": loop " << loop << endl;
ctx->incProperty("RUNNING");
g_info << "step " << stepNo << ": running" << endl;
int opscount = 0;
int n = 0; // steps should hit about same records
while (ctx->getProperty("RUN", (Uint32)0) == (Uint32)1)
{
HugoOperations ops(*pTab);
ops.setQuiet();
CHK2(ops.startTransaction(pNdb) == 0, ops.getNdbError());
const int numreads = 2 + ndb_rand_r(&seed) % 3;
for (int i = 0; i < numreads; i++)
{
NdbOperation::LockMode lm = NdbOperation::LM_Read;
CHK2(ops.pkReadRecord(pNdb, n, 1, lm) == 0, ops.getNdbError());
opscount++;
}
CHK1(result == NDBT_OK);
CHK2(ops.pkDeleteRecord(pNdb, n, 1) == 0, ops.getNdbError());
CHK2(ops.execute_Commit(pNdb) == 0 ||
ops.getNdbError().code == 626 ||
(
ops.getNdbError().status == NdbError::TemporaryError &&
ops.getNdbError().classification != NdbError::NodeRecoveryError
),
ops.getNdbError());
ops.closeTransaction(pNdb);
n = (n + 1) % records;
}
CHK1(result == NDBT_OK);
g_info << "step " << stepNo << ": ops count " << opscount << endl;
ctx->decProperty("RUNNING");
g_info << "step " << stepNo << ": stopped" << endl;
loop++;
}
ctx->stopTest();
return result;
}
/**
* TESTCASE DeleteNdbWhilePoll: Delete an Ndb object while it(trp_clnt)
* is in poll q.
* runInsertOneTuple : inserts one tuple in table.
* runLockTuple : A thread runs transaction 1 (Txn1) which locks the
* tuple with exclusive lock and signals another thread running
* transaction 2 (Txn2).
* runReadLockedTuple : Txn2 issues an exclusive read of the tuple
* locked by Txn1 (and waits for lock), and signals the delete thread.
* deleteNdbWhileWaiting : deletes the ndb object used by Txn2.
* Tx1 commits and Tx2 commits and provokes consequences from deleted Ndb.
*
* The most probable consequence, is :
* TransporterFacade.cpp:1674: require((clnt->m_poll.m_locked == true)) failed
*/
// Candidate for deleteNdbWhileWaiting().
static Ndb* ndbToDelete = NULL;
int
runInsertOneTuple(NDBT_Context *ctx, NDBT_Step* step)
{
int result = NDBT_OK;
const NdbDictionary::Table *table= ctx->getTab();
HugoOperations hugoOp1(*table);
Ndb* pNdb = GETNDB(step);
CHECK2(hugoOp1.startTransaction(pNdb) == 0);
CHECK2(hugoOp1.pkInsertRecord(pNdb, 1, 1) == 0);
CHECK2(hugoOp1.execute_Commit(pNdb) == 0);
CHECK2(hugoOp1.closeTransaction(pNdb) == 0);
g_info << "Rec inserted, ndb " << pNdb <<endl <<endl;
return result;
}
int
runLockTuple(NDBT_Context *ctx, NDBT_Step* step)
{
int result = NDBT_OK;
const NdbDictionary::Table *table= ctx->getTab();
HugoOperations hugoOp1(*table);
Ndb* pNdb = GETNDB(step);
CHECK2(hugoOp1.startTransaction(pNdb) == 0);
// read the inserted tuple (Txn1).
CHECK2(hugoOp1.pkReadRecord(pNdb, 1, 1, NdbOperation::LM_Exclusive) == 0);
CHECK2(hugoOp1.execute_NoCommit(pNdb) == 0);
g_info << "Txn1 readlocked tuple, ndb "<<pNdb << endl;
// Flag Txn2 to read (which will be blocked due to Txn1's read lock).
ctx->setProperty("Txn1-LockedTuple", 1);
// Wait until ndb of Txn2 is deleted by deleteNdbWhileWaiting().
while(ctx->getProperty("NdbDeleted", (Uint32)0) == 0 &&
!ctx->isTestStopped()){
NdbSleep_MilliSleep(20);
}
// Now commit Txn1.
/* Intention is when this commits, Txn1's trp_clnt will relinquish the
* poll rights it had to trp_clnt to Txn2, which is deleted.
* However this is not determisnistic. Sometimes, the poll right
* is owned by Txn2's trp_clnt, causing test to assert-fail in do_poll.
*/
g_info << "Txn1 commits, ndb " << pNdb << endl;
if (!ctx->isTestStopped())
CHECK2(hugoOp1.execute_Commit(pNdb) == 0);
g_info << "Txn1 commited, ndb " << pNdb << endl;
if (!ctx->isTestStopped())
CHECK2(hugoOp1.closeTransaction(pNdb) == 0);
return result;
}
// Read the tuple locked by Txn1, see runLockTuple().
int
runReadLockedTuple(NDBT_Context *ctx, NDBT_Step* step)
{
int result = NDBT_OK;
const NdbDictionary::Table *table= ctx->getTab();
HugoOperations hugoOp2(*table);
Ndb* pNdb = GETNDB(step);
// Wait until the tuple is locked by Txn1
while(ctx->getProperty("Txn1-LockedTuple", (Uint32)0) == 0 &&
!ctx->isTestStopped()){
NdbSleep_MilliSleep(20);
}
CHECK2(hugoOp2.startTransaction(pNdb) == 0);
// Txn2 reads the locked tuple.
CHECK2(hugoOp2.pkReadRecord(pNdb, 1, 1, NdbOperation::LM_Exclusive) == 0);
// Flag deleteNdbWhileWaiting() to delete my ndb object
ndbToDelete = pNdb; // candidate for deleteNdbWhileWaiting()
ctx->setProperty("Txn2-SendCommit", 1);
// Now commit Txn2
g_info << "Txn2 commits, ndb " << pNdb
<< ", Ndb to delete " << ndbToDelete << endl << endl;
CHECK2(hugoOp2.execute_Commit(pNdb) == 0);
CHECK2(hugoOp2.closeTransaction(pNdb) == 0);
ctx->stopTest();
return result;
}
// Delete ndb of Txn2.
int deleteNdbWhileWaiting(NDBT_Context* ctx, NDBT_Step* step)
{
// Wait until Txn2 sends the read of the locked tuple.
while(ctx->getProperty("Txn2-SendCommit", (Uint32)0) == 0 &&
!ctx->isTestStopped()){
g_info << "|- Waiting for read" << endl;
NdbSleep_MilliSleep(20);
}
// Delete ndb of Txn2 while it is waiting in the poll queue.
g_info << "deleteNdbWhileWaiting deletes ndb " << ndbToDelete << endl << endl;
delete ndbToDelete;
// Signal Txn1 to commit
ctx->setProperty("NdbDeleted", 1);
return NDBT_OK;
}
/******* end TESTCASE DeleteNdbWhilePoll*******/
int testAbortRace(NDBT_Context* ctx, NDBT_Step* step)
{
/* Transaction 1 : Lock tuple */
/* Transaction 2 : Issue DELETE, INSERT */
/* ERROR INSERT 5091 */
/* Transaction 1 : Unlock tuple */
/* ... Transaction 2 should timeout due to ERROR INSERTS + ABORT */
/* Wait for Transaction 2 outcome */
/* Scan table via ACC */
int result = NDBT_OK;
const NdbDictionary::Table *table= ctx->getTab();
Ndb* pNdb = GETNDB(step);
NdbRestarter restarter;
for (int r=0; r < 10; r++)
{
ndbout_c("Locking row %u", r);
/* Lock the tuple */
HugoOperations hugoOp1(*table);
CHECK2(hugoOp1.startTransaction(pNdb) == 0);
CHECK2(hugoOp1.pkReadRecord(pNdb, r, 1, NdbOperation::LM_Exclusive) == 0);
CHECK2(hugoOp1.execute_NoCommit(pNdb) == 0);
ndbout_c("Defining DEL, INS on %u", r);
/* Define delete + insert ops which will queue on the row lock */
HugoOperations hugoOp2(*table);
CHECK2(hugoOp2.startTransaction(pNdb) == 0);
CHECK2(hugoOp2.pkDeleteRecord(pNdb, r, 1) == 0);
CHECK2(hugoOp2.pkInsertRecord(pNdb, r, 1) == 0);
CHECK2(hugoOp2.execute_async(pNdb, NdbTransaction::NoCommit) == 0);
ndbout_c("Setting error insert");
restarter.insertErrorInAllNodes(5094);
/* Wait a little */
NdbSleep_MilliSleep(500);
ndbout_c("Releasing the lock");
/* Release the lock */
CHECK2(hugoOp1.execute_Commit(pNdb) == 0);
CHECK2(hugoOp1.closeTransaction(pNdb) == 0);
ndbout_c("Waiting for DEL,INS");
/* Wait for some outcome on the async T2 */
CHECK2(hugoOp2.wait_async(pNdb) != 0); /* Error? */
CHECK2(hugoOp2.closeTransaction(pNdb) == 0);
ndbout_c("Scanning the table");
/* Now scan via ACC */
HugoTransactions hugoTrans(*table);
CHECK2(hugoTrans.scanReadRecords(pNdb,
ctx->getNumRecords()) == 0);
/* Check the table */
//ndbout_c("Checking the table");
//CHECK2(NdbCompareUtils::doScanPkReplicaCheck(pNdb,
// table));
} while (0);
//ndbout_c("Hanging around a while");
//NdbSleep_MilliSleep(4*1000);
restarter.insertErrorInAllNodes(0);
return result;
}
/**
* This test case passes if the # records checkpointed
* is equal to #records in the table given in the test context
* times number of replicas in the cluster.
* It
* - performs a local checkpoint.
* - fills the table with #records given in the test context.
* - performs another local checkpoint. With the pLCP, only the
* the records inserted into the context's table is expected to
* appear in the LCP-statistics calculated by the test.
* - Checks the LCP'd records.
*/
int
runCheckLCPStats(NDBT_Context* ctx, NDBT_Step* step)
{
NdbRestarter restarter;
Uint32 master = restarter.getMasterNodeId();
// Perform an LCP and wait it to start and finish
int dump_req[] = { DumpStateOrd::DihStartLcpImmediately};
CHECK3(restarter.dumpStateOneNode(master, dump_req, 1) == 0);
int filter[] = { 15, NDB_MGM_EVENT_CATEGORY_CHECKPOINT, 0 };
NdbLogEventHandle handle =
ndb_mgm_create_logevent_handle(restarter.handle, filter);
struct ndb_logevent event;
while(ndb_logevent_get_next(handle, &event, 0) >= 0 &&
event.type != NDB_LE_LocalCheckpointStarted);
while(ndb_logevent_get_next(handle, &event, 0) >= 0 &&
event.type != NDB_LE_LocalCheckpointCompleted);
// Insert ctx->getNumRecords()
CHECK3(runLoadTable(ctx,step) == 0);
// Perform an LCP and wait until it is started
CHECK3(restarter.dumpStateOneNode(master, dump_req, 1) == 0);
while(ndb_logevent_get_next(handle, &event, 0) >= 0 &&
event.type != NDB_LE_LocalCheckpointStarted);
NdbMgmd mgmd;
CHECK3(mgmd.connect());
CHECK3(mgmd.subscribe_to_events());
Uint32 no_of_replicas = mgmd.get_config32(CFG_SECTION_NODE,
CFG_DB_NO_REPLICAS);
g_err << "Number of replicas in cluster " << no_of_replicas << endl;
CHECK3(no_of_replicas > 0);
Uint64 expected_records = no_of_replicas * ctx->getNumRecords();
Uint64 checkpointed_records = 0;
Uint64 max_wait_seconds = 120;
Uint64 end_time = NdbTick_CurrentMillisecond() +
(max_wait_seconds * 1000);
// Read 'Completed LCP' events and sum up the checkpointed records
while (NdbTick_CurrentMillisecond() < end_time)
{
char buff[512];
if (!mgmd.get_next_event_line(buff,
sizeof(buff),
10 * 1000) == 0)
{
if (strstr(buff, "Local checkpoint"))
{
/**
* Since we have already seen "Local checkpoint %u started" event
* earlier, this must be "Local checkpoint %u completed" event.
*/
if (checkpointed_records == expected_records)
{
return NDBT_OK;
}
// Probably "Local checkpoint %u completed" came before all
// "Completed LCP" events came. Continue until end_time.
}
if (strstr(buff, "Completed LCP"))
{
unsigned int node = 0;
unsigned int ldm = 0;
unsigned int nfrags = 0;
unsigned int nRecords = 0;
unsigned int nBytes = 0;
sscanf(buff, "Node %u: LDM(%u): Completed LCP, #frags = %u #records = %u, #bytes = %u", &node, &ldm, &nfrags, &nRecords, &nBytes);
g_info << "Node " << node << " ldm " << ldm
<< " Records " << nRecords << endl;
checkpointed_records += nRecords;
}
}
}
// Total checkpointed records includes both primary and the backup replicas
g_err << "Number of records checkpointed " << checkpointed_records << endl;
CHECK3(checkpointed_records == expected_records);
return NDBT_OK;
}
NDBT_TESTSUITE(testBasic);
TESTCASE("PkInsert",
"Verify that we can insert and delete from this table using PK"
"NOTE! No errors are allowed!" ){
INITIALIZER(runInsert);
VERIFIER(runVerifyInsert);
}
TESTCASE("PkRead",
"Verify that we can insert, read and delete from this table using PK"){
TC_PROPERTY("LockMode", NdbOperation::LM_Read);
INITIALIZER(runLoadTable);
STEP(runPkRead);
FINALIZER(runClearTable);
}
TESTCASE("PkDirtyRead",
"Verify that we can insert, dirty read and delete from this table using PK"){
TC_PROPERTY("LockMode", NdbOperation::LM_Dirty);
INITIALIZER(runLoadTable);
STEP(runPkRead);
FINALIZER(runClearTable);
}
TESTCASE("PkSimpleRead",
"Verify that we can insert, simple read and delete from this table using PK"){
TC_PROPERTY("LockMode", NdbOperation::LM_SimpleRead);
INITIALIZER(runLoadTable);
STEP(runPkRead);
FINALIZER(runClearTable);
}
TESTCASE("PkUpdate",
"Verify that we can insert, update and delete from this table using PK"){
INITIALIZER(runLoadTable);
STEP(runPkUpdate);
FINALIZER(runClearTable);
}
TESTCASE("PkDelete",
"Verify that we can delete from this table using PK"){
INITIALIZER(runLoadTable);
STEP(runPkDelete);
FINALIZER(runClearTable);
}
TESTCASE("UpdateAndRead",
"Verify that we can read and update at the same time"){
INITIALIZER(runLoadTable);
STEP(runPkRead);
STEP(runPkRead);
STEP(runPkRead);
STEP(runPkUpdate);
STEP(runPkUpdate);
STEP(runPkUpdate);
FINALIZER(runClearTable);
}
TESTCASE("PkReadAndLocker",
"Verify that we can read although there are "\
" a number of 1 second locks in the table"){
INITIALIZER(runLoadTable);
STEP(runPkReadUntilStopped);
STEP(runLocker);
FINALIZER(runClearTable);
}
TESTCASE("PkReadAndLocker2",
"Verify that we can read and update although there are "\
" a number of 1 second locks in the table"){
INITIALIZER(runLoadTable);
STEP(runPkReadUntilStopped);
STEP(runPkReadUntilStopped);
STEP(runPkReadUntilStopped);
STEP(runPkReadUntilStopped);
STEP(runPkReadUntilStopped);
STEP(runPkReadUntilStopped);
STEP(runLocker);
FINALIZER(runClearTable);
}
TESTCASE("PkReadUpdateAndLocker",
"Verify that we can read and update although there are "\
" a number of 1 second locks in the table"){
INITIALIZER(runLoadTable);
STEP(runPkReadUntilStopped);
STEP(runPkReadUntilStopped);
STEP(runPkUpdateUntilStopped);
STEP(runPkUpdateUntilStopped);
STEP(runLocker);
FINALIZER(runClearTable);
}
TESTCASE("ReadWithLocksAndInserts",
"TR457: This test is added to verify that an insert of a records "\
"that is already in the database does not delete the record"){
INITIALIZER(runLoadTable);
STEP(runPkReadUntilStopped);
STEP(runPkReadUntilStopped);
STEP(runLocker);
STEP(runInsertUntilStopped);
FINALIZER(runClearTable);
}
TESTCASE("PkInsertTwice",
"Verify that we can't insert an already inserted record."
"Error should be returned" ){
INITIALIZER(runLoadTable);
STEP(runInsertTwice);
FINALIZER(runClearTable);
}
TESTCASE("NoCommitSleep",
"Verify what happens when a NoCommit transaction is aborted by "
"NDB because the application is sleeping" ){
INITIALIZER(runLoadTable);
INITIALIZER(runNoCommitSleep);
FINALIZER(runClearTable2);
}
TESTCASE("Commit626",
"Verify what happens when a Commit transaction is aborted by "
"NDB because the record does no exist" ){
INITIALIZER(runClearTable2);
INITIALIZER(runCommit626);
FINALIZER(runClearTable2);
}
TESTCASE("CommitTry626",
"Verify what happens when a Commit(TryCommit) \n"
"transaction is aborted by "
"NDB because the record does no exist" ){
INITIALIZER(runClearTable2);
INITIALIZER(runCommit_TryCommit626);
FINALIZER(runClearTable2);
}
TESTCASE("CommitAsMuch626",
"Verify what happens when a Commit(CommitAsMuchAsPossible) \n"
"transaction is aborted by\n"
"NDB because the record does no exist" ){
INITIALIZER(runClearTable2);
INITIALIZER(runCommit_CommitAsMuchAsPossible626);
FINALIZER(runClearTable2);
}
TESTCASE("NoCommit626",
"Verify what happens when a NoCommit transaction is aborted by "
"NDB because the record does no exist" ){
INITIALIZER(runClearTable2);
INITIALIZER(runNoCommit626);
FINALIZER(runClearTable2);
}
TESTCASE("NoCommitRollback626",
"Verify what happens when a NoCommit transaction is aborted by "
"NDB because the record does no exist and then we try to rollback\n"
"the transaction" ){
INITIALIZER(runClearTable2);
INITIALIZER(runNoCommitRollback626);
FINALIZER(runClearTable2);
}
TESTCASE("Commit630",
"Verify what happens when a Commit transaction is aborted by "
"NDB because the record already exist" ){
INITIALIZER(runLoadTable);
INITIALIZER(runCommit630);
FINALIZER(runClearTable2);
}
TESTCASE("CommitTry630",
"Verify what happens when a Commit(TryCommit) \n"
"transaction is aborted by "
"NDB because the record already exist" ){
INITIALIZER(runLoadTable);
INITIALIZER(runCommit_TryCommit630);
FINALIZER(runClearTable2);
}
TESTCASE("CommitAsMuch630",
"Verify what happens when a Commit(CommitAsMuchAsPossible) \n"
"transaction is aborted by\n"
"NDB because the record already exist" ){
INITIALIZER(runLoadTable);
INITIALIZER(runCommit_CommitAsMuchAsPossible630);
FINALIZER(runClearTable2);
}
TESTCASE("NoCommit630",
"Verify what happens when a NoCommit transaction is aborted by "
"NDB because the record already exist" ){
INITIALIZER(runLoadTable);
INITIALIZER(runNoCommit630);
FINALIZER(runClearTable2);
}
TESTCASE("NoCommitRollback630",
"Verify what happens when a NoCommit transaction is aborted by "
"NDB because the record already exist and then we try to rollback\n"
"the transaction" ){
INITIALIZER(runLoadTable);
INITIALIZER(runNoCommitRollback630);
FINALIZER(runClearTable2);
}
TESTCASE("NoCommitAndClose",
"Verify what happens when a NoCommit transaction is closed "
"without rolling back the transaction " ){
INITIALIZER(runLoadTable);
INITIALIZER(runNoCommitAndClose);
FINALIZER(runClearTable2);
}
TESTCASE("RollbackDelete",
"Test rollback of a no committed delete"){
INITIALIZER(runLoadTable);
INITIALIZER(runCheckRollbackDelete);
FINALIZER(runClearTable2);
}
TESTCASE("RollbackUpdate",
"Test rollback of a no committed update"){
INITIALIZER(runLoadTable);
INITIALIZER(runCheckRollbackUpdate);
FINALIZER(runClearTable2);
}
TESTCASE("RollbackDeleteMultiple",
"Test rollback of 10 non committed delete"){
INITIALIZER(runLoadTable);
INITIALIZER(runCheckRollbackDeleteMultiple);
FINALIZER(runClearTable2);
}
TESTCASE("ImplicitRollbackDelete",
"Test close transaction after a no commited delete\n"
"this would give an implicit rollback of the delete\n"){
INITIALIZER(runLoadTable);
INITIALIZER(runCheckImplicitRollbackDelete);
FINALIZER(runClearTable2);
}
TESTCASE("CommitDelete",
"Test close transaction after a no commited delete\n"
"this would give an implicit rollback of the delete\n"){
INITIALIZER(runLoadTable);
INITIALIZER(runCheckCommitDelete);
FINALIZER(runClearTable2);
}
TESTCASE("RollbackNothing",
"Test rollback of nothing"){
INITIALIZER(runLoadTable);
INITIALIZER(runRollbackNothing);
FINALIZER(runClearTable2);
}
TESTCASE("MassiveRollback",
"Test rollback of 4096 operations"){
INITIALIZER(runClearTable2);
INITIALIZER(runMassiveRollback);
FINALIZER(runClearTable2);
}
TESTCASE("MassiveRollback2",
"Test rollback of 4096 operations"){
INITIALIZER(runClearTable2);
INITIALIZER(runMassiveRollback2);
FINALIZER(runClearTable2);
}
TESTCASE("MassiveRollback3",
"Test rollback of 4096 operations"){
INITIALIZER(runClearTable2);
STEP(runMassiveRollback3);
STEP(runMassiveRollback3);
FINALIZER(runClearTable2);
}
TESTCASE("MassiveRollback4",
"Test rollback of 4096 operations"){
INITIALIZER(runClearTable2);
STEP(runMassiveRollback4);
STEP(runMassiveRollback4);
FINALIZER(runClearTable2);
}
TESTCASE("MassiveTransaction",
"Test very large insert transaction"){
INITIALIZER(runLoadTable2);
FINALIZER(runClearTable2);
}
TESTCASE("TupError",
"Verify what happens when we fill the db" ){
INITIALIZER(runTupErrors);
}
TESTCASE("InsertError", "" ){
INITIALIZER(runInsertError);
}
TESTCASE("InsertError2", "" ){
INITIALIZER(runInsertError2);
}
TESTCASE("Fill",
"Verify what happens when we fill the db" ){
STEP(runFillTable);
}
TESTCASE("Bug25090",
"Verify what happens when we fill the db" ){
STEP(runBug25090);
}
TESTCASE("DeleteRead",
"Verify Delete+Read" ){
INITIALIZER(runLoadTable);
INITIALIZER(runDeleteRead);
FINALIZER(runClearTable2);
}
TESTCASE("Bug27756",
"Verify what happens when we fill the db" ){
STEP(runBug27756);
}
TESTCASE("Bug28073",
"Infinite loop in lock queue" ){
STEP(runBug28073);
}
TESTCASE("Bug20535",
"Verify what happens when we fill the db" ){
STEP(runBug20535);
}
TESTCASE("DDInsertFailUpdateBatch",
"Verify DD insert failure effect on other ops in batch on same PK"){
STEP(runDDInsertFailUpdateBatch);
}
TESTCASE("Bug34348",
"Test fragment directory range full in ACC.\n"
"NOTE: If interrupted, must clear error insert 3002 manually"){
STEP(runBug34348);
}
TESTCASE("UnlockBatch",
"Test that batched unlock operations work ok"){
TC_PROPERTY("Batchsize", 33);
INITIALIZER(runLoadTable);
STEP(runUnlocker);
FINALIZER(runClearTable);
}
TESTCASE("DoubleUnlock",
"Test that batched unlock operations work ok"){
TC_PROPERTY("DoubleUnlock", 1);
INITIALIZER(runLoadTable);
STEP(runUnlocker);
FINALIZER(runClearTable);
}
TESTCASE("UnlockUpdateBatch",
"Test Unlock mixed with Update"){
TC_PROPERTY("Batchsize", 32);
INITIALIZER(runLoadTable);
STEP(runUnlocker);
STEP(runUnlocker);
STEP(runLocker);
STEP(runPkUpdate);
STEP(runPkUpdate);
STEP(runPkRead);
FINALIZER(runClearTable);
}
TESTCASE("RefreshTuple",
"Test refreshTuple() operation properties"){
INITIALIZER(initSubscription);
INITIALIZER(runRefreshTuple);
FINALIZER(removeSubscription);
}
TESTCASE("Bug54986", "")
{
INITIALIZER(runBug54986);
}
TESTCASE("Bug54944", "")
{
TC_PROPERTY("DATABUFFER", (Uint32)0);
INITIALIZER(runBug54944);
}
TESTCASE("Bug54944DATABUFFER", "")
{
TC_PROPERTY("DATABUFFER", (Uint32)1);
INITIALIZER(runBug54944);
}
TESTCASE("Bug59496_case1", "")
{
STEP(runBug59496_case1);
STEPS(runBug59496_scan, 10);
}
TESTCASE("Bug59496_case2", "")
{
TC_PROPERTY("CHECK_ROWCOUNT", 1);
INITIALIZER(runLoadTable);
STEP(runBug59496_case2);
STEPS(runBug59496_scan, 10);
}
TESTCASE("899", "")
{
INITIALIZER(runLoadTable);
INITIALIZER(runInit899);
STEP(runTest899);
FINALIZER(runEnd899);
}
TESTCASE("LeakApiConnectObjects", "")
{
INITIALIZER(runLeakApiConnectObjects);
}
TESTCASE("RefreshLocking",
"Test Refresh locking properties")
{
INITIALIZER(runRefreshLocking);
}
TESTCASE("BugXXX","")
{
INITIALIZER(runBugXXX_init);
STEP(runBugXXX_createIndex);
STEP(runBugXXX_trans);
}
TESTCASE("Bug16834333","")
{
INITIALIZER(runBug16834333);
}
TESTCASE("DeleteNdbInFlight","")
{
INITIALIZER(runDeleteNdbInFlight);
}
TESTCASE("FillQueueREDOLog",
"Verify that we can handle a REDO log queue situation")
{
INITIALIZER(insertError5083);
STEP(runLoadTableFail);
FINALIZER(clearError5083);
}
TESTCASE("AccCommitOrder",
"Bug19031389. MT kernel crash on deleted tuple in read*-delete.")
{
TC_PROPERTY("OPSTEPS", (Uint32)2);
TC_PROPERTY("RUN", (Uint32)0);
TC_PROPERTY("RUNNING", (Uint32)0);
STEP(runAccCommitOrder);
STEPS(runAccCommitOrderOps, 2);
}
TESTCASE("DeleteNdbWhilePoll",
"Delete an Ndb while it(trp_clnt) is in poll queue. Will crash the test, and thus not to be run in a regular test" ){
INITIALIZER(runInsertOneTuple);
STEP(runLockTuple);
STEP(runReadLockedTuple);
STEP(deleteNdbWhileWaiting);
FINALIZER(runClearTable2);
}
TESTCASE("AbortRace",
"Test race between ABORT and PREPARE processing at LDM")
{
INITIALIZER(runLoadTable);
STEP(testAbortRace);
FINALIZER(runClearTable);
}
TESTCASE("CheckCompletedLCPStats",
"Check if the LCP'd #records is equal to "
"nReplicas * #records inserted" )
{
STEP(runCheckLCPStats);
}
TESTCASE("ParallelReadUpdate",
"Test interaction of read and updates for Query Thread")
{
TC_PROPERTY("Records", Uint32(10));
INITIALIZER(runLoadTable);
STEP(runPkUpdateUntilStopped);
STEP(runPkUpdateUntilStopped);
STEP(runPkDirtyReadUntilStopped);
STEP(runPkDirtyReadUntilStopped);
STEP(runPkDirtyReadUntilStopped);
STEP(runPkDirtyReadUntilStopped);
STEP(runTimer);
FINALIZER(runClearTable);
}
NDBT_TESTSUITE_END(testBasic)
#if 0
TESTCASE("ReadConsistency",
"Check that a read within a transaction returns the " \
"same result no matter"){
STEP(runInsertOne);
STEP(runReadOne);
FINALIZER(runClearTable2);
}
TESTCASE("Fill",
"Verify what happens when we fill the db" ){
INITIALIZER(runFillTable);
INITIALIZER(runPkRead);
FINALIZER(runClearTable2);
}
#endif
int main(int argc, const char** argv){
ndb_init();
NDBT_TESTSUITE_INSTANCE(testBasic);
return testBasic.execute(argc, argv);
}
| 28.062487 | 141 | 0.630551 | [
"object",
"vector"
] |
9cc61c09f05a38fdfe96bcbee0105256f1ed2600 | 7,022 | hpp | C++ | include/seqan3/alphabet/composite/detail.hpp | qPCR4vir/seqan3 | 67ebf427dc1d49fb55e684acc108ed75d224f5d4 | [
"CC-BY-4.0",
"CC0-1.0"
] | null | null | null | include/seqan3/alphabet/composite/detail.hpp | qPCR4vir/seqan3 | 67ebf427dc1d49fb55e684acc108ed75d224f5d4 | [
"CC-BY-4.0",
"CC0-1.0"
] | null | null | null | include/seqan3/alphabet/composite/detail.hpp | qPCR4vir/seqan3 | 67ebf427dc1d49fb55e684acc108ed75d224f5d4 | [
"CC-BY-4.0",
"CC0-1.0"
] | null | null | null | // -----------------------------------------------------------------------------------------------------
// Copyright (c) 2006-2020, Knut Reinert & Freie Universität Berlin
// Copyright (c) 2016-2020, Knut Reinert & MPI für molekulare Genetik
// This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License
// shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md
// -----------------------------------------------------------------------------------------------------
/*!\file
* \author Hannes Hauswedell <hannes.hauswedell AT fu-berlin.de>
* \brief Provides implementation detail for seqan3::alphabet_variant and seqan3::alphabet_tuple_base.
*/
#pragma once
#include <seqan3/alphabet/concept.hpp>
#include <seqan3/utility/detail/exposition_only_concept.hpp>
#include <seqan3/utility/type_list/type_list.hpp>
#include <seqan3/utility/type_traits/lazy_conditional.hpp>
namespace seqan3::detail
{
// ------------------------------------------------------------------
// alphabet_tuple_like
// ------------------------------------------------------------------
/*!\interface seqan3::detail::alphabet_tuple_like <>
* \brief seqan3::alphabet_tuple_base and its derivates model this concept.
* \ingroup composite
*
* \details
*
* This concept is necessary/helpful, because CRTP-specialisations cannot easily be tracked via regular inheritance or
* specialisation mechanisms.
*/
//!\cond
template <typename t>
SEQAN3_CONCEPT alphabet_tuple_like = requires
{
requires t::seqan3_alphabet_tuple_like;
};
//!\endcond
// ------------------------------------------------------------------
// required_types
// ------------------------------------------------------------------
/*!\brief A seqan3::type_list with types that the given type depends on.
* \implements seqan3::transformation_trait
* \ingroup composite
*
* \details
*
* The list is empty by default. This trait maybe used in metaprogramming to indicate that certain types need to be
* complete and not depend on the given type to avoid recursive template instantiation.
*/
template <typename t>
struct required_types
{
//!\brief The returned type.
using type = type_list<>;
};
/*!\brief A seqan3::type_list with types that the given type depends on.
* [specialisation for seqan3::alphabet_variant and derivates of seqan3::alphabet_tuple_base].
* \implements seqan3::transformation_trait
* \ingroup composite
*
* \details
*
* Exposes for seqan3::alphabet_tuple_base its components and for seqan3::alphabet_variant its alternatives.
*/
template <typename t>
//!\cond
requires requires { typename t::seqan3_required_types; }
//!\endcond
struct required_types<t>
{
//!\brief The returned type.
using type = typename t::seqan3_required_types;
};
/*!\brief A seqan3::type_list with types that the given type depends on. [Trait shortcut]
* \relates seqan3::detail::required_types
*/
template <typename t>
using required_types_t = typename required_types<t>::type;
// ------------------------------------------------------------------
// recursive_required_types
// ------------------------------------------------------------------
//TODO: This can be replaced with metaprogramming magic once a few more functions land in list_traits.
/*!\brief Like seqan3::detail::required_types, but recursive.
* \implements seqan3::transformation_trait
* \ingroup composite
*/
template <typename t>
struct recursive_required_types
{
//!\brief The returned type.
using type = type_list<>;
};
/*!\brief Like seqan3::detail::required_types, but recursive.
* \implements seqan3::transformation_trait
* \ingroup composite
*/
template <typename t>
//!\cond
requires requires
{
typename t::seqan3_recursive_required_types;
}
//!\endcond
struct recursive_required_types<t>
{
//!\brief The returned type.
using type = typename t::seqan3_recursive_required_types;
};
/*!\brief Shortcut for seqan3::detail::recursive_required_types.
* \relates seqan3::detail::recursive_required_types
*/
template <typename t>
using recursive_required_types_t = typename recursive_required_types<t>::type;
// ------------------------------------------------------------------
// Callable concept helpers for meta::invoke
// ------------------------------------------------------------------
/*!\brief 'Callable' helper class that is invokable by meta::invoke.
* Returns an std::true_type if the `type` is constructable from `T`.
*/
template <typename T>
struct constructible_from
{
//!\brief The returned type when invoked.
template <typename type>
using invoke = std::integral_constant<bool, std::is_constructible_v<type, T>>;
};
/*!\brief 'Callable' helper class that is invokable by meta::invoke.
* Returns an std::true_type if the `T` is implicitly convertible to `type`.
*/
template <typename T>
struct implicitly_convertible_from
{
//!\brief The returned type when invoked.
template <typename type>
using invoke = std::integral_constant<bool, implicitly_convertible_to<T, type>>;
};
/*!\brief 'Callable' helper class that is invokable by meta::invoke.
* Returns an std::true_type if the `type` is assignable from `T`.
*/
template <typename T>
struct assignable_from
{
//!\brief The returned type when invoked.
template <typename type>
using invoke = std::integral_constant<bool, weakly_assignable_from<type, T>>;
};
/*!\brief 'Callable' helper class that is invokable by meta::invoke.
* Returns an std::true_type if the `type` is weakly equality comparable to `T`.
*/
template <typename T>
struct weakly_equality_comparable_with_
{
//!\brief The returned type when invoked.
template <typename type>
using invoke = std::integral_constant<bool, weakly_equality_comparable_with<type, T>>;
};
/*!\brief 'Callable' helper class that is invokable by meta::invoke.
* Returns an std::true_type if the `type` is comparable via <,<=,>,>= to `T`.
*/
template <typename T>
struct weakly_ordered_with_
{
//!\brief The returned type when invoked.
template <typename type>
using invoke = std::integral_constant<bool, weakly_ordered_with<type, T>>;
};
} // namespace seqan3::detail
// ------------------------------------------------------------------
// Forwards
// ------------------------------------------------------------------
namespace seqan3
{
// forward
template <typename ...alternative_types>
//!\cond
requires (detail::writable_constexpr_alphabet<alternative_types> && ...) &&
(std::regular<alternative_types> && ...) &&
(sizeof...(alternative_types) >= 2)
//TODO same char_type
//!\endcond
class alphabet_variant;
template <typename derived_type,
typename ...component_types>
//!\cond
requires (detail::writable_constexpr_semialphabet<component_types> && ...) &&
(std::regular<component_types> && ...)
//!\endcond
class alphabet_tuple_base;
} // namespace seqan3
| 32.509259 | 118 | 0.63771 | [
"model"
] |
9cc6b6e36d1a50001f5cfd48114249e16faf3903 | 7,009 | hpp | C++ | spike/models/mineral/MineralStore.hpp | davidson16807/libtectonics | aa0ae2b8a4a1d2a9a346bbdeb334be876ad75646 | [
"CC-BY-4.0"
] | 7 | 2020-06-09T19:56:55.000Z | 2021-02-17T01:53:30.000Z | spike/models/mineral/MineralStore.hpp | davidson16807/tectonics.cpp | c40278dba14260c598764467c7abf23b190e676b | [
"CC-BY-4.0"
] | null | null | null | spike/models/mineral/MineralStore.hpp | davidson16807/tectonics.cpp | c40278dba14260c598764467c7abf23b190e676b | [
"CC-BY-4.0"
] | null | null | null | #pragma once
// C libraries
#include <cstdint>
// std libraries
#include <algorithm>
#include <array>
// in-house libraries
#include <units/si.hpp>
#include "Mineral.hpp"
namespace mineral
{
namespace
{
const float epsilon(1e-4f);
enum struct Phases
{
supercritical,
gas,
liquid,
solid
};
}
/*
`MineralStore` is a memory efficient variant of the
`Mineral` data structure. Isn't it adorable!?
It would take ridiculous amounts of memory to store a `Mineral`
for every mineral within a raster, so we store each mineral in a raster
as a `MineralStore`, then convert back to `Mineral` when
we want to perform some operation on it.
The interpretation of attributes within `MineralStore` is error prone,
so to prevent users from doing so we encapsulate the class.
The interpretation of attributes also comes with some performance penalty,
so to encourage users not to spam calls to getters,
we only expose methods to convert to and from `StratumStore`.
This also grants a certain mathematical purity to the object,
since in the spirit of category theory the object at high level can be
treated strictly by its mappings to other states,
which in this case are isomorphic to within precision requirements and therefore invertible.
*/
class MineralStore
{
float mass;
std::uint8_t phase_id : 4;
std::uint8_t unweathered_extrusive_part_count : 4;
std::uint8_t unweathered_intrusive_part_count : 4;
std::uint8_t mechanically_weathered_extrusive_part_count : 4;
std::uint8_t mechanically_weathered_intrusive_part_count : 4;
std::uint8_t chemically_weathered_extrusive_part_count : 4;
std::uint8_t chemically_weathered_intrusive_part_count : 4;
std::uint8_t unused : 4;
public:
~MineralStore()
{
}
// convenience constructor, equivalent to pack()
MineralStore(Mineral& output)
{
pack(output);
}
// identity constructor
MineralStore():
mass(0),
phase_id(std::uint8_t(Phases::solid)),
unweathered_extrusive_part_count(1),
unweathered_intrusive_part_count(1),
mechanically_weathered_extrusive_part_count(1),
mechanically_weathered_intrusive_part_count(1),
chemically_weathered_extrusive_part_count(1),
chemically_weathered_intrusive_part_count(1),
unused(1)
{
}
void unpack(Mineral& output) const
{
output.mass = mass * si::kilogram;
output.phase_id = phase_id;
float total_relative_volume(epsilon);
total_relative_volume += unweathered_extrusive_part_count ;
total_relative_volume += unweathered_intrusive_part_count ;
total_relative_volume += mechanically_weathered_extrusive_part_count;
total_relative_volume += mechanically_weathered_intrusive_part_count;
total_relative_volume += chemically_weathered_extrusive_part_count ;
total_relative_volume += chemically_weathered_intrusive_part_count ;
const float scaling_factor(1.0f / total_relative_volume);
output.grain_type_relative_volume[0] = unweathered_extrusive_part_count * scaling_factor;
output.grain_type_relative_volume[1] = unweathered_intrusive_part_count * scaling_factor;
output.grain_type_relative_volume[2] = mechanically_weathered_extrusive_part_count * scaling_factor;
output.grain_type_relative_volume[3] = mechanically_weathered_intrusive_part_count * scaling_factor;
output.grain_type_relative_volume[4] = chemically_weathered_extrusive_part_count * scaling_factor;
output.grain_type_relative_volume[5] = chemically_weathered_intrusive_part_count * scaling_factor;
}
void pack(const Mineral& input)
{
mass = input.mass / si::kilogram;
phase_id = std::clamp(input.phase_id, 0u, 15u);
// rescale bin counts by the new max to fit inside a uint8_t
float grain_type_relative_volume_max(epsilon);
grain_type_relative_volume_max = std::max(grain_type_relative_volume_max, input.grain_type_relative_volume[0]);
grain_type_relative_volume_max = std::max(grain_type_relative_volume_max, input.grain_type_relative_volume[1]);
grain_type_relative_volume_max = std::max(grain_type_relative_volume_max, input.grain_type_relative_volume[2]);
grain_type_relative_volume_max = std::max(grain_type_relative_volume_max, input.grain_type_relative_volume[3]);
grain_type_relative_volume_max = std::max(grain_type_relative_volume_max, input.grain_type_relative_volume[4]);
grain_type_relative_volume_max = std::max(grain_type_relative_volume_max, input.grain_type_relative_volume[5]);
const float max_part_count(15.0f);
float scaling_factor(max_part_count / grain_type_relative_volume_max);
unweathered_extrusive_part_count = std::clamp(std::round(input.grain_type_relative_volume[0] * scaling_factor), 0.0f, max_part_count);
unweathered_intrusive_part_count = std::clamp(std::round(input.grain_type_relative_volume[1] * scaling_factor), 0.0f, max_part_count);
mechanically_weathered_extrusive_part_count = std::clamp(std::round(input.grain_type_relative_volume[2] * scaling_factor), 0.0f, max_part_count);
mechanically_weathered_intrusive_part_count = std::clamp(std::round(input.grain_type_relative_volume[3] * scaling_factor), 0.0f, max_part_count);
chemically_weathered_extrusive_part_count = std::clamp(std::round(input.grain_type_relative_volume[4] * scaling_factor), 0.0f, max_part_count);
chemically_weathered_intrusive_part_count = std::clamp(std::round(input.grain_type_relative_volume[5] * scaling_factor), 0.0f, max_part_count);
}
/*
void unpack(Mineral& output) const
{
output.mass = mass;
float total_relative_volume(0);
for (std::size_t i=0; i<6; i++)
{
total_relative_volume += grain_type_relative_volume[i];
}
for (std::size_t i=0; i<6; i++)
{
output.grain_type_relative_volume[i] = grain_type_relative_volume[i] / total_relative_volume;
}
}
void pack(const Mineral& input)
{
mass = input.mass;
// rescale bin counts by the new max to fit inside a uint8_t
float grain_type_relative_volume_max(epsilon);
for (std::size_t i=0; i<6; i++)
{
grain_type_relative_volume_max = std::max(grain_type_relative_volume_max, input.grain_type_relative_volume[i]);
}
const float max_part_count(255.0f);
float scaling_factor(max_part_count / grain_type_relative_volume_max);
for (std::size_t i=0; i<6; i++)
{
grain_type_relative_volume[i] =
std::clamp(input.grain_type_relative_volume[i] * scaling_factor, 0.0f, max_part_count);
}
}
*/
};
}
| 44.360759 | 157 | 0.711086 | [
"object",
"solid"
] |
9ccb6b9856185c1cebe64b37c4a33da5e853f0ae | 7,364 | hpp | C++ | include/db/sqldb_pgsql_extension.hpp | TinkerLuoxs/sqlconnection | 50f05c13d1392f5b42b545e52346581681e6c29b | [
"Apache-2.0"
] | 1 | 2017-11-09T09:39:22.000Z | 2017-11-09T09:39:22.000Z | include/db/sqldb_pgsql_extension.hpp | TinkerLuoxs/sqlconnection | 50f05c13d1392f5b42b545e52346581681e6c29b | [
"Apache-2.0"
] | null | null | null | include/db/sqldb_pgsql_extension.hpp | TinkerLuoxs/sqlconnection | 50f05c13d1392f5b42b545e52346581681e6c29b | [
"Apache-2.0"
] | null | null | null | //
// Created by Luoxs on 2017-03-16
//
#pragma once
namespace sql
{
/// support for composites, arrays and composite arrays
/// serialization.hpp required to include.
namespace db_pgsql_extension
{
class composite
{
public:
class decoder;
class encoder;
template <typename T>
static void from_string(T&& t, const char *reply)
{
decoder dec(reply);
dec.read(t);
}
template <typename T>
static std::string to_string(T&& t)
{
std::string result;
{
encoder enc(result);
enc.write(t);
}
return std::move(result);
}
};
class composite::encoder
{
public:
explicit encoder(std::string& reply) : _iter(reply)
{
}
~encoder()
{
remove();
}
template <typename T>
std::enable_if_t<std::is_arithmetic<T>::value> write(T const& t)
{
_iter += std::to_string(t);
_iter += ",";
}
template <typename T>
std::enable_if_t<has_series<T>::value> write(T const& t)
{
_iter += "\"(";
serialize::foreach([this](auto &&elem) {this->write(elem); }, t);
remove();
_iter += ")\",";
}
template <typename T>
void write(std::vector<T> const& t)
{
_iter += "{";
for (auto& i : t)
write(i);
remove();
_iter += "},";
}
void write(std::string const& v)
{
#if 0
bool q = v.find(' ') == std::string::npos;
if (!q)
{
_iter += "\\\"";
_iter += v;
_iter += "\\\",";
}
else
{
_iter += v;
_iter += ",";
}
#endif
_iter += v;
_iter += ",";
}
private:
void remove()
{
if (_iter.back() == ',')
_iter.pop_back();
}
std::string& _iter;
};
class composite::decoder
{
public:
explicit decoder(const char *reply) : _iter(reply), _array_count(0),
_field_head(nullptr), _field_tail(nullptr)
{
}
template <typename T>
std::enable_if_t<std::is_arithmetic<T>::value> read(T& t)
{
if (!read_field())
return;
if (_field_tail == _field_head)
memset(&t, 0, sizeof(t));
else
read_field_impl(t);
}
void read(std::string& v)
{
if (read_field())
read_field_impl(v);
}
template <typename T>
std::enable_if_t<has_series<T>::value> read(T& t)
{
serialize::foreach([this](auto &&elem) {this->read(elem); }, t);
}
template <typename T>
void read(std::vector<T>& t)
{
int count = -1;
do
{
if (!next_array(count))
break;
t.emplace_back();
auto& last = t.back();
serialize::foreach([this](auto &&elem) { this->read(elem); }, last);
} while (true);
}
private:
template <typename T>
std::enable_if_t<std::is_integral<T>::value> read_field_impl(T& val)
{
char *end;
val = static_cast<T>(std::strtoll(_field_head, &end, 10));
}
template <typename T>
std::enable_if_t<std::is_floating_point<T>::value> read_field_impl(T& val)
{
char *end;
val = static_cast<T>(std::strtold(_field_head, &end));
}
void read_field_impl(std::string& val)
{
val.assign(_field_head, _field_tail);
}
bool next_array(int& count)
{
while (*_iter)
{
switch (*_iter)
{
case '{':
if (count < 0) count = _array_count;
++_array_count;
++_iter;
return true;
case '}':
--_array_count;
++_iter;
break;
case ',':
++_iter;
if (_array_count > 0)
return count < _array_count;
return false;
case ' ': case '(': case ')': case '\\': case '\"':
++_iter;
break;
default:
return false;
}
}
return false;
}
bool next_field()
{
bool nvl = false;
while (*_iter)
{
switch (*_iter)
{
case ' ': case '(': case ')': case '\\': case '\"':
++_iter;
break;
case ',':
if (nvl)
return true;
++_iter;
nvl = true;
break;
case '{':
++_array_count;
++_iter;
break;
case '}':
--_array_count;
++_iter;
break;
case '\0':
return false;
default:
return true;
}
}
return false;
}
bool read_field()
{
if (!next_field())
return false;
_field_tail = _field_head = _iter;
while (consume(*_iter))
++_iter;
return true;
}
bool consume(char c)
{
switch (c)
{
case '\0': case '{': case '}': case ',':
case '(': case ')': case '\\': case '\"':
_field_tail = _iter;
return false;
default:
return true;
}
}
int _array_count;
const char *_iter;
const char *_field_head;
const char *_field_tail;
};
}
} | 27.580524 | 88 | 0.332564 | [
"vector"
] |
9ccc6d7c5bea260d7f2833f0ac56265d76234de5 | 1,301 | cpp | C++ | ch5_strategies_decoration_and_statistics/StatsMain1.cpp | WongYatChun/Design_Patterns_and_Derivatives_Pricing | 4aa8fa6794f70b086e66c1a8752a596b448cd8d8 | [
"MIT"
] | null | null | null | ch5_strategies_decoration_and_statistics/StatsMain1.cpp | WongYatChun/Design_Patterns_and_Derivatives_Pricing | 4aa8fa6794f70b086e66c1a8752a596b448cd8d8 | [
"MIT"
] | null | null | null | ch5_strategies_decoration_and_statistics/StatsMain1.cpp | WongYatChun/Design_Patterns_and_Derivatives_Pricing | 4aa8fa6794f70b086e66c1a8752a596b448cd8d8 | [
"MIT"
] | null | null | null | /*
Uses source files
MCStatistics.cpp
Parameters.cpp
PayOff3.cpp
PayOffBridge.cpp
Random1.cpp
SimleMC7.cpp
Vanilla3.cpp
*/
#include "SimpleMC7.h"
#include "Vanilla3.h"
#include "MCStatistics.h"
#include <iostream>
using namespace std;
int main(){
double Expiry;
double Strike;
double Spot;
double Vol;
double r;
unsigned long NumberOfPaths;
cout << "\nEnter expiry\n";
cin >> Expiry;
cout << "\nEnter Strike\n";
cin >> Strike;
cout << "\nEnter Spot\n";
cin >> Spot;
cout << "\nEnter vol\n";
cin >> Vol;
cout << "\nEnter r\n";
cin >> r;
cout << "\nEnter Number Of Paths\n";
cin >> NumberOfPaths;
PayOffCall thePayOff(Strike);
VanillaOption theOption(thePayOff, Expiry);
ParametersConstant VolParam(Vol);
ParametersConstant rParam(r);
StatisticsMean gatherer;
SimpleMonteCarlo5(theOption, Spot, VolParam, rParam, NumberOfPaths, gatherer);
vector<vector<double>> results = gatherer.GetResultsSoFar();
cout << "\nFor the call price the results are \n";
for(unsigned long i = 0; i < results.size(); i++){
for (unsigned long j = 0; j < results[i].size(); j++)
cout << results[i][j] << " ";
cout << "\n";
}
return 0;
} | 20.015385 | 82 | 0.605688 | [
"vector"
] |
9ccd5bc610e8a33f44e7a4012b2d49367757a396 | 2,690 | cpp | C++ | external_codes/boost_multi/multi/examples/lu_fact.cpp | djstaros/qmcpack | 280f67e638bae280448b47fa618f05b848c530d2 | [
"NCSA"
] | null | null | null | external_codes/boost_multi/multi/examples/lu_fact.cpp | djstaros/qmcpack | 280f67e638bae280448b47fa618f05b848c530d2 | [
"NCSA"
] | 11 | 2020-05-09T20:57:21.000Z | 2020-06-10T00:00:17.000Z | external_codes/boost_multi/multi/examples/lu_fact.cpp | djstaros/qmcpack | 280f67e638bae280448b47fa618f05b848c530d2 | [
"NCSA"
] | null | null | null | #ifdef COMPILATION// -*-indent-tabs-mode:t;c-basic-offset:4;tab-width:4;-*-
$CXX $0 -o $0x -lboost_timer `pkg-config --libs tbb` &&$0x&&rm $0x;exit
#endif
// © Alfredo A. Correa 2018-2020
#include "../../multi/array.hpp"
#include<numeric> // iota
#include<algorithm> // transform
#include<execution>
namespace multi = boost::multi;
template<class Matrix>
Matrix&& lu_fact(Matrix&& A){
using multi::size;
auto m = size(A);// n = size(A[0]);//std::get<1>(sizes(A));
using std::begin; using std::end; using multi::rotated;
for(auto k = 0*m; k != std::min(m - 1, size(rotated(A))); ++k){
auto const& Ak = A[k];
auto const& Akk = Ak[k];
std::for_each(std::execution::par,
begin(A) + k + 1, end(A), [&](auto&& Ai){
std::transform(
begin(Ai)+k+1, end(Ai), begin(Ak)+k+1, begin(Ai)+k+1,
[z=(Ai[k]/=Akk)](auto&& a, auto&& b){return a-z*b;}
);
}
);
}
return std::forward<Matrix>(A);
}
template<class Matrix>
Matrix&& lu_fact2(Matrix&& A){
using multi::size;
auto m = A.size(), n = std::get<1>(sizes(A));
for(auto k = 0*m; k != m - 1; ++k){
for(auto i = k + 1; i != m; ++i){
auto const z = A[i][k]/A[k][k];
A[i][k] = z;
std::transform(begin(A[i]) + k + 1, begin(A[i]) + std::max(n, k + 1), A[k].begin() + k + 1, begin(A[i]) + k + 1, [&](auto&& a, auto&& b){return a - z*b;});
}
}
return std::forward<Matrix>(A);
}
template<class Matrix>
Matrix&& lu_fact3(Matrix&& A){
using multi::size;
auto m = A.size(), n = std::get<1>(sizes(A));
for(auto k = 0*m; k != m - 1; ++k){
auto&& Ak = A[k];
std::for_each(std::execution::par, begin(A) + k + 1, end(A), [&](auto&& Ai){
auto const z = Ai[k]/Ak[k];
Ai[k] = z;
assert( k + 1 <= n );
for(auto j = k + 1; j < n; ++j) Ai[j] -= z*Ak[j];
});
}
return std::forward<Matrix>(A);
}
#include<boost/timer/timer.hpp>
#include<iostream>
using std::cout;
int main(){
{
multi::array<double, 2> A = {
{-3., 2., -4.},
{ 0., 1., 2.},
{ 2., 4., 5.}
};
multi::array<double, 1> y = {12.,5.,2.};
double AA[3][3];
using std::copy;
copy( begin(A), end(A), begin(*multi::array_ptr(&AA)) );
lu_fact(A);
lu_fact(AA);
using std::equal; using std::begin;
assert( equal(begin(A), end(A), begin(*multi::array_ptr(&AA))) );
}
// return 0;
{
multi::array<double, 2> A({6000, 7000}); std::iota(A.data(), A.data() + A.num_elements(), 0.1);
std::transform(A.data(), A.data() + A.num_elements(), A.data(), [](auto x){return x/=2.e6;});
// std::vector<double> y(3000); std::iota(y.begin(), y.end(), 0.2);
{
boost::timer::auto_cpu_timer t;
lu_fact(A({3000, 6000}, {0, 4000}));
cout << A[456][123] << std::endl;
}
// cout << y[45] << std::endl;
}
}
| 26.9 | 159 | 0.547955 | [
"vector",
"transform"
] |
9cd18acdcf15ee0eb8301f11de557727277f6e2c | 29,656 | cpp | C++ | nvvk/appbase_vk.cpp | theHamsta/nvpro_core | 46d28f10aac7f951256ed759cf47fc44615a4f81 | [
"Apache-2.0"
] | null | null | null | nvvk/appbase_vk.cpp | theHamsta/nvpro_core | 46d28f10aac7f951256ed759cf47fc44615a4f81 | [
"Apache-2.0"
] | null | null | null | nvvk/appbase_vk.cpp | theHamsta/nvpro_core | 46d28f10aac7f951256ed759cf47fc44615a4f81 | [
"Apache-2.0"
] | 1 | 2021-07-25T19:30:40.000Z | 2021-07-25T19:30:40.000Z | /*
* Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-FileCopyrightText: Copyright (c) 2014-2021 NVIDIA CORPORATION
* SPDX-License-Identifier: Apache-2.0
*/
#include "nvvk/appbase_vk.hpp"
#ifndef PROJECT_NAME
#define PROJECT_NAME "AppBaseVk"
#endif
//--------------------------------------------------------------------------------------------------
// Setup the low level Vulkan for various operations
//
void nvvk::AppBaseVk::setup(const VkInstance& instance, const VkDevice& device, const VkPhysicalDevice& physicalDevice, uint32_t graphicsQueueIndex)
{
m_instance = instance;
m_device = device;
m_physicalDevice = physicalDevice;
m_graphicsQueueIndex = graphicsQueueIndex;
vkGetDeviceQueue(m_device, m_graphicsQueueIndex, 0, &m_queue);
VkCommandPoolCreateInfo poolCreateInfo{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO};
poolCreateInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
vkCreateCommandPool(m_device, &poolCreateInfo, nullptr, &m_cmdPool);
VkPipelineCacheCreateInfo pipelineCacheInfo{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO};
vkCreatePipelineCache(m_device, &pipelineCacheInfo, nullptr, &m_pipelineCache);
ImGuiH::SetCameraJsonFile(PROJECT_NAME);
}
//--------------------------------------------------------------------------------------------------
// To call on exit
//
void nvvk::AppBaseVk::destroy()
{
vkDeviceWaitIdle(m_device);
if(ImGui::GetCurrentContext() != nullptr)
{
//ImGui::ShutdownVK();
ImGui_ImplVulkan_Shutdown();
ImGui::DestroyContext();
}
vkDestroyRenderPass(m_device, m_renderPass, nullptr);
vkDestroyImageView(m_device, m_depthView, nullptr);
vkDestroyImage(m_device, m_depthImage, nullptr);
vkFreeMemory(m_device, m_depthMemory, nullptr);
vkDestroyPipelineCache(m_device, m_pipelineCache, nullptr);
for(uint32_t i = 0; i < m_swapChain.getImageCount(); i++)
{
vkDestroyFence(m_device, m_waitFences[i], nullptr);
vkDestroyFramebuffer(m_device, m_framebuffers[i], nullptr);
vkFreeCommandBuffers(m_device, m_cmdPool, 1, &m_commandBuffers[i]);
}
m_swapChain.deinit();
vkDestroyDescriptorPool(m_device, m_imguiDescPool, nullptr);
vkDestroyCommandPool(m_device, m_cmdPool, nullptr);
if(m_surface)
{
vkDestroySurfaceKHR(m_instance, m_surface, nullptr);
}
}
//--------------------------------------------------------------------------------------------------
// Return the surface "screen" for the display
//
VkSurfaceKHR nvvk::AppBaseVk::getVkSurface(const VkInstance& instance, GLFWwindow* window)
{
assert(instance);
m_window = window;
VkSurfaceKHR surface{};
VkResult err = glfwCreateWindowSurface(instance, window, nullptr, &surface);
if(err != VK_SUCCESS)
{
assert(!"Failed to create a Window surface");
}
m_surface = surface;
return surface;
}
//--------------------------------------------------------------------------------------------------
// Creating the surface for rendering
//
void nvvk::AppBaseVk::createSwapchain(const VkSurfaceKHR& surface,
uint32_t width,
uint32_t height,
VkFormat colorFormat /*= VK_FORMAT_B8G8R8A8_UNORM*/,
VkFormat depthFormat /*= VK_FORMAT_UNDEFINED*/,
bool vsync /*= false*/)
{
m_size = VkExtent2D{width, height};
m_colorFormat = colorFormat;
m_depthFormat = depthFormat;
m_vsync = vsync;
// Find the most suitable depth format
if(m_depthFormat == VK_FORMAT_UNDEFINED)
{
auto feature = VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT;
for(const auto& f : {VK_FORMAT_D24_UNORM_S8_UINT, VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D16_UNORM_S8_UINT})
{
VkFormatProperties formatProp{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2};
vkGetPhysicalDeviceFormatProperties(m_physicalDevice, f, &formatProp);
if((formatProp.optimalTilingFeatures & feature) == feature)
{
m_depthFormat = f;
break;
}
}
}
m_swapChain.init(m_device, m_physicalDevice, m_queue, m_graphicsQueueIndex, surface, static_cast<VkFormat>(colorFormat));
m_size = m_swapChain.update(m_size.width, m_size.height, vsync);
m_colorFormat = static_cast<VkFormat>(m_swapChain.getFormat());
// Create Synchronization Primitives
m_waitFences.resize(m_swapChain.getImageCount());
for(auto& fence : m_waitFences)
{
VkFenceCreateInfo fenceCreateInfo{VK_STRUCTURE_TYPE_FENCE_CREATE_INFO};
fenceCreateInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
vkCreateFence(m_device, &fenceCreateInfo, nullptr, &fence);
}
// Command buffers store a reference to the frame buffer inside their render pass info
// so for static usage without having to rebuild them each frame, we use one per frame buffer
VkCommandBufferAllocateInfo allocateInfo{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO};
allocateInfo.commandPool = m_cmdPool;
allocateInfo.commandBufferCount = m_swapChain.getImageCount();
allocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
m_commandBuffers.resize(m_swapChain.getImageCount());
vkAllocateCommandBuffers(m_device, &allocateInfo, m_commandBuffers.data());
#ifdef _DEBUG
for(size_t i = 0; i < m_commandBuffers.size(); i++)
{
std::string name = std::string("AppBase") + std::to_string(i);
VkDebugUtilsObjectNameInfoEXT nameInfo{VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT};
nameInfo.objectHandle = (uint64_t)m_commandBuffers[i];
nameInfo.objectType = VK_OBJECT_TYPE_COMMAND_BUFFER;
nameInfo.pObjectName = name.c_str();
vkSetDebugUtilsObjectNameEXT(m_device, &nameInfo);
}
#endif // _DEBUG
// Setup camera
CameraManip.setWindowSize(m_size.width, m_size.height);
}
//--------------------------------------------------------------------------------------------------
// Create all the framebuffers in which the image will be rendered
// - Swapchain need to be created before calling this
//
void nvvk::AppBaseVk::createFrameBuffers()
{
// Recreate the frame buffers
for(auto framebuffer : m_framebuffers)
{
vkDestroyFramebuffer(m_device, framebuffer, nullptr);
}
// Array of attachment (color, depth)
std::array<VkImageView, 2> attachments{};
// Create frame buffers for every swap chain image
VkFramebufferCreateInfo framebufferCreateInfo{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO};
framebufferCreateInfo.renderPass = m_renderPass;
framebufferCreateInfo.attachmentCount = 2;
framebufferCreateInfo.width = m_size.width;
framebufferCreateInfo.height = m_size.height;
framebufferCreateInfo.layers = 1;
framebufferCreateInfo.pAttachments = attachments.data();
// Create frame buffers for every swap chain image
m_framebuffers.resize(m_swapChain.getImageCount());
for(uint32_t i = 0; i < m_swapChain.getImageCount(); i++)
{
attachments[0] = m_swapChain.getImageView(i);
attachments[1] = m_depthView;
vkCreateFramebuffer(m_device, &framebufferCreateInfo, nullptr, &m_framebuffers[i]);
}
#ifdef _DEBUG
for(size_t i = 0; i < m_framebuffers.size(); i++)
{
std::string name = std::string("AppBase") + std::to_string(i);
VkDebugUtilsObjectNameInfoEXT nameInfo{VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT};
nameInfo.objectHandle = (uint64_t)m_framebuffers[i];
nameInfo.objectType = VK_OBJECT_TYPE_FRAMEBUFFER;
nameInfo.pObjectName = name.c_str();
vkSetDebugUtilsObjectNameEXT(m_device, &nameInfo);
}
#endif // _DEBUG
}
//--------------------------------------------------------------------------------------------------
// Creating a default render pass, very simple one.
// Other examples will mostly override this one.
//
void nvvk::AppBaseVk::createRenderPass()
{
if(m_renderPass)
{
vkDestroyRenderPass(m_device, m_renderPass, nullptr);
}
std::array<VkAttachmentDescription, 2> attachments{};
// Color attachment
attachments[0].format = m_colorFormat;
attachments[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachments[0].finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
attachments[0].samples = VK_SAMPLE_COUNT_1_BIT;
// Depth attachment
attachments[1].format = m_depthFormat;
attachments[1].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachments[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachments[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
attachments[1].samples = VK_SAMPLE_COUNT_1_BIT;
// One color, one depth
const VkAttachmentReference colorReference{0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL};
const VkAttachmentReference depthReference{1, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL};
std::array<VkSubpassDependency, 1> subpassDependencies{};
// Transition from final to initial (VK_SUBPASS_EXTERNAL refers to all commands executed outside of the actual renderpass)
subpassDependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL;
subpassDependencies[0].dstSubpass = 0;
subpassDependencies[0].srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
subpassDependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
subpassDependencies[0].srcAccessMask = VK_ACCESS_MEMORY_READ_BIT;
subpassDependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
subpassDependencies[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
VkSubpassDescription subpassDescription{};
subpassDescription.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpassDescription.colorAttachmentCount = 1;
subpassDescription.pColorAttachments = &colorReference;
subpassDescription.pDepthStencilAttachment = &depthReference;
VkRenderPassCreateInfo renderPassInfo{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO};
renderPassInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
renderPassInfo.pAttachments = attachments.data();
renderPassInfo.subpassCount = 1;
renderPassInfo.pSubpasses = &subpassDescription;
renderPassInfo.dependencyCount = static_cast<uint32_t>(subpassDependencies.size());
renderPassInfo.pDependencies = subpassDependencies.data();
vkCreateRenderPass(m_device, &renderPassInfo, nullptr, &m_renderPass);
#ifdef _DEBUG
VkDebugUtilsObjectNameInfoEXT nameInfo{VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT};
nameInfo.objectHandle = (uint64_t)m_renderPass;
nameInfo.objectType = VK_OBJECT_TYPE_RENDER_PASS;
nameInfo.pObjectName = R"(AppBaseVk)";
vkSetDebugUtilsObjectNameEXT(m_device, &nameInfo);
#endif // _DEBUG
}
//--------------------------------------------------------------------------------------------------
// Creating an image to be used as depth buffer
//
void nvvk::AppBaseVk::createDepthBuffer()
{
if(m_depthView)
vkDestroyImageView(m_device, m_depthView, nullptr);
if(m_depthImage)
vkDestroyImage(m_device, m_depthImage, nullptr);
if(m_depthMemory)
vkFreeMemory(m_device, m_depthMemory, nullptr);
// Depth information
const VkImageAspectFlags aspect = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
VkImageCreateInfo depthStencilCreateInfo{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
depthStencilCreateInfo.imageType = VK_IMAGE_TYPE_2D;
depthStencilCreateInfo.extent = VkExtent3D{m_size.width, m_size.height, 1};
depthStencilCreateInfo.format = m_depthFormat;
depthStencilCreateInfo.mipLevels = 1;
depthStencilCreateInfo.arrayLayers = 1;
depthStencilCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT;
depthStencilCreateInfo.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
// Create the depth image
vkCreateImage(m_device, &depthStencilCreateInfo, nullptr, &m_depthImage);
// Allocate the memory
VkMemoryRequirements memReqs;
vkGetImageMemoryRequirements(m_device, m_depthImage, &memReqs);
VkMemoryAllocateInfo memAllocInfo{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
memAllocInfo.allocationSize = memReqs.size;
memAllocInfo.memoryTypeIndex = getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
vkAllocateMemory(m_device, &memAllocInfo, nullptr, &m_depthMemory);
// Bind image and memory
vkBindImageMemory(m_device, m_depthImage, m_depthMemory, 0);
// Create an image barrier to change the layout from undefined to DepthStencilAttachmentOptimal
VkCommandBufferAllocateInfo allocateInfo{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO};
allocateInfo.commandBufferCount = 1;
allocateInfo.commandPool = m_cmdPool;
allocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
VkCommandBuffer cmdBuffer;
vkAllocateCommandBuffers(m_device, &allocateInfo, &cmdBuffer);
VkCommandBufferBeginInfo beginInfo{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer(cmdBuffer, &beginInfo);
// Put barrier on top, Put barrier inside setup command buffer
VkImageSubresourceRange subresourceRange{};
subresourceRange.aspectMask = aspect;
subresourceRange.levelCount = 1;
subresourceRange.layerCount = 1;
VkImageMemoryBarrier imageMemoryBarrier{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
imageMemoryBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
imageMemoryBarrier.newLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
imageMemoryBarrier.image = m_depthImage;
imageMemoryBarrier.subresourceRange = subresourceRange;
imageMemoryBarrier.srcAccessMask = VkAccessFlags();
imageMemoryBarrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
const VkPipelineStageFlags srcStageMask = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
const VkPipelineStageFlags destStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
vkCmdPipelineBarrier(cmdBuffer, srcStageMask, destStageMask, VK_FALSE, 0, nullptr, 0, nullptr, 1, &imageMemoryBarrier);
vkEndCommandBuffer(cmdBuffer);
VkSubmitInfo submitInfo{VK_STRUCTURE_TYPE_SUBMIT_INFO};
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &cmdBuffer;
vkQueueSubmit(m_queue, 1, &submitInfo, {});
vkQueueWaitIdle(m_queue);
vkFreeCommandBuffers(m_device, m_cmdPool, 1, &cmdBuffer);
// Setting up the view
VkImageViewCreateInfo depthStencilView{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
depthStencilView.viewType = VK_IMAGE_VIEW_TYPE_2D;
depthStencilView.format = m_depthFormat;
depthStencilView.subresourceRange = subresourceRange;
depthStencilView.image = m_depthImage;
vkCreateImageView(m_device, &depthStencilView, nullptr, &m_depthView);
}
//--------------------------------------------------------------------------------------------------
// Convenient function to call before rendering.
// Waits for a framebuffer to be available
//
void nvvk::AppBaseVk::prepareFrame()
{
// Resize protection - should be cached by the glFW callback
int w, h;
glfwGetFramebufferSize(m_window, &w, &h);
if(w != (int)m_size.width || h != (int)m_size.height)
{
onFramebufferSize(w, h);
}
// Acquire the next image from the swap chain
if(!m_swapChain.acquire())
{
assert(!"This shouldn't happen");
}
// Use a fence to wait until the command buffer has finished execution before using it again
uint32_t imageIndex = m_swapChain.getActiveImageIndex();
VkResult result = vkWaitForFences(m_device, 1, &m_waitFences[imageIndex], VK_TRUE, ~0);
assert(result == VK_SUCCESS);
}
//--------------------------------------------------------------------------------------------------
// Convenient function to call for submitting the rendering command
// Sending the command buffer of the current frame and add a fence to know when it will be free to use
//
void nvvk::AppBaseVk::submitFrame()
{
uint32_t imageIndex = m_swapChain.getActiveImageIndex();
vkResetFences(m_device, 1, &m_waitFences[imageIndex]);
// In case of using NVLINK
const uint32_t deviceMask = m_useNvlink ? 0b0000'0011 : 0b0000'0001;
const std::array<uint32_t, 2> deviceIndex = {0, 1};
VkDeviceGroupSubmitInfo deviceGroupSubmitInfo{VK_STRUCTURE_TYPE_DEVICE_GROUP_SUBMIT_INFO_KHR};
deviceGroupSubmitInfo.waitSemaphoreCount = 1;
deviceGroupSubmitInfo.commandBufferCount = 1;
deviceGroupSubmitInfo.pCommandBufferDeviceMasks = &deviceMask;
deviceGroupSubmitInfo.signalSemaphoreCount = m_useNvlink ? 2 : 1;
deviceGroupSubmitInfo.pSignalSemaphoreDeviceIndices = deviceIndex.data();
deviceGroupSubmitInfo.pWaitSemaphoreDeviceIndices = deviceIndex.data();
VkSemaphore semaphoreRead = m_swapChain.getActiveReadSemaphore();
VkSemaphore semaphoreWrite = m_swapChain.getActiveWrittenSemaphore();
// Pipeline stage at which the queue submission will wait (via pWaitSemaphores)
const VkPipelineStageFlags waitStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
// The submit info structure specifies a command buffer queue submission batch
VkSubmitInfo submitInfo{VK_STRUCTURE_TYPE_SUBMIT_INFO};
submitInfo.pWaitDstStageMask = &waitStageMask; // Pointer to the list of pipeline stages that the semaphore waits will occur at
submitInfo.pWaitSemaphores = &semaphoreRead; // Semaphore(s) to wait upon before the submitted command buffer starts executing
submitInfo.waitSemaphoreCount = 1; // One wait semaphore
submitInfo.pSignalSemaphores = &semaphoreWrite; // Semaphore(s) to be signaled when command buffers have completed
submitInfo.signalSemaphoreCount = 1; // One signal semaphore
submitInfo.pCommandBuffers = &m_commandBuffers[imageIndex]; // Command buffers(s) to execute in this batch (submission)
submitInfo.commandBufferCount = 1; // One command buffer
submitInfo.pNext = &deviceGroupSubmitInfo;
// Submit to the graphics queue passing a wait fence
vkQueueSubmit(m_queue, 1, &submitInfo, m_waitFences[imageIndex]);
// Presenting frame
m_swapChain.present(m_queue);
}
//--------------------------------------------------------------------------------------------------
// When the pipeline is set for using dynamic, this becomes useful
//
void nvvk::AppBaseVk::setViewport(const VkCommandBuffer& cmdBuf)
{
VkViewport viewport{0.0f, 0.0f, static_cast<float>(m_size.width), static_cast<float>(m_size.height), 0.0f, 1.0f};
vkCmdSetViewport(cmdBuf, 0, 1, &viewport);
VkRect2D scissor{{0, 0}, {m_size.width, m_size.height}};
vkCmdSetScissor(cmdBuf, 0, 1, &scissor);
}
//--------------------------------------------------------------------------------------------------
// Window callback when the it is resized
// - Destroy allocated frames, then rebuild them with the new size
// - Call onResize() of the derived class
//
void nvvk::AppBaseVk::onFramebufferSize(int w, int h)
{
if(w == 0 || h == 0)
{
return;
}
// Update imgui
if(ImGui::GetCurrentContext() != nullptr)
{
auto& imgui_io = ImGui::GetIO();
imgui_io.DisplaySize = ImVec2(static_cast<float>(w), static_cast<float>(h));
}
// Wait to finish what is currently drawing
vkDeviceWaitIdle(m_device);
vkQueueWaitIdle(m_queue);
// Request new swapchain image size
m_size = m_swapChain.update(m_size.width, m_size.height, m_vsync);
if(m_size.width != w || m_size.height != h)
{
LOGW("Requested size (%d, %d) is different from created size (%u, %u) ", w, h, m_size.width, m_size.height);
}
CameraManip.setWindowSize(m_size.width, m_size.height);
// Invoking Sample callback
onResize(m_size.width, m_size.height); // <-- to implement on derived class
// Recreating other resources
createDepthBuffer();
createFrameBuffers();
}
//--------------------------------------------------------------------------------------------------
// Window callback when the mouse move
// - Handling ImGui and a default camera
//
void nvvk::AppBaseVk::onMouseMotion(int x, int y)
{
if(ImGui::GetCurrentContext() != nullptr && ImGui::GetIO().WantCaptureMouse)
{
return;
}
if(m_inputs.lmb || m_inputs.rmb || m_inputs.mmb)
{
CameraManip.mouseMove(x, y, m_inputs);
}
}
//--------------------------------------------------------------------------------------------------
// Window callback when a special key gets hit
// - Handling ImGui and a default camera
//
void nvvk::AppBaseVk::onKeyboard(int key, int scancode, int action, int mods)
{
const bool capture = ImGui::GetCurrentContext() != nullptr && ImGui::GetIO().WantCaptureKeyboard;
const bool pressed = action != GLFW_RELEASE;
// Keeping track of the modifiers
m_inputs.ctrl = mods & GLFW_MOD_CONTROL;
m_inputs.shift = mods & GLFW_MOD_SHIFT;
m_inputs.alt = mods & GLFW_MOD_ALT;
// Remember all keys that are pressed for animating the camera when
// many keys are pressed and stop when all keys are released.
if(pressed)
{
m_keys.insert(key);
}
else
{
m_keys.erase(key);
}
// For all pressed keys - apply the action
CameraManip.keyMotion(0, 0, nvh::CameraManipulator::NoAction);
for(auto key : m_keys)
{
switch(key)
{
case GLFW_KEY_F10:
m_show_gui = !m_show_gui;
break;
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(m_window, 1);
break;
default:
break;
}
// Allow camera movement only when not editing
if(!capture)
{
switch(key)
{
case GLFW_KEY_W:
CameraManip.keyMotion(1.f, 0, nvh::CameraManipulator::Dolly);
break;
case GLFW_KEY_S:
CameraManip.keyMotion(-1.f, 0, nvh::CameraManipulator::Dolly);
break;
case GLFW_KEY_A:
case GLFW_KEY_LEFT:
CameraManip.keyMotion(-1.f, 0, nvh::CameraManipulator::Pan);
break;
case GLFW_KEY_UP:
CameraManip.keyMotion(0, 1, nvh::CameraManipulator::Pan);
break;
case GLFW_KEY_D:
case GLFW_KEY_RIGHT:
CameraManip.keyMotion(1.f, 0, nvh::CameraManipulator::Pan);
break;
case GLFW_KEY_DOWN:
CameraManip.keyMotion(0, -1, nvh::CameraManipulator::Pan);
break;
default:
break;
}
}
}
}
//--------------------------------------------------------------------------------------------------
// Window callback when a key gets hit
//
void nvvk::AppBaseVk::onKeyboardChar(unsigned char key)
{
if(ImGui::GetCurrentContext() != nullptr && ImGui::GetIO().WantCaptureKeyboard)
{
return;
}
// Toggling vsync
if(key == 'v')
{
m_vsync = !m_vsync;
vkDeviceWaitIdle(m_device);
vkQueueWaitIdle(m_queue);
m_swapChain.update(m_size.width, m_size.height, m_vsync);
createFrameBuffers();
}
if(key == 'h' || key == '?')
m_showHelp = !m_showHelp;
}
//--------------------------------------------------------------------------------------------------
// Window callback when the mouse button is pressed
// - Handling ImGui and a default camera
//
void nvvk::AppBaseVk::onMouseButton(int button, int action, int mods)
{
(void)mods;
double x, y;
glfwGetCursorPos(m_window, &x, &y);
CameraManip.setMousePosition(static_cast<int>(x), static_cast<int>(y));
m_inputs.lmb = (button == GLFW_MOUSE_BUTTON_LEFT) && (action == GLFW_PRESS);
m_inputs.mmb = (button == GLFW_MOUSE_BUTTON_MIDDLE) && (action == GLFW_PRESS);
m_inputs.rmb = (button == GLFW_MOUSE_BUTTON_RIGHT) && (action == GLFW_PRESS);
}
//--------------------------------------------------------------------------------------------------
// Window callback when the mouse wheel is modified
// - Handling ImGui and a default camera
//
void nvvk::AppBaseVk::onMouseWheel(int delta)
{
if(ImGui::GetCurrentContext() != nullptr && ImGui::GetIO().WantCaptureMouse)
{
return;
}
CameraManip.wheel(delta > 0 ? 1 : -1, m_inputs);
}
//--------------------------------------------------------------------------------------------------
// Initialization of the GUI
// - Need to be call after the device creation
//
void nvvk::AppBaseVk::initGUI(uint32_t subpassID /*= 0*/)
{
assert(m_renderPass && "Render Pass must be set");
// UI
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
io.IniFilename = nullptr; // Avoiding the INI file
io.LogFilename = nullptr;
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking
//io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows
ImGuiH::setStyle();
ImGuiH::setFonts();
std::vector<VkDescriptorPoolSize> poolSize{{VK_DESCRIPTOR_TYPE_SAMPLER, 1}, {VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1}};
VkDescriptorPoolCreateInfo poolInfo{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO};
poolInfo.maxSets = 2;
poolInfo.poolSizeCount = 2;
poolInfo.pPoolSizes = poolSize.data();
vkCreateDescriptorPool(m_device, &poolInfo, nullptr, &m_imguiDescPool);
// Setup Platform/Renderer back ends
ImGui_ImplVulkan_InitInfo init_info = {};
init_info.Instance = m_instance;
init_info.PhysicalDevice = m_physicalDevice;
init_info.Device = m_device;
init_info.QueueFamily = m_graphicsQueueIndex;
init_info.Queue = m_queue;
init_info.PipelineCache = VK_NULL_HANDLE;
init_info.DescriptorPool = m_imguiDescPool;
init_info.Subpass = subpassID;
init_info.MinImageCount = 2;
init_info.ImageCount = static_cast<int>(m_framebuffers.size());
init_info.MSAASamples = VK_SAMPLE_COUNT_1_BIT; // <--- need argument?
init_info.CheckVkResultFn = nullptr;
init_info.Allocator = nullptr;
ImGui_ImplVulkan_Init(&init_info, m_renderPass);
// Upload Fonts
VkCommandBufferAllocateInfo allocateInfo{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO};
allocateInfo.commandBufferCount = 1;
allocateInfo.commandPool = m_cmdPool;
allocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
VkCommandBuffer cmdbuf;
vkAllocateCommandBuffers(m_device, &allocateInfo, &cmdbuf);
VkCommandBufferBeginInfo beginInfo{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer(cmdbuf, &beginInfo);
ImGui_ImplVulkan_CreateFontsTexture(cmdbuf);
vkEndCommandBuffer(cmdbuf);
VkSubmitInfo submitInfo{VK_STRUCTURE_TYPE_SUBMIT_INFO};
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &cmdbuf;
vkQueueSubmit(m_queue, 1, &submitInfo, {});
vkQueueWaitIdle(m_queue);
vkFreeCommandBuffers(m_device, m_cmdPool, 1, &cmdbuf);
}
//--------------------------------------------------------------------------------------------------
// Fit the camera to the Bounding box
//
void nvvk::AppBaseVk::fitCamera(const nvmath::vec3f& boxMin, const nvmath::vec3f& boxMax, bool instantFit /*= true*/)
{
CameraManip.fit(boxMin, boxMax, instantFit, false, m_size.width / static_cast<float>(m_size.height));
}
//--------------------------------------------------------------------------------------------------
// Return true if the window is minimized
//
bool nvvk::AppBaseVk::isMinimized(bool doSleeping /*= true*/)
{
int w, h;
glfwGetWindowSize(m_window, &w, &h);
bool minimized(w == 0 || h == 0);
if(minimized && doSleeping)
{
#ifdef _WIN32
Sleep(50);
#else
usleep(50);
#endif
}
return minimized;
}
void nvvk::AppBaseVk::setupGlfwCallbacks(GLFWwindow* window)
{
m_window = window;
glfwSetWindowUserPointer(window, this);
glfwSetKeyCallback(window, &key_cb);
glfwSetCharCallback(window, &char_cb);
glfwSetCursorPosCallback(window, &cursorpos_cb);
glfwSetMouseButtonCallback(window, &mousebutton_cb);
glfwSetScrollCallback(window, &scroll_cb);
glfwSetFramebufferSizeCallback(window, &framebuffersize_cb);
glfwSetDropCallback(window, &drop_cb);
}
uint32_t nvvk::AppBaseVk::getMemoryType(uint32_t typeBits, const VkMemoryPropertyFlags& properties) const
{
VkPhysicalDeviceMemoryProperties memoryProperties;
vkGetPhysicalDeviceMemoryProperties(m_physicalDevice, &memoryProperties);
for(uint32_t i = 0; i < memoryProperties.memoryTypeCount; i++)
{
if(((typeBits & (1 << i)) > 0) && (memoryProperties.memoryTypes[i].propertyFlags & properties) == properties)
{
return i;
}
}
std::string err = "Unable to find memory type " + std::to_string(properties);
LOGE(err.c_str());
assert(0);
return ~0u;
}
void nvvk::AppBaseVk::uiDisplayHelp()
{
if(m_showHelp)
{
ImGui::BeginChild("Help", ImVec2(370, 120), true);
ImGui::Text("%s", CameraManip.getHelp().c_str());
ImGui::EndChild();
}
}
| 38.315245 | 148 | 0.684786 | [
"render",
"vector"
] |
9cd56003b6d0b963aadd06b08c1442c29bb12a34 | 697 | cpp | C++ | trunk/day36/solution.cpp | itsjacob/90pp | eca71e624d28d216feb06d615e587fc6792c36b6 | [
"MIT"
] | null | null | null | trunk/day36/solution.cpp | itsjacob/90pp | eca71e624d28d216feb06d615e587fc6792c36b6 | [
"MIT"
] | null | null | null | trunk/day36/solution.cpp | itsjacob/90pp | eca71e624d28d216feb06d615e587fc6792c36b6 | [
"MIT"
] | null | null | null | #define sortArray_ countingSort
class Solution
{
public:
vector<int> sortArray(vector<int> &nums) { return sortArray_(nums); }
private:
std::vector<int> countingSort(std::vector<int> &nums)
{
std::vector<int> res;
int constexpr MIN_VAL{ -50000 };
int constexpr MAX_VAL{ 50000 };
std::vector<int> countTable(MAX_VAL - MIN_VAL + 1, 0);
for (auto const &num : nums) {
countTable[num - MIN_VAL]++;
}
for (int ii = 0; ii < countTable.size(); ii++) {
if (countTable[ii] == 0) continue;
// record current number count times
for (int jj = 0; jj < countTable[ii]; jj++) {
res.push_back(ii + MIN_VAL);
}
}
return res;
}
};
| 24.892857 | 71 | 0.601148 | [
"vector"
] |
9cda6c1980ae57a2047ac12e4e9c583d7ff22dac | 335 | cpp | C++ | Binary Trees/14_diagonal_traversal.cpp | ritikrajdev/450DSA | a9efa8c8be781fd7b101407ac807a83b8a0929f4 | [
"MIT"
] | null | null | null | Binary Trees/14_diagonal_traversal.cpp | ritikrajdev/450DSA | a9efa8c8be781fd7b101407ac807a83b8a0929f4 | [
"MIT"
] | null | null | null | Binary Trees/14_diagonal_traversal.cpp | ritikrajdev/450DSA | a9efa8c8be781fd7b101407ac807a83b8a0929f4 | [
"MIT"
] | null | null | null | vector<int> diagonal(Node *root)
{
vector<int> v;
queue <Node*> q;
q.push(root);
while (q.size()) {
Node* itr = q.front();
while (itr) {
v.push_back(itr->data);
if (itr->left) q.push(itr->left);
itr = itr->right;
}
q.pop();
}
return v;
}
| 18.611111 | 45 | 0.432836 | [
"vector"
] |
9cdbec8d0cffe30593b464d7925864bb0d999a6c | 977 | cc | C++ | test/runtime.cc | mberaha/bayesmix | 4448f0e9f69ac71f3aacc11a239e3114790c1aaa | [
"BSD-3-Clause"
] | 17 | 2020-10-13T16:45:06.000Z | 2022-03-22T13:50:42.000Z | test/runtime.cc | mberaha/bayesmix | 4448f0e9f69ac71f3aacc11a239e3114790c1aaa | [
"BSD-3-Clause"
] | 90 | 2020-10-26T09:49:37.000Z | 2022-03-29T07:23:38.000Z | test/runtime.cc | mberaha/bayesmix | 4448f0e9f69ac71f3aacc11a239e3114790c1aaa | [
"BSD-3-Clause"
] | 15 | 2020-11-17T06:52:40.000Z | 2022-02-15T12:08:47.000Z | // Checks that all the combinations of Algorithms, Mixings and Hierarchies
// can be combined into a sampleable model.
#include <gtest/gtest.h>
#include "src/includes.h"
TEST(can_build, allmodels) {
auto &factory_algo = AlgorithmFactory::Instance();
auto &factory_hier = HierarchyFactory::Instance();
auto &factory_mixing = MixingFactory::Instance();
for (auto &algo_id : factory_algo.list_of_known_builders()) {
auto algo = factory_algo.create_object(algo_id);
for (auto &mix_id : factory_mixing.list_of_known_builders()) {
auto mix = factory_mixing.create_object(mix_id);
algo->set_mixing(mix);
for (auto &hier_id : factory_hier.list_of_known_builders()) {
auto hier = factory_hier.create_object(hier_id);
if (hier->is_conjugate() & algo->requires_conjugate_hierarchy())
algo->set_hierarchy(hier);
else if (!algo->requires_conjugate_hierarchy())
algo->set_hierarchy(hier);
}
}
}
}
| 34.892857 | 74 | 0.700102 | [
"model"
] |
9cdff111d76abe3bddd5cf2b2216bd59e4ecf260 | 11,168 | cpp | C++ | Source/SVWidgetsLib/FilterParameterWidgets/ShapeTypeSelectionWidget.cpp | mmarineBlueQuartz/SIMPL | 834f9009944efe69d94b5b77a641d96db3e9543b | [
"NRL"
] | null | null | null | Source/SVWidgetsLib/FilterParameterWidgets/ShapeTypeSelectionWidget.cpp | mmarineBlueQuartz/SIMPL | 834f9009944efe69d94b5b77a641d96db3e9543b | [
"NRL"
] | 2 | 2019-02-23T20:46:12.000Z | 2019-07-11T15:34:13.000Z | Source/SVWidgetsLib/FilterParameterWidgets/ShapeTypeSelectionWidget.cpp | mmarineBlueQuartz/SIMPL | 834f9009944efe69d94b5b77a641d96db3e9543b | [
"NRL"
] | null | null | null | /* ============================================================================
* Copyright (c) 2009-2016 BlueQuartz Software, LLC
*
* 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 BlueQuartz Software, the US Air Force, nor the names of its
* contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The code contained herein was partially funded by the followig contracts:
* United States Air Force Prime Contract FA8650-07-D-5800
* United States Air Force Prime Contract FA8650-10-D-5210
* United States Prime Contract Navy N00173-07-C-2068
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
#include "ShapeTypeSelectionWidget.h"
#include <QtCore/QList>
#include <QtCore/QMetaProperty>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QLabel>
#include "SIMPLib/Common/ShapeType.h"
#include "SIMPLib/DataArrays/StringDataArray.h"
#include "SIMPLib/DataContainers/DataArrayPath.h"
#include "SIMPLib/FilterParameters/ShapeTypeSelectionFilterParameter.h"
#include "SIMPLib/Filtering/QMetaObjectUtilities.h"
#include "SVWidgetsLib/Core/SVWidgetsLibConstants.h"
#include "FilterParameterWidgetsDialogs.h"
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
ShapeTypeSelectionWidget::ShapeTypeSelectionWidget(FilterParameter* parameter, AbstractFilter* filter, QWidget* parent)
: FilterParameterWidget(parameter, filter, parent)
, m_DidCausePreflight(false)
{
m_FilterParameter = dynamic_cast<ShapeTypeSelectionFilterParameter*>(parameter);
Q_ASSERT_X(m_FilterParameter != nullptr, "NULL Pointer", "ShapeTypeSelectionWidget can ONLY be used with a ShapeTypeSelectionFilterParameter object");
setupUi(this);
setupGui();
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
ShapeTypeSelectionWidget::ShapeTypeSelectionWidget(QWidget* parent)
: FilterParameterWidget(nullptr, nullptr, parent)
, m_DidCausePreflight(false)
{
setupUi(this);
setupGui();
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
ShapeTypeSelectionWidget::~ShapeTypeSelectionWidget() = default;
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void ShapeTypeSelectionWidget::setupGui()
{
if(getFilter() == nullptr)
{
return;
}
// Catch when the filter is about to execute the preflight
connect(getFilter(), SIGNAL(preflightAboutToExecute()), this, SLOT(beforePreflight()));
// Catch when the filter is finished running the preflight
connect(getFilter(), SIGNAL(preflightExecuted()), this, SLOT(afterPreflight()));
// Catch when the filter wants its values updated
connect(getFilter(), SIGNAL(updateFilterParameters(AbstractFilter*)), this, SLOT(filterNeedsInputParameters(AbstractFilter*)));
if(getFilterParameter() == nullptr)
{
return;
}
label->setText(getFilterParameter()->getHumanLabel());
updateComboBoxes();
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void ShapeTypeSelectionWidget::updateComboBoxes()
{
StringDataArray::Pointer names = StringDataArray::NullPointer();
// If there is a PhaseName array in the Ensemble AttributeMatrix then use that to
// label the QComboBoxes.
AbstractFilter* filter = getFilter();
if(filter != nullptr)
{
DataArrayPath phasePath = getFilter()->property("InputPhaseTypesArrayPath").value<DataArrayPath>();
phasePath.setDataArrayName("PhaseName");
DataContainer::Pointer dc = filter->getDataContainerArray()->getDataContainer(phasePath);
if(dc)
{
AttributeMatrix::Pointer am = dc->getAttributeMatrix(phasePath);
if(am)
{
names = am->getAttributeArrayAs<StringDataArray>("PhaseName");
}
}
}
bool ok = false;
// setup the list of choices for the widget
ShapeTypeSelectionFilterParameter* shapeType = dynamic_cast<ShapeTypeSelectionFilterParameter*>(getFilterParameter());
QString countProp = shapeType->getPhaseTypeCountProperty();
int numPhases = getFilter()->property(countProp.toLatin1().constData()).toInt(&ok);
if(!ok)
{
numPhases = 0;
}
ShapeType::Types shapeTypesFromFilter = getFilter()->property(PROPERTY_NAME_AS_CHAR).value<ShapeType::Types>();
if (shapeTypesFromFilter.size() > 1 && numPhases <= 0)
{
numPhases = shapeTypesFromFilter.size();
}
// Get our list of predefined Shape Type Strings
QVector<QString> shapeTypeStrings;
ShapeType::getShapeTypeStrings(shapeTypeStrings);
// Pop the back value off because it will invariably allow us to walk off the end of an array
shapeTypeStrings.pop_back();
shapeTypeStrings.pop_back();
// Get our list of predefined enumeration values
ShapeType::Types shapeTypeEnums;
ShapeType::getShapeTypeEnums(shapeTypeEnums);
shapeTypeEnums.pop_back();
shapeTypeEnums.pop_back();
// We skip the first Ensemble as it is always a dummy
QLabel* shapeTypeLabel = nullptr;
QComboBox* shapeTypeComboBox = nullptr;
for(int i = 1; i < numPhases; i++)
{
shapeTypeLabel = nullptr;
shapeTypeComboBox = nullptr;
if(i > m_ShapeTypeLabels.size() )
{
shapeTypeLabel = new QLabel(m_ShapeTypeScrollContents);
QString str;
if((names.get() != nullptr) && names->getNumberOfTuples() > 0)
{
str = names->getValue(i);
}
else
{
str = QString("Phase ");
str.append(QString::number(i, 10));
}
str.append(":");
shapeTypeLabel->setText(str);
shapeTypeLabel->setObjectName(str);
m_ShapeTypeLabels.push_back(shapeTypeLabel);
m_ShapeTypeScrollContentsLayout->setWidget(i-1, QFormLayout::LabelRole, shapeTypeLabel);
shapeTypeComboBox = new QComboBox(m_ShapeTypeScrollContents);
str.append(" ComboBox");
shapeTypeComboBox->setObjectName(str);
for(int32_t s = 0; s < static_cast<int>(ShapeType::Type::ShapeTypeEnd); ++s)
{
shapeTypeComboBox->addItem((shapeTypeStrings[s]), static_cast<ShapeType::EnumType>(shapeTypeEnums[s]));
shapeTypeComboBox->setItemData(static_cast<int>(s), static_cast<ShapeType::EnumType>(shapeTypeEnums[s]), Qt::UserRole);
}
m_ShapeTypeCombos.push_back(shapeTypeComboBox);
m_ShapeTypeScrollContentsLayout->setWidget(i-1, QFormLayout::FieldRole, shapeTypeComboBox);
connect(shapeTypeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(comboboxChanged(int)));
}
else {
shapeTypeLabel = m_ShapeTypeLabels.at(i-1);
shapeTypeComboBox = m_ShapeTypeCombos.at(i-1);
QString str;
if((names.get() != nullptr) && names->getNumberOfTuples() > 0)
{
str = names->getValue(i);
}
else
{
str = QString("Phase ");
str.append(QString::number(i, 10));
}
str.append(":");
shapeTypeLabel->setText(str);
}
if(i<shapeTypesFromFilter.size()) {
shapeTypeComboBox->setCurrentIndex( static_cast<int>(shapeTypesFromFilter[i]));
}
}
// Check to see if we lost a phase during the preflight
int diff = m_ShapeTypeCombos.size() - numPhases;
for(int i = 0; i < diff + 1; i++)
{
if(!m_ShapeTypeLabels.isEmpty() && !m_ShapeTypeCombos.isEmpty())
{
shapeTypeLabel = m_ShapeTypeLabels.takeLast();
shapeTypeComboBox = m_ShapeTypeCombos.takeLast();
shapeTypeLabel->setParent(nullptr);
shapeTypeComboBox->setParent(nullptr);
shapeTypeLabel->setVisible(false);
shapeTypeComboBox->setVisible(false);
shapeTypeLabel->deleteLater();
shapeTypeComboBox->deleteLater();
}
}
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void ShapeTypeSelectionWidget::comboboxChanged(int index)
{
Q_UNUSED(index)
m_DidCausePreflight = true;
emit parametersChanged();
m_DidCausePreflight = false;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void ShapeTypeSelectionWidget::beforePreflight()
{
if(nullptr == getFilter())
{
return;
}
if(m_DidCausePreflight)
{
// std::cout << "*** ShapeTypeSelectionWidget already caused a preflight, just returning" << std::endl;
return;
}
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void ShapeTypeSelectionWidget::afterPreflight()
{
updateComboBoxes();
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void ShapeTypeSelectionWidget::filterNeedsInputParameters(AbstractFilter* filter)
{
int count = m_ShapeTypeCombos.count();
ShapeType::Types shapeTypes(count + 1, static_cast<ShapeType::Type>(ShapeType::Type::Unknown));
bool ok = false;
for(int i = 0; i < count; ++i)
{
QComboBox* cb = m_ShapeTypeCombos.at(i);
ShapeType::Type sType = static_cast<ShapeType::Type>(cb->itemData(cb->currentIndex(), Qt::UserRole).toUInt(&ok));
shapeTypes[i + 1] = sType;
}
QVariant var;
var.setValue(shapeTypes);
ok = false;
// Set the value into the Filter
ok = filter->setProperty(PROPERTY_NAME_AS_CHAR, var);
if(!ok)
{
getFilter()->notifyMissingProperty(getFilterParameter());
}
}
| 36.37785 | 152 | 0.619807 | [
"object",
"shape"
] |
9ce59cd6deadd5ffe9805cbba97f6a7c454ed130 | 3,150 | hpp | C++ | dfd/include/network/Message.hpp | dfdchain/dfd_project | 77a5cf59e6882575b9948d93cefbb556d857fd32 | [
"MIT"
] | 2 | 2020-09-02T02:10:06.000Z | 2020-09-19T03:16:32.000Z | dfd/include/network/Message.hpp | dfdchain/dfd_project | 77a5cf59e6882575b9948d93cefbb556d857fd32 | [
"MIT"
] | 2 | 2020-08-31T09:49:10.000Z | 2020-09-05T05:09:53.000Z | dfd/include/network/Message.hpp | dfdchain/dfd_project | 77a5cf59e6882575b9948d93cefbb556d857fd32 | [
"MIT"
] | 1 | 2020-11-19T03:36:27.000Z | 2020-11-19T03:36:27.000Z | #pragma once
#include <fc/array.hpp>
#include <fc/io/varint.hpp>
#include <fc/network/ip.hpp>
#include <fc/io/raw.hpp>
#include <fc/crypto/ripemd160.hpp>
#include <fc/reflect/variant.hpp>
namespace dfdcore {
namespace network {
/**
* Defines an 8 byte header that is always present because the minimum encrypted packet
* size is 8 bytes (blowfish). The maximum message size is defined in config.hpp. The channel,
* and message type is also included because almost every channel will have a message type
* field and we might as well include it in the 8 byte header to save space.
*/
struct MessageHeader
{
uint32_t size; // number of bytes in message, capped at MAX_MESSAGE_SIZE
uint32_t msg_type; // every channel gets a 16 bit message type specifier
};
typedef fc::uint160_t MessageHashType;
/**
* Abstracts the process of packing/unpacking a message for a
* particular channel.
*/
struct Message : public MessageHeader
{
std::vector<char> data;
Message(){}
Message(Message&& m)
:MessageHeader(m), data(std::move(m.data)){}
Message(const Message& m)
:MessageHeader(m), data(m.data){}
/**
* Assumes that T::type specifies the message type
*/
template<typename T>
Message(const T& m)
{
msg_type = T::type;
data = fc::raw::pack(m);
size = (uint32_t)data.size();
}
fc::uint160_t id()const
{
return fc::ripemd160::hash(data.data(), (uint32_t)data.size());
}
/**
* Automatically checks the type and deserializes T in the
* opposite process from the constructor.
*/
template<typename T>
T as()const
{
try {
FC_ASSERT(msg_type == T::type);
T tmp;
if (data.size())
{
fc::datastream<const char*> ds(data.data(), data.size());
fc::raw::unpack(ds, tmp);
}
else
{
// just to make sure that tmp shouldn't have any data
fc::datastream<const char*> ds(nullptr, 0);
fc::raw::unpack(ds, tmp);
}
return tmp;
} FC_RETHROW_EXCEPTIONS(warn,
"error unpacking network message as a '${type}' ${x} !=? ${msg_type}",
("type", fc::get_typename<T>::name())
("x", T::type)
("msg_type", msg_type)
);
}
};
}
} // dfdcore::net
FC_REFLECT(dfdcore::network::MessageHeader, (size)(msg_type))
FC_REFLECT_DERIVED(dfdcore::network::Message, (dfdcore::network::MessageHeader), (data))
| 32.474227 | 104 | 0.489524 | [
"vector"
] |
9ce9f297154bbfa75fde78b03f1629dbd461f0ae | 1,628 | cpp | C++ | Puzzles/Easy/RockPaperScisorsLizardSpock.cpp | Naheuldark/Codingame | 1ded71fad8386f3dda74f9b57ff1c056146206c3 | [
"MIT"
] | null | null | null | Puzzles/Easy/RockPaperScisorsLizardSpock.cpp | Naheuldark/Codingame | 1ded71fad8386f3dda74f9b57ff1c056146206c3 | [
"MIT"
] | null | null | null | Puzzles/Easy/RockPaperScisorsLizardSpock.cpp | Naheuldark/Codingame | 1ded71fad8386f3dda74f9b57ff1c056146206c3 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct Player {
int id;
std::string sign;
std::vector<int> adv;
Player(int id, std::string sign) : id(id), sign(sign) {}
};
Player battle(Player& p1, Player& p2) {
p1.adv.emplace_back(p2.id);
p2.adv.emplace_back(p1.id);
if ((p1.sign == "C" && p2.sign == "P") ||
(p1.sign == "P" && p2.sign == "R") ||
(p1.sign == "R" && p2.sign == "L") ||
(p1.sign == "L" && p2.sign == "S") ||
(p1.sign == "S" && p2.sign == "C") ||
(p1.sign == "C" && p2.sign == "L") ||
(p1.sign == "L" && p2.sign == "P") ||
(p1.sign == "P" && p2.sign == "S") ||
(p1.sign == "S" && p2.sign == "R") ||
(p1.sign == "R" && p2.sign == "C") ||
// They played the same sign
(p1.sign == p2.sign && p1.id < p2.id)) {
return p1;
} else {
return p2;
}
}
int main()
{
int N;
cin >> N; cin.ignore();
std::vector<Player> players;
for (int i = 0; i < N; i++) {
int NUMPLAYER;
string SIGNPLAYER;
cin >> NUMPLAYER >> SIGNPLAYER; cin.ignore();
players.emplace_back(NUMPLAYER, SIGNPLAYER);
}
while (players.size() > 1) {
// Play a round
std::vector<Player> nextRoundPlayers;
for (size_t idx = 0; idx < players.size(); idx += 2) {
nextRoundPlayers.emplace_back(battle(players[idx], players[idx+1]));
}
players = nextRoundPlayers;
}
cout << players[0].id << endl;
for (size_t i = 0; i < players[0].adv.size(); ++i) {
cout << players[0].adv[i];
if (i < players[0].adv.size()-1) cout << " ";
}
cout << endl;
} | 25.046154 | 71 | 0.517199 | [
"vector"
] |
9cecd7c4408376f9cbc1d9704f136fc25a955edd | 3,384 | cpp | C++ | cdb/src/v20170320/model/SlaveInfo.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | cdb/src/v20170320/model/SlaveInfo.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | cdb/src/v20170320/model/SlaveInfo.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/cdb/v20170320/model/SlaveInfo.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Cdb::V20170320::Model;
using namespace std;
SlaveInfo::SlaveInfo() :
m_firstHasBeenSet(false),
m_secondHasBeenSet(false)
{
}
CoreInternalOutcome SlaveInfo::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("First") && !value["First"].IsNull())
{
if (!value["First"].IsObject())
{
return CoreInternalOutcome(Core::Error("response `SlaveInfo.First` is not object type").SetRequestId(requestId));
}
CoreInternalOutcome outcome = m_first.Deserialize(value["First"]);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_firstHasBeenSet = true;
}
if (value.HasMember("Second") && !value["Second"].IsNull())
{
if (!value["Second"].IsObject())
{
return CoreInternalOutcome(Core::Error("response `SlaveInfo.Second` is not object type").SetRequestId(requestId));
}
CoreInternalOutcome outcome = m_second.Deserialize(value["Second"]);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_secondHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void SlaveInfo::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_firstHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "First";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
m_first.ToJsonObject(value[key.c_str()], allocator);
}
if (m_secondHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Second";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
m_second.ToJsonObject(value[key.c_str()], allocator);
}
}
SlaveInstanceInfo SlaveInfo::GetFirst() const
{
return m_first;
}
void SlaveInfo::SetFirst(const SlaveInstanceInfo& _first)
{
m_first = _first;
m_firstHasBeenSet = true;
}
bool SlaveInfo::FirstHasBeenSet() const
{
return m_firstHasBeenSet;
}
SlaveInstanceInfo SlaveInfo::GetSecond() const
{
return m_second;
}
void SlaveInfo::SetSecond(const SlaveInstanceInfo& _second)
{
m_second = _second;
m_secondHasBeenSet = true;
}
bool SlaveInfo::SecondHasBeenSet() const
{
return m_secondHasBeenSet;
}
| 26.4375 | 126 | 0.672577 | [
"object",
"model"
] |
9cf21e9c8c8f00ea4d8f8ea02b575f37472a2a4d | 33,519 | cpp | C++ | launchers/win32/LauncherDlg.cpp | makitsune/hifi | 55238200f1302aeb58ddb0c420f4e40e1a53c296 | [
"Apache-2.0"
] | null | null | null | launchers/win32/LauncherDlg.cpp | makitsune/hifi | 55238200f1302aeb58ddb0c420f4e40e1a53c296 | [
"Apache-2.0"
] | null | null | null | launchers/win32/LauncherDlg.cpp | makitsune/hifi | 55238200f1302aeb58ddb0c420f4e40e1a53c296 | [
"Apache-2.0"
] | null | null | null | //
// LauncherDlg.cpp
//
// Created by Luis Cuenca on 6/5/2019.
// Copyright 2019 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include "stdafx.h"
#include <regex>
#include "LauncherApp.h"
#include "LauncherDlg.h"
#include <d2d1.h>
#pragma comment(lib, "d2d1")
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
static int ACTION_FONT_SIZE = 40;
static int MESSAGE_FONT_SIZE = 19;
static int FIELDS_FONT_SIZE = 24;
static int BUTTON_FONT_SIZE = 25;
static int TERMS_FONT_SIZE = 17;
static int TROUBLE_FONT_SIZE = 14;
static COLORREF COLOR_GREY = RGB(120, 120, 120);
static COLORREF COLOR_BLACK= RGB(0, 0, 0);
static COLORREF COLOR_WHITE = RGB(255, 255, 255);
static COLORREF COLOR_LIGHTER_GREY = RGB(230, 230, 230);
static COLORREF COLOR_LIGHT_GREY = RGB(200, 200, 200);
static COLORREF COLOR_BLUE = RGB(50, 160, 200);
static CString GRAPHIK_REGULAR = _T("Graphik-Regular");
static CString GRAPHIK_SEMIBOLD = _T("Graphik-Semibold");
static CString TROUBLE_URL = _T("https://www.highfidelity.com/hq-support");
static CString TERMS_URL = _T("https://www.highfidelity.com/termsofservice");
static int SPLASH_DURATION = 100;
CLauncherDlg::CLauncherDlg(CWnd* pParent)
: CDialog(IDD_LAUNCHER_DIALOG, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
EnableD2DSupport();
}
CLauncherDlg::~CLauncherDlg() {
theApp._manager.closeLog();
}
void CLauncherDlg::DoDataExchange(CDataExchange* pDX)
{
DDX_Control(pDX, IDC_BUTTON_NEXT, m_btnNext);
DDX_Control(pDX, IDC_TROUBLE_LINK, m_trouble_link);
DDX_Control(pDX, IDC_TERMS_LINK, m_terms_link);
DDX_Control(pDX, IDC_ORGNAME, m_orgname);
DDX_Control(pDX, IDC_USERNAME, m_username);
DDX_Control(pDX, IDC_PASSWORD, m_password);
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CLauncherDlg, CDialog)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_WM_TIMER()
ON_EN_SETFOCUS(IDC_ORGNAME, &CLauncherDlg::OnOrgEditChangeFocus)
ON_EN_SETFOCUS(IDC_USERNAME, &CLauncherDlg::OnUserEditChangeFocus)
ON_EN_SETFOCUS(IDC_PASSWORD, &CLauncherDlg::OnPassEditChangeFocus)
ON_BN_CLICKED(IDC_BUTTON_NEXT, &CLauncherDlg::OnNextClicked)
ON_BN_CLICKED(IDC_TROUBLE_LINK, &CLauncherDlg::OnTroubleClicked)
ON_BN_CLICKED(IDC_TERMS_LINK, &CLauncherDlg::OnTermsClicked)
ON_WM_CTLCOLOR()
ON_WM_DRAWITEM()
ON_WM_SETCURSOR()
END_MESSAGE_MAP()
// CLauncherDlg message handlers
BOOL CLauncherDlg::OnInitDialog() {
CDialog::OnInitDialog();
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
CFont editFont;
if (LauncherUtils::getFont(GRAPHIK_REGULAR, FIELDS_FONT_SIZE, true, editFont)) {
m_orgname.SetFont(&editFont);
m_username.SetFont(&editFont);
m_password.SetFont(&editFont);
}
CFont buttonFont;
if (LauncherUtils::getFont(_T("Graphik-Bold"), BUTTON_FONT_SIZE, true, buttonFont)) {
m_btnNext.SetFont(&editFont);
}
m_message_label = (CStatic *)GetDlgItem(IDC_MESSAGE_LABEL);
m_action_label = (CStatic *)GetDlgItem(IDC_ACTION_LABEL);
m_message2_label = (CStatic *)GetDlgItem(IDC_MESSAGE2_LABEL);
m_action2_label = (CStatic *)GetDlgItem(IDC_ACTION2_LABEL);
m_orgname_banner = (CStatic *)GetDlgItem(IDC_ORGNAME_BANNER);
m_username_banner = (CStatic *)GetDlgItem(IDC_USERNAME_BANNER);
m_password_banner = (CStatic *)GetDlgItem(IDC_PASSWORD_BANNER);
m_terms = (CStatic *)GetDlgItem(IDC_TERMS);
m_trouble = (CStatic *)GetDlgItem(IDC_TROUBLE);
m_voxel = (CStatic *)GetDlgItem(IDC_VOXEL);
m_progress = (CStatic *)GetDlgItem(IDC_PROGRESS);
m_version = (CStatic *)GetDlgItem(IDC_VERSION);
CString version;
version.Format(_T("V.%s"), theApp._manager.getLauncherVersion());
m_version->SetWindowTextW(version);
m_voxel->EnableD2DSupport();
m_progress->EnableD2DSupport();
m_pRenderTarget = GetRenderTarget();
SetTimer(1, 2, NULL);
return TRUE;
}
POINT CLauncherDlg::getMouseCoords(MSG* pMsg) {
POINT pos;
pos.x = (int)(short)LOWORD(pMsg->lParam);
pos.y = (int)(short)HIWORD(pMsg->lParam);
return pos;
}
BOOL CLauncherDlg::PreTranslateMessage(MSG* pMsg) {
switch (pMsg->message) {
case WM_KEYDOWN:
if (pMsg->wParam == 'A' && GetKeyState(VK_CONTROL) < 0) {
CWnd* wnd = GetFocus();
CWnd* myWnd = this->GetDlgItem(IDC_ORGNAME);
if (wnd && (wnd == this->GetDlgItem(IDC_ORGNAME) ||
wnd == this->GetDlgItem(IDC_USERNAME) ||
wnd == this->GetDlgItem(IDC_PASSWORD))) {
((CEdit*)wnd)->SetSel(0, -1);
}
return TRUE;
} else if (pMsg->wParam == VK_RETURN) {
OnNextClicked();
return TRUE;
} else if (pMsg->wParam == VK_ESCAPE) {
theApp._manager.onCancel();
}
break;
case WM_LBUTTONDOWN:
if (pMsg->hwnd == GetSafeHwnd()) {
_draggingWindow = true;
_dragOffset = getMouseCoords(pMsg);
SetCapture();
}
break;
case WM_LBUTTONUP:
if (_draggingWindow) {
ReleaseCapture();
_draggingWindow = false;
}
break;
case WM_MOUSEMOVE:
if (_draggingWindow) {
POINT pos = getMouseCoords(pMsg);
RECT windowRect;
GetWindowRect(&windowRect);
int width = windowRect.right - windowRect.left;
int height = windowRect.bottom - windowRect.top;
ClientToScreen(&pos);
MoveWindow(pos.x - _dragOffset.x, pos.y - _dragOffset.y, width, height, FALSE);
}
break;
default:
break;
}
return CDialog::PreTranslateMessage(pMsg);
}
void CLauncherDlg::setCustomDialog() {
LONG lStyle = GetWindowLong(GetSafeHwnd(), GWL_STYLE);
lStyle &= ~(WS_CAPTION | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_SYSMENU);
SetWindowLong(GetSafeHwnd(), GWL_STYLE, lStyle);
LONG lExStyle = GetWindowLong(GetSafeHwnd(), GWL_EXSTYLE);
lExStyle &= ~(WS_EX_DLGMODALFRAME | WS_EX_CLIENTEDGE | WS_EX_STATICEDGE);
SetWindowLong(GetSafeHwnd(), GWL_EXSTYLE, lExStyle);
SetWindowPos(NULL, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
}
void CLauncherDlg::OnPaint()
{
CPaintDC dc(this);
setCustomDialog();
CDialog::OnPaint();
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CLauncherDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CLauncherDlg::startProcess() {
if (theApp._manager.needsUpdate()) {
theApp._manager.addToLog(_T("Starting Process Update"));
setDrawDialog(DrawStep::DrawProcessUpdate);
} else {
theApp._manager.addToLog(_T("Starting Process Setup"));
setDrawDialog(DrawStep::DrawProcessSetup);
}
theApp._manager.addToLog(_T("Deleting download directory"));
CString downloadDir;
theApp._manager.getAndCreatePaths(LauncherManager::PathType::Download_Directory, downloadDir);
LauncherUtils::deleteDirectoryOnThread(downloadDir, [&](bool error) {
if (!error) {
if (!theApp._manager.isLoggedIn()) {
theApp._manager.addToLog(_T("Downloading Content"));
theApp._manager.downloadContent();
} else {
theApp._manager.addToLog(_T("Downloading App"));
theApp._manager.downloadApplication();
}
} else {
theApp._manager.addToLog(_T("Error deleting download directory."));
theApp._manager.setFailed(true);
}
});
}
BOOL CLauncherDlg::getHQInfo(const CString& orgname) {
CString hash;
CString lowerOrgName = orgname;
lowerOrgName.MakeLower();
LauncherUtils::hMac256(lowerOrgName, LAUNCHER_HMAC_SECRET, hash);
CString msg;
msg.Format(_T("Calculated hash: \"%s\" => \"%s\""), lowerOrgName, hash);
theApp._manager.addToLog(msg);
return theApp._manager.readOrganizationJSON(hash) == LauncherUtils::ResponseError::NoError;
}
afx_msg void CLauncherDlg::OnTroubleClicked() {
LauncherUtils::executeOnForeground(TROUBLE_URL, _T(""));
}
afx_msg void CLauncherDlg::OnTermsClicked() {
LauncherUtils::executeOnForeground(TERMS_URL, _T(""));
}
afx_msg void CLauncherDlg::OnNextClicked() {
if (_drawStep == DrawStep::DrawChoose) {
CString displayName;
m_username.GetWindowTextW(displayName);
theApp._manager.setDisplayName(displayName);
theApp._manager.addToLog(_T("Setting display name: " + displayName));
startProcess();
} else if (_drawStep == DrawStep::DrawError) {
theApp._manager.restartLauncher();
} else if (_drawStep == DrawStep::DrawLoginLogin ||
_drawStep == DrawStep::DrawLoginErrorCred ||
_drawStep == DrawStep::DrawLoginErrorOrg) {
CString token;
CString username, password, orgname;
m_orgname.GetWindowTextW(orgname);
m_username.GetWindowTextW(username);
m_password.GetWindowTextW(password);
// trim spaces
orgname = CString(std::regex_replace(LauncherUtils::cStringToStd(orgname), std::regex("^ +| +$|( ) +"), "$1").c_str());
username = CString(std::regex_replace(LauncherUtils::cStringToStd(username), std::regex("^ +| +$|( ) +"), "$1").c_str());
// encode
username = LauncherUtils::urlEncodeString(username);
password = LauncherUtils::urlEncodeString(password);
LauncherUtils::ResponseError error;
if (orgname.GetLength() > 0 && username.GetLength() > 0 && password.GetLength() > 0) {
theApp._manager.addToLog(_T("Trying to get organization data"));
if (getHQInfo(orgname)) {
theApp._manager.addToLog(_T("Organization data received."));
theApp._manager.addToLog(_T("Trying to log in with credentials"));
error = theApp._manager.getAccessTokenForCredentials(username, password);
if (error == LauncherUtils::ResponseError::NoError) {
theApp._manager.addToLog(_T("Logged in correctly."));
setDrawDialog(DrawStep::DrawChoose);
} else if (error == LauncherUtils::ResponseError::BadCredentials) {
theApp._manager.addToLog(_T("Bad credentials. Try again"));
setDrawDialog(DrawStep::DrawLoginErrorCred);
} else {
theApp._manager.addToLog(_T("Error Reading or retrieving response."));
MessageBox(L"Error Reading or retrieving response.", L"Network Error", MB_OK | MB_ICONERROR);
}
} else {
theApp._manager.addToLog(_T("Organization name does not exist."));
setDrawDialog(DrawStep::DrawLoginErrorOrg);
}
}
}
}
void CLauncherDlg::drawBackground(CHwndRenderTarget* pRenderTarget) {
CD2DBitmap m_pBitmamBackground(pRenderTarget, IDB_PNG1, _T("PNG"));
auto size = GetRenderTarget()->GetSize();
CD2DRectF backRec(0.0f, 0.0f, size.width, size.height);
GetRenderTarget()->DrawBitmap(&m_pBitmamBackground, backRec);
pRenderTarget->DrawBitmap(&m_pBitmamBackground, backRec);
}
void CLauncherDlg::drawLogo(CHwndRenderTarget* pRenderTarget) {
CD2DBitmap m_pBitmamLogo(pRenderTarget, IDB_PNG2, _T("PNG"));
auto size = pRenderTarget->GetSize();
int logoWidth = 231;
int logoHeight = 173;
float logoPosX = 0.5f * (size.width - logoWidth);
float logoPosY = 0.5f * (size.height - logoHeight);
CD2DRectF logoRec(logoPosX, logoPosY, logoPosX + logoWidth, logoPosY + logoHeight);
pRenderTarget->DrawBitmap(&m_pBitmamLogo, logoRec);
}
void CLauncherDlg::drawSmallLogo(CHwndRenderTarget* pRenderTarget) {
CD2DBitmap m_pBitmamLogo(pRenderTarget, IDB_PNG5, _T("PNG"));
auto size = pRenderTarget->GetSize();
int xPadding = 6;
int yPadding = 22;
int logoWidth = 100;
int logoHeight = 18;
float logoPosX = size.width - logoWidth - xPadding;
float logoPosY = size.height - logoHeight - yPadding;
CD2DRectF logoRec(logoPosX, logoPosY, logoPosX + logoWidth, logoPosY + logoHeight);
pRenderTarget->DrawBitmap(&m_pBitmamLogo, logoRec);
}
void CLauncherDlg::drawVoxel(CHwndRenderTarget* pRenderTarget) {
CD2DBitmap m_pBitmamVoxel(pRenderTarget, IDB_PNG4, _T("PNG"));
auto size = pRenderTarget->GetSize();
int logoWidth = 132;
int logoHeight = 134;
float voxelPosX = 0.5f * (size.width - logoWidth);
float voxelPosY = 0.5f * (size.height - logoHeight);
CD2DRectF voxelRec(voxelPosX, voxelPosY, voxelPosX + logoWidth, voxelPosY + logoHeight);
auto midPoint = D2D1::Point2F(0.5f * size.width, 0.5f * size.height);
_logoRotation += 2.0f;
CD2DSolidColorBrush brush(pRenderTarget, D2D1::ColorF(0.0f, 0.0f, 0.0f));
pRenderTarget->SetTransform(D2D1::Matrix3x2F::Rotation(_logoRotation - 2.0f, midPoint));
pRenderTarget->FillRectangle(voxelRec, &brush);
pRenderTarget->SetTransform(D2D1::Matrix3x2F::Rotation(_logoRotation, midPoint));
pRenderTarget->DrawBitmap(&m_pBitmamVoxel, voxelRec);
pRenderTarget->SetTransform(D2D1::Matrix3x2F::Identity());
}
void CLauncherDlg::drawProgress(CHwndRenderTarget* pRenderTarget, float progress, const D2D1::ColorF& color) {
auto size = pRenderTarget->GetSize();
if (progress == 0.0f) {
return;
} else {
progress = min(1.0f, progress);
}
CRect winRec;
float fullHeight = (float)size.height;
float halfHeight = 0.5f * (float)size.height;
CD2DRectF bkCircleRect1 = CD2DRectF(0.0f, 0.0f, fullHeight, fullHeight);
float progPos = halfHeight + (float)(size.width - size.height) * progress;
CD2DRectF bkCircleRect2 = CD2DRectF(progPos - halfHeight, 0.0f, progPos + halfHeight, fullHeight);
CD2DRectF bkRect = CD2DRectF(halfHeight, 0.0f, progPos, fullHeight);
CD2DEllipse bkCircle1 = CD2DEllipse(bkCircleRect1);
CD2DEllipse bkCircle2 = CD2DEllipse(bkCircleRect2);
CD2DSolidColorBrush brush(pRenderTarget, color);
pRenderTarget->FillEllipse(bkCircle1, &brush);
pRenderTarget->FillEllipse(bkCircle2, &brush);
pRenderTarget->FillRectangle(bkRect, &brush);
}
void CLauncherDlg::showWindows(std::vector<CStatic*> windows, bool show) {
for (auto window : windows) {
window->ShowWindow(show ? SW_SHOW : SW_HIDE);
}
}
void CLauncherDlg::prepareLogin(DrawStep step) {
m_voxel->ShowWindow(SW_HIDE);
m_progress->ShowWindow(SW_HIDE);
m_orgname_banner->SetWindowTextW(_T("Organization Name"));
m_username_banner->SetWindowTextW(_T("Username"));
m_password_banner->SetWindowTextW(_T("Password"));
CString editText;
m_orgname.GetWindowTextW(editText);
m_orgname_banner->ShowWindow(editText.GetLength() == 0 ? SW_SHOW : SW_HIDE);
m_username.GetWindowTextW(editText);
m_username_banner->ShowWindow(editText.GetLength() == 0 ? SW_SHOW : SW_HIDE);
m_password.GetWindowTextW(editText);
m_password_banner->ShowWindow(editText.GetLength() == 0 ? SW_SHOW : SW_HIDE);
m_orgname.ShowWindow(SW_SHOW);
m_username.ShowWindow(SW_SHOW);
m_password.ShowWindow(SW_SHOW);
CString actionText = step == DrawStep::DrawLoginLogin ? _T("Please log in") : _T("Uh-oh, we have a problem");
CString messageText = step == DrawStep::DrawLoginLogin ? _T("Be sure you've uploaded your Avatar before signing in.") :
step == DrawStep::DrawLoginErrorCred ? _T("There is a problem with your credentials.\n Please try again.") : _T("There is a problem with your Organization name.\n Please try again.");
m_action_label->SetWindowTextW(actionText);
m_message_label->SetWindowTextW(messageText);
m_action_label->ShowWindow(SW_SHOW);
m_message_label->ShowWindow(SW_SHOW);
m_btnNext.ShowWindow(SW_SHOW);
m_trouble->SetWindowTextW(_T("Having Trouble?"));
m_trouble->ShowWindow(SW_SHOW);
m_trouble_link.ShowWindow(SW_SHOW);
}
void CLauncherDlg::prepareChoose() {
m_orgname.ShowWindow(SW_HIDE);
m_username.SetWindowTextW(_T(""));
m_username_banner->SetWindowTextW(_T("Display Name"));
CString editText;
m_username.GetWindowTextW(editText);
m_username_banner->ShowWindow(editText.GetLength() == 0 ? SW_SHOW : SW_HIDE);
m_password.ShowWindow(SW_HIDE);
m_orgname_banner->ShowWindow(SW_HIDE);
m_password_banner->ShowWindow(SW_HIDE);
m_action_label->SetWindowTextW(_T("Choose a display name"));
m_message_label->SetWindowTextW(_T("This is the name that your teammates will see."));
m_terms->ShowWindow(SW_SHOW);
m_terms_link.ShowWindow(SW_SHOW);
m_terms->SetWindowTextW(_T("By signing in, you agree to the High Fidelity"));
m_terms_link.SetWindowTextW(_T("Terms of Service"));
setVerticalElement(&m_btnNext, -35, 0, false);
m_btnNext.ShowWindow(SW_SHOW);
}
void CLauncherDlg::prepareProcess(DrawStep step) {
m_trouble->ShowWindow(SW_HIDE);
m_trouble_link.ShowWindow(SW_HIDE);
m_terms->ShowWindow(SW_HIDE);
m_terms_link.ShowWindow(SW_HIDE);
m_orgname_banner->ShowWindow(SW_HIDE);
m_username_banner->ShowWindow(SW_HIDE);
m_password_banner->ShowWindow(SW_HIDE);
m_orgname.ShowWindow(SW_HIDE);
m_username.ShowWindow(SW_HIDE);
m_password.ShowWindow(SW_HIDE);
m_action_label->SetWindowTextW(_T(""));
m_message_label->SetWindowTextW(_T(""));
m_btnNext.ShowWindow(SW_HIDE);
m_action_label->ShowWindow(SW_HIDE);
m_message_label->ShowWindow(SW_HIDE);
m_voxel->ShowWindow(SW_SHOW);
m_progress->ShowWindow(SW_SHOW);
CString actionText = _T("");
CString messageText = _T("");
switch (step) {
case DrawStep::DrawProcessSetup:
actionText = _T("We're building your virtual HQ");
messageText = _T("Set up may take several minutes.");
break;
case DrawStep::DrawProcessUpdate:
actionText = _T("Getting updates...");
messageText = _T("We're getting the latest and greatest for you, one sec.");
break;
case DrawStep::DrawProcessFinishHq:
actionText = _T("Your new HQ is all setup");
messageText = _T("Thanks for being patient.");
break;
case DrawStep::DrawProcessFinishUpdate:
actionText = _T("You're good to go!");
messageText = _T("Thanks for being patient.");
break;
case DrawStep::DrawProcessUninstall:
actionText = _T("Uninstalling...");
messageText = _T("It'll take one sec.");
break;
case DrawStep::DrawError:
actionText = _T("Uh oh.");
messageText = _T("We seem to have a problem.\nPlease restart HQ.");
setVerticalElement(m_message2_label, 0, 5, false);
setVerticalElement(&m_btnNext, 10);
m_btnNext.ShowWindow(SW_SHOW);
m_progress->ShowWindow(SW_HIDE);
break;
default:
break;
}
m_action2_label->SetWindowTextW(actionText);
m_message2_label->SetWindowTextW(messageText);
m_action2_label->ShowWindow(SW_SHOW);
m_message2_label->ShowWindow(SW_SHOW);
}
BOOL CLauncherDlg::getTextFormat(int resID, TextFormat& formatOut) {
// Set default values for message
BOOL isText = TRUE;
formatOut.color = COLOR_LIGHT_GREY;
formatOut.isBold = false;
formatOut.isButton = false;
formatOut.size = MESSAGE_FONT_SIZE;
formatOut.underlined = false;
switch (resID) {
case IDC_VOXEL:
case IDD_LAUNCHER_DIALOG:
isText = FALSE;
case IDC_MESSAGE_LABEL:
case IDC_MESSAGE2_LABEL:
// Default values
break;
case IDC_ACTION_LABEL:
case IDC_ACTION2_LABEL:
formatOut.size = ACTION_FONT_SIZE;
formatOut.isBold = true;
formatOut.color = COLOR_LIGHTER_GREY;
break;
case IDC_USERNAME:
case IDC_PASSWORD:
case IDC_ORGNAME:
formatOut.color = COLOR_WHITE;
formatOut.size = FIELDS_FONT_SIZE;
formatOut.underlined = true;
break;
case IDC_USERNAME_BANNER:
case IDC_PASSWORD_BANNER:
case IDC_ORGNAME_BANNER:
formatOut.size = FIELDS_FONT_SIZE;
formatOut.color = COLOR_GREY;
break;
case IDC_VERSION:
case IDC_TERMS:
formatOut.size = TERMS_FONT_SIZE;
break;
case IDC_TERMS_LINK:
formatOut.size = TERMS_FONT_SIZE;
formatOut.isBold = true;
break;
case IDC_TROUBLE:
formatOut.size = TROUBLE_FONT_SIZE;
formatOut.color = COLOR_BLUE;
break;
}
return isText;
}
HBRUSH CLauncherDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
TextFormat textFormat;
int resId = pWnd->GetDlgCtrlID();
if (getTextFormat(resId, textFormat)) {
pDC->SetTextColor(textFormat.color);
pDC->SetBkMode(TRANSPARENT);
CFont textFont;
CString fontFamily = textFormat.isBold ? GRAPHIK_SEMIBOLD : GRAPHIK_REGULAR;
if (LauncherUtils::getFont(fontFamily, textFormat.size, textFormat.isBold, textFont)) {
pDC->SelectObject(&textFont);
}
if (textFormat.underlined) {
CRect rect;
pWnd->GetClientRect(&rect);
int borderThick = 1;
int padding = 4;
CRect lineRect = CRect(rect.left + padding, rect.bottom, rect.right - padding, rect.bottom + borderThick);
lineRect.MoveToY(lineRect.bottom + 1);
pDC->FillSolidRect(lineRect, COLOR_GREY);
}
}
return (HBRUSH)GetStockObject(BLACK_BRUSH);
}
void CLauncherDlg::OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct)
{
CDC dc;
dc.Attach(lpDrawItemStruct->hDC);
CRect rect = lpDrawItemStruct->rcItem;
CRect defrect = rect;
CString btnName = _T("");
int xpan = 0;
if (nIDCtl == IDC_BUTTON_NEXT) {
if (_drawStep == DrawStep::DrawChoose || _drawStep == DrawStep::DrawLoginLogin) {
btnName += _drawStep == DrawStep::DrawLoginLogin ? _T("LOG IN") : _T("NEXT");
int xpan = -20;
defrect = CRect(rect.left - xpan, rect.top, rect.right + xpan, rect.bottom);
} else if (_drawStep == DrawStep::DrawError) {
btnName += _T("RESTART");
} else {
btnName += _T("TRY AGAIN");
}
int borderThick = 2;
dc.FillSolidRect(rect, COLOR_BLACK);
dc.FillSolidRect(defrect, COLOR_WHITE);
defrect.DeflateRect(borderThick, borderThick, borderThick, borderThick);
dc.FillSolidRect(defrect, COLOR_BLACK);
UINT state = lpDrawItemStruct->itemState;
dc.SetTextColor(COLOR_WHITE);
CFont buttonFont;
if (LauncherUtils::getFont(GRAPHIK_SEMIBOLD, BUTTON_FONT_SIZE, true, buttonFont)) {
dc.SelectObject(buttonFont);
}
dc.DrawText(btnName, CRect(rect.left, rect.top + 4, rect.right, rect.bottom - 8), DT_CENTER | DT_VCENTER | DT_SINGLELINE);
dc.Detach();
} else if (nIDCtl == IDC_TROUBLE_LINK) {
dc.FillSolidRect(rect, COLOR_BLACK);
dc.SetTextColor(COLOR_BLUE);
CFont buttonFont;
if (LauncherUtils::getFont(GRAPHIK_SEMIBOLD, TROUBLE_FONT_SIZE, true, buttonFont)) {
dc.SelectObject(buttonFont);
}
dc.DrawText(_T("Having Trouble"), CRect(rect.left, rect.top, rect.right, rect.bottom), DT_CENTER | DT_VCENTER | DT_SINGLELINE);
} else if (nIDCtl == IDC_TERMS_LINK) {
dc.FillSolidRect(rect, COLOR_BLACK);
dc.SetTextColor(COLOR_LIGHT_GREY);
CFont buttonFont;
if (LauncherUtils::getFont(GRAPHIK_SEMIBOLD, TERMS_FONT_SIZE, true, buttonFont)) {
dc.SelectObject(buttonFont);
}
dc.DrawText(_T("Terms of Service"), CRect(rect.left, rect.top, rect.right, rect.bottom), DT_LEFT | DT_TOP | DT_SINGLELINE);
}
}
void CLauncherDlg::redrawBanner(const CEdit& edit, CStatic* banner) {
CString editText;
edit.GetWindowTextW(editText);
if (editText.GetLength() == 0) {
banner->Invalidate();
}
}
void CLauncherDlg::OnOrgEditChangeFocus() {
redrawBanner(m_username, m_username_banner);
redrawBanner(m_password, m_password_banner);
}
void CLauncherDlg::OnUserEditChangeFocus() {
redrawBanner(m_orgname, m_orgname_banner);
redrawBanner(m_password, m_password_banner);
}
void CLauncherDlg::OnPassEditChangeFocus() {
redrawBanner(m_orgname, m_orgname_banner);
redrawBanner(m_username, m_username_banner);
}
BOOL CLauncherDlg::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message)
{
if (pWnd->IsKindOf(RUNTIME_CLASS(CButton))) {
::SetCursor(AfxGetApp()->LoadStandardCursor(IDC_HAND));
return TRUE;
}
return CDialog::OnSetCursor(pWnd, nHitTest, message);
}
void CLauncherDlg::OnTimer(UINT_PTR nIDEvent) {
if (theApp._manager.hasFailed() && _drawStep != DrawStep::DrawError) {
theApp._manager.saveErrorLog();
prepareProcess(DrawStep::DrawError);
setDrawDialog(DrawStep::DrawError, false);
}
if (_drawStep != DrawStep::DrawError) {
if (_drawStep == DrawStep::DrawProcessSetup ||
_drawStep == DrawStep::DrawProcessUpdate ||
_drawStep == DrawStep::DrawProcessUninstall ||
_drawStep == DrawStep::DrawProcessFinishHq ||
_drawStep == DrawStep::DrawProcessFinishUpdate) {
// Refresh
setDrawDialog(_drawStep, true);
}
if (theApp._manager.needsSelfUpdate()) {
if (theApp._manager.needsSelfDownload()) {
theApp._manager.downloadNewLauncher();
} else {
if (_splashStep > SPLASH_DURATION && _splashStep < 2 * SPLASH_DURATION) {
float progress = (float)(_splashStep - SPLASH_DURATION) / SPLASH_DURATION;
if (theApp._manager.willContinueUpdating()) {
progress = CONTINUE_UPDATING_GLOBAL_OFFSET * progress;
progress = min(progress, CONTINUE_UPDATING_GLOBAL_OFFSET);
}
theApp._manager.updateProgress(LauncherManager::ProcessType::Uninstall, progress);
_splashStep++;
}
if (theApp._manager.needsRestartNewLauncher()) {
if (_splashStep >= 2 * SPLASH_DURATION) {
theApp._manager.restartNewLauncher();
exit(0);
}
}
}
}
LauncherManager::ContinueActionOnStart continueAction = theApp._manager.getContinueAction();
if (_showSplash) {
if (_splashStep == 0) {
if (theApp._manager.needsUninstall()) {
theApp._manager.addToLog(_T("Waiting to uninstall"));
setDrawDialog(DrawStep::DrawProcessUninstall);
} else if (continueAction == LauncherManager::ContinueActionOnStart::ContinueUpdate) {
setDrawDialog(DrawStep::DrawProcessUpdate);
theApp._manager.updateProgress(LauncherManager::ProcessType::Uninstall, 0.0f);
} else if (continueAction == LauncherManager::ContinueActionOnStart::ContinueLogIn) {
_splashStep = SPLASH_DURATION;
} else if (continueAction == LauncherManager::ContinueActionOnStart::ContinueFinish) {
theApp._manager.updateProgress(LauncherManager::ProcessType::Uninstall, 1.0f);
setDrawDialog(DrawStep::DrawProcessFinishUpdate);
_splashStep = SPLASH_DURATION;
_showSplash = false;
} else {
theApp._manager.addToLog(_T("Start splash screen"));
setDrawDialog(DrawStep::DrawLogo);
}
} else if (_splashStep > SPLASH_DURATION && !theApp._manager.needsToWait()) {
_showSplash = false;
if (theApp._manager.shouldShutDown()) {
if (_applicationWND != NULL) {
::SetForegroundWindow(_applicationWND);
::SetActiveWindow(_applicationWND);
}
if (LauncherUtils::isProcessWindowOpened(L"interface.exe")) {
exit(0);
}
} else if (theApp._manager.needsUpdate()) {
startProcess();
} else if (theApp._manager.needsUninstall()) {
if (theApp._manager.uninstallApplication()) {
theApp._manager.addToLog(_T("HQ uninstalled successfully."));
exit(0);
} else {
theApp._manager.addToLog(_T("HQ failed to uninstall."));
theApp._manager.setFailed(true);
}
} else if (theApp._manager.needsSelfUpdate()) {
setDrawDialog(DrawStep::DrawProcessUpdate);
} else {
theApp._manager.addToLog(_T("Starting login"));
setDrawDialog(DrawStep::DrawLoginLogin);
}
} else if (theApp._manager.needsUninstall()) {
theApp._manager.updateProgress(LauncherManager::ProcessType::Uninstall, (float)_splashStep / SPLASH_DURATION);
}
_splashStep++;
} else if (theApp._manager.shouldShutDown()) {
if (LauncherUtils::isProcessWindowOpened(L"interface.exe")) {
exit(0);
}
}
if (theApp._manager.shouldLaunch()) {
if (theApp._manager.needsInstall() || theApp._manager.needsUpdate()) {
auto finishProcess = theApp._manager.needsUpdate() ? DrawStep::DrawProcessFinishUpdate : DrawStep::DrawProcessFinishHq;
setDrawDialog(finishProcess);
}
_applicationWND = theApp._manager.launchApplication();
}
}
if (theApp._manager.needsToSelfInstall()) {
theApp._manager.tryToInstallLauncher(TRUE);
}
}
void CLauncherDlg::setVerticalElement(CWnd* element, int verticalOffset, int heightOffset, bool fromMainWindowBottom) {
CRect elementRec;
CRect windowRec;
if (element != NULL) {
element->GetWindowRect(&elementRec);
ScreenToClient(&elementRec);
int offset = verticalOffset;
if (fromMainWindowBottom) {
GetWindowRect(&windowRec);
ScreenToClient(&windowRec);
int currentDistance = windowRec.bottom - elementRec.bottom;
offset = currentDistance - verticalOffset;
}
elementRec.bottom = elementRec.bottom + offset + heightOffset;
elementRec.top = elementRec.top + offset;
element->MoveWindow(elementRec, FALSE);
}
}
void CLauncherDlg::setDrawDialog(DrawStep step, BOOL isUpdate) {
_drawStep = step;
float progress = 0.0f;
auto m_pRenderTarget = GetRenderTarget();
auto m_voxelRenderTarget = m_voxel->GetRenderTarget();
auto m_progressRenderTarget = m_progress->GetRenderTarget();
switch (_drawStep) {
case DrawStep::DrawLogo: {
m_pRenderTarget->BeginDraw();
drawBackground(m_pRenderTarget);
drawLogo(m_pRenderTarget);
m_pRenderTarget->EndDraw();
CRect redrawRec;
GetClientRect(redrawRec);
redrawRec.top = redrawRec.bottom - 30;
RedrawWindow(redrawRec);
break;
}
case DrawStep::DrawLoginLogin:
case DrawStep::DrawLoginErrorOrg:
case DrawStep::DrawLoginErrorCred:
prepareLogin(_drawStep);
m_pRenderTarget->BeginDraw();
drawBackground(m_pRenderTarget);
drawSmallLogo(m_pRenderTarget);
m_pRenderTarget->EndDraw();
RedrawWindow();
break;
case DrawStep::DrawChoose:
prepareChoose();
m_pRenderTarget->BeginDraw();
drawBackground(m_pRenderTarget);
drawSmallLogo(m_pRenderTarget);
m_pRenderTarget->EndDraw();
RedrawWindow();
break;
case DrawStep::DrawError:
case DrawStep::DrawProcessFinishHq:
case DrawStep::DrawProcessFinishUpdate:
case DrawStep::DrawProcessUpdate:
case DrawStep::DrawProcessUninstall:
case DrawStep::DrawProcessSetup:
if (!isUpdate) {
m_voxelRenderTarget->BeginDraw();
m_voxelRenderTarget->Clear(D2D1::ColorF(0.0f, 0.0f, 0.0f, 1.0f));
m_voxelRenderTarget->EndDraw();
m_pRenderTarget->BeginDraw();
prepareProcess(_drawStep);
drawBackground(m_pRenderTarget);
drawSmallLogo(m_pRenderTarget);
m_pRenderTarget->EndDraw();
RedrawWindow();
}
m_progressRenderTarget->BeginDraw();
m_progressRenderTarget->Clear(D2D1::ColorF(0.0f, 0.0f, 0.0f, 1.0f));
drawProgress(m_progressRenderTarget, 1.0f, D2D1::ColorF(0.2f, 0.2f, 0.2f));
drawProgress(m_progressRenderTarget, theApp._manager.getProgress(), D2D1::ColorF(0.0f, 0.62f, 0.9f));
m_progressRenderTarget->EndDraw();
m_voxelRenderTarget->BeginDraw();
drawVoxel(m_voxelRenderTarget);
m_voxelRenderTarget->EndDraw();
break;
default:
break;
}
}
| 39.387779 | 191 | 0.651422 | [
"vector"
] |
14016fea14c5cdec3995228b806ecf883672397a | 597 | cpp | C++ | inference-engine/tests/ngraph_helpers/ngraph_functions/src/tile.cpp | Andruxin52rus/openvino | d824e371fe7dffb90e6d3d58e4e34adecfce4606 | [
"Apache-2.0"
] | 1 | 2022-01-19T15:36:45.000Z | 2022-01-19T15:36:45.000Z | inference-engine/tests/ngraph_helpers/ngraph_functions/src/tile.cpp | Andruxin52rus/openvino | d824e371fe7dffb90e6d3d58e4e34adecfce4606 | [
"Apache-2.0"
] | 30 | 2020-11-13T11:44:07.000Z | 2022-02-21T13:03:16.000Z | inference-engine/tests/ngraph_helpers/ngraph_functions/src/tile.cpp | mmakridi/openvino | 769bb7709597c14debdaa356dd60c5a78bdfa97e | [
"Apache-2.0"
] | 1 | 2020-12-18T15:47:45.000Z | 2020-12-18T15:47:45.000Z | // Copyright (C) 2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "ngraph_functions/builders.hpp"
namespace ngraph {
namespace builder {
std::shared_ptr<ngraph::Node> makeTile(const ngraph::Output<Node>& in,
const std::vector<int64_t>& repeats) {
auto repeatsNode = std::make_shared<ngraph::opset1::Constant>(ngraph::element::i64, std::vector<size_t>{repeats.size()}, repeats);
auto tileNode = std::make_shared<ngraph::opset1::Tile>(in, repeatsNode);
return tileNode;
}
} // namespace builder
} // namespace ngraph
| 31.421053 | 134 | 0.676717 | [
"vector"
] |
140697b4e325d03f7287750eed5c7ca0de295dcf | 9,110 | cpp | C++ | Polyhedron.cpp | darkedge/GT1 | b9b569909c4d505f16400e8b744fba714077c952 | [
"MIT"
] | 1 | 2020-11-08T21:08:04.000Z | 2020-11-08T21:08:04.000Z | Polyhedron.cpp | darkedge/GT1 | b9b569909c4d505f16400e8b744fba714077c952 | [
"MIT"
] | null | null | null | Polyhedron.cpp | darkedge/GT1 | b9b569909c4d505f16400e8b744fba714077c952 | [
"MIT"
] | null | null | null | #include "Polyhedron.h"
#include "Transform.h"
#include <GL/glew.h>
using namespace GT1;
/************************************************************************/
/* Class Edge */
/************************************************************************/
bool Edge::operator==(const Edge &other) const {
return
this->v0 == other.v0 && this->v1 == other.v1
||
this->v0 == other.v1 && this->v1 == other.v0;
}
glm::vec3 Edge::operator[](int index) const {
assert(index == 0 || index == 1);
if(index == 0) return v0;
return v1;
}
Edge Edge::GetTransformedCopy() const {
return Edge(
transform,
transform->TransformPoint(v0),
transform->TransformPoint(v1)
);
}
/************************************************************************/
/* Class Face */
/************************************************************************/
void Face::InsertEdge(Edge edge) {
edges.push_back(edge);
if(std::find(vertices.begin(), vertices.end(), edge.v0) == vertices.end()) vertices.push_back(edge.v0);
if(std::find(vertices.begin(), vertices.end(), edge.v1) == vertices.end()) vertices.push_back(edge.v1);
}
bool Face::Contains(Edge edge) const {
return std::find(edges.begin(), edges.end(), edge) != edges.end();
}
glm::vec3 Face::GetTransformedVertex(int i) const {
return transform->TransformPoint(vertices[i]);
}
bool Face::Contains(glm::vec3 vertex) const {
return std::find(vertices.begin(), vertices.end(), vertex) != vertices.end();
}
Edge Face::GetTransformedEdge(int i) const {
return edges[i].GetTransformedCopy();
}
Face Face::GetTransformedCopy() const {
Face face(transform);
face.normal = GetTransformedNormal();
for(const glm::vec3& vertex : vertices)
face.vertices.push_back(transform->TransformPoint(vertex));
for(const Edge& edge : edges) {
face.edges.push_back(edge.GetTransformedCopy());
}
// Compute plane
face.plane.normal = face.normal;
face.plane.distance = glm::dot(face.vertices[0], face.normal);
return face;
}
glm::vec3 Face::GetTransformedNormal() const {
return transform->TransformDirection(normal);
}
/************************************************************************/
/* Class Polyhedron */
/************************************************************************/
// Also calculates the face's normal and plane
void Polyhedron::InsertFace(Face face) {
// Compute normal
face.normal = glm::normalize(glm::cross(face.edges[0].Get(), face.edges[1].Get()));
// Compute plane
face.plane.normal = face.normal;
face.plane.distance = glm::dot(face.vertices[0], face.normal);
// Insert face
faces.push_back(face);
// Add unique edges and vertices to polyhedron
for(Edge edge : face.edges) {
if(std::find(edges.begin(), edges.end(), edge) == edges.end()) edges.push_back(edge);
if(std::find(vertices.begin(), vertices.end(), edge.v0) == vertices.end()) vertices.push_back(edge.v0);
if(std::find(vertices.begin(), vertices.end(), edge.v1) == vertices.end()) vertices.push_back(edge.v1);
}
}
glm::vec3 Polyhedron::GetTransformedVertex(int i) const {
return transform->TransformPoint(vertices[i]);
}
glm::vec3 Polyhedron::GetTransformedNormal(int i) const {
return faces[i].GetTransformedNormal();
}
Edge Polyhedron::GetTransformedEdge(int i) const {
return edges[i].GetTransformedCopy();
}
Face Polyhedron::GetTransformedFace(int i) const {
return faces[i].GetTransformedCopy();
}
glm::vec3 Polyhedron::GetSupportPoint(const glm::vec3& dir) const {
std::vector<glm::vec3> transformed;
transform->TransformPoints(vertices, transformed);
float bestProjection = -FLT_MAX;
glm::vec3 bestVertex;
for(const glm::vec3& v : transformed) {
float projection = glm::dot(v, dir);
if(projection > bestProjection) {
bestVertex = v;
bestProjection = projection;
}
}
return bestVertex;
}
/************************************************************************/
/* Class Cube */
/************************************************************************/
Cube::Cube(Transform* transform) : Polyhedron(transform)
{
/************************************************************************/
/* Physics data */
/************************************************************************/
glm::vec3 v0(-0.5f, 0.5f, 0.5f);
glm::vec3 v1(-0.5f,-0.5f, 0.5f);
glm::vec3 v2(0.5f, -0.5f, 0.5f);
glm::vec3 v3(0.5f, 0.5f, 0.5f);
glm::vec3 v4(0.5f, 0.5f, -0.5f);
glm::vec3 v5(0.5f, -0.5f, -0.5f);
glm::vec3 v6(-0.5f, -0.5f, -0.5f);
glm::vec3 v7(-0.5f, 0.5f, -0.5f);
// Front
Face face(transform);
face.InsertEdge(Edge(transform, v0, v1));
face.InsertEdge(Edge(transform, v1, v2));
face.InsertEdge(Edge(transform, v2, v3));
face.InsertEdge(Edge(transform, v3, v0));
InsertFace(face);
// Right
face = Face(transform);
face.InsertEdge(Edge(transform, v3, v2));
face.InsertEdge(Edge(transform, v2, v5));
face.InsertEdge(Edge(transform, v5, v4));
face.InsertEdge(Edge(transform, v4, v3));
InsertFace(face);
// Back
face = Face(transform);
face.InsertEdge(Edge(transform, v4, v5));
face.InsertEdge(Edge(transform, v5, v6));
face.InsertEdge(Edge(transform, v6, v7));
face.InsertEdge(Edge(transform, v7, v4));
InsertFace(face);
// Left
face = Face(transform);
face.InsertEdge(Edge(transform, v7, v6));
face.InsertEdge(Edge(transform, v6, v1));
face.InsertEdge(Edge(transform, v1, v0));
face.InsertEdge(Edge(transform, v0, v7));
InsertFace(face);
// Up
face = Face(transform);
face.InsertEdge(Edge(transform, v7, v0));
face.InsertEdge(Edge(transform, v0, v3));
face.InsertEdge(Edge(transform, v3, v4));
face.InsertEdge(Edge(transform, v4, v7));
InsertFace(face);
// Down
face = Face(transform);
face.InsertEdge(Edge(transform, v1, v6));
face.InsertEdge(Edge(transform, v6, v5));
face.InsertEdge(Edge(transform, v5, v2));
face.InsertEdge(Edge(transform, v2, v1));
InsertFace(face);
assert(GetVertexCount() == 8);
assert(GetEdgeCount() == 12);
assert(GetFaceCount() == 6);
/************************************************************************/
/* Rendering data */
/************************************************************************/
GLfloat vertexData[] = {
0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
-0.5f,-0.5f, 0.5f,
-0.5f,-0.5f, 0.5f,
0.5f,-0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
0.5f,-0.5f, 0.5f,
0.5f,-0.5f,-0.5f,
0.5f,-0.5f,-0.5f,
0.5f, 0.5f,-0.5f,
0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
0.5f, 0.5f,-0.5f,
-0.5f, 0.5f,-0.5f,
-0.5f, 0.5f,-0.5f,
-0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
-0.5f, 0.5f,-0.5f,
-0.5f,-0.5f,-0.5f,
-0.5f,-0.5f,-0.5f,
-0.5f,-0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
-0.5f,-0.5f,-0.5f,
0.5f,-0.5f,-0.5f,
0.5f,-0.5f, 0.5f,
0.5f,-0.5f, 0.5f,
-0.5f,-0.5f, 0.5f,
-0.5f,-0.5f,-0.5f,
0.5f,-0.5f,-0.5f,
-0.5f,-0.5f,-0.5f,
-0.5f, 0.5f,-0.5f,
-0.5f, 0.5f,-0.5f,
0.5f, 0.5f,-0.5f,
0.5f,-0.5f,-0.5f
};
float colorData[] = {
1.0f,1.0f,1.0f,
1.0f,1.0f,0.0f,
1.0f,0.0f,0.0f,
1.0f,0.0f,0.0f,
1.0f,0.0f,1.0f,
1.0f,1.0f,1.0f,
1.0f,1.0f,1.0f,
1.0f,0.0f,1.0f,
0.0f,0.0f,1.0f,
0.0f,0.0f,1.0f,
0.0f,1.0f,1.0f,
1.0f,1.0f,1.0f,
1.0f,1.0f,1.0f,
0.0f,1.0f,1.0f,
0.0f,1.0f,0.0f,
0.0f,1.0f,0.0f,
1.0f,1.0f,0.0f,
1.0f,1.0f,1.0f,
1.0f,1.0f,0.0f,
0.0f,1.0f,0.0f,
0.0f,0.0f,0.0f,
0.0f,0.0f,0.0f,
1.0f,0.0f,0.0f,
1.0f,1.0f,0.0f,
0.0f,0.0f,0.0f,
0.0f,0.0f,1.0f,
1.0f,0.0f,1.0f,
1.0f,0.0f,1.0f,
1.0f,0.0f,0.0f,
0.0f,0.0f,0.0f,
0.0f,0.0f,1.0f,
0.0f,0.0f,0.0f,
0.0f,1.0f,0.0f,
0.0f,1.0f,0.0f,
0.0f,1.0f,1.0f,
0.0f,0.0f,1.0f
};
glGenBuffers(1, &vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW);
glGenBuffers(1, &colorbuffer);
glBindBuffer(GL_ARRAY_BUFFER, colorbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(colorData), colorData, GL_STATIC_DRAW);
}
void Cube::Render() {
// 1rst attribute buffer : vertices
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glVertexAttribPointer(
0, // attribute. No particular reason for 0, but must match the layout in the shader.
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
// 2nd attribute buffer : colors
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, colorbuffer);
glVertexAttribPointer(
1, // attribute. No particular reason for 1, but must match the layout in the shader.
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
// Draw the triangle !
glDrawArrays(GL_TRIANGLES, 0, 12*3); // 12*3 indices starting at 0 -> 12 triangles
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
} | 25.376045 | 105 | 0.564764 | [
"render",
"vector",
"transform"
] |
1406a32c54d014fbea088c23fb9a3b56ea8a7e83 | 1,360 | cpp | C++ | LeetCode/ThousandOne/0804-unique_morse_code.cpp | Ginkgo-Biloba/Cpp-Repo1-VS | 231c68a055e6bf69a3f7c224e7c0182b67ce5b67 | [
"Apache-2.0"
] | null | null | null | LeetCode/ThousandOne/0804-unique_morse_code.cpp | Ginkgo-Biloba/Cpp-Repo1-VS | 231c68a055e6bf69a3f7c224e7c0182b67ce5b67 | [
"Apache-2.0"
] | null | null | null | LeetCode/ThousandOne/0804-unique_morse_code.cpp | Ginkgo-Biloba/Cpp-Repo1-VS | 231c68a055e6bf69a3f7c224e7c0182b67ce5b67 | [
"Apache-2.0"
] | null | null | null | #include "leetcode.hpp"
/* 804. 唯一摩尔斯密码词
国际摩尔斯密码定义一种标准编码方式,将每个字母对应于一个由一系列点和短线组成的字符串。
比如: "a" 对应 ".-", "b" 对应 "-...", "c" 对应 "-.-.", 等等。
为了方便,所有26个英文字母对应摩尔斯密码表如下:
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
给定一个单词列表,每个单词可以写成每个字母对应摩尔斯密码的组合。
例如,"cbs" 可以写成 "-.-..--...",(即 "-.-." + "-..." + ".-"字符串的结合)。
我们将这样一个连接过程称作单词翻译。
返回我们可以获得所有词不同单词翻译的数量。
例如:
输入: words = ["gin", "zen", "gig", "msg"]
输出: 2
解释:
各单词翻译如下:
"gin" -> "--...-."
"zen" -> "--...-."
"gig" -> "--...--."
"msg" -> "--...--."
共有 2 种不同翻译, "--...-." 和 "--...--.".
注意:
单词列表words 的长度不会超过 100。
每个单词 words[i]的长度范围为 [1, 12]。
每个单词 words[i]只包含小写字母。
*/
static char const* morse[] = {
".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
"....", "..", ".---", "-.-", ".-..", "--", "-.",
"---", ".--.", "--.-", ".-.", "...", "-",
"..-", "...-", ".--", "-..-", "-.--", "--.."
};
int uniqueMorseRepresentations(vector<string>& words)
{
int const ida = 'a';
unordered_set<string> dst;
string cur;
for (string const& w : words)
{
cur.clear();
for (char c : w)
cur.append(morse[c - ida]);
dst.insert(cur);
}
return static_cast<int>(dst.size());
}
int main()
{
vector<string> words = { "gin", "zen", "gig", "msg" };
OutExpr(uniqueMorseRepresentations(words), "%d");
}
| 21.25 | 161 | 0.425 | [
"vector"
] |
1408d59ad7892bcc8a78ec3ba29571e39e0ff602 | 50,085 | cpp | C++ | engine/physics/src/physics/physics_3d.cpp | hapass/defold | fd3602f27a2596a2ad62bf9a70ae9d7acda24ad8 | [
"Apache-2.0"
] | null | null | null | engine/physics/src/physics/physics_3d.cpp | hapass/defold | fd3602f27a2596a2ad62bf9a70ae9d7acda24ad8 | [
"Apache-2.0"
] | null | null | null | engine/physics/src/physics/physics_3d.cpp | hapass/defold | fd3602f27a2596a2ad62bf9a70ae9d7acda24ad8 | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 The Defold Foundation
// Licensed under the Defold License version 1.0 (the "License"); you may not use
// this file except in compliance with the License.
//
// You may obtain a copy of the License, together with FAQs at
// https://www.defold.com/license
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
#include <stdint.h>
#include <stdlib.h> // qsort
#include <dlib/array.h>
#include <dlib/log.h>
#include <dlib/math.h>
#include <dlib/profile.h>
#include "btBulletDynamicsCommon.h"
#include "BulletCollision/CollisionDispatch/btGhostObject.h"
#include "physics_3d.h"
#include <stdio.h>
namespace dmPhysics
{
using namespace Vectormath::Aos;
/*
* NOTE
* This struct has the sole purpose of wrapping a collision object along with its collision group/mask.
* The reason is that the way we do enabling/disabling (by adding/removing from the world)
* looses the group/mask (bullet stores them in the broadphase-handle).
* The first attempt was to use the collision flags ACTIVE_TAG vs DISABLE_SIMULATION, but that does not
* work for static bodies and ghost objects (=triggers).
* See: https://defold.fogbugz.com/default.asp?2085
*/
struct CollisionObject3D
{
btCollisionObject* m_CollisionObject;
uint16_t m_CollisionGroup;
uint16_t m_CollisionMask;
};
static Vectormath::Aos::Point3 GetWorldPosition(HContext3D context, btCollisionObject* collision_object);
static Vectormath::Aos::Quat GetWorldRotation(HContext3D context, btCollisionObject* collision_object);
static btCollisionObject* GetCollisionObject(HCollisionObject3D co)
{
return ((CollisionObject3D*)co)->m_CollisionObject;
}
class MotionState : public btMotionState
{
public:
MotionState(HContext3D context, void* user_data, GetWorldTransformCallback get_world_transform, SetWorldTransformCallback set_world_transform)
: m_Context(context)
, m_UserData(user_data)
, m_GetWorldTransform(get_world_transform)
, m_SetWorldTransform(set_world_transform)
{
}
virtual ~MotionState()
{
}
virtual void getWorldTransform(btTransform& world_trans) const
{
if (m_GetWorldTransform != 0x0)
{
dmTransform::Transform world_transform;
m_GetWorldTransform(m_UserData, world_transform);
Vectormath::Aos::Point3 position = Vectormath::Aos::Point3(world_transform.GetTranslation());
Vectormath::Aos::Quat rotation = Vectormath::Aos::Quat(world_transform.GetRotation());
btVector3 origin;
ToBt(position, origin, m_Context->m_Scale);
world_trans.setOrigin(origin);
world_trans.setRotation(btQuaternion(rotation.getX(), rotation.getY(), rotation.getZ(), rotation.getW()));
}
else
{
world_trans = btTransform::getIdentity();
}
}
virtual void setWorldTransform(const btTransform &worldTrans)
{
if (m_SetWorldTransform != 0x0)
{
btVector3 bt_pos = worldTrans.getOrigin();
btQuaternion bt_rot = worldTrans.getRotation();
Vector3 translation;
FromBt(bt_pos, translation, m_Context->m_InvScale);
Quat rot = Quat(bt_rot.getX(), bt_rot.getY(), bt_rot.getZ(), bt_rot.getW());
m_SetWorldTransform(m_UserData, Point3(translation), rot);
}
}
protected:
HContext3D m_Context;
void* m_UserData;
GetWorldTransformCallback m_GetWorldTransform;
SetWorldTransformCallback m_SetWorldTransform;
};
Context3D::Context3D()
: m_Worlds()
, m_DebugCallbacks()
, m_Gravity(0.0f, -10.0f, 0.0f)
, m_Socket(0)
, m_Scale(1.0f)
, m_InvScale(1.0f)
, m_ContactImpulseLimit(0.0f)
, m_TriggerEnterLimit(0.0f)
, m_RayCastLimit(0)
, m_TriggerOverlapCapacity(0)
, m_AllowDynamicTransforms(0)
{
}
World3D::World3D(HContext3D context, const NewWorldParams& params)
: m_TriggerOverlaps(context->m_TriggerOverlapCapacity)
, m_DebugDraw(&context->m_DebugCallbacks)
, m_Context(context)
, m_AllowDynamicTransforms(context->m_AllowDynamicTransforms)
{
m_CollisionConfiguration = new btDefaultCollisionConfiguration();
m_Dispatcher = new btCollisionDispatcher(m_CollisionConfiguration);
///the maximum size of the collision world. Make sure objects stay within these boundaries
///Don't make the world AABB size too large, it will harm simulation quality and performance
btVector3 world_aabb_min;
ToBt(params.m_WorldMin, world_aabb_min, context->m_Scale);
btVector3 world_aabb_max;
ToBt(params.m_WorldMax, world_aabb_max, context->m_Scale);
int maxProxies = 1024;
m_OverlappingPairCache = new btAxisSweep3(world_aabb_min,world_aabb_max,maxProxies);
m_Solver = new btSequentialImpulseConstraintSolver;
m_DynamicsWorld = new btDiscreteDynamicsWorld(m_Dispatcher, m_OverlappingPairCache, m_Solver, m_CollisionConfiguration);
m_DynamicsWorld->setGravity(btVector3(context->m_Gravity.getX(), context->m_Gravity.getY(), context->m_Gravity.getZ()));
m_DynamicsWorld->setDebugDrawer(&m_DebugDraw);
m_GetWorldTransform = params.m_GetWorldTransformCallback;
m_SetWorldTransform = params.m_SetWorldTransformCallback;
m_RayCastRequests.SetCapacity(context->m_RayCastLimit);
OverlapCacheInit(&m_TriggerOverlaps);
}
World3D::~World3D()
{
delete m_DynamicsWorld;
delete m_Solver;
delete m_OverlappingPairCache;
delete m_Dispatcher;
delete m_CollisionConfiguration;
}
static void ResponseFromRayCastResult(RayCastResponse& response, btScalar inv_scale, btScalar fraction,
const btVector3& point, const btVector3& normal, const btCollisionObject* co)
{
response.m_Hit = 1;
response.m_Fraction = fraction;
FromBt(point, response.m_Position, inv_scale);
FromBt(normal, response.m_Normal, 1.0f); // don't scale normal
if (co != 0x0)
{
response.m_CollisionObjectUserData = co->getUserPointer();
response.m_CollisionObjectGroup = co->getBroadphaseHandle()->m_collisionFilterGroup;
}
}
struct RayCastResultClosestCallback3D : public btCollisionWorld::ClosestRayResultCallback
{
RayCastResultClosestCallback3D(const btVector3& from, const btVector3& to, uint16_t mask, void* ignored_user_data)
: btCollisionWorld::ClosestRayResultCallback(from, to)
, m_IgnoredUserData(ignored_user_data)
{
// *all* groups for now, bullet will test this against the colliding object's mask
m_collisionFilterGroup = ~0;
m_collisionFilterMask = mask;
}
virtual btScalar addSingleResult(btCollisionWorld::LocalRayResult& rayResult, bool normalInWorldSpace)
{
if (rayResult.m_collisionObject->getUserPointer() == m_IgnoredUserData)
return 1.0f;
else if (!rayResult.m_collisionObject->hasContactResponse())
return 1.0f;
else
return btCollisionWorld::ClosestRayResultCallback::addSingleResult(rayResult, normalInWorldSpace);
}
void* m_IgnoredUserData;
RayCastResponse m_Response;
};
// Grabbed from a more recent Bullet version for now
/// BULLET (do not modify) ->
struct AllHitsRayResultCallback : public btCollisionWorld::RayResultCallback
{
AllHitsRayResultCallback(const btVector3& rayFromWorld, const btVector3& rayToWorld)
: m_rayFromWorld(rayFromWorld)
, m_rayToWorld(rayToWorld)
{
}
btAlignedObjectArray<const btCollisionObject*> m_collisionObjects;
btAlignedObjectArray<btVector3> m_hitNormalWorld;
btAlignedObjectArray<btVector3> m_hitPointWorld;
btAlignedObjectArray<btScalar> m_hitFractions;
btVector3 m_rayFromWorld;//used to calculate hitPointWorld from hitFraction
btVector3 m_rayToWorld;
virtual btScalar addSingleResult(btCollisionWorld::LocalRayResult& rayResult, bool normalInWorldSpace)
{
m_collisionObject = rayResult.m_collisionObject;
m_collisionObjects.push_back(rayResult.m_collisionObject);
btVector3 hitNormalWorld;
if (normalInWorldSpace)
{
hitNormalWorld = rayResult.m_hitNormalLocal;
} else
{
hitNormalWorld = m_collisionObject->getWorldTransform().getBasis()*rayResult.m_hitNormalLocal;
}
m_hitNormalWorld.push_back(hitNormalWorld);
btVector3 hitPointWorld;
hitPointWorld.setInterpolate3(m_rayFromWorld,m_rayToWorld,rayResult.m_hitFraction);
m_hitPointWorld.push_back(hitPointWorld);
m_hitFractions.push_back(rayResult.m_hitFraction);
return m_closestHitFraction;
}
};
/// <- END BULLET
struct RayCastResultAllCallback3D : public AllHitsRayResultCallback
{
RayCastResultAllCallback3D(const btVector3& from, const btVector3& to, uint16_t mask, void* ignored_user_data)
: AllHitsRayResultCallback(from, to)
, m_IgnoredUserData(ignored_user_data)
{
// *all* groups for now, bullet will test this against the colliding object's mask
m_collisionFilterGroup = ~0;
m_collisionFilterMask = mask;
}
virtual btScalar addSingleResult(btCollisionWorld::LocalRayResult& rayResult, bool normalInWorldSpace)
{
if (rayResult.m_collisionObject->getUserPointer() == m_IgnoredUserData)
return 1.0f;
else if (!rayResult.m_collisionObject->hasContactResponse())
return 1.0f;
else
return AllHitsRayResultCallback::addSingleResult(rayResult, normalInWorldSpace);
}
void* m_IgnoredUserData;
};
HContext3D NewContext3D(const NewContextParams& params)
{
if (params.m_Scale < MIN_SCALE || params.m_Scale > MAX_SCALE)
{
dmLogFatal("Physics scale is outside the valid range %.2f - %.2f.", MIN_SCALE, MAX_SCALE);
return 0x0;
}
Context3D* context = new Context3D();
ToBt(params.m_Gravity, context->m_Gravity, params.m_Scale);
context->m_Worlds.SetCapacity(params.m_WorldCount);
context->m_Scale = params.m_Scale;
context->m_InvScale = 1.0f / params.m_Scale;
context->m_ContactImpulseLimit = params.m_ContactImpulseLimit * params.m_Scale;
context->m_TriggerEnterLimit = params.m_TriggerEnterLimit * params.m_Scale;
context->m_RayCastLimit = params.m_RayCastLimit3D;
context->m_TriggerOverlapCapacity = params.m_TriggerOverlapCapacity;
context->m_AllowDynamicTransforms = params.m_AllowDynamicTransforms;
dmMessage::Result result = dmMessage::NewSocket(PHYSICS_SOCKET_NAME, &context->m_Socket);
if (result != dmMessage::RESULT_OK)
{
dmLogFatal("Could not create socket '%s'.", PHYSICS_SOCKET_NAME);
DeleteContext3D(context);
return 0x0;
}
return context;
}
void DeleteContext3D(HContext3D context)
{
if (!context->m_Worlds.Empty())
{
dmLogWarning("Deleting %ud 3d worlds since the context is deleted.", context->m_Worlds.Size());
for (uint32_t i = 0; i < context->m_Worlds.Size(); ++i)
delete context->m_Worlds[i];
}
if (context->m_Socket != 0)
dmMessage::DeleteSocket(context->m_Socket);
delete context;
}
dmMessage::HSocket GetSocket3D(HContext3D context)
{
return context->m_Socket;
}
HWorld3D NewWorld3D(HContext3D context, const NewWorldParams& params)
{
if (context->m_Worlds.Full())
{
dmLogError("%s", "Physics world buffer full, world could not be created.");
return 0x0;
}
World3D* world = new World3D(context, params);
context->m_Worlds.Push(world);
return world;
}
void DeleteWorld3D(HContext3D context, HWorld3D world)
{
for (uint32_t i = 0; i < context->m_Worlds.Size(); ++i)
if (context->m_Worlds[i] == world)
context->m_Worlds.EraseSwap(i);
delete world;
}
void SetDrawDebug3D(HWorld3D world, bool draw_debug)
{
int debug_mode = 0;
if (draw_debug)
{
debug_mode = btIDebugDraw::DBG_NoDebug
| btIDebugDraw::DBG_DrawWireframe
| btIDebugDraw::DBG_DrawAabb
| btIDebugDraw::DBG_DrawFeaturesText
| btIDebugDraw::DBG_DrawContactPoints
| btIDebugDraw::DBG_DrawText
| btIDebugDraw::DBG_ProfileTimings
| btIDebugDraw::DBG_EnableSatComparison
| btIDebugDraw::DBG_EnableCCD
| btIDebugDraw::DBG_DrawConstraints
| btIDebugDraw::DBG_DrawConstraintLimits;
}
world->m_DebugDraw.setDebugMode(debug_mode);
}
static void UpdateOverlapCache(OverlapCache* cache, HContext3D context, btDispatcher* dispatcher, const StepWorldContext& step_context);
void StepWorld3D(HWorld3D world, const StepWorldContext& step_context)
{
float dt = step_context.m_DT;
HContext3D context = world->m_Context;
float scale = context->m_Scale;
// Epsilon defining what transforms are considered noise and not
// Values are picked by inspection, current rot value is roughly equivalent to 1 degree
const float POS_EPSILON = 0.00005f * scale;
const float ROT_EPSILON = 0.00007f;
// Update all trigger transforms before physics world step
if (world->m_GetWorldTransform != 0x0)
{
DM_PROFILE(Physics, "UpdateTriggers");
int collision_object_count = world->m_DynamicsWorld->getNumCollisionObjects();
btCollisionObjectArray& collision_objects = world->m_DynamicsWorld->getCollisionObjectArray();
for (int i = 0; i < collision_object_count; ++i)
{
btCollisionObject* collision_object = collision_objects[i];
bool retrieve_gameworld_transform = world->m_AllowDynamicTransforms && !collision_object->isStaticObject();
if (collision_object->getInternalType() == btCollisionObject::CO_GHOST_OBJECT || collision_object->isKinematicObject() || retrieve_gameworld_transform)
{
Point3 old_position = GetWorldPosition(context, collision_object);
Quat old_rotation = GetWorldRotation(context, collision_object);
dmTransform::Transform world_transform;
(*world->m_GetWorldTransform)(collision_object->getUserPointer(), world_transform);
Vectormath::Aos::Point3 position = Vectormath::Aos::Point3(world_transform.GetTranslation());
Vectormath::Aos::Quat rotation = Vectormath::Aos::Quat(world_transform.GetRotation());
float dp = distSqr(old_position, position);
float dr = norm(rotation - old_rotation);
if (dp > POS_EPSILON || dr > ROT_EPSILON)
{
btVector3 bt_pos;
ToBt(position, bt_pos, scale);
btTransform world_t(btQuaternion(rotation.getX(), rotation.getY(), rotation.getZ(), rotation.getW()), bt_pos);
collision_object->setWorldTransform(world_t);
collision_object->activate(true);
}
}
// Scaling
if (retrieve_gameworld_transform)
{
dmTransform::Transform world_transform;
world->m_GetWorldTransform(collision_object->getUserPointer(), world_transform);
// The compound shape scale always defaults to 1
btCollisionShape* shape = collision_object->getCollisionShape();
float object_scale = world_transform.GetUniformScale();
float shape_scale = shape->getLocalScaling().getX();
if (object_scale != shape_scale)
{
shape->setLocalScaling(btVector3(object_scale,object_scale,object_scale));
if (!collision_object->isActive())
collision_object->activate(true);
}
}
}
}
{
DM_PROFILE(Physics, "StepSimulation");
// Step simulation
// TODO: Max substeps = 1 for now...
world->m_DynamicsWorld->stepSimulation(dt, 1);
}
// Handle ray cast requests
uint32_t size = world->m_RayCastRequests.Size();
if (size > 0)
{
DM_PROFILE(Physics, "RayCasts");
for (uint32_t i = 0; i < size; ++i)
{
const RayCastRequest& request = world->m_RayCastRequests[i];
if (step_context.m_RayCastCallback == 0x0)
{
dmLogWarning("Ray cast requested without any response callback, skipped.");
continue;
}
float scale = world->m_Context->m_Scale;
btVector3 from;
ToBt(request.m_From, from, scale);
btVector3 to;
ToBt(request.m_To, to, scale);
RayCastResultClosestCallback3D result_callback(from, to, request.m_Mask, request.m_IgnoredUserData);
world->m_DynamicsWorld->rayTest(from, to, result_callback);
RayCastResponse response;
response.m_Hit = result_callback.hasHit() ? 1 : 0;
response.m_Fraction = result_callback.m_closestHitFraction;
float inv_scale = world->m_Context->m_InvScale;
FromBt(result_callback.m_hitPointWorld, response.m_Position, inv_scale);
FromBt(result_callback.m_hitNormalWorld, response.m_Normal, 1.0f); // don't scale normal
if (result_callback.m_collisionObject != 0x0)
{
response.m_CollisionObjectUserData = result_callback.m_collisionObject->getUserPointer();
response.m_CollisionObjectGroup = result_callback.m_collisionObject->getBroadphaseHandle()->m_collisionFilterGroup;
}
step_context.m_RayCastCallback(response, request, step_context.m_RayCastUserData);
}
world->m_RayCastRequests.SetSize(0);
}
// Report collisions
bool requests_collision_callbacks = true;
bool requests_contact_callbacks = true;
CollisionCallback collision_callback = step_context.m_CollisionCallback;
ContactPointCallback contact_point_callback = step_context.m_ContactPointCallback;
btDispatcher* dispatcher = world->m_DynamicsWorld->getDispatcher();
float contact_impulse_limit = world->m_Context->m_ContactImpulseLimit;
if (collision_callback != 0x0 || contact_point_callback != 0x0)
{
DM_PROFILE(Physics, "CollisionCallbacks");
int num_manifolds = dispatcher->getNumManifolds();
for (int i = 0; i < num_manifolds && (requests_collision_callbacks || requests_contact_callbacks); ++i)
{
btPersistentManifold* contact_manifold = dispatcher->getManifoldByIndexInternal(i);
btCollisionObject* object_a = static_cast<btCollisionObject*>(contact_manifold->getBody0());
btCollisionObject* object_b = static_cast<btCollisionObject*>(contact_manifold->getBody1());
if (!object_a->isActive() && !object_b->isActive())
continue;
// verify that the impulse is large enough to be reported
float max_impulse = 0.0f;
int num_contacts = contact_manifold->getNumContacts();
for (int j = 0; j < num_contacts && requests_contact_callbacks; ++j)
{
btManifoldPoint& pt = contact_manifold->getContactPoint(j);
max_impulse = dmMath::Max(max_impulse, pt.getAppliedImpulse());
}
// early out if the impulse is too small to be reported
if (max_impulse < contact_impulse_limit)
continue;
if (collision_callback != 0x0 && requests_collision_callbacks)
{
requests_collision_callbacks = collision_callback(object_a->getUserPointer(), object_a->getBroadphaseHandle()->m_collisionFilterGroup, object_b->getUserPointer(), object_b->getBroadphaseHandle()->m_collisionFilterGroup, step_context.m_CollisionUserData);
}
if (contact_point_callback != 0x0)
{
for (int j = 0; j < num_contacts && requests_contact_callbacks; ++j)
{
btManifoldPoint& pt = contact_manifold->getContactPoint(j);
btRigidBody* body_a = btRigidBody::upcast(object_a);
btRigidBody* body_b = btRigidBody::upcast(object_b);
ContactPoint point;
float inv_scale = world->m_Context->m_InvScale;
const btVector3& pt_a = pt.getPositionWorldOnA();
FromBt(pt_a, point.m_PositionA, inv_scale);
point.m_UserDataA = object_a->getUserPointer();
point.m_GroupA = object_a->getBroadphaseHandle()->m_collisionFilterGroup;
if (body_a)
point.m_MassA = 1.0f / body_a->getInvMass();
const btVector3& pt_b = pt.getPositionWorldOnB();
FromBt(pt_b, point.m_PositionB, inv_scale);
point.m_UserDataB = object_b->getUserPointer();
point.m_GroupB = object_b->getBroadphaseHandle()->m_collisionFilterGroup;
if (body_b)
point.m_MassB = 1.0f / body_b->getInvMass();
const btVector3& normal = pt.m_normalWorldOnB;
FromBt(-normal, point.m_Normal, 1.0f); // Don't scale normals
point.m_Distance = -pt.getDistance() * inv_scale;
point.m_AppliedImpulse = pt.getAppliedImpulse() * inv_scale;
Vectormath::Aos::Vector3 vel_a(0.0f, 0.0f, 0.0f);
if (body_a)
{
const btVector3& v = body_a->getLinearVelocity();
FromBt(v, vel_a, inv_scale);
}
Vectormath::Aos::Vector3 vel_b(0.0f, 0.0f, 0.0f);
if (body_b)
{
const btVector3& v = body_b->getLinearVelocity();
FromBt(v, vel_b, inv_scale);
}
point.m_RelativeVelocity = vel_a - vel_b;
requests_contact_callbacks = contact_point_callback(point, step_context.m_ContactPointUserData);
}
}
}
}
UpdateOverlapCache(&world->m_TriggerOverlaps, context, dispatcher, step_context);
world->m_DynamicsWorld->debugDrawWorld();
}
void UpdateOverlapCache(OverlapCache* cache, HContext3D context, btDispatcher* dispatcher, const StepWorldContext& step_context)
{
DM_PROFILE(Physics, "TriggerCallbacks");
OverlapCacheReset(cache);
OverlapCacheAddData add_data;
add_data.m_TriggerEnteredCallback = step_context.m_TriggerEnteredCallback;
add_data.m_TriggerEnteredUserData = step_context.m_TriggerEnteredUserData;
int num_manifolds = dispatcher->getNumManifolds();
for (int i = 0; i < num_manifolds; ++i)
{
btPersistentManifold* contact_manifold = dispatcher->getManifoldByIndexInternal(i);
btCollisionObject* object_a = static_cast<btCollisionObject*>(contact_manifold->getBody0());
btCollisionObject* object_b = static_cast<btCollisionObject*>(contact_manifold->getBody1());
if (!object_a->isActive() || !object_b->isActive())
continue;
if (btGhostObject::upcast(object_a) != 0x0 || btGhostObject::upcast(object_b) != 0x0)
{
float max_distance = 0.0f;
int contact_count = contact_manifold->getNumContacts();
for (int j = 0; j < contact_count; ++j)
{
const btManifoldPoint& point = contact_manifold->getContactPoint(j);
max_distance = dmMath::Max(max_distance, point.getDistance());
}
if (max_distance >= context->m_TriggerEnterLimit)
{
add_data.m_ObjectA = object_a;
add_data.m_UserDataA = object_a->getUserPointer();
add_data.m_ObjectB = object_b;
add_data.m_UserDataB = object_b->getUserPointer();
add_data.m_GroupA = object_a->getBroadphaseHandle()->m_collisionFilterGroup;
add_data.m_GroupB = object_b->getBroadphaseHandle()->m_collisionFilterGroup;
OverlapCacheAdd(cache, add_data);
}
}
}
OverlapCachePruneData prune_data;
prune_data.m_TriggerExitedCallback = step_context.m_TriggerExitedCallback;
prune_data.m_TriggerExitedUserData = step_context.m_TriggerExitedUserData;
OverlapCachePrune(cache, prune_data);
}
HCollisionShape3D NewSphereShape3D(HContext3D context, float radius)
{
return new btSphereShape(context->m_Scale * radius);
}
HCollisionShape3D NewBoxShape3D(HContext3D context, const Vector3& half_extents)
{
btVector3 dims;
ToBt(half_extents, dims, context->m_Scale);
return new btBoxShape(dims);
}
HCollisionShape3D NewCapsuleShape3D(HContext3D context, float radius, float height)
{
float scale = context->m_Scale;
return new btCapsuleShape(scale * radius, scale * height);
}
HCollisionShape3D NewConvexHullShape3D(HContext3D context, const float* vertices, uint32_t vertex_count)
{
assert(sizeof(btScalar) == sizeof(float));
float scale = context->m_Scale;
const uint32_t elem_count = vertex_count * 3;
float* v = new float[elem_count];
for (uint32_t i = 0; i < elem_count; ++i)
{
v[i] = vertices[i] * scale;
}
btConvexHullShape* hull = new btConvexHullShape(v, vertex_count, sizeof(float) * 3);
delete [] v;
return hull;
}
void DeleteCollisionShape3D(HCollisionShape3D shape)
{
delete (btConvexShape*)shape;
}
bool g_ShapeGroupWarning = false;
static btConvexShape* CloneShape(btConvexShape* shape)
{
switch(shape->getShapeType())
{
case SPHERE_SHAPE_PROXYTYPE: return new btSphereShape(((btSphereShape*)shape)->getRadius()); break;
case BOX_SHAPE_PROXYTYPE: return new btBoxShape(((btBoxShape*)shape)->getHalfExtentsWithoutMargin()); break;
case CAPSULE_SHAPE_PROXYTYPE: return new btCapsuleShape(((btCapsuleShape*)shape)->getRadius(), 2.0f * ((btCapsuleShape*)shape)->getHalfHeight()); break;
case CONVEX_HULL_SHAPE_PROXYTYPE: return new btConvexHullShape((btScalar*)((btConvexHullShape*)shape)->getPoints(), ((btConvexHullShape*)shape)->getNumPoints()); break;
}
return shape;
}
HCollisionObject3D NewCollisionObject3D(HWorld3D world, const CollisionObjectData& data, HCollisionShape3D* shapes, uint32_t shape_count)
{
return NewCollisionObject3D(world, data, shapes, 0, 0, shape_count);
}
HCollisionObject3D NewCollisionObject3D(HWorld3D world, const CollisionObjectData& data, HCollisionShape3D* shapes,
Vectormath::Aos::Vector3* translations, Vectormath::Aos::Quat* rotations,
uint32_t shape_count)
{
if (shape_count == 0)
{
dmLogError("Collision objects must have a shape.");
return 0x0;
}
switch (data.m_Type)
{
case COLLISION_OBJECT_TYPE_DYNAMIC:
if (data.m_Mass == 0.0f)
{
dmLogError("Collision objects can not be dynamic and have zero mass.");
return 0x0;
}
break;
default:
if (data.m_Mass > 0.0f)
{
dmLogError("Only dynamic collision objects can have a positive mass.");
return 0x0;
}
break;
}
bool has_world_transform = world->m_GetWorldTransform != 0x0 && data.m_UserData;
dmTransform::Transform world_transform;
if (has_world_transform)
{
world->m_GetWorldTransform(data.m_UserData, world_transform);
}
float object_scale = 1.0f;
if (has_world_transform)
{
if( data.m_Type != COLLISION_OBJECT_TYPE_TRIGGER)
{
object_scale = world_transform.GetUniformScale();
}
}
bool clone_shapes = world->m_AllowDynamicTransforms || object_scale != 1.0f;
float scale = world->m_Context->m_Scale;
btCompoundShape* compound_shape = new btCompoundShape(false);
for (uint32_t i = 0; i < shape_count; ++i)
{
btConvexShape* shape = clone_shapes ? CloneShape((btConvexShape*)shapes[i]) : (btConvexShape*)shapes[i];
if (translations && rotations)
{
const Vectormath::Aos::Vector3& trans = translations[i];
const Vectormath::Aos::Quat& rot = rotations[i];
btVector3 bt_trans;
ToBt(trans, bt_trans, scale);
btTransform transform(btQuaternion(rot.getX(), rot.getY(), rot.getZ(), rot.getW()), bt_trans);
compound_shape->addChildShape(transform, shape);
}
else
{
compound_shape->addChildShape(btTransform::getIdentity(), shape);
}
}
if (object_scale != 1.0f)
{
compound_shape->setLocalScaling(btVector3(object_scale, object_scale, object_scale));
}
btVector3 local_inertia(0.0f, 0.0f, 0.0f);
if (data.m_Type == COLLISION_OBJECT_TYPE_DYNAMIC)
{
compound_shape->calculateLocalInertia(data.m_Mass, local_inertia);
}
btCollisionObject* collision_object = 0x0;
if (data.m_Type != COLLISION_OBJECT_TYPE_TRIGGER)
{
MotionState* motion_state = new MotionState(world->m_Context, data.m_UserData, world->m_GetWorldTransform, world->m_SetWorldTransform);
btRigidBody::btRigidBodyConstructionInfo rb_info(data.m_Mass, motion_state, compound_shape, local_inertia);
rb_info.m_friction = data.m_Friction;
rb_info.m_restitution = data.m_Restitution;
rb_info.m_linearDamping = data.m_LinearDamping;
rb_info.m_angularDamping = data.m_AngularDamping;
btRigidBody* body = new btRigidBody(rb_info);
float angular_factor = 1.0f;
if (data.m_LockedRotation) {
angular_factor = 0.0f;
}
body->setAngularFactor(angular_factor);
switch (data.m_Type)
{
case COLLISION_OBJECT_TYPE_KINEMATIC:
body->setCollisionFlags(btCollisionObject::CF_KINEMATIC_OBJECT);
break;
case COLLISION_OBJECT_TYPE_STATIC:
body->setCollisionFlags(btCollisionObject::CF_STATIC_OBJECT);
break;
default:
break;
}
if (data.m_Enabled) {
world->m_DynamicsWorld->addRigidBody(body, data.m_Group, data.m_Mask);
}
collision_object = body;
}
else
{
collision_object = new btGhostObject();
btTransform world_t;
if (has_world_transform)
{
Vectormath::Aos::Point3 position = Vectormath::Aos::Point3(world_transform.GetTranslation());
Vectormath::Aos::Quat rotation = Vectormath::Aos::Quat(world_transform.GetRotation());
btVector3 bt_pos;
ToBt(position, bt_pos, world->m_Context->m_Scale);
world_t = btTransform(btQuaternion(rotation.getX(), rotation.getY(), rotation.getZ(), rotation.getW()), bt_pos);
}
else
{
world_t = btTransform::getIdentity();
}
collision_object->setWorldTransform(world_t);
collision_object->setCollisionShape(compound_shape);
collision_object->setCollisionFlags(collision_object->getCollisionFlags() | btCollisionObject::CF_NO_CONTACT_RESPONSE);
if (data.m_Enabled) {
world->m_DynamicsWorld->addCollisionObject(collision_object, data.m_Group, data.m_Mask);
}
}
collision_object->setUserPointer(data.m_UserData);
CollisionObject3D* co = new CollisionObject3D();
co->m_CollisionObject = collision_object;
co->m_CollisionGroup = data.m_Group;
co->m_CollisionMask = data.m_Mask;
return co;
}
void DeleteCollisionObject3D(HWorld3D world, HCollisionObject3D collision_object)
{
CollisionObject3D* co = (CollisionObject3D*)collision_object;
OverlapCacheRemove(&world->m_TriggerOverlaps, co->m_CollisionObject);
btCollisionObject* bt_co = co->m_CollisionObject;
if (bt_co == 0x0)
return;
btCollisionShape* shape = bt_co->getCollisionShape();
if (shape->isCompound())
{
delete shape;
}
btRigidBody* rigid_body = btRigidBody::upcast(bt_co);
if (rigid_body != 0x0 && rigid_body->getMotionState())
delete rigid_body->getMotionState();
world->m_DynamicsWorld->removeCollisionObject(bt_co);
delete bt_co;
delete co;
}
uint32_t GetCollisionShapes3D(HCollisionObject3D collision_object, HCollisionShape3D* out_buffer, uint32_t buffer_size)
{
btCollisionShape* shape = GetCollisionObject(collision_object)->getCollisionShape();
uint32_t n = 1;
if (shape->isCompound())
{
btCompoundShape* compound = (btCompoundShape*)shape;
n = compound->getNumChildShapes();
for (uint32_t i = 0; i < n && i < buffer_size; ++i)
{
out_buffer[i] = compound->getChildShape(i);
}
}
else if (buffer_size > 0)
{
out_buffer[0] = shape;
}
return n;
}
void SetCollisionObjectUserData3D(HCollisionObject3D collision_object, void* user_data)
{
GetCollisionObject(collision_object)->setUserPointer(user_data);
}
void* GetCollisionObjectUserData3D(HCollisionObject3D collision_object)
{
return GetCollisionObject(collision_object)->getUserPointer();
}
void ApplyForce3D(HContext3D context, HCollisionObject3D collision_object, const Vector3& force, const Point3& position)
{
btCollisionObject* bt_co = GetCollisionObject(collision_object);
btRigidBody* rigid_body = btRigidBody::upcast(bt_co);
if (rigid_body != 0x0 && !(rigid_body->isStaticOrKinematicObject()))
{
bool force_activate = false;
rigid_body->activate(force_activate);
btVector3 bt_force;
ToBt(force, bt_force, context->m_Scale);
btVector3 bt_position;
ToBt(position, bt_position, context->m_Scale);
rigid_body->applyForce(bt_force, bt_position - bt_co->getWorldTransform().getOrigin());
}
}
Vector3 GetTotalForce3D(HContext3D context, HCollisionObject3D collision_object)
{
btRigidBody* rigid_body = btRigidBody::upcast(GetCollisionObject(collision_object));
if (rigid_body != 0x0 && !(rigid_body->isStaticOrKinematicObject()))
{
const btVector3& bt_total_force = rigid_body->getTotalForce();
Vector3 total_force;
FromBt(bt_total_force, total_force, context->m_InvScale);
return total_force;
}
else
{
return Vector3(0.0f, 0.0f, 0.0f);
}
}
static Vectormath::Aos::Point3 GetWorldPosition(HContext3D context, btCollisionObject* collision_object)
{
const btVector3& bt_position = collision_object->getWorldTransform().getOrigin();
Vectormath::Aos::Point3 position;
FromBt(bt_position, position, context->m_InvScale);
return position;
}
Vectormath::Aos::Point3 GetWorldPosition3D(HContext3D context, HCollisionObject3D collision_object)
{
return GetWorldPosition(context, GetCollisionObject(collision_object));
}
static Vectormath::Aos::Quat GetWorldRotation(HContext3D context, btCollisionObject* collision_object)
{
btQuaternion rotation = collision_object->getWorldTransform().getRotation();
return Vectormath::Aos::Quat(rotation.getX(), rotation.getY(), rotation.getZ(), rotation.getW());
}
Vectormath::Aos::Quat GetWorldRotation3D(HContext3D context, HCollisionObject3D collision_object)
{
return GetWorldRotation(context, GetCollisionObject(collision_object));
}
Vectormath::Aos::Vector3 GetLinearVelocity3D(HContext3D context, HCollisionObject3D collision_object)
{
Vectormath::Aos::Vector3 linear_velocity(0.0f, 0.0f, 0.0f);
btRigidBody* body = btRigidBody::upcast(GetCollisionObject(collision_object));
if (body != 0x0)
{
const btVector3& v = body->getLinearVelocity();
FromBt(v, linear_velocity, context->m_InvScale);
}
return linear_velocity;
}
Vectormath::Aos::Vector3 GetAngularVelocity3D(HContext3D context, HCollisionObject3D collision_object)
{
Vectormath::Aos::Vector3 angular_velocity(0.0f, 0.0f, 0.0f);
btRigidBody* body = btRigidBody::upcast(GetCollisionObject(collision_object));
if (body != 0x0)
{
const btVector3& v = body->getAngularVelocity();
FromBt(v, angular_velocity, 1.0f);
}
return angular_velocity;
}
bool IsEnabled3D(HCollisionObject3D collision_object)
{
btCollisionObject* co = GetCollisionObject(collision_object);
return co->isInWorld();
}
void SetEnabled3D(HWorld3D world, HCollisionObject3D collision_object, bool enabled)
{
DM_PROFILE(Physics, "SetEnabled");
bool prev_enabled = IsEnabled3D(collision_object);
// avoid multiple adds/removes
if (prev_enabled == enabled)
return;
CollisionObject3D* co = (CollisionObject3D*)collision_object;
btCollisionObject* bt_co = co->m_CollisionObject;
if (enabled)
{
btRigidBody* body = btRigidBody::upcast(bt_co);
if (body != 0x0)
{
// sync world transform
if (world->m_GetWorldTransform != 0x0)
{
dmTransform::Transform world_transform;
world->m_GetWorldTransform(body->getUserPointer(), world_transform);
Vectormath::Aos::Point3 position = Vectormath::Aos::Point3(world_transform.GetTranslation());
Vectormath::Aos::Quat rotation = Vectormath::Aos::Quat(world_transform.GetRotation());
btVector3 bt_position;
ToBt(position, bt_position, world->m_Context->m_Scale);
btTransform world_t(btQuaternion(rotation.getX(), rotation.getY(), rotation.getZ(), rotation.getW()), bt_position);
body->setWorldTransform(world_t);
}
world->m_DynamicsWorld->addRigidBody(body, co->m_CollisionGroup, co->m_CollisionMask);
}
else
{
world->m_DynamicsWorld->addCollisionObject(bt_co, co->m_CollisionGroup, co->m_CollisionMask);
}
}
else
{
btRigidBody* body = btRigidBody::upcast(bt_co);
if (body != 0x0)
{
// Reset state
body->clearForces();
body->setLinearVelocity(btVector3(0.0f, 0.0f, 0.0f));
body->setAngularVelocity(btVector3(0.0f, 0.0f, 0.0f));
world->m_DynamicsWorld->removeRigidBody(body);
}
else
{
world->m_DynamicsWorld->removeCollisionObject(bt_co);
}
}
}
bool IsSleeping3D(HCollisionObject3D collision_object)
{
btCollisionObject* co = GetCollisionObject(collision_object);
return co->getActivationState() == ISLAND_SLEEPING;
}
void SetLockedRotation3D(HCollisionObject3D collision_object, bool locked_rotation) {
btCollisionObject* co = GetCollisionObject(collision_object);
btRigidBody* body = btRigidBody::upcast(co);
if (body != 0x0) {
if (locked_rotation) {
body->setAngularFactor(0.0f);
// Reset velocity
body->setAngularVelocity(btVector3(0.0f, 0.0f, 0.0f));
} else {
body->setAngularFactor(1.0f);
}
}
}
float GetLinearDamping3D(HCollisionObject3D collision_object) {
btCollisionObject* co = GetCollisionObject(collision_object);
btRigidBody* body = btRigidBody::upcast(co);
if (body != 0x0) {
return body->getLinearDamping();
} else {
return 0.0f;
}
}
void SetLinearDamping3D(HCollisionObject3D collision_object, float linear_damping) {
btCollisionObject* co = GetCollisionObject(collision_object);
btRigidBody* body = btRigidBody::upcast(co);
if (body != 0x0) {
body->setDamping(linear_damping, body->getAngularDamping());
}
}
float GetAngularDamping3D(HCollisionObject3D collision_object) {
btCollisionObject* co = GetCollisionObject(collision_object);
btRigidBody* body = btRigidBody::upcast(co);
if (body != 0x0) {
return body->getAngularDamping();
} else {
return 0.0f;
}
}
void SetAngularDamping3D(HCollisionObject3D collision_object, float angular_damping) {
btCollisionObject* co = GetCollisionObject(collision_object);
btRigidBody* body = btRigidBody::upcast(co);
if (body != 0x0) {
body->setDamping(body->getLinearDamping(), angular_damping);
}
}
float GetMass3D(HCollisionObject3D collision_object) {
btCollisionObject* co = GetCollisionObject(collision_object);
btRigidBody* body = btRigidBody::upcast(co);
if (body != 0x0 && !body->isKinematicObject() && !body->isStaticObject()) {
// Creating a dynamic body with 0 mass results in an error and the body is not created
// Assert here just in case that would change
assert(body->getInvMass() != 0.0f);
return 1.0f / body->getInvMass();
} else {
return 0.0f;
}
}
void RequestRayCast3D(HWorld3D world, const RayCastRequest& request)
{
if (!world->m_RayCastRequests.Full())
{
// Verify that the ray is not 0-length
if (Vectormath::Aos::lengthSqr(request.m_To - request.m_From) <= 0.0f)
{
dmLogWarning("Ray had 0 length when ray casting, ignoring request.");
}
else
{
world->m_RayCastRequests.Push(request);
}
}
else
{
dmLogWarning("Ray cast query buffer is full (%d), ignoring request.", world->m_RayCastRequests.Capacity());
}
}
static int Sort_RayCastResponse(const dmPhysics::RayCastResponse* a, const dmPhysics::RayCastResponse* b)
{
float diff = a->m_Fraction - b->m_Fraction;
if (diff == 0)
return 0;
return diff < 0 ? -1 : 1;
}
void RayCast3D(HWorld3D world, const RayCastRequest& request, dmArray<RayCastResponse>& results)
{
DM_PROFILE(Physics, "RayCasts");
if (Vectormath::Aos::lengthSqr(request.m_To - request.m_From) <= 0.0f)
{
dmLogWarning("Ray had 0 length when ray casting, ignoring request.");
return;
}
float scale = world->m_Context->m_Scale;
btVector3 from;
ToBt(request.m_From, from, scale);
btVector3 to;
ToBt(request.m_To, to, scale);
float inv_scale = world->m_Context->m_InvScale;
if (request.m_ReturnAllResults)
{
RayCastResultAllCallback3D result_callback(from, to, request.m_Mask, request.m_IgnoredUserData);
world->m_DynamicsWorld->rayTest(from, to, result_callback);
int size = result_callback.m_collisionObjects.size();
if (results.Capacity() < size)
results.SetCapacity(size);
results.SetSize(size);
for (int i = 0; i < size; ++i)
{
const btCollisionObject* co = result_callback.m_collisionObjects[i];
const btVector3& point = result_callback.m_hitPointWorld[i];
const btVector3& normal = result_callback.m_hitNormalWorld[i];
const btScalar fraction = result_callback.m_hitFractions[i];
ResponseFromRayCastResult(results[i], inv_scale, fraction, point, normal, co);
}
qsort(results.Begin(), results.Size(), sizeof(dmPhysics::RayCastResponse), (int(*)(const void*, const void*))Sort_RayCastResponse);
}
else
{
RayCastResultClosestCallback3D result_callback(from, to, request.m_Mask, request.m_IgnoredUserData);
world->m_DynamicsWorld->rayTest(from, to, result_callback);
if (result_callback.hasHit())
{
if (results.Full())
results.OffsetCapacity(1);
results.SetSize(1);
ResponseFromRayCastResult(results[0], inv_scale, result_callback.m_closestHitFraction, result_callback.m_hitPointWorld, result_callback.m_hitNormalWorld, result_callback.m_collisionObject);
}
}
}
void SetGravity3D(HWorld3D world, const Vectormath::Aos::Vector3& gravity)
{
HContext3D context = world->m_Context;
ToBt(gravity, context->m_Gravity, context->m_Scale);
world->m_DynamicsWorld->setGravity(btVector3(context->m_Gravity.getX(), context->m_Gravity.getY(), context->m_Gravity.getZ()));
}
Vectormath::Aos::Vector3 GetGravity3D(HWorld3D world)
{
HContext3D context = world->m_Context;
Vectormath::Aos::Vector3 gravity;
FromBt(context->m_Gravity, gravity, context->m_InvScale);
return gravity;
}
void SetDebugCallbacks3D(HContext3D context, const DebugCallbacks& callbacks)
{
context->m_DebugCallbacks = callbacks;
}
void ReplaceShape3D(HContext3D context, HCollisionShape3D old_shape, HCollisionShape3D new_shape)
{
for (uint32_t i = 0; i < context->m_Worlds.Size(); ++i)
{
btCollisionObjectArray& objects = context->m_Worlds[i]->m_DynamicsWorld->getCollisionObjectArray();
for (int j = 0; j < objects.size(); ++j)
{
btCollisionShape* shape = objects[j]->getCollisionShape();
if (shape->isCompound())
{
btCompoundShape* compound_shape = (btCompoundShape*)shape;
uint32_t n = compound_shape->getNumChildShapes();
for (uint32_t k = 0; k < n; ++k)
{
btCollisionShape* child = compound_shape->getChildShape(k);
if (child == old_shape)
{
btTransform t = compound_shape->getChildTransform(k);
compound_shape->removeChildShape(child);
compound_shape->addChildShape(t, (btConvexShape*)new_shape);
break;
}
}
}
else if (shape == old_shape)
{
objects[j]->setCollisionShape((btConvexShape*)new_shape);
objects[j]->activate(true);
}
}
}
}
}
| 42.230185 | 274 | 0.61164 | [
"object",
"shape",
"transform",
"3d"
] |
140b52211be3f00e944c93542d41678444e58cd8 | 5,306 | cpp | C++ | HelperFunctions/getVkValidationFeatureEnableEXTCollection.cpp | dkaip/jvulkan-natives-Linux-x86_64 | ea7932f74e828953c712feea11e0b01751f9dc9b | [
"Apache-2.0"
] | null | null | null | HelperFunctions/getVkValidationFeatureEnableEXTCollection.cpp | dkaip/jvulkan-natives-Linux-x86_64 | ea7932f74e828953c712feea11e0b01751f9dc9b | [
"Apache-2.0"
] | null | null | null | HelperFunctions/getVkValidationFeatureEnableEXTCollection.cpp | dkaip/jvulkan-natives-Linux-x86_64 | ea7932f74e828953c712feea11e0b01751f9dc9b | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2019-2020 Douglas Kaip
*
* 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.
*/
/*
* getVkValidationFeatureEnableEXTCollection.cpp
*
* Created on: May 10, 2019
* Author: Douglas Kaip
*/
#include "JVulkanHelperFunctions.hh"
#include "slf4j.hh"
namespace jvulkan
{
void getVkValidationFeatureEnableEXTCollection(
JNIEnv *env,
const jobject jVkValidationFeatureEnableEXTCollectionObject,
VkValidationFeatureEnableEXT **vkValidationFeatureEnableEXTs,
int *numberOfVkValidationFeatureEnableEXTs,
std::vector<void *> *memoryToFree)
{
jclass vkValidationFeatureEnableEXTCollectionClass = env->GetObjectClass(jVkValidationFeatureEnableEXTCollectionObject);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Could not get class for jVkValidationFeatureEnableEXTCollectionObject");
return;
}
jmethodID methodId = env->GetMethodID(vkValidationFeatureEnableEXTCollectionClass, "size", "()I");
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Could not get method id for size");
return;
}
jint numberOfElements = env->CallIntMethod(jVkValidationFeatureEnableEXTCollectionObject, methodId);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error calling CallIntMethod on size method.");
return;
}
*numberOfVkValidationFeatureEnableEXTs = numberOfElements;
*vkValidationFeatureEnableEXTs = (VkValidationFeatureEnableEXT *)calloc(numberOfElements, sizeof(VkValidationFeatureEnableEXT));
memoryToFree->push_back(*vkValidationFeatureEnableEXTs);
jmethodID iteratorMethodId = env->GetMethodID(vkValidationFeatureEnableEXTCollectionClass, "iterator", "()Ljava/util/Iterator;");
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Could not get method id for iterator");
return;
}
jobject iteratorObject = env->CallObjectMethod(jVkValidationFeatureEnableEXTCollectionObject, iteratorMethodId);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error calling CallObjectMethod on iteratorMethodId.");
return;
}
jclass iteratorClass = env->GetObjectClass(iteratorObject);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Could not get class for iteratorObject.");
return;
}
jmethodID hasNextMethodId = env->GetMethodID(iteratorClass, "hasNext", "()Z");
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Could not get method id for hasNext");
return;
}
jmethodID nextMethod = env->GetMethodID(iteratorClass, "next", "()Ljava/lang/Object;");
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Could not get method id for next");
return;
}
int i = 0;
do
{
jboolean hasNext = env->CallBooleanMethod(iteratorObject, hasNextMethodId);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error calling CallBooleanMethod on hasNextMethodId.");
break;
}
if (hasNext == false)
{
break;
}
jobject jVkValidationFeatureEnableEXTObject = env->CallObjectMethod(iteratorObject, nextMethod);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error calling CallObjectMethod on nextMethod.");
break;
}
// TODO move this out of the loop
jclass vkValidationFeatureEnableEXTEnumClass = env->GetObjectClass(jVkValidationFeatureEnableEXTObject);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error trying to get class for jVkValidationFeatureEnableEXTObject.");
break;
}
jmethodID valueOfMethodId = env->GetMethodID(vkValidationFeatureEnableEXTEnumClass, "valueOf", "()I");
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Could not get method id for valueOf");
return;
}
VkValidationFeatureEnableEXT vkValidationFeatureEnableEXTEnumValue = (VkValidationFeatureEnableEXT)env->CallIntMethod(jVkValidationFeatureEnableEXTObject, valueOfMethodId);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error calling CallIntMethod on valueOf.");
return;
}
(*vkValidationFeatureEnableEXTs)[i] = vkValidationFeatureEnableEXTEnumValue;
i++;
} while(true);
}
}
| 36.342466 | 184 | 0.626272 | [
"object",
"vector"
] |
140ff7c0d2e71f17ee42dea85e77bfb24e6e485f | 5,114 | cc | C++ | mindspore/ccsrc/plugin/device/cpu/kernel/mkldnn/softmax_cross_entropy_with_logits_cpu_kernel.cc | httpsgithu/mindspore | c29d6bb764e233b427319cb89ba79e420f1e2c64 | [
"Apache-2.0"
] | 1 | 2022-02-23T09:13:43.000Z | 2022-02-23T09:13:43.000Z | mindspore/ccsrc/plugin/device/cpu/kernel/mkldnn/softmax_cross_entropy_with_logits_cpu_kernel.cc | 949144093/mindspore | c29d6bb764e233b427319cb89ba79e420f1e2c64 | [
"Apache-2.0"
] | null | null | null | mindspore/ccsrc/plugin/device/cpu/kernel/mkldnn/softmax_cross_entropy_with_logits_cpu_kernel.cc | 949144093/mindspore | c29d6bb764e233b427319cb89ba79e420f1e2c64 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2020-2022 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "plugin/device/cpu/kernel/mkldnn/softmax_cross_entropy_with_logits_cpu_kernel.h"
#include <numeric>
#include <limits>
#include <functional>
#include "plugin/device/cpu/hal/device/cpu_device_address.h"
#include "utils/ms_utils.h"
namespace mindspore {
namespace kernel {
namespace {
constexpr size_t kSoftmaxCrossEntropyWithLogitsInputsNum = 2;
constexpr size_t kSoftmaxCrossEntropyWithLogitsOutputsNum = 2;
constexpr size_t kSoftmaxCrossEntropyWithLogitsWorkspaceSize = 1;
} // namespace
void SoftmaxCrossEntropyWithLogitsCpuKernelMod::InitInputOutputSize(const CNodePtr &kernel_node) {
DeprecatedNativeCpuKernelMod::InitInputOutputSize(kernel_node);
MS_EXCEPTION_IF_NULL(kernel_node);
size_t type_size = sizeof(float);
std::vector<size_t> shape = AnfAlgo::GetInputDeviceShape(kernel_node, 0);
size_t tensor_size = std::accumulate(shape.begin(), shape.end(), type_size, std::multiplies<size_t>());
(void)workspace_size_list_.emplace_back(tensor_size);
}
void SoftmaxCrossEntropyWithLogitsCpuKernelMod::InitKernel(const CNodePtr &kernel_node) {
MS_EXCEPTION_IF_NULL(kernel_node);
kernel_name_ = common::AnfAlgo::GetCNodeName(kernel_node);
std::vector<size_t> shape = AnfAlgo::GetInputDeviceShape(kernel_node, 0);
dnnl::memory::dims mem_dims;
(void)mem_dims.insert(mem_dims.end(), shape.begin(), shape.end());
if (mem_dims.size() != 2) {
MS_LOG(EXCEPTION) << "SoftmaxCrossEntropyWithLogits kernel dims invalid " << mem_dims.size();
}
batch_size_ = shape[0];
class_num_ = shape[1];
if (batch_size_ == 0 || class_num_ == 0) {
MS_LOG(EXCEPTION) << "Invalid batch size or class num input!";
}
auto mem_desc = CreateDesc<dnnl::memory::desc>(mem_dims, dnnl::memory::data_type::f32, dnnl::memory::format_tag::nc);
auto desc = CreateDesc<dnnl::softmax_forward::desc>(dnnl::prop_kind::forward_training, mem_desc, 1);
auto prim_desc = CreateDesc<dnnl::softmax_forward::primitive_desc>(desc, engine_);
primitive_ = CreatePrimitive<dnnl::softmax_forward>(prim_desc);
AddArgument(DNNL_ARG_SRC, mem_desc);
AddArgument(DNNL_ARG_DST, mem_desc);
}
void SoftmaxCrossEntropyWithLogitsCpuKernelMod::ForwardPostExecute(const float *logits, const float *labels,
float *output1, float *output2) const {
float epsilon = std::numeric_limits<float>::min();
for (size_t i = 0; i < batch_size_; ++i) {
output1[i] = 0;
float loss = 0.0;
for (size_t j = 0; j < class_num_; ++j) {
float logit = logf(logits[i * class_num_ + j] <= 0.0 ? epsilon : logits[i * class_num_ + j]);
output2[i * class_num_ + j] = logits[i * class_num_ + j] - labels[i * class_num_ + j];
loss += labels[i * class_num_ + j] * logit;
}
output1[i] = -loss;
}
}
bool SoftmaxCrossEntropyWithLogitsCpuKernelMod::Launch(const std::vector<kernel::AddressPtr> &inputs,
const std::vector<kernel::AddressPtr> &workspace,
const std::vector<kernel::AddressPtr> &outputs) {
CHECK_KERNEL_INPUTS_NUM(inputs.size(), kSoftmaxCrossEntropyWithLogitsInputsNum, kernel_name_);
CHECK_KERNEL_OUTPUTS_NUM(outputs.size(), kSoftmaxCrossEntropyWithLogitsOutputsNum, kernel_name_);
CHECK_KERNEL_WORKSPACE_SIZE(workspace.size(), kSoftmaxCrossEntropyWithLogitsWorkspaceSize, kernel_name_);
size_t batch_float_size = batch_size_ * sizeof(float);
size_t batch_class_float_size = class_num_ * batch_float_size;
if (inputs[0]->size != workspace[0]->size || inputs[0]->size != batch_class_float_size ||
inputs[1]->size != batch_class_float_size) {
MS_LOG(EXCEPTION) << "Error input data size!";
}
if (outputs[1]->size != batch_class_float_size || outputs[0]->size != batch_float_size) {
MS_LOG(EXCEPTION) << "Error output data size!";
}
SetArgumentHandle(DNNL_ARG_SRC, inputs[0]->addr);
SetArgumentHandle(DNNL_ARG_DST, workspace[0]->addr);
ExecutePrimitive();
const auto *labels = reinterpret_cast<float *>(inputs[1]->addr);
const auto *logits = reinterpret_cast<float *>(workspace[0]->addr);
auto *output1 = reinterpret_cast<float *>(outputs[0]->addr);
auto *output2 = reinterpret_cast<float *>(outputs[1]->addr);
ForwardPostExecute(logits, labels, output1, output2);
return true;
}
MS_KERNEL_FACTORY_REG(NativeCpuKernelMod, SoftmaxCrossEntropyWithLogits, SoftmaxCrossEntropyWithLogitsCpuKernelMod);
} // namespace kernel
} // namespace mindspore
| 46.490909 | 119 | 0.722135 | [
"shape",
"vector"
] |
1411ca28f174edd517222bd41e81e76a0fe52f63 | 65,146 | cc | C++ | v8_7_5/src/torque/torque-parser.cc | wenfeifei/miniblink49 | 2ed562ff70130485148d94b0e5f4c343da0c2ba4 | [
"Apache-2.0"
] | 5,964 | 2016-09-27T03:46:29.000Z | 2022-03-31T16:25:27.000Z | v8_7_5/src/torque/torque-parser.cc | w4454962/miniblink49 | b294b6eacb3333659bf7b94d670d96edeeba14c0 | [
"Apache-2.0"
] | 459 | 2016-09-29T00:51:38.000Z | 2022-03-07T14:37:46.000Z | v8_7_5/src/torque/torque-parser.cc | w4454962/miniblink49 | b294b6eacb3333659bf7b94d670d96edeeba14c0 | [
"Apache-2.0"
] | 1,006 | 2016-09-27T05:17:27.000Z | 2022-03-30T02:46:51.000Z | // Copyright 2018 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <cctype>
#include "src/torque/earley-parser.h"
#include "src/torque/torque-parser.h"
#include "src/torque/utils.h"
namespace v8 {
namespace internal {
namespace torque {
DEFINE_CONTEXTUAL_VARIABLE(CurrentAst)
using TypeList = std::vector<TypeExpression*>;
using GenericParameters = std::vector<Identifier*>;
struct ExpressionWithSource {
Expression* expression;
std::string source;
};
struct TypeswitchCase {
SourcePosition pos;
base::Optional<std::string> name;
TypeExpression* type;
Statement* block;
};
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<std::string>::id =
ParseResultTypeId::kStdString;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<bool>::id =
ParseResultTypeId::kBool;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId
ParseResultHolder<std::vector<std::string>>::id =
ParseResultTypeId::kStdVectorOfString;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<Declaration*>::id =
ParseResultTypeId::kDeclarationPtr;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId
ParseResultHolder<TypeExpression*>::id =
ParseResultTypeId::kTypeExpressionPtr;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId
ParseResultHolder<base::Optional<TypeExpression*>>::id =
ParseResultTypeId::kOptionalTypeExpressionPtr;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<LabelBlock*>::id =
ParseResultTypeId::kLabelBlockPtr;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId
ParseResultHolder<base::Optional<LabelBlock*>>::id =
ParseResultTypeId::kOptionalLabelBlockPtr;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<Expression*>::id =
ParseResultTypeId::kExpressionPtr;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<Identifier*>::id =
ParseResultTypeId::kIdentifierPtr;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId
ParseResultHolder<base::Optional<Identifier*>>::id =
ParseResultTypeId::kOptionalIdentifierPtr;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId
ParseResultHolder<LocationExpression*>::id =
ParseResultTypeId::kLocationExpressionPtr;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<Statement*>::id =
ParseResultTypeId::kStatementPtr;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId
ParseResultHolder<NameAndTypeExpression>::id =
ParseResultTypeId::kNameAndTypeExpression;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId
ParseResultHolder<ClassFieldExpression>::id =
ParseResultTypeId::kClassFieldExpression;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId
ParseResultHolder<StructFieldExpression>::id =
ParseResultTypeId::kStructFieldExpression;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId
ParseResultHolder<std::vector<NameAndTypeExpression>>::id =
ParseResultTypeId::kStdVectorOfNameAndTypeExpression;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId
ParseResultHolder<std::vector<ClassFieldExpression>>::id =
ParseResultTypeId::kStdVectorOfClassFieldExpression;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId
ParseResultHolder<std::vector<StructFieldExpression>>::id =
ParseResultTypeId::kStdVectorOfStructFieldExpression;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId
ParseResultHolder<IncrementDecrementOperator>::id =
ParseResultTypeId::kIncrementDecrementOperator;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId
ParseResultHolder<base::Optional<std::string>>::id =
ParseResultTypeId::kOptionalStdString;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId
ParseResultHolder<std::vector<Statement*>>::id =
ParseResultTypeId::kStdVectorOfStatementPtr;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId
ParseResultHolder<std::vector<Declaration*>>::id =
ParseResultTypeId::kStdVectorOfDeclarationPtr;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId
ParseResultHolder<std::vector<Expression*>>::id =
ParseResultTypeId::kStdVectorOfExpressionPtr;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId
ParseResultHolder<ExpressionWithSource>::id =
ParseResultTypeId::kExpressionWithSource;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<ParameterList>::id =
ParseResultTypeId::kParameterList;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId
ParseResultHolder<RangeExpression>::id =
ParseResultTypeId::kRangeExpression;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId
ParseResultHolder<base::Optional<RangeExpression>>::id =
ParseResultTypeId::kOptionalRangeExpression;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<TypeList>::id =
ParseResultTypeId::kTypeList;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId
ParseResultHolder<base::Optional<TypeList>>::id =
ParseResultTypeId::kOptionalTypeList;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<LabelAndTypes>::id =
ParseResultTypeId::kLabelAndTypes;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId
ParseResultHolder<std::vector<LabelAndTypes>>::id =
ParseResultTypeId::kStdVectorOfLabelAndTypes;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId
ParseResultHolder<std::vector<LabelBlock*>>::id =
ParseResultTypeId::kStdVectorOfLabelBlockPtr;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId
ParseResultHolder<base::Optional<Statement*>>::id =
ParseResultTypeId::kOptionalStatementPtr;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId
ParseResultHolder<base::Optional<Expression*>>::id =
ParseResultTypeId::kOptionalExpressionPtr;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId
ParseResultHolder<TypeswitchCase>::id = ParseResultTypeId::kTypeswitchCase;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId
ParseResultHolder<std::vector<TypeswitchCase>>::id =
ParseResultTypeId::kStdVectorOfTypeswitchCase;
template <>
V8_EXPORT_PRIVATE const ParseResultTypeId
ParseResultHolder<std::vector<Identifier*>>::id =
ParseResultTypeId::kStdVectorOfIdentifierPtr;
namespace {
base::Optional<ParseResult> AddGlobalDeclaration(
ParseResultIterator* child_results) {
auto declaration = child_results->NextAs<Declaration*>();
CurrentAst::Get().declarations().push_back(declaration);
return base::nullopt;
}
void LintGenericParameters(const GenericParameters& parameters) {
for (const Identifier* parameter : parameters) {
if (!IsUpperCamelCase(parameter->value)) {
NamingConventionError("Generic parameter", parameter->value,
"UpperCamelCase");
}
}
}
void CheckNotDeferredStatement(Statement* statement) {
CurrentSourcePosition::Scope source_position(statement->pos);
if (BlockStatement* block = BlockStatement::DynamicCast(statement)) {
if (block->deferred) {
LintError(
"cannot use deferred with a statement block here, it will have no "
"effect");
}
}
}
Expression* MakeCall(IdentifierExpression* callee,
base::Optional<Expression*> target,
std::vector<Expression*> arguments,
const std::vector<Statement*>& otherwise) {
std::vector<std::string> labels;
// All IdentifierExpressions are treated as label names and can be directly
// used as labels identifiers. All other statements in a call's otherwise
// must create intermediate Labels for the otherwise's statement code.
size_t label_id = 0;
std::vector<LabelBlock*> temp_labels;
for (auto* statement : otherwise) {
if (auto* e = ExpressionStatement::DynamicCast(statement)) {
if (auto* id = IdentifierExpression::DynamicCast(e->expression)) {
if (id->generic_arguments.size() != 0) {
ReportError("An otherwise label cannot have generic parameters");
}
labels.push_back(id->name->value);
continue;
}
}
auto label_name = std::string("_label") + std::to_string(label_id++);
labels.push_back(label_name);
auto* label_block =
MakeNode<LabelBlock>(label_name, ParameterList::Empty(), statement);
temp_labels.push_back(label_block);
}
// Create nested try-label expression for all of the temporary Labels that
// were created.
Expression* result = nullptr;
if (target) {
result = MakeNode<CallMethodExpression>(*target, callee, arguments, labels);
} else {
result = MakeNode<CallExpression>(callee, arguments, labels);
}
for (auto* label : temp_labels) {
result = MakeNode<TryLabelExpression>(false, result, label);
}
return result;
}
Expression* MakeCall(const std::string& callee,
const std::vector<TypeExpression*>& generic_arguments,
const std::vector<Expression*>& arguments,
const std::vector<Statement*>& otherwise) {
return MakeCall(MakeNode<IdentifierExpression>(MakeNode<Identifier>(callee),
generic_arguments),
base::nullopt, arguments, otherwise);
}
base::Optional<ParseResult> MakeCall(ParseResultIterator* child_results) {
auto callee = child_results->NextAs<LocationExpression*>();
auto args = child_results->NextAs<std::vector<Expression*>>();
auto otherwise = child_results->NextAs<std::vector<Statement*>>();
IdentifierExpression* target = IdentifierExpression::cast(callee);
return ParseResult{MakeCall(target, base::nullopt, args, otherwise)};
}
base::Optional<ParseResult> MakeMethodCall(ParseResultIterator* child_results) {
auto this_arg = child_results->NextAs<Expression*>();
auto callee = child_results->NextAs<std::string>();
auto args = child_results->NextAs<std::vector<Expression*>>();
auto otherwise = child_results->NextAs<std::vector<Statement*>>();
return ParseResult{
MakeCall(MakeNode<IdentifierExpression>(MakeNode<Identifier>(callee)),
this_arg, args, otherwise)};
}
base::Optional<ParseResult> MakeNew(ParseResultIterator* child_results) {
TypeExpression* type = child_results->NextAs<TypeExpression*>();
auto args = child_results->NextAs<std::vector<Expression*>>();
Expression* result = MakeNode<NewExpression>(type, args);
return ParseResult{result};
}
base::Optional<ParseResult> MakeBinaryOperator(
ParseResultIterator* child_results) {
auto left = child_results->NextAs<Expression*>();
auto op = child_results->NextAs<std::string>();
auto right = child_results->NextAs<Expression*>();
return ParseResult{MakeCall(op, TypeList{},
std::vector<Expression*>{left, right},
std::vector<Statement*>{})};
}
base::Optional<ParseResult> MakeIntrinsicCallExpression(
ParseResultIterator* child_results) {
auto callee = child_results->NextAs<std::string>();
auto generic_arguments =
child_results->NextAs<std::vector<TypeExpression*>>();
auto args = child_results->NextAs<std::vector<Expression*>>();
Expression* result =
MakeNode<IntrinsicCallExpression>(callee, generic_arguments, args);
return ParseResult{result};
}
base::Optional<ParseResult> MakeUnaryOperator(
ParseResultIterator* child_results) {
auto op = child_results->NextAs<std::string>();
auto e = child_results->NextAs<Expression*>();
return ParseResult{MakeCall(op, TypeList{}, std::vector<Expression*>{e},
std::vector<Statement*>{})};
}
template <bool has_varargs>
base::Optional<ParseResult> MakeParameterListFromTypes(
ParseResultIterator* child_results) {
auto implicit_params =
child_results->NextAs<std::vector<NameAndTypeExpression>>();
auto explicit_types = child_results->NextAs<TypeList>();
ParameterList result;
result.has_varargs = has_varargs;
result.implicit_count = implicit_params.size();
for (NameAndTypeExpression& implicit_param : implicit_params) {
if (!IsLowerCamelCase(implicit_param.name->value)) {
NamingConventionError("Parameter", implicit_param.name->value,
"lowerCamelCase");
}
result.names.push_back(implicit_param.name);
result.types.push_back(implicit_param.type);
}
for (auto* explicit_type : explicit_types) {
result.types.push_back(explicit_type);
}
return ParseResult{std::move(result)};
}
template <bool has_varargs>
base::Optional<ParseResult> MakeParameterListFromNameAndTypeList(
ParseResultIterator* child_results) {
auto implicit_params =
child_results->NextAs<std::vector<NameAndTypeExpression>>();
auto explicit_params =
child_results->NextAs<std::vector<NameAndTypeExpression>>();
std::string arguments_variable = "";
if (child_results->HasNext()) {
arguments_variable = child_results->NextAs<std::string>();
}
ParameterList result;
for (NameAndTypeExpression& pair : implicit_params) {
if (!IsLowerCamelCase(pair.name->value)) {
NamingConventionError("Parameter", pair.name->value, "lowerCamelCase");
}
result.names.push_back(std::move(pair.name));
result.types.push_back(pair.type);
}
for (NameAndTypeExpression& pair : explicit_params) {
if (!IsLowerCamelCase(pair.name->value)) {
NamingConventionError("Parameter", pair.name->value, "lowerCamelCase");
}
result.names.push_back(pair.name);
result.types.push_back(pair.type);
}
result.implicit_count = implicit_params.size();
result.has_varargs = has_varargs;
result.arguments_variable = arguments_variable;
return ParseResult{std::move(result)};
}
base::Optional<ParseResult> MakeAssertStatement(
ParseResultIterator* child_results) {
auto kind = child_results->NextAs<std::string>();
auto expr_with_source = child_results->NextAs<ExpressionWithSource>();
DCHECK(kind == "assert" || kind == "check");
Statement* result = MakeNode<AssertStatement>(
kind == "assert", expr_with_source.expression, expr_with_source.source);
return ParseResult{result};
}
base::Optional<ParseResult> MakeDebugStatement(
ParseResultIterator* child_results) {
auto kind = child_results->NextAs<std::string>();
DCHECK(kind == "unreachable" || kind == "debug");
Statement* result = MakeNode<DebugStatement>(kind, kind == "unreachable");
return ParseResult{result};
}
base::Optional<ParseResult> MakeVoidType(ParseResultIterator* child_results) {
TypeExpression* result =
MakeNode<BasicTypeExpression>(std::vector<std::string>{}, false, "void");
return ParseResult{result};
}
base::Optional<ParseResult> MakeExternalMacro(
ParseResultIterator* child_results) {
auto transitioning = child_results->NextAs<bool>();
auto operator_name = child_results->NextAs<base::Optional<std::string>>();
auto external_assembler_name =
child_results->NextAs<base::Optional<std::string>>();
auto name = child_results->NextAs<std::string>();
auto generic_parameters = child_results->NextAs<GenericParameters>();
LintGenericParameters(generic_parameters);
auto args = child_results->NextAs<ParameterList>();
auto return_type = child_results->NextAs<TypeExpression*>();
auto labels = child_results->NextAs<LabelAndTypesVector>();
MacroDeclaration* macro = MakeNode<ExternalMacroDeclaration>(
transitioning,
external_assembler_name ? *external_assembler_name : "CodeStubAssembler",
name, operator_name, args, return_type, labels);
Declaration* result;
if (generic_parameters.empty()) {
result = MakeNode<StandardDeclaration>(macro, base::nullopt);
} else {
result = MakeNode<GenericDeclaration>(macro, generic_parameters);
}
return ParseResult{result};
}
base::Optional<ParseResult> MakeIntrinsicDeclaration(
ParseResultIterator* child_results) {
auto name = child_results->NextAs<std::string>();
auto generic_parameters = child_results->NextAs<GenericParameters>();
LintGenericParameters(generic_parameters);
auto args = child_results->NextAs<ParameterList>();
auto return_type = child_results->NextAs<TypeExpression*>();
IntrinsicDeclaration* macro =
MakeNode<IntrinsicDeclaration>(name, args, return_type);
Declaration* result;
if (generic_parameters.empty()) {
result = MakeNode<StandardDeclaration>(macro, base::nullopt);
} else {
result = MakeNode<GenericDeclaration>(macro, generic_parameters);
}
return ParseResult{result};
}
base::Optional<ParseResult> MakeTorqueMacroDeclaration(
ParseResultIterator* child_results) {
auto transitioning = child_results->NextAs<bool>();
auto operator_name = child_results->NextAs<base::Optional<std::string>>();
auto name = child_results->NextAs<std::string>();
if (!IsUpperCamelCase(name)) {
NamingConventionError("Macro", name, "UpperCamelCase");
}
auto generic_parameters = child_results->NextAs<GenericParameters>();
LintGenericParameters(generic_parameters);
auto args = child_results->NextAs<ParameterList>();
auto return_type = child_results->NextAs<TypeExpression*>();
auto labels = child_results->NextAs<LabelAndTypesVector>();
auto body = child_results->NextAs<base::Optional<Statement*>>();
MacroDeclaration* macro = MakeNode<TorqueMacroDeclaration>(
transitioning, name, operator_name, args, return_type, labels);
Declaration* result;
if (generic_parameters.empty()) {
if (!body) ReportError("A non-generic declaration needs a body.");
result = MakeNode<StandardDeclaration>(macro, *body);
} else {
result = MakeNode<GenericDeclaration>(macro, generic_parameters, body);
}
return ParseResult{result};
}
base::Optional<ParseResult> MakeTorqueBuiltinDeclaration(
ParseResultIterator* child_results) {
auto transitioning = child_results->NextAs<bool>();
auto javascript_linkage = child_results->NextAs<bool>();
auto name = child_results->NextAs<std::string>();
if (!IsUpperCamelCase(name)) {
NamingConventionError("Builtin", name, "UpperCamelCase");
}
auto generic_parameters = child_results->NextAs<GenericParameters>();
LintGenericParameters(generic_parameters);
auto args = child_results->NextAs<ParameterList>();
auto return_type = child_results->NextAs<TypeExpression*>();
auto body = child_results->NextAs<base::Optional<Statement*>>();
BuiltinDeclaration* builtin = MakeNode<TorqueBuiltinDeclaration>(
transitioning, javascript_linkage, name, args, return_type);
Declaration* result;
if (generic_parameters.empty()) {
if (!body) ReportError("A non-generic declaration needs a body.");
result = MakeNode<StandardDeclaration>(builtin, *body);
} else {
result = MakeNode<GenericDeclaration>(builtin, generic_parameters, body);
}
return ParseResult{result};
}
base::Optional<ParseResult> MakeConstDeclaration(
ParseResultIterator* child_results) {
auto name = child_results->NextAs<Identifier*>();
if (!IsValidNamespaceConstName(name->value)) {
NamingConventionError("Constant", name->value, "kUpperCamelCase");
}
auto type = child_results->NextAs<TypeExpression*>();
auto expression = child_results->NextAs<Expression*>();
Declaration* result = MakeNode<ConstDeclaration>(name, type, expression);
return ParseResult{result};
}
base::Optional<ParseResult> MakeExternConstDeclaration(
ParseResultIterator* child_results) {
auto name = child_results->NextAs<Identifier*>();
auto type = child_results->NextAs<TypeExpression*>();
auto literal = child_results->NextAs<std::string>();
Declaration* result =
MakeNode<ExternConstDeclaration>(name, type, std::move(literal));
return ParseResult{result};
}
base::Optional<ParseResult> MakeTypeAliasDeclaration(
ParseResultIterator* child_results) {
auto name = child_results->NextAs<Identifier*>();
auto type = child_results->NextAs<TypeExpression*>();
Declaration* result = MakeNode<TypeAliasDeclaration>(name, type);
return ParseResult{result};
}
base::Optional<ParseResult> MakeTypeDeclaration(
ParseResultIterator* child_results) {
auto transient = child_results->NextAs<bool>();
auto name = child_results->NextAs<Identifier*>();
if (!IsValidTypeName(name->value)) {
NamingConventionError("Type", name->value, "UpperCamelCase");
}
auto extends = child_results->NextAs<base::Optional<Identifier*>>();
auto generates = child_results->NextAs<base::Optional<std::string>>();
auto constexpr_generates =
child_results->NextAs<base::Optional<std::string>>();
Declaration* result =
MakeNode<TypeDeclaration>(name, transient, extends, std::move(generates),
std::move(constexpr_generates));
return ParseResult{result};
}
base::Optional<ParseResult> MakeMethodDeclaration(
ParseResultIterator* child_results) {
auto transitioning = child_results->NextAs<bool>();
auto operator_name = child_results->NextAs<base::Optional<std::string>>();
auto name = child_results->NextAs<std::string>();
if (!IsUpperCamelCase(name)) {
NamingConventionError("Method", name, "UpperCamelCase");
}
auto args = child_results->NextAs<ParameterList>();
auto return_type = child_results->NextAs<TypeExpression*>();
auto labels = child_results->NextAs<LabelAndTypesVector>();
auto body = child_results->NextAs<Statement*>();
MacroDeclaration* macro = MakeNode<TorqueMacroDeclaration>(
transitioning, name, operator_name, args, return_type, labels);
Declaration* result = MakeNode<StandardDeclaration>(macro, body);
return ParseResult{result};
}
base::Optional<ParseResult> MakeClassDeclaration(
ParseResultIterator* child_results) {
auto is_extern = child_results->NextAs<bool>();
auto transient = child_results->NextAs<bool>();
auto name = child_results->NextAs<Identifier*>();
if (!IsValidTypeName(name->value)) {
NamingConventionError("Type", name->value, "UpperCamelCase");
}
auto extends = child_results->NextAs<base::Optional<std::string>>();
auto generates = child_results->NextAs<base::Optional<std::string>>();
auto methods = child_results->NextAs<std::vector<Declaration*>>();
auto fields = child_results->NextAs<std::vector<ClassFieldExpression>>();
Declaration* result = MakeNode<ClassDeclaration>(
name, is_extern, transient, std::move(extends), std::move(generates),
std::move(methods), fields);
return ParseResult{result};
}
base::Optional<ParseResult> MakeNamespaceDeclaration(
ParseResultIterator* child_results) {
auto name = child_results->NextAs<std::string>();
if (!IsSnakeCase(name)) {
NamingConventionError("Namespace", name, "snake_case");
}
auto declarations = child_results->NextAs<std::vector<Declaration*>>();
Declaration* result =
MakeNode<NamespaceDeclaration>(std::move(name), std::move(declarations));
return ParseResult{result};
}
base::Optional<ParseResult> MakeSpecializationDeclaration(
ParseResultIterator* child_results) {
auto name = child_results->NextAs<std::string>();
auto generic_parameters =
child_results->NextAs<std::vector<TypeExpression*>>();
auto parameters = child_results->NextAs<ParameterList>();
auto return_type = child_results->NextAs<TypeExpression*>();
auto labels = child_results->NextAs<LabelAndTypesVector>();
auto body = child_results->NextAs<Statement*>();
CheckNotDeferredStatement(body);
Declaration* result = MakeNode<SpecializationDeclaration>(
std::move(name), std::move(generic_parameters), std::move(parameters),
return_type, std::move(labels), body);
return ParseResult{result};
}
base::Optional<ParseResult> MakeStructDeclaration(
ParseResultIterator* child_results) {
auto name = child_results->NextAs<Identifier*>();
auto methods = child_results->NextAs<std::vector<Declaration*>>();
auto fields = child_results->NextAs<std::vector<StructFieldExpression>>();
Declaration* result =
MakeNode<StructDeclaration>(name, std::move(methods), std::move(fields));
return ParseResult{result};
}
base::Optional<ParseResult> MakeCppIncludeDeclaration(
ParseResultIterator* child_results) {
auto include_path = child_results->NextAs<std::string>();
Declaration* result =
MakeNode<CppIncludeDeclaration>(std::move(include_path));
return ParseResult{result};
}
base::Optional<ParseResult> MakeExternalBuiltin(
ParseResultIterator* child_results) {
auto transitioning = child_results->NextAs<bool>();
auto js_linkage = child_results->NextAs<bool>();
auto name = child_results->NextAs<std::string>();
auto generic_parameters = child_results->NextAs<GenericParameters>();
LintGenericParameters(generic_parameters);
auto args = child_results->NextAs<ParameterList>();
auto return_type = child_results->NextAs<TypeExpression*>();
BuiltinDeclaration* builtin = MakeNode<ExternalBuiltinDeclaration>(
transitioning, js_linkage, name, args, return_type);
Declaration* result;
if (generic_parameters.empty()) {
result = MakeNode<StandardDeclaration>(builtin, base::nullopt);
} else {
result = MakeNode<GenericDeclaration>(builtin, generic_parameters);
}
return ParseResult{result};
}
base::Optional<ParseResult> MakeExternalRuntime(
ParseResultIterator* child_results) {
auto transitioning = child_results->NextAs<bool>();
auto name = child_results->NextAs<std::string>();
auto args = child_results->NextAs<ParameterList>();
auto return_type = child_results->NextAs<TypeExpression*>();
ExternalRuntimeDeclaration* runtime = MakeNode<ExternalRuntimeDeclaration>(
transitioning, name, args, return_type);
Declaration* result = MakeNode<StandardDeclaration>(runtime, base::nullopt);
return ParseResult{result};
}
base::Optional<ParseResult> StringLiteralUnquoteAction(
ParseResultIterator* child_results) {
return ParseResult{
StringLiteralUnquote(child_results->NextAs<std::string>())};
}
base::Optional<ParseResult> MakeBasicTypeExpression(
ParseResultIterator* child_results) {
auto namespace_qualification =
child_results->NextAs<std::vector<std::string>>();
auto is_constexpr = child_results->NextAs<bool>();
auto name = child_results->NextAs<std::string>();
TypeExpression* result = MakeNode<BasicTypeExpression>(
std::move(namespace_qualification), is_constexpr, std::move(name));
return ParseResult{result};
}
base::Optional<ParseResult> MakeFunctionTypeExpression(
ParseResultIterator* child_results) {
auto parameters = child_results->NextAs<std::vector<TypeExpression*>>();
auto return_type = child_results->NextAs<TypeExpression*>();
TypeExpression* result =
MakeNode<FunctionTypeExpression>(std::move(parameters), return_type);
return ParseResult{result};
}
base::Optional<ParseResult> MakeUnionTypeExpression(
ParseResultIterator* child_results) {
auto a = child_results->NextAs<TypeExpression*>();
auto b = child_results->NextAs<TypeExpression*>();
TypeExpression* result = MakeNode<UnionTypeExpression>(a, b);
return ParseResult{result};
}
base::Optional<ParseResult> MakeExpressionStatement(
ParseResultIterator* child_results) {
auto expression = child_results->NextAs<Expression*>();
Statement* result = MakeNode<ExpressionStatement>(expression);
return ParseResult{result};
}
base::Optional<ParseResult> MakeIfStatement(
ParseResultIterator* child_results) {
auto is_constexpr = child_results->NextAs<bool>();
auto condition = child_results->NextAs<Expression*>();
auto if_true = child_results->NextAs<Statement*>();
auto if_false = child_results->NextAs<base::Optional<Statement*>>();
if (if_false && !(BlockStatement::DynamicCast(if_true) &&
(BlockStatement::DynamicCast(*if_false) ||
IfStatement::DynamicCast(*if_false)))) {
ReportError("if-else statements require curly braces");
}
if (is_constexpr) {
CheckNotDeferredStatement(if_true);
if (if_false) CheckNotDeferredStatement(*if_false);
}
Statement* result =
MakeNode<IfStatement>(is_constexpr, condition, if_true, if_false);
return ParseResult{result};
}
base::Optional<ParseResult> MakeTypeswitchStatement(
ParseResultIterator* child_results) {
auto expression = child_results->NextAs<Expression*>();
auto cases = child_results->NextAs<std::vector<TypeswitchCase>>();
CurrentSourcePosition::Scope current_source_position(
child_results->matched_input().pos);
// typeswitch (expression) case (x1 : T1) {
// ...b1
// } case (x2 : T2) {
// ...b2
// } case (x3 : T3) {
// ...b3
// }
//
// desugars to
//
// {
// const _value = expression;
// try {
// const x1 : T1 = cast<T1>(_value) otherwise _NextCase;
// ...b1
// } label _NextCase {
// try {
// const x2 : T2 = cast<T2>(%assume_impossible<T1>(_value));
// ...b2
// } label _NextCase {
// const x3 : T3 = %assume_impossible<T1|T2>(_value);
// ...b3
// }
// }
// }
BlockStatement* current_block = MakeNode<BlockStatement>();
Statement* result = current_block;
{
CurrentSourcePosition::Scope current_source_position(expression->pos);
current_block->statements.push_back(MakeNode<VarDeclarationStatement>(
true, MakeNode<Identifier>("_value"), base::nullopt, expression));
}
TypeExpression* accumulated_types;
for (size_t i = 0; i < cases.size(); ++i) {
CurrentSourcePosition::Scope current_source_position(cases[i].pos);
Expression* value =
MakeNode<IdentifierExpression>(MakeNode<Identifier>("_value"));
if (i >= 1) {
value =
MakeNode<AssumeTypeImpossibleExpression>(accumulated_types, value);
}
BlockStatement* case_block;
if (i < cases.size() - 1) {
value = MakeCall("Cast", std::vector<TypeExpression*>{cases[i].type},
std::vector<Expression*>{value},
std::vector<Statement*>{MakeNode<ExpressionStatement>(
MakeNode<IdentifierExpression>(
MakeNode<Identifier>("_NextCase")))});
case_block = MakeNode<BlockStatement>();
} else {
case_block = current_block;
}
std::string name = "_case_value";
if (cases[i].name) name = *cases[i].name;
case_block->statements.push_back(MakeNode<VarDeclarationStatement>(
true, MakeNode<Identifier>(name), cases[i].type, value));
case_block->statements.push_back(cases[i].block);
if (i < cases.size() - 1) {
BlockStatement* next_block = MakeNode<BlockStatement>();
current_block->statements.push_back(
MakeNode<ExpressionStatement>(MakeNode<TryLabelExpression>(
false, MakeNode<StatementExpression>(case_block),
MakeNode<LabelBlock>("_NextCase", ParameterList::Empty(),
next_block))));
current_block = next_block;
}
accumulated_types =
i > 0 ? MakeNode<UnionTypeExpression>(accumulated_types, cases[i].type)
: cases[i].type;
}
return ParseResult{result};
}
base::Optional<ParseResult> MakeTypeswitchCase(
ParseResultIterator* child_results) {
auto name = child_results->NextAs<base::Optional<std::string>>();
auto type = child_results->NextAs<TypeExpression*>();
auto block = child_results->NextAs<Statement*>();
return ParseResult{TypeswitchCase{child_results->matched_input().pos,
std::move(name), type, block}};
}
base::Optional<ParseResult> MakeWhileStatement(
ParseResultIterator* child_results) {
auto condition = child_results->NextAs<Expression*>();
auto body = child_results->NextAs<Statement*>();
Statement* result = MakeNode<WhileStatement>(condition, body);
CheckNotDeferredStatement(result);
return ParseResult{result};
}
base::Optional<ParseResult> MakeReturnStatement(
ParseResultIterator* child_results) {
auto value = child_results->NextAs<base::Optional<Expression*>>();
Statement* result = MakeNode<ReturnStatement>(value);
return ParseResult{result};
}
base::Optional<ParseResult> MakeTailCallStatement(
ParseResultIterator* child_results) {
auto value = child_results->NextAs<Expression*>();
Statement* result = MakeNode<TailCallStatement>(CallExpression::cast(value));
return ParseResult{result};
}
base::Optional<ParseResult> MakeVarDeclarationStatement(
ParseResultIterator* child_results) {
auto kind = child_results->NextAs<std::string>();
bool const_qualified = kind == "const";
if (!const_qualified) DCHECK_EQ("let", kind);
auto name = child_results->NextAs<Identifier*>();
if (!IsLowerCamelCase(name->value)) {
NamingConventionError("Variable", name->value, "lowerCamelCase");
}
auto type = child_results->NextAs<base::Optional<TypeExpression*>>();
base::Optional<Expression*> initializer;
if (child_results->HasNext())
initializer = child_results->NextAs<Expression*>();
if (!initializer && !type) {
ReportError("Declaration is missing a type.");
}
Statement* result = MakeNode<VarDeclarationStatement>(const_qualified, name,
type, initializer);
return ParseResult{result};
}
base::Optional<ParseResult> MakeBreakStatement(
ParseResultIterator* child_results) {
Statement* result = MakeNode<BreakStatement>();
return ParseResult{result};
}
base::Optional<ParseResult> MakeContinueStatement(
ParseResultIterator* child_results) {
Statement* result = MakeNode<ContinueStatement>();
return ParseResult{result};
}
base::Optional<ParseResult> MakeGotoStatement(
ParseResultIterator* child_results) {
auto label = child_results->NextAs<std::string>();
auto arguments = child_results->NextAs<std::vector<Expression*>>();
Statement* result =
MakeNode<GotoStatement>(std::move(label), std::move(arguments));
return ParseResult{result};
}
base::Optional<ParseResult> MakeBlockStatement(
ParseResultIterator* child_results) {
auto deferred = child_results->NextAs<bool>();
auto statements = child_results->NextAs<std::vector<Statement*>>();
for (Statement* statement : statements) {
CheckNotDeferredStatement(statement);
}
Statement* result = MakeNode<BlockStatement>(deferred, std::move(statements));
return ParseResult{result};
}
base::Optional<ParseResult> MakeTryLabelExpression(
ParseResultIterator* child_results) {
auto try_block = child_results->NextAs<Statement*>();
CheckNotDeferredStatement(try_block);
Statement* result = try_block;
auto label_blocks = child_results->NextAs<std::vector<LabelBlock*>>();
auto catch_block = child_results->NextAs<base::Optional<LabelBlock*>>();
for (auto block : label_blocks) {
result = MakeNode<ExpressionStatement>(MakeNode<TryLabelExpression>(
false, MakeNode<StatementExpression>(result), block));
}
if (catch_block) {
result = MakeNode<ExpressionStatement>(MakeNode<TryLabelExpression>(
true, MakeNode<StatementExpression>(result), *catch_block));
}
return ParseResult{result};
}
base::Optional<ParseResult> MakeForOfLoopStatement(
ParseResultIterator* child_results) {
auto var_decl = child_results->NextAs<Statement*>();
CheckNotDeferredStatement(var_decl);
auto iterable = child_results->NextAs<Expression*>();
auto range = child_results->NextAs<base::Optional<RangeExpression>>();
auto body = child_results->NextAs<Statement*>();
CheckNotDeferredStatement(body);
Statement* result =
MakeNode<ForOfLoopStatement>(var_decl, iterable, range, body);
return ParseResult{result};
}
base::Optional<ParseResult> MakeForLoopStatement(
ParseResultIterator* child_results) {
auto var_decl = child_results->NextAs<base::Optional<Statement*>>();
auto test = child_results->NextAs<base::Optional<Expression*>>();
auto action = child_results->NextAs<base::Optional<Expression*>>();
base::Optional<Statement*> action_stmt;
if (action) action_stmt = MakeNode<ExpressionStatement>(*action);
auto body = child_results->NextAs<Statement*>();
CheckNotDeferredStatement(body);
Statement* result =
MakeNode<ForLoopStatement>(var_decl, test, action_stmt, body);
return ParseResult{result};
}
base::Optional<ParseResult> MakeLabelBlock(ParseResultIterator* child_results) {
auto label = child_results->NextAs<std::string>();
if (!IsUpperCamelCase(label)) {
NamingConventionError("Label", label, "UpperCamelCase");
}
auto parameters = child_results->NextAs<ParameterList>();
auto body = child_results->NextAs<Statement*>();
LabelBlock* result =
MakeNode<LabelBlock>(std::move(label), std::move(parameters), body);
return ParseResult{result};
}
base::Optional<ParseResult> MakeCatchBlock(ParseResultIterator* child_results) {
auto variable = child_results->NextAs<std::string>();
auto body = child_results->NextAs<Statement*>();
if (!IsLowerCamelCase(variable)) {
NamingConventionError("Exception", variable, "lowerCamelCase");
}
ParameterList parameters;
parameters.names.push_back(MakeNode<Identifier>(variable));
parameters.types.push_back(MakeNode<BasicTypeExpression>(
std::vector<std::string>{}, false, "Object"));
parameters.has_varargs = false;
LabelBlock* result =
MakeNode<LabelBlock>("_catch", std::move(parameters), body);
return ParseResult{result};
}
base::Optional<ParseResult> MakeRangeExpression(
ParseResultIterator* child_results) {
auto begin = child_results->NextAs<base::Optional<Expression*>>();
auto end = child_results->NextAs<base::Optional<Expression*>>();
RangeExpression result = {begin, end};
return ParseResult{result};
}
base::Optional<ParseResult> MakeExpressionWithSource(
ParseResultIterator* child_results) {
auto e = child_results->NextAs<Expression*>();
return ParseResult{
ExpressionWithSource{e, child_results->matched_input().ToString()}};
}
base::Optional<ParseResult> MakeIdentifier(ParseResultIterator* child_results) {
auto name = child_results->NextAs<std::string>();
Identifier* result = MakeNode<Identifier>(std::move(name));
return ParseResult{result};
}
base::Optional<ParseResult> MakeIdentifierExpression(
ParseResultIterator* child_results) {
auto namespace_qualification =
child_results->NextAs<std::vector<std::string>>();
auto name = child_results->NextAs<Identifier*>();
auto generic_arguments =
child_results->NextAs<std::vector<TypeExpression*>>();
LocationExpression* result = MakeNode<IdentifierExpression>(
std::move(namespace_qualification), name, std::move(generic_arguments));
return ParseResult{result};
}
base::Optional<ParseResult> MakeFieldAccessExpression(
ParseResultIterator* child_results) {
auto object = child_results->NextAs<Expression*>();
auto field = child_results->NextAs<Identifier*>();
LocationExpression* result = MakeNode<FieldAccessExpression>(object, field);
return ParseResult{result};
}
base::Optional<ParseResult> MakeElementAccessExpression(
ParseResultIterator* child_results) {
auto object = child_results->NextAs<Expression*>();
auto field = child_results->NextAs<Expression*>();
LocationExpression* result = MakeNode<ElementAccessExpression>(object, field);
return ParseResult{result};
}
base::Optional<ParseResult> MakeStructExpression(
ParseResultIterator* child_results) {
auto namespace_qualification =
child_results->NextAs<std::vector<std::string>>();
auto name = child_results->NextAs<std::string>();
auto expressions = child_results->NextAs<std::vector<Expression*>>();
Expression* result =
MakeNode<StructExpression>(std::move(namespace_qualification),
std::move(name), std::move(expressions));
return ParseResult{result};
}
base::Optional<ParseResult> MakeAssignmentExpression(
ParseResultIterator* child_results) {
auto location = child_results->NextAs<LocationExpression*>();
auto op = child_results->NextAs<base::Optional<std::string>>();
auto value = child_results->NextAs<Expression*>();
Expression* result =
MakeNode<AssignmentExpression>(location, std::move(op), value);
return ParseResult{result};
}
base::Optional<ParseResult> MakeNumberLiteralExpression(
ParseResultIterator* child_results) {
auto number = child_results->NextAs<std::string>();
Expression* result = MakeNode<NumberLiteralExpression>(std::move(number));
return ParseResult{result};
}
base::Optional<ParseResult> MakeStringLiteralExpression(
ParseResultIterator* child_results) {
auto literal = child_results->NextAs<std::string>();
Expression* result = MakeNode<StringLiteralExpression>(std::move(literal));
return ParseResult{result};
}
base::Optional<ParseResult> MakeIncrementDecrementExpressionPostfix(
ParseResultIterator* child_results) {
auto location = child_results->NextAs<LocationExpression*>();
auto op = child_results->NextAs<IncrementDecrementOperator>();
Expression* result =
MakeNode<IncrementDecrementExpression>(location, op, true);
return ParseResult{result};
}
base::Optional<ParseResult> MakeIncrementDecrementExpressionPrefix(
ParseResultIterator* child_results) {
auto op = child_results->NextAs<IncrementDecrementOperator>();
auto location = child_results->NextAs<LocationExpression*>();
Expression* result =
MakeNode<IncrementDecrementExpression>(location, op, false);
return ParseResult{result};
}
base::Optional<ParseResult> MakeLogicalOrExpression(
ParseResultIterator* child_results) {
auto left = child_results->NextAs<Expression*>();
auto right = child_results->NextAs<Expression*>();
Expression* result = MakeNode<LogicalOrExpression>(left, right);
return ParseResult{result};
}
base::Optional<ParseResult> MakeLogicalAndExpression(
ParseResultIterator* child_results) {
auto left = child_results->NextAs<Expression*>();
auto right = child_results->NextAs<Expression*>();
Expression* result = MakeNode<LogicalAndExpression>(left, right);
return ParseResult{result};
}
base::Optional<ParseResult> MakeConditionalExpression(
ParseResultIterator* child_results) {
auto condition = child_results->NextAs<Expression*>();
auto if_true = child_results->NextAs<Expression*>();
auto if_false = child_results->NextAs<Expression*>();
Expression* result =
MakeNode<ConditionalExpression>(condition, if_true, if_false);
return ParseResult{result};
}
base::Optional<ParseResult> MakeLabelAndTypes(
ParseResultIterator* child_results) {
auto name = child_results->NextAs<std::string>();
if (!IsUpperCamelCase(name)) {
NamingConventionError("Label", name, "UpperCamelCase");
}
auto types = child_results->NextAs<std::vector<TypeExpression*>>();
return ParseResult{LabelAndTypes{std::move(name), std::move(types)}};
}
base::Optional<ParseResult> MakeNameAndType(
ParseResultIterator* child_results) {
auto name = child_results->NextAs<Identifier*>();
auto type = child_results->NextAs<TypeExpression*>();
return ParseResult{NameAndTypeExpression{name, type}};
}
base::Optional<ParseResult> MakeClassField(ParseResultIterator* child_results) {
auto weak = child_results->NextAs<bool>();
auto name = child_results->NextAs<Identifier*>();
auto index = child_results->NextAs<base::Optional<std::string>>();
auto type = child_results->NextAs<TypeExpression*>();
return ParseResult{ClassFieldExpression{{name, type}, index, weak}};
}
base::Optional<ParseResult> MakeStructField(
ParseResultIterator* child_results) {
auto name = child_results->NextAs<Identifier*>();
auto type = child_results->NextAs<TypeExpression*>();
return ParseResult{StructFieldExpression{{name, type}}};
}
base::Optional<ParseResult> ExtractAssignmentOperator(
ParseResultIterator* child_results) {
auto op = child_results->NextAs<std::string>();
base::Optional<std::string> result = std::string(op.begin(), op.end() - 1);
return ParseResult(std::move(result));
}
struct TorqueGrammar : Grammar {
static bool MatchWhitespace(InputPosition* pos) {
while (true) {
if (MatchChar(std::isspace, pos)) continue;
if (MatchString("//", pos)) {
while (MatchChar([](char c) { return c != '\n'; }, pos)) {
}
continue;
}
return true;
}
}
static bool MatchIdentifier(InputPosition* pos) {
if (!MatchChar(std::isalpha, pos)) return false;
while (MatchChar(std::isalnum, pos) || MatchString("_", pos)) {
}
return true;
}
static bool MatchIntrinsicName(InputPosition* pos) {
InputPosition current = *pos;
if (!MatchString("%", ¤t)) return false;
if (!MatchChar(std::isalpha, ¤t)) return false;
while (MatchChar(std::isalnum, ¤t) || MatchString("_", pos)) {
}
*pos = current;
return true;
}
static bool MatchStringLiteral(InputPosition* pos) {
InputPosition current = *pos;
if (MatchString("\"", ¤t)) {
while (
(MatchString("\\", ¤t) && MatchAnyChar(¤t)) ||
MatchChar([](char c) { return c != '"' && c != '\n'; }, ¤t)) {
}
if (MatchString("\"", ¤t)) {
*pos = current;
return true;
}
}
current = *pos;
if (MatchString("'", ¤t)) {
while (
(MatchString("\\", ¤t) && MatchAnyChar(¤t)) ||
MatchChar([](char c) { return c != '\'' && c != '\n'; }, ¤t)) {
}
if (MatchString("'", ¤t)) {
*pos = current;
return true;
}
}
return false;
}
static bool MatchHexLiteral(InputPosition* pos) {
InputPosition current = *pos;
MatchString("-", ¤t);
if (MatchString("0x", ¤t) && MatchChar(std::isxdigit, ¤t)) {
while (MatchChar(std::isxdigit, ¤t)) {
}
*pos = current;
return true;
}
return false;
}
static bool MatchDecimalLiteral(InputPosition* pos) {
InputPosition current = *pos;
bool found_digit = false;
MatchString("-", ¤t);
while (MatchChar(std::isdigit, ¤t)) found_digit = true;
MatchString(".", ¤t);
while (MatchChar(std::isdigit, ¤t)) found_digit = true;
if (!found_digit) return false;
*pos = current;
if ((MatchString("e", ¤t) || MatchString("E", ¤t)) &&
(MatchString("+", ¤t) || MatchString("-", ¤t) || true) &&
MatchChar(std::isdigit, ¤t)) {
while (MatchChar(std::isdigit, ¤t)) {
}
*pos = current;
return true;
}
return true;
}
TorqueGrammar() : Grammar(&file) { SetWhitespace(MatchWhitespace); }
// Result: std::string
Symbol identifier = {Rule({Pattern(MatchIdentifier)}, YieldMatchedInput)};
// Result: Identifier*
Symbol name = {Rule({&identifier}, MakeIdentifier)};
// Result: std::string
Symbol intrinsicName = {
Rule({Pattern(MatchIntrinsicName)}, YieldMatchedInput)};
// Result: std::string
Symbol stringLiteral = {
Rule({Pattern(MatchStringLiteral)}, YieldMatchedInput)};
// Result: std::string
Symbol externalString = {Rule({&stringLiteral}, StringLiteralUnquoteAction)};
// Result: std::string
Symbol decimalLiteral = {
Rule({Pattern(MatchDecimalLiteral)}, YieldMatchedInput),
Rule({Pattern(MatchHexLiteral)}, YieldMatchedInput)};
// Result: TypeList
Symbol* typeList = List<TypeExpression*>(&type, Token(","));
// Result: TypeExpression*
Symbol simpleType = {
Rule({Token("("), &type, Token(")")}),
Rule({List<std::string>(Sequence({&identifier, Token("::")})),
CheckIf(Token("constexpr")), &identifier},
MakeBasicTypeExpression),
Rule({Token("builtin"), Token("("), typeList, Token(")"), Token("=>"),
&simpleType},
MakeFunctionTypeExpression)};
// Result: TypeExpression*
Symbol type = {Rule({&simpleType}), Rule({&type, Token("|"), &simpleType},
MakeUnionTypeExpression)};
// Result: GenericParameters
Symbol genericParameters = {
Rule({Token("<"),
List<Identifier*>(Sequence({&name, Token(":"), Token("type")}),
Token(",")),
Token(">")})};
// Result: TypeList
Symbol genericSpecializationTypeList = {
Rule({Token("<"), typeList, Token(">")})};
// Result: base::Optional<TypeList>
Symbol* optionalGenericParameters = Optional<TypeList>(&genericParameters);
Symbol* optionalImplicitParameterList{
TryOrDefault<std::vector<NameAndTypeExpression>>(
Sequence({Token("("), Token("implicit"),
List<NameAndTypeExpression>(&nameAndType, Token(",")),
Token(")")}))};
// Result: ParameterList
Symbol typeListMaybeVarArgs = {
Rule({optionalImplicitParameterList, Token("("),
List<TypeExpression*>(Sequence({&type, Token(",")})), Token("..."),
Token(")")},
MakeParameterListFromTypes<true>),
Rule({optionalImplicitParameterList, Token("("), typeList, Token(")")},
MakeParameterListFromTypes<false>)};
// Result: LabelAndTypes
Symbol labelParameter = {Rule(
{&identifier,
TryOrDefault<TypeList>(Sequence({Token("("), typeList, Token(")")}))},
MakeLabelAndTypes)};
// Result: TypeExpression*
Symbol optionalReturnType = {Rule({Token(":"), &type}),
Rule({}, MakeVoidType)};
// Result: LabelAndTypesVector
Symbol* optionalLabelList{TryOrDefault<LabelAndTypesVector>(
Sequence({Token("labels"),
NonemptyList<LabelAndTypes>(&labelParameter, Token(","))}))};
// Result: std::vector<Statement*>
Symbol* optionalOtherwise{TryOrDefault<std::vector<Statement*>>(
Sequence({Token("otherwise"),
NonemptyList<Statement*>(&atomarStatement, Token(","))}))};
// Result: NameAndTypeExpression
Symbol nameAndType = {Rule({&name, Token(":"), &type}, MakeNameAndType)};
Symbol* optionalArraySpecifier = {
Optional<std::string>(Sequence({Token("["), &identifier, Token("]")}))};
Symbol classField = {
Rule({CheckIf(Token("weak")), &name, optionalArraySpecifier, Token(":"),
&type, Token(";")},
MakeClassField)};
Symbol structField = {
Rule({&name, Token(":"), &type, Token(";")}, MakeStructField)};
// Result: ParameterList
Symbol parameterListNoVararg = {
Rule({optionalImplicitParameterList, Token("("),
List<NameAndTypeExpression>(&nameAndType, Token(",")), Token(")")},
MakeParameterListFromNameAndTypeList<false>)};
// Result: ParameterList
Symbol parameterListAllowVararg = {
Rule({¶meterListNoVararg}),
Rule({optionalImplicitParameterList, Token("("),
NonemptyList<NameAndTypeExpression>(&nameAndType, Token(",")),
Token(","), Token("..."), &identifier, Token(")")},
MakeParameterListFromNameAndTypeList<true>)};
// Result: std::string
Symbol* OneOf(const std::vector<std::string>& alternatives) {
Symbol* result = NewSymbol();
for (const std::string& s : alternatives) {
result->AddRule(Rule({Token(s)}, YieldMatchedInput));
}
return result;
}
// Result: Expression*
Symbol* BinaryOperator(Symbol* nextLevel, Symbol* op) {
Symbol* result = NewSymbol();
*result = {Rule({nextLevel}),
Rule({result, op, nextLevel}, MakeBinaryOperator)};
return result;
}
// Result: Expression*
Symbol* expression = &assignmentExpression;
// Result: IncrementDecrementOperator
Symbol incrementDecrementOperator = {
Rule({Token("++")},
YieldIntegralConstant<IncrementDecrementOperator,
IncrementDecrementOperator::kIncrement>),
Rule({Token("--")},
YieldIntegralConstant<IncrementDecrementOperator,
IncrementDecrementOperator::kDecrement>)};
// Result: LocationExpression*
Symbol identifierExpression = {
Rule({List<std::string>(Sequence({&identifier, Token("::")})), &name,
TryOrDefault<TypeList>(&genericSpecializationTypeList)},
MakeIdentifierExpression),
};
// Result: LocationExpression*
Symbol locationExpression = {
Rule({&identifierExpression}),
Rule({&primaryExpression, Token("."), &name}, MakeFieldAccessExpression),
Rule({&primaryExpression, Token("["), expression, Token("]")},
MakeElementAccessExpression)};
// Result: std::vector<Expression*>
Symbol argumentList = {Rule(
{Token("("), List<Expression*>(expression, Token(",")), Token(")")})};
// Result: Expression*
Symbol callExpression = {Rule(
{&identifierExpression, &argumentList, optionalOtherwise}, MakeCall)};
Symbol callMethodExpression = {
Rule({&primaryExpression, Token("."), &identifier, &argumentList,
optionalOtherwise},
MakeMethodCall)};
Symbol initializerList = {Rule(
{Token("{"), List<Expression*>(expression, Token(",")), Token("}")})};
Symbol newExpression = {
Rule({Token("new"), &type, &initializerList}, MakeNew)};
// Result: Expression*
Symbol intrinsicCallExpression = {Rule(
{&intrinsicName, TryOrDefault<TypeList>(&genericSpecializationTypeList),
&argumentList},
MakeIntrinsicCallExpression)};
// Result: Expression*
Symbol primaryExpression = {
Rule({&newExpression}),
Rule({&callExpression}),
Rule({&callMethodExpression}),
Rule({&intrinsicCallExpression}),
Rule({&locationExpression},
CastParseResult<LocationExpression*, Expression*>),
Rule({&decimalLiteral}, MakeNumberLiteralExpression),
Rule({&stringLiteral}, MakeStringLiteralExpression),
Rule(
{List<std::string>(Sequence({&identifier, Token("::")})), &identifier,
Token("{"), List<Expression*>(expression, Token(",")), Token("}")},
MakeStructExpression),
Rule({Token("("), expression, Token(")")})};
// Result: Expression*
Symbol unaryExpression = {
Rule({&primaryExpression}),
Rule({OneOf({"+", "-", "!", "~"}), &unaryExpression}, MakeUnaryOperator),
Rule({&incrementDecrementOperator, &locationExpression},
MakeIncrementDecrementExpressionPrefix),
Rule({&locationExpression, &incrementDecrementOperator},
MakeIncrementDecrementExpressionPostfix)};
// Result: Expression*
Symbol* multiplicativeExpression =
BinaryOperator(&unaryExpression, OneOf({"*", "/", "%"}));
// Result: Expression*
Symbol* additiveExpression =
BinaryOperator(multiplicativeExpression, OneOf({"+", "-"}));
// Result: Expression*
Symbol* shiftExpression =
BinaryOperator(additiveExpression, OneOf({"<<", ">>", ">>>"}));
// Do not allow expressions like a < b > c because this is never
// useful and ambiguous with template parameters.
// Result: Expression*
Symbol relationalExpression = {
Rule({shiftExpression}),
Rule({shiftExpression, OneOf({"<", ">", "<=", ">="}), shiftExpression},
MakeBinaryOperator)};
// Result: Expression*
Symbol* equalityExpression =
BinaryOperator(&relationalExpression, OneOf({"==", "!="}));
// Result: Expression*
Symbol* bitwiseExpression =
BinaryOperator(equalityExpression, OneOf({"&", "|"}));
// Result: Expression*
Symbol logicalAndExpression = {
Rule({bitwiseExpression}),
Rule({&logicalAndExpression, Token("&&"), bitwiseExpression},
MakeLogicalAndExpression)};
// Result: Expression*
Symbol logicalOrExpression = {
Rule({&logicalAndExpression}),
Rule({&logicalOrExpression, Token("||"), &logicalAndExpression},
MakeLogicalOrExpression)};
// Result: Expression*
Symbol conditionalExpression = {
Rule({&logicalOrExpression}),
Rule({&logicalOrExpression, Token("?"), expression, Token(":"),
&conditionalExpression},
MakeConditionalExpression)};
// Result: base::Optional<std::string>
Symbol assignmentOperator = {
Rule({Token("=")}, YieldDefaultValue<base::Optional<std::string>>),
Rule({OneOf({"*=", "/=", "%=", "+=", "-=", "<<=", ">>=", ">>>=", "&=",
"^=", "|="})},
ExtractAssignmentOperator)};
// Result: Expression*
Symbol assignmentExpression = {
Rule({&conditionalExpression}),
Rule({&locationExpression, &assignmentOperator, &assignmentExpression},
MakeAssignmentExpression)};
// Result: Statement*
Symbol block = {Rule({CheckIf(Token("deferred")), Token("{"),
List<Statement*>(&statement), Token("}")},
MakeBlockStatement)};
// Result: LabelBlock*
Symbol labelBlock = {
Rule({Token("label"), &identifier,
TryOrDefault<ParameterList>(¶meterListNoVararg), &block},
MakeLabelBlock)};
Symbol catchBlock = {
Rule({Token("catch"), Token("("), &identifier, Token(")"), &block},
MakeCatchBlock)};
// Result: ExpressionWithSource
Symbol expressionWithSource = {Rule({expression}, MakeExpressionWithSource)};
// Result: RangeExpression
Symbol rangeSpecifier = {
Rule({Token("["), Optional<Expression*>(expression), Token(":"),
Optional<Expression*>(expression), Token("]")},
MakeRangeExpression)};
Symbol* optionalTypeSpecifier =
Optional<TypeExpression*>(Sequence({Token(":"), &type}));
// Result: Statement*
Symbol varDeclaration = {
Rule({OneOf({"let", "const"}), &name, optionalTypeSpecifier},
MakeVarDeclarationStatement)};
// Result: Statement*
Symbol varDeclarationWithInitialization = {
Rule({OneOf({"let", "const"}), &name, optionalTypeSpecifier, Token("="),
expression},
MakeVarDeclarationStatement)};
// Result: Statement*
Symbol atomarStatement = {
Rule({expression}, MakeExpressionStatement),
Rule({Token("return"), Optional<Expression*>(expression)},
MakeReturnStatement),
Rule({Token("tail"), &callExpression}, MakeTailCallStatement),
Rule({Token("break")}, MakeBreakStatement),
Rule({Token("continue")}, MakeContinueStatement),
Rule({Token("goto"), &identifier,
TryOrDefault<std::vector<Expression*>>(&argumentList)},
MakeGotoStatement),
Rule({OneOf({"debug", "unreachable"})}, MakeDebugStatement)};
// Result: Statement*
Symbol statement = {
Rule({&block}),
Rule({&atomarStatement, Token(";")}),
Rule({&varDeclaration, Token(";")}),
Rule({&varDeclarationWithInitialization, Token(";")}),
Rule({Token("if"), CheckIf(Token("constexpr")), Token("("), expression,
Token(")"), &statement,
Optional<Statement*>(Sequence({Token("else"), &statement}))},
MakeIfStatement),
Rule(
{
Token("typeswitch"), Token("("), expression, Token(")"),
Token("{"), NonemptyList<TypeswitchCase>(&typeswitchCase),
Token("}"),
},
MakeTypeswitchStatement),
Rule({Token("try"), &block, List<LabelBlock*>(&labelBlock),
Optional<LabelBlock*>(&catchBlock)},
MakeTryLabelExpression),
Rule({OneOf({"assert", "check"}), Token("("), &expressionWithSource,
Token(")"), Token(";")},
MakeAssertStatement),
Rule({Token("while"), Token("("), expression, Token(")"), &statement},
MakeWhileStatement),
Rule({Token("for"), Token("("), &varDeclaration, Token("of"), expression,
Optional<RangeExpression>(&rangeSpecifier), Token(")"), &statement},
MakeForOfLoopStatement),
Rule({Token("for"), Token("("),
Optional<Statement*>(&varDeclarationWithInitialization), Token(";"),
Optional<Expression*>(expression), Token(";"),
Optional<Expression*>(expression), Token(")"), &statement},
MakeForLoopStatement)};
// Result: TypeswitchCase
Symbol typeswitchCase = {
Rule({Token("case"), Token("("),
Optional<std::string>(Sequence({&identifier, Token(":")})), &type,
Token(")"), Token(":"), &block},
MakeTypeswitchCase)};
// Result: base::Optional<Statement*>
Symbol optionalBody = {
Rule({&block}, CastParseResult<Statement*, base::Optional<Statement*>>),
Rule({Token(";")}, YieldDefaultValue<base::Optional<Statement*>>)};
// Result: Declaration*
Symbol method = {Rule(
{CheckIf(Token("transitioning")),
Optional<std::string>(Sequence({Token("operator"), &externalString})),
&identifier, ¶meterListNoVararg, &optionalReturnType,
optionalLabelList, &block},
MakeMethodDeclaration)};
// Result: Declaration*
Symbol declaration = {
Rule({Token("const"), &name, Token(":"), &type, Token("="), expression,
Token(";")},
MakeConstDeclaration),
Rule({Token("const"), &name, Token(":"), &type, Token("generates"),
&externalString, Token(";")},
MakeExternConstDeclaration),
Rule({CheckIf(Token("extern")), CheckIf(Token("transient")),
Token("class"), &name,
Optional<std::string>(Sequence({Token("extends"), &identifier})),
Optional<std::string>(
Sequence({Token("generates"), &externalString})),
Token("{"), List<Declaration*>(&method),
List<ClassFieldExpression>(&classField), Token("}")},
MakeClassDeclaration),
Rule({Token("struct"), &name, Token("{"), List<Declaration*>(&method),
List<StructFieldExpression>(&structField), Token("}")},
MakeStructDeclaration),
Rule({CheckIf(Token("transient")), Token("type"), &name,
Optional<Identifier*>(Sequence({Token("extends"), &name})),
Optional<std::string>(
Sequence({Token("generates"), &externalString})),
Optional<std::string>(
Sequence({Token("constexpr"), &externalString})),
Token(";")},
MakeTypeDeclaration),
Rule({Token("type"), &name, Token("="), &type, Token(";")},
MakeTypeAliasDeclaration),
Rule({Token("intrinsic"), &intrinsicName,
TryOrDefault<GenericParameters>(&genericParameters),
¶meterListNoVararg, &optionalReturnType, Token(";")},
MakeIntrinsicDeclaration),
Rule({Token("extern"), CheckIf(Token("transitioning")),
Optional<std::string>(
Sequence({Token("operator"), &externalString})),
Token("macro"),
Optional<std::string>(Sequence({&identifier, Token("::")})),
&identifier, TryOrDefault<GenericParameters>(&genericParameters),
&typeListMaybeVarArgs, &optionalReturnType, optionalLabelList,
Token(";")},
MakeExternalMacro),
Rule({Token("extern"), CheckIf(Token("transitioning")),
CheckIf(Token("javascript")), Token("builtin"), &identifier,
TryOrDefault<GenericParameters>(&genericParameters),
&typeListMaybeVarArgs, &optionalReturnType, Token(";")},
MakeExternalBuiltin),
Rule(
{Token("extern"), CheckIf(Token("transitioning")), Token("runtime"),
&identifier, &typeListMaybeVarArgs, &optionalReturnType, Token(";")},
MakeExternalRuntime),
Rule({CheckIf(Token("transitioning")),
Optional<std::string>(
Sequence({Token("operator"), &externalString})),
Token("macro"), &identifier,
TryOrDefault<GenericParameters>(&genericParameters),
¶meterListNoVararg, &optionalReturnType, optionalLabelList,
&optionalBody},
MakeTorqueMacroDeclaration),
Rule({CheckIf(Token("transitioning")), CheckIf(Token("javascript")),
Token("builtin"), &identifier,
TryOrDefault<GenericParameters>(&genericParameters),
¶meterListAllowVararg, &optionalReturnType, &optionalBody},
MakeTorqueBuiltinDeclaration),
Rule({&identifier, &genericSpecializationTypeList,
¶meterListAllowVararg, &optionalReturnType, optionalLabelList,
&block},
MakeSpecializationDeclaration),
Rule({Token("#include"), &externalString}, MakeCppIncludeDeclaration)};
// Result: Declaration*
Symbol namespaceDeclaration = {
Rule({Token("namespace"), &identifier, Token("{"),
List<Declaration*>(&declaration), Token("}")},
MakeNamespaceDeclaration)};
Symbol file = {Rule({&file, &namespaceDeclaration}, AddGlobalDeclaration),
Rule({&file, &declaration}, AddGlobalDeclaration), Rule({})};
};
} // namespace
void ParseTorque(const std::string& input) { TorqueGrammar().Parse(input); }
} // namespace torque
} // namespace internal
} // namespace v8
| 38.8236 | 80 | 0.693396 | [
"object",
"vector"
] |
14160046c15f9ceae6723bfd3357b147c2d17605 | 5,872 | cpp | C++ | source/BeEngine/TextRenderer.cpp | Guillemsc/2D | e92801d5cd8c5e51953cbb54c58f775dace5d40d | [
"MIT"
] | 6 | 2019-04-13T02:54:17.000Z | 2021-05-31T12:22:26.000Z | source/BeEngine/TextRenderer.cpp | Guillemsc/2D | e92801d5cd8c5e51953cbb54c58f775dace5d40d | [
"MIT"
] | null | null | null | source/BeEngine/TextRenderer.cpp | Guillemsc/2D | e92801d5cd8c5e51953cbb54c58f775dace5d40d | [
"MIT"
] | 1 | 2022-01-27T13:49:00.000Z | 2022-01-27T13:49:00.000Z | #include "TextRenderer.h"
#include "ComponentText.h"
#include "App.h"
#include "ModuleShader.h"
#include "GameObject.h"
#include "ComponentTransfrom.h"
#include "ModuleSceneRenderer.h"
#include "ModuleText.h"
#include "TextRenderer.h"
#include "StaticTextRendererItem.h"
TextRenderer::TextRenderer()
{
}
TextRenderer::~TextRenderer()
{
}
void TextRenderer::Start()
{
VertexBuffer quad_vertex_buffer;
quad_vertex_buffer.AddFloat3(float3(-0.5f, -0.5f, 0));
quad_vertex_buffer.AddFloat2(float2(0.0f, 0.0f));
quad_vertex_buffer.AddFloat3(float3(0.5f, -0.5f, 0));
quad_vertex_buffer.AddFloat2(float2(1.0f, 0.0f));
quad_vertex_buffer.AddFloat3(float3(0.5f, 0.5f, 0));
quad_vertex_buffer.AddFloat2(float2(1.0f, 1.0f));
quad_vertex_buffer.AddFloat3(float3(-0.5f, 0.5f, 0));
quad_vertex_buffer.AddFloat2(float2(0.0f, 1.0f));
uint indices[] =
{
0, 1, 3,
1, 2, 3
};
const char* vertex_code =
"#version 330 core\n \
layout(location = 0) in vec3 position; \n \
layout(location = 1) in vec2 uvs; \n \
\
uniform mat4 Model; \
uniform mat4 View; \
uniform mat4 Projection; \
uniform float z_pos; \
\
uniform vec4 col; \
uniform int hasTexture; \
out vec4 oCol; \
flat out int oHasTexture; \
out vec2 oUvs; \
\
void main()\
{\
oCol = col;\
oHasTexture = hasTexture;\
oUvs = uvs; \
gl_Position = Projection * View * Model * vec4(vec3(position.x, position.y, z_pos), 1);\
}";
const char* fragment_code =
"#version 330 core\n \
uniform sampler2D tex; \
in vec4 oCol; \
flat in int oHasTexture; \
in vec2 oUvs; \
out vec4 finalColor; \
void main()\
{\
if(oHasTexture == 1)\
{\
vec4 sampled = vec4(1.0, 1.0, 1.0, texture(tex, oUvs).r); \
finalColor = oCol * sampled;\
}\
else\
{\
finalColor = oCol;\
}\
}";
Shader* vsh = App->shader->CreateShader(ShaderType::VERTEX);
vsh->SetShaderCode(vertex_code);
Shader* fsh = App->shader->CreateShader(ShaderType::FRAGMENT);
fsh->SetShaderCode(fragment_code);
program = App->shader->CreateShaderProgram();
program->AddShader(vsh);
program->AddShader(fsh);
program->LinkProgram();
// VAO
vao = App->renderer->GenVertexArrayBuffer();
App->renderer->BindVertexArrayBuffer(vao);
// VBO
uint vbo = App->renderer->GenBuffer();
App->renderer->BindArrayBuffer(vbo);
App->renderer->LoadArrayToVRAM(quad_vertex_buffer.GetSize(), quad_vertex_buffer.GetBuffer(), GL_STATIC_DRAW);
// Set info
GLint posAttrib = App->renderer->GetVertexAttributeArray(program->GetID(), "position");
App->renderer->EnableVertexAttributeArray(posAttrib);
App->renderer->SetVertexAttributePointer(posAttrib, 3, 5, 0);
GLint uvsAttrib = App->renderer->GetVertexAttributeArray(program->GetID(), "uvs");
App->renderer->EnableVertexAttributeArray(uvsAttrib);
App->renderer->SetVertexAttributePointer(uvsAttrib, 2, 5, 3);
// VBIO
uint vbio = App->renderer->GenBuffer();
App->renderer->BindElementArrayBuffer(vbio);
App->renderer->LoadElementArrayToVRAM(sizeof(indices), &indices[0], GL_STATIC_DRAW);
// Clear
App->renderer->UnbindVertexArrayBuffer();
App->renderer->DisableVertexAttributeArray(posAttrib);
App->renderer->DisableVertexAttributeArray(uvsAttrib);
quad_vertex_buffer.Clear();
}
void TextRenderer::CleanUp()
{
}
void TextRenderer::Render(StaticTextRendererItem * item, const float4x4 & view, const float4x4 & projection, int z_pos)
{
if (item != nullptr)
{
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glDepthFunc(GL_LESS);
program->UseProgram();
App->renderer->BindVertexArrayBuffer(vao);
App->renderer->SetUniformMatrix(program->GetID(), "View", view.ptr());
App->renderer->SetUniformMatrix(program->GetID(), "Projection", projection.ptr());
ComponentText* curr_text = item->GetTextComponent();
Font* font = curr_text->GetCurrentFont();
if (font != nullptr)
{
TextData text_data = curr_text->GetTextData();
float scale = (float)15 / (float)text_data.GetFontSize();
float4 colour = float4(1, 1, 1, 1);
ComponentTransform* transform = curr_text->GetOwner()->transform;
std::vector<Glyph> glyphs = text_data.GetGlyphs();
float curr_x = -text_data.GetFullSize().x * 0.5f * scale;
float curr_y = -text_data.GetFullSize().y * 0.5f * scale;
int counter = 0;
for (std::vector<Glyph>::iterator gl = glyphs.begin(); gl != glyphs.end(); ++gl, ++counter)
{
float4x4 size_mat = float4x4::identity;
float2 glyph_size = (*gl).GetSize();
float2 bearing = (*gl).GetBearing();
float2 final_size = glyph_size * scale;
float2 pos = float2::zero;
pos.x = (curr_x + (bearing.x * scale)) + (final_size.x * 0.5f);
pos.y = (-(glyph_size.y - bearing.y) * scale) + (final_size.y * 0.5f) + curr_y;
size_mat = float4x4::FromTRS(float3(pos.x, pos.y, 0), Quat::identity, float3(final_size.x, final_size.y, 1));
float4x4 world_transform = transform->GetWorldTransform() * size_mat;
world_transform[1][1] = -world_transform[1][1];
App->renderer->SetUniformInt(program->GetID(), "hasTexture", !curr_text->GetRenderQuads());
App->renderer->SetUniformFloat(program->GetID(), "z_pos", z_pos);
App->renderer->SetUniformVec4(program->GetID(), "col", curr_text->GetColour());
App->renderer->SetUniformMatrix(program->GetID(), "Model", world_transform.Transposed().ptr());
App->renderer->BindTexture((*gl).GetTextureId());
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, (void*)0);
GLenum error = glGetError();
if (error != GL_NO_ERROR)
{
INTERNAL_LOG("Error drawing %s\n", gluErrorString(error));
}
App->renderer->UnbindTexture();
curr_x += (*gl).GetAdvance() * scale;
}
}
App->renderer->UnbindVertexArrayBuffer();
glDisable(GL_BLEND);
glDisable(GL_DEPTH_TEST);
}
} | 26.45045 | 119 | 0.690906 | [
"render",
"vector",
"model",
"transform"
] |
1418e366dae7564a72f519cbd17d04affa0fad15 | 9,732 | cc | C++ | modules/rt/src/rt_handler.cc | Emmeral/motis | f5fca133aa703bb00a411f68ceefa023337aef06 | [
"MIT"
] | 2 | 2020-08-11T19:41:58.000Z | 2021-12-10T16:05:52.000Z | modules/rt/src/rt_handler.cc | igorbraun/motis | ab07dc9ebe9220c23626091c0b4080ee772ca081 | [
"MIT"
] | null | null | null | modules/rt/src/rt_handler.cc | igorbraun/motis | ab07dc9ebe9220c23626091c0b4080ee772ca081 | [
"MIT"
] | null | null | null | #include "motis/rt/rt_handler.h"
#include "utl/to_vec.h"
#include "utl/pipes.h"
#include "utl/verify.h"
#include "motis/core/common/logging.h"
#include "motis/core/common/raii.h"
#include "motis/core/conv/trip_conv.h"
#include "motis/module/context/get_schedule.h"
#include "motis/module/context/motis_publish.h"
#include "motis/rt/error.h"
#include "motis/rt/event_resolver.h"
#include "motis/rt/reroute.h"
#include "motis/rt/separate_trip.h"
#include "motis/rt/trip_correction.h"
#include "motis/rt/update_constant_graph.h"
#include "motis/rt/validate_constant_graph.h"
#include "motis/rt/validate_graph.h"
#include "motis/rt/validity_check.h"
using motis::module::msg_ptr;
using namespace motis::logging;
namespace motis::rt {
rt_handler::rt_handler(schedule& sched, bool validate_graph,
bool validate_constant_graph)
: sched_(sched),
propagator_(sched),
update_builder_(sched),
validate_graph_(validate_graph),
validate_constant_graph_(validate_constant_graph) {}
msg_ptr rt_handler::update(msg_ptr const& msg) {
using ris::RISBatch;
auto& s = module::get_schedule();
for (auto const& m : *motis_content(RISBatch, msg)->messages()) {
try {
update(s, m->message_nested_root());
} catch (std::exception const& e) {
printf("rt::on_message: UNEXPECTED ERROR: %s\n", e.what());
} catch (...) {
printf("rt::on_message: UNEXPECTED UNKNOWN ERROR\n");
}
}
return nullptr;
}
msg_ptr rt_handler::single(msg_ptr const& msg) {
using ris::Message;
update(module::get_schedule(), motis_content(Message, msg));
return flush(nullptr);
}
void rt_handler::update(schedule& s, motis::ris::Message const* m) {
stats_.count_message(m->content_type());
auto c = m->content();
switch (m->content_type()) {
case ris::MessageUnion_DelayMessage: {
auto const msg = reinterpret_cast<ris::DelayMessage const*>(c);
stats_.total_updates_ += msg->events()->size();
auto const reason = (msg->type() == ris::DelayType_Is)
? timestamp_reason::IS
: timestamp_reason::FORECAST;
auto const resolved = resolve_events(
stats_, s, msg->trip_id(),
utl::to_vec(*msg->events(),
[](ris::UpdatedEvent const* ev) { return ev->base(); }));
for (auto i = 0UL; i < resolved.size(); ++i) {
auto const& resolved_ev = resolved[i];
if (!resolved_ev) {
++stats_.unresolved_events_;
continue;
}
auto const upd_time =
unix_to_motistime(s, msg->events()->Get(i)->updated_time());
if (upd_time == INVALID_TIME) {
++stats_.update_time_out_of_schedule_;
continue;
}
propagator_.add_delay(*resolved_ev, reason, upd_time);
++stats_.found_updates_;
}
break;
}
case ris::MessageUnion_AdditionMessage: {
auto result = additional_service_builder(s, update_builder_)
.build_additional_train(
reinterpret_cast<ris::AdditionMessage const*>(c));
stats_.count_additional(result);
break;
}
case ris::MessageUnion_CancelMessage: {
auto const msg = reinterpret_cast<ris::CancelMessage const*>(c);
propagate();
std::vector<ev_key> cancelled_evs;
auto const result =
reroute(stats_, s, cancelled_delays_, cancelled_evs, msg->trip_id(),
utl::to_vec(*msg->events()), {}, update_builder_);
if (result.first == reroute_result::OK) {
for (auto const& e : *result.second->edges_) {
propagator_.add_delay(ev_key{e, 0, event_type::DEP});
propagator_.add_delay(ev_key{e, 0, event_type::ARR});
}
for (auto const& e : cancelled_evs) {
propagator_.add_canceled(e);
}
}
break;
}
case ris::MessageUnion_RerouteMessage: {
auto const msg = reinterpret_cast<ris::RerouteMessage const*>(c);
propagate();
std::vector<ev_key> cancelled_evs;
auto const result =
reroute(stats_, s, cancelled_delays_, cancelled_evs, msg->trip_id(),
utl::to_vec(*msg->cancelled_events()),
utl::to_vec(*msg->new_events()), update_builder_);
stats_.count_reroute(result.first);
if (result.first == reroute_result::OK) {
for (auto const& e : *result.second->edges_) {
propagator_.add_delay(ev_key{e, 0, event_type::DEP});
propagator_.add_delay(ev_key{e, 0, event_type::ARR});
}
for (auto const& e : cancelled_evs) {
propagator_.add_canceled(e);
}
}
break;
}
case ris::MessageUnion_TrackMessage: {
auto const msg = reinterpret_cast<ris::TrackMessage const*>(c);
stats_.total_evs_ += msg->events()->size();
auto const resolved = resolve_events(
stats_, s, msg->trip_id(),
utl::to_vec(*msg->events(),
[](ris::UpdatedTrack const* ev) { return ev->base(); }));
for (auto i = 0UL; i < resolved.size(); ++i) {
auto const& k = resolved[i];
if (!k) {
continue;
}
if (auto const it = s.graph_to_track_index_.find(*k);
it == s.graph_to_track_index_.end()) {
s.graph_to_track_index_[*k] = k->ev_type_ == event_type::ARR
? k->lcon()->full_con_->a_track_
: k->lcon()->full_con_->d_track_;
}
auto const ev = msg->events()->Get(i);
track_events_.emplace_back(
track_info{*k, ev->updated_track()->str(),
unix_to_motistime(sched_, ev->base()->schedule_time())});
auto fcon = *k->lcon()->full_con_;
(k->ev_type_ == event_type::ARR ? fcon.a_track_ : fcon.d_track_) =
get_track(s, ev->updated_track()->str());
const_cast<light_connection*>(k->lcon())->full_con_ = // NOLINT
s.full_connections_.emplace_back(mcd::make_unique<connection>(fcon))
.get();
}
break;
}
case ris::MessageUnion_FreeTextMessage: {
auto const msg = reinterpret_cast<ris::FreeTextMessage const*>(c);
stats_.total_evs_ += msg->events()->size();
auto const [trp, resolved] = resolve_events_and_trip(
stats_, s, msg->trip_id(),
utl::to_vec(*msg->events(), [](ris::Event const* ev) { return ev; }));
if (trp == nullptr) {
return;
}
auto const events = utl::all(resolved) //
| utl::remove_if([](auto&& k) { return !k; }) //
| utl::transform([](auto&& k) { return *k; }) //
| utl::vec();
auto const ft =
free_text{msg->free_text()->code(), msg->free_text()->text()->str(),
msg->free_text()->type()->str()};
for (auto const& k : events) {
s.graph_to_free_texts_[k].emplace(ft);
}
free_text_events_.emplace_back(free_texts{trp, ft, events});
break;
}
default: break;
}
}
void rt_handler::propagate() {
MOTIS_FINALLY([this]() { propagator_.reset(); });
propagator_.propagate();
std::set<trip const*> trips_to_correct;
std::set<trip::route_edge> updated_route_edges;
for (auto const& di : propagator_.events()) {
auto const& k = di->get_ev_key();
auto const t = di->get_current_time();
auto const edge_fit = fits_edge(k, t);
auto const trip_fit = fits_trip(sched_, k, t);
if (!edge_fit || !trip_fit) {
auto const trp = sched_.merged_trips_[k.lcon()->trips_]->front();
seperate_trip(sched_, trp);
if (!trip_fit) {
trips_to_correct.insert(trp);
}
}
auto const& updated_k = di->get_ev_key();
if (!updated_k.is_canceled()) {
auto& event_time = updated_k.ev_type_ == event_type::DEP
? updated_k.lcon()->d_time_
: updated_k.lcon()->a_time_;
const_cast<time&>(event_time) = t; // NOLINT
updated_route_edges.insert(updated_k.route_edge_);
}
update_builder_.add_delay(di);
}
for (auto const& trp : trips_to_correct) {
assert(trp->lcon_idx_ == 0 &&
trp->edges_->front()->m_.route_edge_.conns_.size() == 1);
for (auto const& di : trip_corrector(sched_, trp).fix_times()) {
update_builder_.add_delay(di);
updated_route_edges.insert(di->get_ev_key().route_edge_);
}
}
for (auto const& re : updated_route_edges) {
constant_graph_add_route_edge(sched_, re);
}
stats_.propagated_updates_ = propagator_.events().size();
stats_.graph_updates_ = update_builder_.delay_count();
// tracks
for (auto const& t : track_events_) {
update_builder_.add_track_nodes(t.event_, t.track_, t.schedule_time_);
}
// free_texts
for (auto const& f : free_text_events_) {
update_builder_.add_free_text_nodes(f.trp_, f.ft_, f.events_);
}
ctx::await_all(motis_publish(update_builder_.finish()));
update_builder_.reset();
}
msg_ptr rt_handler::flush(msg_ptr const&) {
scoped_timer t("flush");
MOTIS_FINALLY([this]() {
stats_.print();
stats_ = statistics();
propagator_.reset();
update_builder_.reset();
track_events_.clear();
free_text_events_.clear();
});
propagate();
if (validate_graph_) {
validate_graph(sched_);
}
if (validate_constant_graph_) {
validate_constant_graph(sched_);
}
if (stats_.sanity_check_fails()) {
return motis::module::make_error_msg(error::sanity_check_failed);
} else {
return nullptr;
}
}
} // namespace motis::rt
| 30.700315 | 80 | 0.601521 | [
"vector",
"transform"
] |
14193e84360933addfe1a8cc232df3bb67d9daca | 11,734 | cpp | C++ | Plugins/Effect/Effect.cpp | Mefi100/unified | b12a6cc27f291ff779d5ce1226c180ba3f3db800 | [
"MIT"
] | 3 | 2019-02-23T12:51:55.000Z | 2020-10-20T03:24:21.000Z | Plugins/Effect/Effect.cpp | Mefi100/unified | b12a6cc27f291ff779d5ce1226c180ba3f3db800 | [
"MIT"
] | 1 | 2019-11-02T22:02:02.000Z | 2019-11-02T22:02:02.000Z | Plugins/Effect/Effect.cpp | Mefi100/unified | b12a6cc27f291ff779d5ce1226c180ba3f3db800 | [
"MIT"
] | 1 | 2018-12-07T03:06:37.000Z | 2018-12-07T03:06:37.000Z | #include "nwnx.hpp"
#include "API/Constants.hpp"
#include "API/Globals.hpp"
#include "API/CExoString.hpp"
#include "API/CGameEffect.hpp"
#include "API/Functions.hpp"
#include "API/CVirtualMachine.hpp"
#include "API/CNWSObject.hpp"
#include "API/CAppManager.hpp"
#include "API/CServerExoApp.hpp"
#include <string>
using namespace NWNXLib;
using namespace NWNXLib::API;
static std::string s_effectExpiredData;
static uint32_t s_effectExpiredDepth;
static ObjectID s_effectExpiredCreator;
ArgumentStack ResolveUnpack(CGameEffect *eff, bool bLink)
{
ArgumentStack stack;
stack.push(std::to_string(eff->m_nID));
stack.push((int32_t)eff->m_nType);
stack.push((int32_t)eff->m_nSubType);
stack.push((float)eff->m_fDuration);
stack.push((int32_t)eff->m_nExpiryCalendarDay);
stack.push((int32_t)eff->m_nExpiryTimeOfDay);
stack.push((ObjectID)eff->m_oidCreator);
stack.push((int32_t)eff->m_nSpellId);
stack.push((int32_t)eff->m_bExpose);
stack.push((int32_t)eff->m_bShowIcon);
stack.push((int32_t)eff->m_nCasterLevel);
if (bLink)
{
CGameEffect *leftLinkEff = nullptr;
if (eff->m_pLinkLeft != nullptr)
{
leftLinkEff = new CGameEffect(true);
leftLinkEff->CopyEffect(eff->m_pLinkLeft, 0);
}
stack.push(leftLinkEff);
stack.push(eff->m_pLinkLeft != nullptr);
CGameEffect *rightLinkEff = nullptr;
if (eff->m_pLinkRight != nullptr)
{
rightLinkEff = new CGameEffect(true);
rightLinkEff->CopyEffect(eff->m_pLinkRight, 0);
}
stack.push(rightLinkEff);
stack.push(eff->m_pLinkRight != nullptr);
}
stack.push((int32_t)eff->m_nNumIntegers);
stack.push((int32_t)(eff->m_nNumIntegers > 0 ? eff->m_nParamInteger[0] : -1));
stack.push((int32_t)(eff->m_nNumIntegers > 1 ? eff->m_nParamInteger[1] : -1));
stack.push((int32_t)(eff->m_nNumIntegers > 2 ? eff->m_nParamInteger[2] : -1));
stack.push((int32_t)(eff->m_nNumIntegers > 3 ? eff->m_nParamInteger[3] : -1));
stack.push((int32_t)(eff->m_nNumIntegers > 4 ? eff->m_nParamInteger[4] : -1));
stack.push((int32_t)(eff->m_nNumIntegers > 5 ? eff->m_nParamInteger[5] : -1));
stack.push((int32_t)(eff->m_nNumIntegers > 6 ? eff->m_nParamInteger[6] : -1));
stack.push((int32_t)(eff->m_nNumIntegers > 7 ? eff->m_nParamInteger[7] : -1));
stack.push((float)eff->m_nParamFloat[0]);
stack.push((float)eff->m_nParamFloat[1]);
stack.push((float)eff->m_nParamFloat[2]);
stack.push((float)eff->m_nParamFloat[3]);
stack.push(std::string(eff->m_sParamString[0].CStr()));
stack.push(std::string(eff->m_sParamString[1].CStr()));
stack.push(std::string(eff->m_sParamString[2].CStr()));
stack.push(std::string(eff->m_sParamString[3].CStr()));
stack.push(std::string(eff->m_sParamString[4].CStr()));
stack.push(std::string(eff->m_sParamString[5].CStr()));
stack.push((ObjectID)eff->m_oidParamObjectID[0]);
stack.push((ObjectID)eff->m_oidParamObjectID[1]);
stack.push((ObjectID)eff->m_oidParamObjectID[2]);
stack.push((ObjectID)eff->m_oidParamObjectID[3]);
stack.push((float)eff->m_vParamVector[0].x);
stack.push((float)eff->m_vParamVector[0].y);
stack.push((float)eff->m_vParamVector[0].z);
stack.push((float)eff->m_vParamVector[1].x);
stack.push((float)eff->m_vParamVector[1].y);
stack.push((float)eff->m_vParamVector[1].z);
stack.push(std::string(eff->m_sCustomTag.CStr()));
stack.push(std::to_string(eff->m_nItemPropertySourceId));
return stack;
}
void ResolvePack(CGameEffect *eff, ArgumentStack& args, bool bReplace)
{
eff->m_nItemPropertySourceId = std::stoull(args.extract<std::string>());
eff->m_sCustomTag = args.extract<std::string>().c_str();
auto vector1z = args.extract<float>();
auto vector1y = args.extract<float>();
auto vector1x = args.extract<float>();
eff->m_vParamVector[1] = {vector1x, vector1y, vector1z};
auto vector0z = args.extract<float>();
auto vector0y = args.extract<float>();
auto vector0x = args.extract<float>();
eff->m_vParamVector[0] = {vector0x, vector0y, vector0z};
eff->m_oidParamObjectID[3] = args.extract<ObjectID>();
eff->m_oidParamObjectID[2] = args.extract<ObjectID>();
eff->m_oidParamObjectID[1] = args.extract<ObjectID>();
eff->m_oidParamObjectID[0] = args.extract<ObjectID>();
eff->m_sParamString[5] = args.extract<std::string>().c_str();
eff->m_sParamString[4] = args.extract<std::string>().c_str();
eff->m_sParamString[3] = args.extract<std::string>().c_str();
eff->m_sParamString[2] = args.extract<std::string>().c_str();
eff->m_sParamString[1] = args.extract<std::string>().c_str();
eff->m_sParamString[0] = args.extract<std::string>().c_str();
eff->m_nParamFloat[3] = args.extract<float>();
eff->m_nParamFloat[2] = args.extract<float>();
eff->m_nParamFloat[1] = args.extract<float>();
eff->m_nParamFloat[0] = args.extract<float>();
eff->SetNumIntegers(8); // allocate array
eff->m_nParamInteger[7] = args.extract<int32_t>();
eff->m_nParamInteger[6] = args.extract<int32_t>();
eff->m_nParamInteger[5] = args.extract<int32_t>();
eff->m_nParamInteger[4] = args.extract<int32_t>();
eff->m_nParamInteger[3] = args.extract<int32_t>();
eff->m_nParamInteger[2] = args.extract<int32_t>();
eff->m_nParamInteger[1] = args.extract<int32_t>();
eff->m_nParamInteger[0] = args.extract<int32_t>();
// Overwrite num integers from 8
eff->m_nNumIntegers = args.extract<int32_t>();
bool bUpdateLinks = false;
if (!bReplace)
{
auto bRightLinkValid = args.extract<int32_t>();
auto *pRightLink = args.extract<CGameEffect*>();
eff->m_pLinkRight = (bRightLinkValid) ? pRightLink : nullptr;
auto bLeftLinkValid = args.extract<int32_t>();
auto *pLeftLink = args.extract<CGameEffect*>();
eff->m_pLinkLeft = (bLeftLinkValid) ? pLeftLink : nullptr;
if (bLeftLinkValid || bRightLinkValid)
bUpdateLinks = true;
}
eff->m_nCasterLevel = args.extract<int32_t>();
eff->m_bShowIcon = args.extract<int32_t>();
eff->m_bExpose = args.extract<int32_t>();
eff->m_nSpellId = args.extract<int32_t>();
eff->m_oidCreator = args.extract<ObjectID>();
eff->m_nExpiryTimeOfDay = args.extract<int32_t>();
eff->m_nExpiryCalendarDay = args.extract<int32_t>();
eff->m_fDuration = args.extract<float>();
eff->m_nSubType = args.extract<int32_t>();
if (!bReplace)
eff->m_nType = args.extract<int32_t>();
if (bUpdateLinks)
eff->UpdateLinked();
}
NWNX_EXPORT ArgumentStack PackEffect(ArgumentStack&& args)
{
CGameEffect *eff = new CGameEffect(true);
ResolvePack(eff, args, false);
return eff;
}
NWNX_EXPORT ArgumentStack UnpackEffect(ArgumentStack&& args)
{
auto eff = args.extract<CGameEffect*>();
SCOPEGUARD(Utils::DestroyGameEffect(eff));
return ResolveUnpack(eff, true);
}
NWNX_EXPORT ArgumentStack SetEffectExpiredScript(ArgumentStack&& args)
{
static Hooks::Hook pOnEffectRemovedHook =
Hooks::HookFunction(API::Functions::_ZN21CNWSEffectListHandler15OnEffectRemovedEP10CNWSObjectP11CGameEffect,
(void*)+[](CNWSEffectListHandler *pEffectListHandler, CNWSObject* pObject, CGameEffect* pEffect) -> int32_t
{
CExoString& sScriptName = pEffect->m_sParamString[4];
if (!sScriptName.IsEmpty())
{
s_effectExpiredData = std::string(pEffect->m_sParamString[5].CStr());
s_effectExpiredCreator = pEffect->m_oidCreator;
LOG_DEBUG("(SetEffectExpiredScript) Running script '%s' on object '%x' with data '%s'",
sScriptName.CStr(), pObject->m_idSelf, s_effectExpiredData);
++s_effectExpiredDepth;
Globals::VirtualMachine()->RunScript(&sScriptName, pObject->m_idSelf, 1);
--s_effectExpiredDepth;
}
return pOnEffectRemovedHook->CallOriginal<int32_t>(pEffectListHandler, pObject, pEffect);
}, Hooks::Order::Early);
auto effect = args.extract<CGameEffect*>();
// Script name
effect->m_sParamString[4] = args.extract<std::string>().c_str();
// Data
effect->m_sParamString[5] = args.extract<std::string>().c_str();
return effect;
}
NWNX_EXPORT ArgumentStack GetEffectExpiredData(ArgumentStack&&)
{
if (s_effectExpiredDepth == 0)
throw std::runtime_error("Attempted to get effect expired data in an invalid context.");
return s_effectExpiredData;
}
NWNX_EXPORT ArgumentStack GetEffectExpiredCreator(ArgumentStack&&)
{
if (s_effectExpiredDepth == 0)
throw std::runtime_error("Attempted to get effect expired creator in an invalid context.");
return s_effectExpiredCreator;
}
NWNX_EXPORT ArgumentStack ReplaceEffect(ArgumentStack&& args)
{
int found = 0;
auto objId = args.extract<ObjectID>();
auto eOld = args.extract<CGameEffect*>();
auto eNew = args.extract<CGameEffect*>();
SCOPEGUARD(Utils::DestroyGameEffect(eOld));
SCOPEGUARD(Utils::DestroyGameEffect(eNew));
ASSERT_OR_THROW(eNew->m_nType == eOld->m_nType);
if (auto* obj = Utils::AsNWSObject(Utils::GetGameObject(objId)))
{
for (auto* eff : obj->m_appliedEffects)
{
if (eff->m_nID == eOld->m_nID)
{
eff->m_nSubType = eNew->m_nSubType;
eff->m_fDuration = eNew->m_fDuration;
eff->m_nExpiryCalendarDay = eNew->m_nExpiryCalendarDay;
eff->m_nExpiryTimeOfDay = eNew->m_nExpiryTimeOfDay;
eff->m_oidCreator = eNew->m_oidCreator;
eff->m_nSpellId = eNew->m_nSpellId;
eff->m_nCasterLevel = eNew->m_nCasterLevel;
eff->m_nItemPropertySourceId = eNew->m_nItemPropertySourceId;
eff->m_sCustomTag = eNew->m_sCustomTag;
eff->UpdateLinked();
found++;
}
}
}
return found;
}
NWNX_EXPORT ArgumentStack GetTrueEffectCount(ArgumentStack&& args)
{
if (auto *pObject = Utils::PopObject(args))
return pObject->m_appliedEffects.num;
return 0;
}
NWNX_EXPORT ArgumentStack GetTrueEffect(ArgumentStack&& args)
{
auto *pObject = Utils::PopObject(args);
ASSERT_OR_THROW(pObject);
auto it = args.extract<int32_t>();
ASSERT_OR_THROW(it >= 0);
ASSERT_OR_THROW(it < pObject->m_appliedEffects.num);
return ResolveUnpack(pObject->m_appliedEffects[it], false);
}
NWNX_EXPORT ArgumentStack ReplaceEffectByIndex(ArgumentStack&& args)
{
if (auto *pObject = Utils::PopObject(args))
{
auto index = args.extract<int32_t>();
ASSERT_OR_THROW(index >= 0);
ASSERT_OR_THROW(index < pObject->m_appliedEffects.num);
ResolvePack(pObject->m_appliedEffects[index], args, true);
}
return {};
}
NWNX_EXPORT ArgumentStack RemoveEffectById(ArgumentStack&& args)
{
if (auto *pObject = Utils::PopObject(args))
{
uint64_t id = std::stoull(args.extract<std::string>());
return pObject->RemoveEffectById(id);
}
return false;
}
NWNX_EXPORT ArgumentStack Apply(ArgumentStack&& args)
{
auto *pEffect = args.extract<CGameEffect*>();
auto *pObject = Utils::PopObject(args);
if(pObject && pEffect)
{
pObject->ApplyEffect(pEffect, false, true);
}
return {};
}
| 35.131737 | 120 | 0.648457 | [
"object"
] |
141a0cb9c7ea2538f430b708603b3a1a73a7f98f | 4,024 | cpp | C++ | src/2012-04-18_Combinations.cpp | weizhenwei/leetcode | 51386f7f2651ce0562b6f1a49eea7dddc5e02d2e | [
"BSD-3-Clause"
] | 3 | 2015-02-12T01:11:37.000Z | 2015-11-08T08:00:24.000Z | src/2012-04-18_Combinations.cpp | weizhenwei/leetcode | 51386f7f2651ce0562b6f1a49eea7dddc5e02d2e | [
"BSD-3-Clause"
] | null | null | null | src/2012-04-18_Combinations.cpp | weizhenwei/leetcode | 51386f7f2651ce0562b6f1a49eea7dddc5e02d2e | [
"BSD-3-Clause"
] | null | null | null | /*
*
* Copyright (c) 2014, weizhenwei
* 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 {organization} nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* File: 2012-04-18_Combinations.cpp
*
*
* Brief: https://oj.leetcode.com/problems/combinations/
* Given two integers n and k, return all possible combinations of k numbers out
* of 1 ... n.
*
* For example,
* If n = 4 and k = 2, a solution is:
*
* [
* [2,4],
* [3,4],
* [2,3],
* [1,2],
* [1,3],
* [1,4],
* ]
*
*
* Date: 2014.11.20
*
* Author: weizhenwei <weizhenwei1988@gmail.com>
*
* *****************************************************************************
*/
#include <stdio.h>
#include <vector>
using std::vector;
class Solution_Combinations {
public:
// C(n, k) = C(n - 1, k - 1) + C(n - 1, k);
vector<vector<int> > combine(int n, int k) {
vector<vector<int> > combinations;
if (n == k) {
vector<int> elem;
for (int i = 1; i <= n; i++) {
elem.push_back(i);
}
combinations.push_back(elem);
return combinations;
} else if (k == 1) {
vector<int> elem;
for (int i = 1; i <= n; i++) {
elem.clear();
elem.push_back(i);
combinations.push_back(elem);
}
return combinations;
} else {
vector<vector<int> > first = combine(n - 1, k - 1);
for (int i = 0; i < first.size(); i++) {
first[i].push_back(n);
combinations.push_back(first[i]);
}
vector<vector<int> > second = combine(n - 1, k);
for (int i = 0; i < second.size(); i++) {
combinations.push_back(second[i]);
}
return combinations;
}
}
};
static void print_vector(vector<vector<int> > &v) {
for (int i = 0; i < v.size(); i++) {
for (int j = 0; j < v[i].size(); j++) {
printf("%d ", v[i][j]);
}
printf("\n");
}
printf("\n");
}
int main(int argc, char *argv[]) {
Solution_Combinations solution;
int n = 1;
int k = 1;
vector<vector<int> > combinations = solution.combine(n, k);
printf("n = %d, k = %d\n", n, k);
print_vector(combinations);
n = 2;
k = 1;
combinations = solution.combine(n, k);
printf("n = %d, k = %d\n", n, k);
print_vector(combinations);
n = 4;
k = 2;
combinations = solution.combine(n, k);
printf("n = %d, k = %d\n", n, k);
print_vector(combinations);
return 0;
}
| 30.029851 | 81 | 0.580268 | [
"vector"
] |
141a28956af56cc6d0d4ca544a266eb27aee925d | 3,020 | cpp | C++ | examples/advancedLighting/advancedLighting.cpp | Reiex/SplayLibrary | 94b68f371ea4c662c84dfe2dd0a6d1625b60fb04 | [
"MIT"
] | 1 | 2021-12-14T21:36:39.000Z | 2021-12-14T21:36:39.000Z | examples/advancedLighting/advancedLighting.cpp | Reiex/SplayLibrary | 94b68f371ea4c662c84dfe2dd0a6d1625b60fb04 | [
"MIT"
] | null | null | null | examples/advancedLighting/advancedLighting.cpp | Reiex/SplayLibrary | 94b68f371ea4c662c84dfe2dd0a6d1625b60fb04 | [
"MIT"
] | null | null | null | #include "../main.hpp"
int advancedLightingMain()
{
spl::Window window({ 1000, 600 }, "SPL Example");
spl::Context* context = window.getContext();
spl::ContextManager::setCurrentContext(context);
context->setIsDepthTestEnabled(true);
spl::Framebuffer framebuffer;
framebuffer.createNewTextureAttachment<spl::Texture2D>(spl::FramebufferAttachment::ColorAttachment0, spl::uvec2{ 1000, 600 });
framebuffer.createNewRenderBufferAttachment(spl::FramebufferAttachment::DepthAttachment, spl::TextureInternalFormat::Depth24_Stencil8, spl::uvec2{ 1000, 600 });
spl::Shader shader1("examples/advancedLighting/resources/shaders/firstPass.vert", "examples/advancedLighting/resources/shaders/firstPass.frag");
spl::Shader shader2("examples/advancedLighting/resources/shaders/secondPass.vert", "examples/advancedLighting/resources/shaders/secondPass.frag");
spl::PerspectiveCamera camera({ 1000, 600 }, 0.1f, 100.f, 1.f);
camera.setTranslation({ 0.f, 0.f, 2.f });
spl::Mesh<> mesh("examples/advancedLighting/resources/meshes/teapot.obj");
spl::Transformable3D meshTransform;
meshTransform.scale(0.01f);
spl::vec3 lightDir = -spl::normalize(spl::vec3{ 1.0, 0.0, 1.0 });
spl::Mesh<> screen(
{
{ {-1.f, 1.f, 0.f}, {0.f, 0.f, 1.f}, {0.f, 1.f} },
{ {-1.f, -1.f, 0.f}, {0.f, 0.f, 1.f}, {0.f, 0.f} },
{ { 1.f, -1.f, 0.f}, {0.f, 0.f, 1.f}, {1.f, 0.f} },
{ { 1.f, 1.f, 0.f}, {0.f, 0.f, 1.f}, {1.f, 1.f} }
},
{
0, 1, 3, 1, 2, 3
}
);
while (!window.shouldClose())
{
spl::Event* rawEvent = nullptr;
while (window.pollEvent(rawEvent))
{
switch (rawEvent->type)
{
case spl::EventType::ResizeEvent:
{
spl::ResizeEvent event = rawEvent->specialize<spl::EventType::ResizeEvent>();
context->setViewport({0, 0}, event.size);
camera.setAspect(event.size);
framebuffer.createNewTextureAttachment<spl::Texture2D>(spl::FramebufferAttachment::ColorAttachment0, event.size);
framebuffer.createNewRenderBufferAttachment(spl::FramebufferAttachment::DepthAttachment, spl::TextureInternalFormat::Depth24_Stencil8, event.size);
break;
}
}
}
spl::Framebuffer::bind(framebuffer, spl::FramebufferTarget::DrawFramebuffer);
spl::Framebuffer::clear();
meshTransform.rotate({ -0.5f, 1.f, 0.3f }, 0.01f);
spl::Shader::bind(shader1);
shader1.setUniform("cameraPos", camera.getTranslation());
shader1.setUniform("lightDir", lightDir);
shader1.setUniform("projection", camera.getProjectionMatrix());
shader1.setUniform("view", camera.getViewMatrix());
shader1.setUniform("model", meshTransform.getTransformMatrix());
mesh.draw();
spl::Framebuffer::bind(window.getFramebuffer(), spl::FramebufferTarget::DrawFramebuffer);
spl::Framebuffer::clear();
spl::Shader::bind(shader2);
shader2.setUniform("scene", *framebuffer.getTextureAttachment(spl::FramebufferAttachment::ColorAttachment0));
screen.draw();
window.display();
}
return 0;
}
| 34.712644 | 162 | 0.680132 | [
"mesh",
"model"
] |
141c8c19ce3cc253b19f4422d2bb9b744d033171 | 24,371 | cpp | C++ | TestCpp/Classes/NodeTest/NodeTest.cpp | GhostSoar/Cocos2dWindows | 654a018004e358f875bedeb7c9acd6824c0734f8 | [
"MIT"
] | 1 | 2017-01-04T07:05:37.000Z | 2017-01-04T07:05:37.000Z | TestCpp/Classes/NodeTest/NodeTest.cpp | GhostSoar/Cocos2dWindows | 654a018004e358f875bedeb7c9acd6824c0734f8 | [
"MIT"
] | null | null | null | TestCpp/Classes/NodeTest/NodeTest.cpp | GhostSoar/Cocos2dWindows | 654a018004e358f875bedeb7c9acd6824c0734f8 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "NodeTest.h"
#include "../testResource.h"
enum
{
kTagSprite1 = 1,
kTagSprite2 = 2,
kTagSprite3 = 3,
kTagSlider,
};
CCLayer* nextCocosNodeAction();
CCLayer* backCocosNodeAction();
CCLayer* restartCocosNodeAction();
//------------------------------------------------------------------
//
// TestCocosNodeDemo
//
//------------------------------------------------------------------
static int sceneIdx = -1;
#define MAX_LAYER 14
CCLayer* createCocosNodeLayer(int nIndex)
{
switch(nIndex)
{
case 0: return new CameraCenterTest();
case 1: return new Test2();
case 2: return new Test4();
case 3: return new Test5();
case 4: return new Test6();
case 5: return new StressTest1();
case 6: return new StressTest2();
case 7: return new NodeToWorld();
case 8: return new SchedulerTest1();
case 9: return new CameraOrbitTest();
case 10: return new CameraZoomTest();
case 11: return new ConvertToNode();
case 12: return new NodeOpaqueTest();
case 13: return new NodeNonOpaqueTest();
}
return NULL;
}
CCLayer* nextCocosNodeAction()
{
sceneIdx++;
sceneIdx = sceneIdx % MAX_LAYER;
CCLayer* pLayer = createCocosNodeLayer(sceneIdx);
pLayer->autorelease();
return pLayer;
}
CCLayer* backCocosNodeAction()
{
sceneIdx--;
int total = MAX_LAYER;
if( sceneIdx < 0 )
sceneIdx += total;
CCLayer* pLayer = createCocosNodeLayer(sceneIdx);
pLayer->autorelease();
return pLayer;
}
CCLayer* restartCocosNodeAction()
{
CCLayer* pLayer = createCocosNodeLayer(sceneIdx);
pLayer->autorelease();
return pLayer;
}
TestCocosNodeDemo::TestCocosNodeDemo(void)
{
}
TestCocosNodeDemo::~TestCocosNodeDemo(void)
{
}
std::string TestCocosNodeDemo::title()
{
return "No title";
}
std::string TestCocosNodeDemo::subtitle()
{
return "";
}
void TestCocosNodeDemo::onEnter()
{
CCLayer::onEnter();
CCSize s = CCDirector::sharedDirector()->getWinSize();
CCLabelTTF* label = CCLabelTTF::create(title().c_str(), "Arial", 32);
addChild(label, 10);
label->setPosition( ccp(s.width/2, s.height-50) );
std::string strSubtitle = subtitle();
if( ! strSubtitle.empty() )
{
CCLabelTTF* l = CCLabelTTF::create(strSubtitle.c_str(), "Thonburi", 16);
addChild(l, 1);
l->setPosition( ccp(s.width/2, s.height-80) );
}
CCMenuItemImage *item1 = CCMenuItemImage::create(s_pPathB1, s_pPathB2, this, menu_selector(TestCocosNodeDemo::backCallback) );
CCMenuItemImage *item2 = CCMenuItemImage::create(s_pPathR1,s_pPathR2, this, menu_selector(TestCocosNodeDemo::restartCallback) );
CCMenuItemImage *item3 = CCMenuItemImage::create(s_pPathF1, s_pPathF2, this, menu_selector(TestCocosNodeDemo::nextCallback) );
CCMenu *menu = CCMenu::create(item1, item2, item3, NULL);
menu->setPosition( CCPointZero );
item1->setPosition(ccp(VisibleRect::center().x - item2->getContentSize().width*2, VisibleRect::bottom().y+item2->getContentSize().height/2));
item2->setPosition(ccp(VisibleRect::center().x, VisibleRect::bottom().y+item2->getContentSize().height/2));
item3->setPosition(ccp(VisibleRect::center().x + item2->getContentSize().width*2, VisibleRect::bottom().y+item2->getContentSize().height/2));
addChild(menu, 11);
}
void TestCocosNodeDemo::restartCallback(CCObject* pSender)
{
CCScene* s = new CocosNodeTestScene();//CCScene::create();
s->addChild(restartCocosNodeAction());
CCDirector::sharedDirector()->replaceScene(s);
s->release();
}
void TestCocosNodeDemo::nextCallback(CCObject* pSender)
{
CCScene* s = new CocosNodeTestScene();//CCScene::create();
s->addChild( nextCocosNodeAction() );
CCDirector::sharedDirector()->replaceScene(s);
s->release();
}
void TestCocosNodeDemo::backCallback(CCObject* pSender)
{
CCScene* s = new CocosNodeTestScene();//CCScene::create();
s->addChild( backCocosNodeAction() );
CCDirector::sharedDirector()->replaceScene(s);
s->release();
}
//------------------------------------------------------------------
//
// Test2
//
//------------------------------------------------------------------
void Test2::onEnter()
{
TestCocosNodeDemo::onEnter();
CCSize s = CCDirector::sharedDirector()->getWinSize();
CCSprite *sp1 = CCSprite::create(s_pPathSister1);
CCSprite *sp2 = CCSprite::create(s_pPathSister2);
CCSprite *sp3 = CCSprite::create(s_pPathSister1);
CCSprite *sp4 = CCSprite::create(s_pPathSister2);
sp1->setPosition(ccp(100, s.height /2 ));
sp2->setPosition(ccp(380, s.height /2 ));
addChild(sp1);
addChild(sp2);
sp3->setScale(0.25f);
sp4->setScale(0.25f);
sp1->addChild(sp3);
sp2->addChild(sp4);
CCActionInterval* a1 = CCRotateBy::create(2, 360);
CCActionInterval* a2 = CCScaleBy::create(2, 2);
CCAction* action1 = CCRepeatForever::create( CCSequence::create(a1, a2, a2->reverse(), NULL) );
CCAction* action2 = CCRepeatForever::create(
CCSequence::create(
(CCActionInterval*)(a1->copy()->autorelease()),
(CCActionInterval*)(a2->copy()->autorelease()),
a2->reverse(),
NULL)
);
sp2->setAnchorPoint(ccp(0,0));
sp1->runAction(action1);
sp2->runAction(action2);
}
std::string Test2::title()
{
return "anchorPoint and children";
}
//------------------------------------------------------------------
//
// Test4
//
//------------------------------------------------------------------
#define SID_DELAY2 1
#define SID_DELAY4 2
Test4::Test4()
{
CCSprite *sp1 = CCSprite::create(s_pPathSister1);
CCSprite *sp2 = CCSprite::create(s_pPathSister2);
sp1->setPosition( ccp(100,160) );
sp2->setPosition( ccp(380,160) );
addChild(sp1, 0, 2);
addChild(sp2, 0, 3);
schedule( schedule_selector(Test4::delay2), 2.0f);
schedule( schedule_selector(Test4::delay4), 4.0f);
}
void Test4::delay2(float dt)
{
CCSprite* node = (CCSprite*)(getChildByTag(2));
CCAction* action1 = CCRotateBy::create(1, 360);
node->runAction(action1);
}
void Test4::delay4(float dt)
{
unschedule(schedule_selector(Test4::delay4));
removeChildByTag(3, false);
}
std::string Test4::title()
{
return "tags";
}
//------------------------------------------------------------------
//
// Test5
//
//------------------------------------------------------------------
Test5::Test5()
{
CCSprite* sp1 = CCSprite::create(s_pPathSister1);
CCSprite* sp2 = CCSprite::create(s_pPathSister2);
sp1->setPosition(ccp(100,160));
sp2->setPosition(ccp(380,160));
CCRotateBy* rot = CCRotateBy::create(2, 360);
CCActionInterval* rot_back = rot->reverse();
CCAction* forever = CCRepeatForever::create(CCSequence::create(rot, rot_back, NULL));
CCAction* forever2 = (CCAction*)(forever->copy()->autorelease());
forever->setTag(101);
forever2->setTag(102);
addChild(sp1, 0, kTagSprite1);
addChild(sp2, 0, kTagSprite2);
sp1->runAction(forever);
sp2->runAction(forever2);
schedule( schedule_selector(Test5::addAndRemove), 2.0f);
}
void Test5::addAndRemove(float dt)
{
CCNode* sp1 = getChildByTag(kTagSprite1);
CCNode* sp2 = getChildByTag(kTagSprite2);
sp1->retain();
sp2->retain();
removeChild(sp1, false);
removeChild(sp2, true);
addChild(sp1, 0, kTagSprite1);
addChild(sp2, 0, kTagSprite2);
sp1->release();
sp2->release();
}
std::string Test5::title()
{
return "remove and cleanup";
}
//------------------------------------------------------------------
//
// Test6
//
//------------------------------------------------------------------
Test6::Test6()
{
CCSprite* sp1 = CCSprite::create(s_pPathSister1);
CCSprite* sp11 = CCSprite::create(s_pPathSister1);
CCSprite* sp2 = CCSprite::create(s_pPathSister2);
CCSprite* sp21 = CCSprite::create(s_pPathSister2);
sp1->setPosition(ccp(100,160));
sp2->setPosition(ccp(380,160));
CCActionInterval* rot = CCRotateBy::create(2, 360);
CCActionInterval* rot_back = rot->reverse();
CCAction* forever1 = CCRepeatForever::create(CCSequence::create(rot, rot_back, NULL));
CCAction* forever11 = (CCAction*)(forever1->copy()->autorelease());
CCAction* forever2 = (CCAction*)(forever1->copy()->autorelease());
CCAction* forever21 = (CCAction*)(forever1->copy()->autorelease());
addChild(sp1, 0, kTagSprite1);
sp1->addChild(sp11);
addChild(sp2, 0, kTagSprite2);
sp2->addChild(sp21);
sp1->runAction(forever1);
sp11->runAction(forever11);
sp2->runAction(forever2);
sp21->runAction(forever21);
schedule( schedule_selector(Test6::addAndRemove), 2.0f);
}
void Test6::addAndRemove(float dt)
{
CCNode* sp1 = getChildByTag(kTagSprite1);
CCNode* sp2 = getChildByTag(kTagSprite2);
sp1->retain();
sp2->retain();
removeChild(sp1, false);
removeChild(sp2, true);
addChild(sp1, 0, kTagSprite1);
addChild(sp2, 0, kTagSprite2);
sp1->release();
sp2->release();
}
std::string Test6::title()
{
return "remove/cleanup with children";
}
//------------------------------------------------------------------
//
// StressTest1
//
//------------------------------------------------------------------
StressTest1::StressTest1()
{
CCSize s = CCDirector::sharedDirector()->getWinSize();
CCSprite *sp1 = CCSprite::create(s_pPathSister1);
addChild(sp1, 0, kTagSprite1);
sp1->setPosition( ccp(s.width/2, s.height/2) );
schedule( schedule_selector(StressTest1::shouldNotCrash), 1.0f);
}
void StressTest1::shouldNotCrash(float dt)
{
unschedule(schedule_selector(StressTest1::shouldNotCrash));
CCSize s = CCDirector::sharedDirector()->getWinSize();
// if the node has timers, it crashes
CCNode* explosion = CCParticleSun::create();
((CCParticleSun*)explosion)->setTexture(CCTextureCache::sharedTextureCache()->addImage("Images/fire.png"));
// if it doesn't, it works Ok.
// CocosNode *explosion = [Sprite create:@"grossinis_sister2.png");
explosion->setPosition( ccp(s.width/2, s.height/2) );
runAction( CCSequence::create(
CCRotateBy::create(2, 360),
CCCallFuncN::create(this, callfuncN_selector(StressTest1::removeMe)),
NULL) );
addChild(explosion);
}
// remove
void StressTest1::removeMe(CCNode* node)
{
m_pParent->removeChild(node, true);
nextCallback(this);
}
std::string StressTest1::title()
{
return "stress test #1: no crashes";
}
//------------------------------------------------------------------
//
// StressTest2
//
//------------------------------------------------------------------
StressTest2::StressTest2()
{
CCSize s = CCDirector::sharedDirector()->getWinSize();
CCLayer* sublayer = CCLayer::create();
CCSprite *sp1 = CCSprite::create(s_pPathSister1);
sp1->setPosition( ccp(80, s.height/2) );
CCActionInterval* move = CCMoveBy::create(3, ccp(350,0));
CCActionInterval* move_ease_inout3 = CCEaseInOut::create((CCActionInterval*)(move->copy()->autorelease()), 2.0f);
CCActionInterval* move_ease_inout_back3 = move_ease_inout3->reverse();
CCSequence* seq3 = CCSequence::create( move_ease_inout3, move_ease_inout_back3, NULL);
sp1->runAction( CCRepeatForever::create(seq3) );
sublayer->addChild(sp1, 1);
CCParticleFire* fire = CCParticleFire::create();
fire->setTexture(CCTextureCache::sharedTextureCache()->addImage("Images/fire.png"));
fire->setPosition( ccp(80, s.height/2-50) );
CCActionInterval* copy_seq3 = (CCActionInterval*)(seq3->copy()->autorelease());
fire->runAction( CCRepeatForever::create(copy_seq3) );
sublayer->addChild(fire, 2);
schedule(schedule_selector(StressTest2::shouldNotLeak), 6.0f);
addChild(sublayer, 0, kTagSprite1);
}
void StressTest2::shouldNotLeak(float dt)
{
unschedule( schedule_selector(StressTest2::shouldNotLeak) );
CCLayer* sublayer = (CCLayer*)getChildByTag(kTagSprite1);
sublayer->removeAllChildrenWithCleanup(true);
}
std::string StressTest2::title()
{
return "stress test #2: no leaks";
}
//------------------------------------------------------------------
//
// SchedulerTest1
//
//------------------------------------------------------------------
SchedulerTest1::SchedulerTest1()
{
CCLayer*layer = CCLayer::create();
//UXLOG("retain count after init is %d", layer->retainCount()); // 1
addChild(layer, 0);
//UXLOG("retain count after addChild is %d", layer->retainCount()); // 2
layer->schedule( schedule_selector(SchedulerTest1::doSomething) );
//UXLOG("retain count after schedule is %d", layer->retainCount()); // 3 : (object-c viersion), but win32 version is still 2, because CCTimer class don't save target.
layer->unschedule(schedule_selector(SchedulerTest1::doSomething));
//UXLOG("retain count after unschedule is %d", layer->retainCount()); // STILL 3! (win32 is '2')
}
void SchedulerTest1::doSomething(float dt)
{
}
std::string SchedulerTest1::title()
{
return "cocosnode scheduler test #1";
}
//------------------------------------------------------------------
//
// NodeToWorld
//
//------------------------------------------------------------------
NodeToWorld::NodeToWorld()
{
//
// This code tests that nodeToParent works OK:
// - It tests different anchor Points
// - It tests different children anchor points
CCSprite *back = CCSprite::create(s_back3);
addChild( back, -10);
back->setAnchorPoint( ccp(0,0) );
CCSize backSize = back->getContentSize();
CCMenuItem *item = CCMenuItemImage::create(s_PlayNormal, s_PlaySelect);
CCMenu *menu = CCMenu::create(item, NULL);
menu->alignItemsVertically();
menu->setPosition( ccp(backSize.width/2, backSize.height/2));
back->addChild(menu);
CCActionInterval* rot = CCRotateBy::create(5, 360);
CCAction* fe = CCRepeatForever::create( rot);
item->runAction( fe );
CCActionInterval* move = CCMoveBy::create(3, ccp(200,0));
CCActionInterval* move_back = move->reverse();
CCSequence* seq = CCSequence::create( move, move_back, NULL);
CCAction* fe2 = CCRepeatForever::create(seq);
back->runAction(fe2);
}
std::string NodeToWorld::title()
{
return "nodeToParent transform";
}
//------------------------------------------------------------------
//
// CameraOrbitTest
//
//------------------------------------------------------------------
void CameraOrbitTest::onEnter()
{
TestCocosNodeDemo::onEnter();
CCDirector::sharedDirector()->setProjection(kCCDirectorProjection3D);
}
void CameraOrbitTest::onExit()
{
CCDirector::sharedDirector()->setProjection(kCCDirectorProjection2D);
TestCocosNodeDemo::onExit();
}
CameraOrbitTest::CameraOrbitTest()
{
CCSize s = CCDirector::sharedDirector()->getWinSize();
CCSprite *p = CCSprite::create(s_back3);
addChild( p, 0);
p->setPosition( ccp(s.width/2, s.height/2) );
p->setOpacity( 128 );
CCSprite* sprite;
CCOrbitCamera* orbit;
CCCamera* cam;
CCSize ss;
// LEFT
s = p->getContentSize();
sprite = CCSprite::create(s_pPathGrossini);
sprite->setScale(0.5f);
p->addChild(sprite, 0);
sprite->setPosition( ccp(s.width/4*1, s.height/2) );
cam = sprite->getCamera();
orbit = CCOrbitCamera::create(2, 1, 0, 0, 360, 0, 0);
sprite->runAction( CCRepeatForever::create( orbit ) );
// CENTER
sprite = CCSprite::create(s_pPathGrossini);
sprite->setScale( 1.0f );
p->addChild(sprite, 0);
sprite->setPosition( ccp(s.width/4*2, s.height/2) );
orbit = CCOrbitCamera::create(2, 1, 0, 0, 360, 45, 0);
sprite->runAction( CCRepeatForever::create( orbit ) );
// RIGHT
sprite = CCSprite::create(s_pPathGrossini);
sprite->setScale( 2.0f );
p->addChild(sprite, 0);
sprite->setPosition( ccp(s.width/4*3, s.height/2) );
ss = sprite->getContentSize();
orbit = CCOrbitCamera::create(2, 1, 0, 0, 360, 90, -45),
sprite->runAction( CCRepeatForever::create(orbit) );
// PARENT
orbit = CCOrbitCamera::create(10, 1, 0, 0, 360, 0, 90);
p->runAction( CCRepeatForever::create( orbit ) );
setScale( 1 );
}
std::string CameraOrbitTest::title()
{
return "Camera Orbit test";
}
//------------------------------------------------------------------
//
// CameraZoomTest
//
//------------------------------------------------------------------
void CameraZoomTest::onEnter()
{
TestCocosNodeDemo::onEnter();
CCDirector::sharedDirector()->setProjection(kCCDirectorProjection3D);
}
void CameraZoomTest::onExit()
{
CCDirector::sharedDirector()->setProjection(kCCDirectorProjection2D);
TestCocosNodeDemo::onExit();
}
CameraZoomTest::CameraZoomTest()
{
CCSize s = CCDirector::sharedDirector()->getWinSize();
CCSprite *sprite;
CCCamera *cam;
// LEFT
sprite = CCSprite::create(s_pPathGrossini);
addChild( sprite, 0);
sprite->setPosition( ccp(s.width/4*1, s.height/2) );
cam = sprite->getCamera();
cam->setEyeXYZ(0, 0, 415/2);
cam->setCenterXYZ(0, 0, 0);
// CENTER
sprite = CCSprite::create(s_pPathGrossini);
addChild( sprite, 0, 40);
sprite->setPosition(ccp(s.width/4*2, s.height/2));
// RIGHT
sprite = CCSprite::create(s_pPathGrossini);
addChild( sprite, 0, 20);
sprite->setPosition(ccp(s.width/4*3, s.height/2));
m_z = 0;
scheduleUpdate();
}
void CameraZoomTest::update(float dt)
{
CCNode *sprite;
CCCamera *cam;
m_z += dt * 100;
sprite = getChildByTag(20);
cam = sprite->getCamera();
cam->setEyeXYZ(0, 0, m_z);
sprite = getChildByTag(40);
cam = sprite->getCamera();
cam->setEyeXYZ(0, 0, -m_z);
}
std::string CameraZoomTest::title()
{
return "Camera Zoom test";
}
//------------------------------------------------------------------
//
// CameraCenterTest
//
//------------------------------------------------------------------
CameraCenterTest::CameraCenterTest()
{
CCSize s = CCDirector::sharedDirector()->getWinSize();
CCSprite *sprite;
CCOrbitCamera *orbit;
// LEFT-TOP
sprite = CCSprite::create("Images/white-512x512.png");
addChild( sprite, 0);
sprite->setPosition(ccp(s.width/5*1, s.height/5*1));
sprite->setColor(ccRED);
sprite->setTextureRect(CCRectMake(0, 0, 120, 50));
orbit = CCOrbitCamera::create(10, 1, 0, 0, 360, 0, 0);
sprite->runAction(CCRepeatForever::create( orbit ));
// [sprite setAnchorPoint: ccp(0,1));
// LEFT-BOTTOM
sprite = CCSprite::create("Images/white-512x512.png");
addChild( sprite, 0, 40);
sprite->setPosition(ccp(s.width/5*1, s.height/5*4));
sprite->setColor(ccBLUE);
sprite->setTextureRect(CCRectMake(0, 0, 120, 50));
orbit = CCOrbitCamera::create(10, 1, 0, 0, 360, 0, 0);
sprite->runAction(CCRepeatForever::create( orbit ));
// RIGHT-TOP
sprite = CCSprite::create("Images/white-512x512.png");
addChild( sprite, 0);
sprite->setPosition(ccp(s.width/5*4, s.height/5*1));
sprite->setColor(ccYELLOW);
sprite->setTextureRect(CCRectMake(0, 0, 120, 50));
orbit = CCOrbitCamera::create(10, 1, 0, 0, 360, 0, 0);
sprite->runAction(CCRepeatForever::create( orbit) );
// RIGHT-BOTTOM
sprite = CCSprite::create("Images/white-512x512.png");
addChild( sprite, 0, 40);
sprite->setPosition(ccp(s.width/5*4, s.height/5*4));
sprite->setColor(ccGREEN);
sprite->setTextureRect(CCRectMake(0, 0, 120, 50));
orbit = CCOrbitCamera::create(10, 1, 0, 0, 360, 0, 0);
sprite->runAction( CCRepeatForever::create( orbit ) );
// CENTER
sprite = CCSprite::create("Images/white-512x512.png");
addChild( sprite, 0, 40);
sprite->setPosition(ccp(s.width/2, s.height/2));
sprite->setColor(ccWHITE);
sprite->setTextureRect(CCRectMake(0, 0, 120, 50));
orbit = CCOrbitCamera::create(10, 1, 0, 0, 360, 0, 0);
sprite->runAction(CCRepeatForever::create( orbit ) );
}
std::string CameraCenterTest::title()
{
return "Camera Center test";
}
std::string CameraCenterTest::subtitle()
{
return "Sprites should rotate at the same speed";
}
//------------------------------------------------------------------
//
// ConvertToNode
//
//------------------------------------------------------------------
ConvertToNode::ConvertToNode()
{
setTouchEnabled(true);
CCSize s = CCDirector::sharedDirector()->getWinSize();
CCRotateBy* rotate = CCRotateBy::create(10, 360);
CCRepeatForever* action = CCRepeatForever::create(rotate);
for(int i = 0; i < 3; i++)
{
CCSprite *sprite = CCSprite::create("Images/grossini.png");
sprite->setPosition(ccp( s.width/4*(i+1), s.height/2));
CCSprite *point = CCSprite::create("Images/r1.png");
point->setScale(0.25f);
point->setPosition(sprite->getPosition());
addChild(point, 10, 100 + i);
switch(i)
{
case 0:
sprite->setAnchorPoint(CCPointZero);
break;
case 1:
sprite->setAnchorPoint(ccp(0.5f, 0.5f));
break;
case 2:
sprite->setAnchorPoint(ccp(1,1));
break;
}
point->setPosition(sprite->getPosition());
CCRepeatForever* copy = (CCRepeatForever*) action->copy();
copy->autorelease();
sprite->runAction(copy);
addChild(sprite, i);
}
}
void ConvertToNode::ccTouchesEnded(CCSet* touches, CCEvent *event)
{
for( CCSetIterator it = touches->begin(); it != touches->end(); ++it)
{
CCTouch* touch = (CCTouch*)(*it);
CCPoint location = touch->getLocation();
for( int i = 0; i < 3; i++)
{
CCNode *node = getChildByTag(100+i);
CCPoint p1, p2;
p1 = node->convertToNodeSpaceAR(location);
p2 = node->convertToNodeSpace(location);
CCLOG("AR: x=%.2f, y=%.2f -- Not AR: x=%.2f, y=%.2f", p1.x, p1.y, p2.x, p2.y);
}
}
}
std::string ConvertToNode::title()
{
return "Convert To Node Space";
}
std::string ConvertToNode::subtitle()
{
return "testing convertToNodeSpace / AR. Touch and see console";
}
/// NodeOpaqueTest
NodeOpaqueTest::NodeOpaqueTest()
{
CCSprite *background = NULL;
for (int i = 0; i < 50; i++)
{
background = CCSprite::create("Images/background1.png");
ccBlendFunc blendFunc = {CC_ONE, CC_ONE_MINUS_SRC_ALPHA};
background->setBlendFunc(blendFunc);
background->setAnchorPoint(CCPointZero);
addChild(background);
}
}
std::string NodeOpaqueTest::title()
{
return "Node Opaque Test";
}
std::string NodeOpaqueTest::subtitle()
{
return "Node rendered with GL_BLEND disabled";
}
/// NodeNonOpaqueTest
NodeNonOpaqueTest::NodeNonOpaqueTest()
{
CCSprite *background = NULL;
for (int i = 0; i < 50; i++)
{
background = CCSprite::create("Images/background1.jpg");
background->setBlendFunc(kCCBlendFuncDisable);
background->setAnchorPoint(CCPointZero);
addChild(background);
}
}
std::string NodeNonOpaqueTest::title()
{
return "Node Non Opaque Test";
}
std::string NodeNonOpaqueTest::subtitle()
{
return "Node rendered with GL_BLEND enabled";
}
void CocosNodeTestScene::runThisTest()
{
CCLayer* pLayer = nextCocosNodeAction();
addChild(pLayer);
CCDirector::sharedDirector()->replaceScene(this);
}
| 27.631519 | 175 | 0.585655 | [
"object",
"transform"
] |
141c8d9bdbde7f9fd74bb2964effc399c160e06f | 5,547 | cxx | C++ | Filters/ParallelDIY2/Testing/Cxx/TestRedistributeDataSetFilter.cxx | fluentgcc/VTK | dcbfc0df70212ef9f01cbc2a68387b2d44dce808 | [
"BSD-3-Clause"
] | null | null | null | Filters/ParallelDIY2/Testing/Cxx/TestRedistributeDataSetFilter.cxx | fluentgcc/VTK | dcbfc0df70212ef9f01cbc2a68387b2d44dce808 | [
"BSD-3-Clause"
] | null | null | null | Filters/ParallelDIY2/Testing/Cxx/TestRedistributeDataSetFilter.cxx | fluentgcc/VTK | dcbfc0df70212ef9f01cbc2a68387b2d44dce808 | [
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: Visualization Toolkit
Module: TestRedistributeDataSetFilter.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
===========================================================================*/
#include "vtkActor.h"
#include "vtkCamera.h"
#include "vtkCellData.h"
#include "vtkCompositePolyDataMapper.h"
#include "vtkCompositeRenderManager.h"
#include "vtkDataSetSurfaceFilter.h"
#include "vtkExodusIIReader.h"
#include "vtkLogger.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkPartitionedDataSet.h"
#include "vtkRandomAttributeGenerator.h"
#include "vtkRedistributeDataSetFilter.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRenderer.h"
#include "vtkTestUtilities.h"
#include "vtkUnstructuredGrid.h"
#if VTK_MODULE_ENABLE_VTK_ParallelMPI
#include "vtkMPIController.h"
#else
#include "vtkDummyController.h"
#endif
#include "vtk_diy2.h"
#include VTK_DIY2(diy/mpi.hpp)
namespace {
bool ValidateDataset(vtkUnstructuredGrid* input, vtkPartitionedDataSet* output, vtkMultiProcessController* controller)
{
const int rank = controller->GetLocalProcessId();
vtkIdType local_cellid_max = 0;
for (unsigned int part = 0; part < output->GetNumberOfPartitions(); ++part)
{
if (auto ds = vtkDataSet::SafeDownCast(output->GetPartition(part)))
{
if (auto gcids = vtkIdTypeArray::SafeDownCast(ds->GetCellData()->GetGlobalIds()))
{
local_cellid_max =
std::max(static_cast<vtkIdType>(gcids->GetRange(0)[1]), local_cellid_max);
}
}
}
vtkIdType global_cellid_max;
controller->AllReduce(&local_cellid_max, &global_cellid_max, 1, vtkCommunicator::MAX_OP);
if (rank == 0 && global_cellid_max != input->GetNumberOfCells() - 1)
{
vtkLogF(ERROR, "incorrect global cell ids! expected %lld, actual %lld",
input->GetNumberOfCells() - 1, global_cellid_max);
return false;
}
return true;
}
}
int TestRedistributeDataSetFilter(int argc, char* argv[])
{
#if VTK_MODULE_ENABLE_VTK_ParallelMPI
vtkNew<vtkMPIController> controller;
#else
vtkNew<vtkDummyController> controller;
#endif
controller->Initialize(&argc, &argv);
vtkMultiProcessController::SetGlobalController(controller);
const int rank = controller->GetLocalProcessId();
vtkLogger::SetThreadName("rank:" + std::to_string(rank));
vtkSmartPointer<vtkUnstructuredGrid> data;
if (rank == 0)
{
char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/disk_out_ref.ex2");
if (!fname)
{
vtkLogF(ERROR, "Could not obtain filename for test data.");
return EXIT_FAILURE;
}
vtkNew<vtkExodusIIReader> rdr;
if (!rdr->CanReadFile(fname))
{
vtkLogF(ERROR, "Cannot read `%s`", fname);
return 1;
}
rdr->SetFileName(fname);
delete[] fname;
rdr->Update();
data = vtkUnstructuredGrid::SafeDownCast(
vtkMultiBlockDataSet::SafeDownCast(rdr->GetOutput()->GetBlock(0))->GetBlock(0));
}
else
{
data = vtkSmartPointer<vtkUnstructuredGrid>::New();
}
vtkNew<vtkRedistributeDataSetFilter> rdsf;
rdsf->SetInputDataObject(data);
rdsf->SetNumberOfPartitions(16);
rdsf->GenerateGlobalCellIdsOn();
rdsf->PreservePartitionsInOutputOn();
rdsf->Update();
if (!ValidateDataset(data, vtkPartitionedDataSet::SafeDownCast(rdsf->GetOutputDataObject(0)), controller))
{
return EXIT_FAILURE;
}
vtkNew<vtkDataSetSurfaceFilter> dsf;
dsf->SetInputConnection(rdsf->GetOutputPort());
vtkNew<vtkRandomAttributeGenerator> rag;
rag->SetDataTypeToDouble();
rag->SetNumberOfComponents(1);
rag->SetComponentRange(0, 1.0);
rag->GenerateCellScalarsOn();
rag->AttributesConstantPerBlockOn();
rag->SetInputConnection(dsf->GetOutputPort());
vtkNew<vtkCompositePolyDataMapper> mapper;
mapper->SetInputConnection(rag->GetOutputPort());
vtkNew<vtkCompositeRenderManager> prm;
vtkSmartPointer<vtkRenderer> renderer =
vtkSmartPointer<vtkRenderer>::Take(prm->MakeRenderer());
vtkSmartPointer<vtkRenderWindow> renWin =
vtkSmartPointer<vtkRenderWindow>::Take(prm->MakeRenderWindow());
renWin->AddRenderer(renderer);
renWin->DoubleBufferOn();
renWin->SetMultiSamples(0);
renWin->SetSize(400, 400);
vtkNew<vtkRenderWindowInteractor> iren;
iren->SetRenderWindow(renWin);
prm->SetRenderWindow(renWin);
prm->SetController(controller);
vtkNew<vtkActor> actor;
actor->SetMapper(mapper);
renderer->AddActor(actor);
int retVal = 1;
if (rank == 0)
{
prm->ResetAllCameras();
if (auto camera = renderer->GetActiveCamera())
{
camera->SetFocalPoint(-0.531007, -1.16954, -1.12284);
camera->SetPosition(8.62765, 28.0586, -33.585);
camera->SetViewUp(-0.373065, 0.739388, 0.560472);
}
renWin->Render();
retVal = vtkRegressionTestImage(renWin);
if (retVal == vtkRegressionTester::DO_INTERACTOR)
{
prm->StartInteractor();
}
controller->TriggerBreakRMIs();
}
else
{
prm->StartServices();
}
controller->Broadcast(&retVal, 1, 0);
controller->Finalize();
vtkMultiProcessController::SetGlobalController(nullptr);
return !retVal;
}
| 28.592784 | 118 | 0.704705 | [
"render"
] |
141e2200adc9a3501717032c2652fc1dc7d5cab4 | 2,559 | cpp | C++ | RequiemEngine/src/Graphics/GraphicsRenderPipeline.cpp | A-RAVEN/Crimson | a170beb9bf43ba135468f9593f38cf0a21865afe | [
"MIT"
] | 2 | 2020-10-19T15:59:27.000Z | 2020-10-19T15:59:37.000Z | RequiemEngine/src/Graphics/GraphicsRenderPipeline.cpp | A-RAVEN/Crimson | a170beb9bf43ba135468f9593f38cf0a21865afe | [
"MIT"
] | null | null | null | RequiemEngine/src/Graphics/GraphicsRenderPipeline.cpp | A-RAVEN/Crimson | a170beb9bf43ba135468f9593f38cf0a21865afe | [
"MIT"
] | null | null | null | #include <headers/Graphics/GraphicsRenderPipeline.h>
using namespace Crimson;
GraphicsContext::GraphicsContext(PGPUDevice device) : m_Device(device)
{
}
Ptr64 GraphicsContext::CreateResizableRenderTarget(uint32_t format, bool can_sample, bool can_blit)
{
std::vector<Crimson::EImageUsage> usages;
Crimson::EFormat eformat = static_cast<Crimson::EFormat>(format);
if (Crimson::IsColorFormat(eformat))
{
usages.push_back(EImageUsage::E_IMAGE_USAGE_COLOR_ATTACHMENT);
}
else
{
usages.push_back(EImageUsage::E_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT);
}
if (can_sample)
{
usages.push_back(EImageUsage::E_IMAGE_USAGE_SAMPLE);
}
if (can_blit)
{
usages.push_back(EImageUsage::E_IMAGE_USAGE_COPY_SRC);
usages.push_back(EImageUsage::E_IMAGE_USAGE_COPY_DST);
}
PGPUImage new_rendertarget = m_Device->CreateImage(eformat, 1024, 1024, 1, usages, EMemoryType::E_MEMORY_TYPE_DEVICE);
m_RenderTargets.push_back(new_rendertarget);
return Ptr64::WrapUint(m_RenderTargets.size() - 1);
}
Ptr64 GraphicsContext::CreateFramebuffer(std::vector<Ptr64> const& renderTargets)
{
PFramebuffer framebuffer = m_Device->CreateFramebuffer();
framebuffer->m_Images.resize(renderTargets.size());
for (size_t i = 0; i < renderTargets.size(); ++i)
{
framebuffer->m_Images[i] = m_RenderTargets[renderTargets[i].uintT];
}
m_FrameBuffers.push_back(framebuffer);
return Ptr64::WrapUint(m_FrameBuffers.size() - 1);
}
Ptr64 GraphicsContext::CreateRenderPassInstance(Ptr64 renderPass, Ptr64 frameBuffer)
{
PRenderPassInstance instance = m_Device->CreateRenderPassInstance(m_RenderPasses[renderPass.uintT], m_FrameBuffers[frameBuffer.uintT]);
m_RenderPassInstances.push_back(instance);
return Ptr64::WrapUint(m_RenderPassInstances.size() - 1);
}
Ptr64 GraphicsContext::AddRenderPass(PRenderPass renderPass)
{
Ptr64 return_val;
m_RenderPasses.push_back(renderPass);
return Ptr64::WrapUint(m_RenderPasses.size() - 1);
}
Ptr64 GraphicsContext::AddLocalGraphicsPipelines(PGraphicsPipeline pipeline)
{
Ptr64 return_val;
m_LocalGraphicsPipelines.push_back(pipeline);
return Ptr64::WrapUint(m_LocalGraphicsPipelines.size() - 1);
}
void GraphicsContext::ClearContext()
{
for (auto instance : m_RenderPassInstances)
{
instance->Dispose();
}
for (auto renderpass : m_RenderPasses)
{
renderpass->Dispose();
}
for (auto framebuffer : m_FrameBuffers)
{
framebuffer->Dispose();
}
for (auto graphics_pipeline : m_LocalGraphicsPipelines)
{
graphics_pipeline->Dispose();
}
for (auto rendertarget : m_RenderTargets)
{
rendertarget->Dispose();
}
}
| 28.752809 | 136 | 0.781946 | [
"vector"
] |
141fd75d42aa2e242fcb93552beac63897d22862 | 905 | cpp | C++ | tests/test-type_traits.cpp | jin1xiao3long2/libmozart | 78ba2e0d2cb7fbf8b721b94d05c9f2845c6b0281 | [
"Apache-2.0"
] | 2 | 2021-03-01T06:41:30.000Z | 2021-03-01T07:28:15.000Z | tests/test-type_traits.cpp | jin1xiao3long2/libmozart | 78ba2e0d2cb7fbf8b721b94d05c9f2845c6b0281 | [
"Apache-2.0"
] | null | null | null | tests/test-type_traits.cpp | jin1xiao3long2/libmozart | 78ba2e0d2cb7fbf8b721b94d05c9f2845c6b0281 | [
"Apache-2.0"
] | 1 | 2021-04-22T16:48:25.000Z | 2021-04-22T16:48:25.000Z | /**
* Mozart++ Template Library
* Licensed under Apache 2.0
* Copyright (C) 2020-2021 Chengdu Covariant Technologies Co., LTD.
* Website: https://covariant.cn/
* Github: https://github.com/chengdu-zhirui/
*/
#include <mozart++/core>
#include <cstdio>
#include <vector>
#include <list>
#include <deque>
#include <unordered_map>
int main() {
using namespace mpp;
static_assert(is_iterable_v<std::vector<int>>, "You wrote a bug");
static_assert(is_iterable_v<std::vector<std::vector<int>>>, "You wrote a bug");
static_assert(!is_iterable_v<std::string>, "You wrote a bug");
static_assert(!is_iterable_v<int>, "You wrote a bug");
static_assert(!is_iterable_v<mpp::function<void()>>, "You wrote a bug");
static_assert(!is_iterable_v<mpp::function<const char *()>>, "You wrote a bug");
static_assert(!is_iterable_v<mpp::function<const char *()>>, "You wrote a bug");
}
| 33.518519 | 84 | 0.690608 | [
"vector"
] |
142153e5d5145cc2bc9534de4b85855eb00adcef | 6,222 | hpp | C++ | third_party/include/mvscxx/oglplus/dsa/buffer_map.hpp | Simmesimme/swift2d | 147a862208dee56f972361b5325009e020124137 | [
"MIT"
] | null | null | null | third_party/include/mvscxx/oglplus/dsa/buffer_map.hpp | Simmesimme/swift2d | 147a862208dee56f972361b5325009e020124137 | [
"MIT"
] | null | null | null | third_party/include/mvscxx/oglplus/dsa/buffer_map.hpp | Simmesimme/swift2d | 147a862208dee56f972361b5325009e020124137 | [
"MIT"
] | null | null | null | /**
* @file oglplus/dsa/buffer_map.hpp
* @brief BufferMap wrappers with direct state access
*
* @author Matus Chochlik
*
* Copyright 2010-2014 Matus Chochlik. 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)
*/
#pragma once
#ifndef OGLPLUS_DSA_BUFFER_MAP_1309301821_HPP
#define OGLPLUS_DSA_BUFFER_MAP_1309301821_HPP
#include <oglplus/buffer.hpp>
namespace oglplus {
#if OGLPLUS_DOCUMENTATION_ONLY || GL_VERSION_4_5 || GL_ARB_direct_state_access
class DSABufferRawMap
{
private:
const GLintptr _offset;
GLsizeiptr _size;
GLvoid* _ptr;
const GLuint _name;
static GLsizeiptr _get_size(GLuint name)
{
GLint value = 0;
OGLPLUS_GLFUNC(GetNamedBufferParameteriv)(
name,
GL_BUFFER_SIZE,
&value
);
OGLPLUS_CHECK(
GetNamedBufferParameteriv,
ObjectError,
Object(BufferName(name))
);
return GLsizeiptr(value);
}
static GLenum _translate(GLbitfield access)
{
switch(access)
{
case GL_MAP_READ_BIT:
return GL_READ_ONLY;
case GL_MAP_WRITE_BIT:
return GL_WRITE_ONLY;
case GL_MAP_READ_BIT|GL_MAP_WRITE_BIT:
return GL_READ_WRITE;
}
return GL_READ_ONLY;
}
public:
/// Maps a range of the buffer
/**
* @param target use the buffer bound to the target specified
* @param offset map offset in units of Type
* @param size map size in units of Type
* @param access the access specifier for the buffer mapping
*
* @throws Error
*/
DSABufferRawMap(
BufferName buffer,
BufferSize offset,
BufferSize size,
Bitfield<BufferMapAccess> access
): _offset(GLintptr(offset.Get()))
, _size(GLsizeiptr(size.Get()))
, _ptr(
OGLPLUS_GLFUNC(MapNamedBufferRange)(
GetGLName(buffer),
_offset,
_size,
GLbitfield(access)
)
), _name(GetGLName(buffer))
{
OGLPLUS_CHECK(
MapNamedBufferRange,
ObjectError,
Object(buffer)
);
}
/// Maps the whole buffer
/**
* @param target use the buffer bound to the target specified
* @param access the access specifier for the buffer mapping
*
* This class is non-copyable.
*
* @throws Error
*/
DSABufferRawMap(
BufferName buffer,
Bitfield<BufferMapAccess> access
): _offset(0)
, _size(_get_size(GetGLName(buffer)))
, _ptr(
OGLPLUS_GLFUNC(MapNamedBuffer)(
GetGLName(buffer),
_translate(GLbitfield(access))
)
), _name(GetGLName(buffer))
{
OGLPLUS_CHECK(
MapNamedBuffer,
ObjectError,
Object(buffer)
);
}
#if !OGLPLUS_NO_DELETED_FUNCTIONS
DSABufferRawMap(const DSABufferRawMap&) = delete;
#else
private:
DSABufferRawMap(const DSABufferRawMap&);
public:
#endif
/// Move construction is enabled
DSABufferRawMap(DSABufferRawMap&& temp)
: _offset(temp._offset)
, _size(temp._size)
, _ptr(temp._ptr)
, _name(temp._name)
{
temp._ptr = nullptr;
}
~DSABufferRawMap(void)
{
try { Unmap(); }
catch(...) { }
}
/// Unmaps the buffer from client address space
/**
* @glsymbols
* @glfunref{UnmapNamedBuffer}
*
* @throws Error
*/
void Unmap(void)
{
if(_ptr != nullptr)
{
OGLPLUS_GLFUNC(UnmapNamedBuffer)(_name);
OGLPLUS_IGNORE(UnmapNamedBuffer);
_ptr = nullptr;
}
}
/// Returns true if the buffer is mapped
bool Mapped(void) const
{
return _ptr != nullptr;
}
/// Returns the size (in bytes) of the mapped buffer
GLsizeiptr Size(void) const
{
return _size;
}
/// Returns a const pointer to the mapped data
/**
* @pre Mapped()
*/
const GLvoid* RawData(void) const
{
assert(Mapped());
return _ptr;
}
/// Returns a pointer to the mapped data
/**
* @pre Mapped()
*/
GLvoid* RawData(void)
{
assert(Mapped());
return _ptr;
}
/// Indicate modifications to a mapped range
/**
* @glsymbols
* @glfunref{FlushMappedNamedBufferRange}
*
* @pre Mapped()
*
* @throws Error
*/
void FlushRange(BufferSize offset, BufferSize length)
{
OGLPLUS_GLFUNC(FlushMappedNamedBufferRange)(
_name,
GLintptr(offset.Get()),
GLsizeiptr(length.Get())
);
OGLPLUS_CHECK(
FlushMappedNamedBufferRange,
ObjectError,
Object(BufferName(_name))
);
}
};
/// Untyped mapping of the buffer to the client address space
template <typename Type>
class DSABufferTypedMap
: public DSABufferRawMap
{
public:
/// Maps a range of the buffer
/**
* @param target use the buffer bound to the target specified
* @param offset map offset in units of Type
* @param size map size in units of Type
* @param access the access specifier for the buffer mapping
*
* @throws Error
*/
DSABufferTypedMap(
BufferName buffer,
BufferTypedSize<Type> offset,
BufferTypedSize<Type> size,
Bitfield<BufferMapAccess> access
): DSABufferRawMap(buffer, offset, size, access)
{ }
/// Maps the whole buffer
/**
* @param target use the buffer bound to the target specified
* @param access the access specifier for the buffer mapping
*
* This class is non-copyable.
*
* @throws Error
*/
DSABufferTypedMap(
BufferName buffer,
Bitfield<BufferMapAccess> access
): DSABufferRawMap(buffer, access)
{ }
/// Move construction is enabled
DSABufferTypedMap(DSABufferTypedMap&& temp)
: DSABufferRawMap(static_cast<DSABufferRawMap&&>(temp))
{ }
/// Returns the count of elements of Type in the mapped buffer
GLsizeiptr Count(void) const
{
assert(this->Size() % sizeof(Type) == 0);
return this->Size() / sizeof(Type);
}
/// Returns a const pointer to the mapped data
const Type* Data(void) const
{
return static_cast<const Type*>(this->RawData());
}
/// Returns a pointer to the mapped data
Type* Data(void)
{
return static_cast<Type*>(this->RawData());
}
/// Returns a const reference to the element at the specified index
const Type& At(GLuint index) const
{
assert(Data() != nullptr);
assert(((index+1)*sizeof(Type)) <= std::size_t(this->Size()));
return Data()[index];
}
/// Returns a reference to the element at the specified index
Type& At(GLuint index)
{
assert(Data() != nullptr);
assert(((index+1)*sizeof(Type)) <= std::size_t(this->Size()));
return Data()[index];
}
};
#endif // GL_ARB_direct_state_access
} // namespace oglplus
#endif // include guard
| 20.671096 | 78 | 0.69415 | [
"object"
] |
1423bd6fcdc250f9b29da73f3262a4768d0e9dfb | 46,873 | cc | C++ | src/numbers/conversions.cc | levijskal/v8 | b5979eaa5b5c09a6b8ba15a22997cb36da21a258 | [
"BSD-3-Clause"
] | 37 | 2015-02-04T22:02:40.000Z | 2021-07-29T03:47:29.000Z | src/numbers/conversions.cc | levijskal/v8 | b5979eaa5b5c09a6b8ba15a22997cb36da21a258 | [
"BSD-3-Clause"
] | 54 | 2020-06-23T17:34:04.000Z | 2022-03-31T02:04:06.000Z | src/numbers/conversions.cc | levijskal/v8 | b5979eaa5b5c09a6b8ba15a22997cb36da21a258 | [
"BSD-3-Clause"
] | 19 | 2015-04-13T15:23:46.000Z | 2021-05-12T10:47:06.000Z | // Copyright 2011 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/numbers/conversions.h"
#include <limits.h>
#include <stdarg.h>
#include <cmath>
#include "src/common/assert-scope.h"
#include "src/handles/handles.h"
#include "src/heap/factory.h"
#include "src/numbers/dtoa.h"
#include "src/numbers/strtod.h"
#include "src/objects/bigint.h"
#include "src/objects/objects-inl.h"
#include "src/strings/char-predicates-inl.h"
#include "src/utils/allocation.h"
#include "src/utils/utils.h"
#if defined(_STLP_VENDOR_CSTD)
// STLPort doesn't import fpclassify into the std namespace.
#define FPCLASSIFY_NAMESPACE
#else
#define FPCLASSIFY_NAMESPACE std
#endif
namespace v8 {
namespace internal {
inline double JunkStringValue() {
return bit_cast<double, uint64_t>(kQuietNaNMask);
}
inline double SignedZero(bool negative) {
return negative ? uint64_to_double(Double::kSignMask) : 0.0;
}
inline bool isDigit(int x, int radix) {
return (x >= '0' && x <= '9' && x < '0' + radix) ||
(radix > 10 && x >= 'a' && x < 'a' + radix - 10) ||
(radix > 10 && x >= 'A' && x < 'A' + radix - 10);
}
inline bool isBinaryDigit(int x) { return x == '0' || x == '1'; }
template <class Iterator, class EndMark>
bool SubStringEquals(Iterator* current, EndMark end, const char* substring) {
DCHECK(**current == *substring);
for (substring++; *substring != '\0'; substring++) {
++*current;
if (*current == end || **current != *substring) return false;
}
++*current;
return true;
}
// Returns true if a nonspace character has been found and false if the
// end was been reached before finding a nonspace character.
template <class Iterator, class EndMark>
inline bool AdvanceToNonspace(Iterator* current, EndMark end) {
while (*current != end) {
if (!IsWhiteSpaceOrLineTerminator(**current)) return true;
++*current;
}
return false;
}
// Parsing integers with radix 2, 4, 8, 16, 32. Assumes current != end.
template <int radix_log_2, class Iterator, class EndMark>
double InternalStringToIntDouble(Iterator current, EndMark end, bool negative,
bool allow_trailing_junk) {
DCHECK(current != end);
// Skip leading 0s.
while (*current == '0') {
++current;
if (current == end) return SignedZero(negative);
}
int64_t number = 0;
int exponent = 0;
const int radix = (1 << radix_log_2);
int lim_0 = '0' + (radix < 10 ? radix : 10);
int lim_a = 'a' + (radix - 10);
int lim_A = 'A' + (radix - 10);
do {
int digit;
if (*current >= '0' && *current < lim_0) {
digit = static_cast<char>(*current) - '0';
} else if (*current >= 'a' && *current < lim_a) {
digit = static_cast<char>(*current) - 'a' + 10;
} else if (*current >= 'A' && *current < lim_A) {
digit = static_cast<char>(*current) - 'A' + 10;
} else {
if (allow_trailing_junk || !AdvanceToNonspace(¤t, end)) {
break;
} else {
return JunkStringValue();
}
}
number = number * radix + digit;
int overflow = static_cast<int>(number >> 53);
if (overflow != 0) {
// Overflow occurred. Need to determine which direction to round the
// result.
int overflow_bits_count = 1;
while (overflow > 1) {
overflow_bits_count++;
overflow >>= 1;
}
int dropped_bits_mask = ((1 << overflow_bits_count) - 1);
int dropped_bits = static_cast<int>(number) & dropped_bits_mask;
number >>= overflow_bits_count;
exponent = overflow_bits_count;
bool zero_tail = true;
while (true) {
++current;
if (current == end || !isDigit(*current, radix)) break;
zero_tail = zero_tail && *current == '0';
exponent += radix_log_2;
}
if (!allow_trailing_junk && AdvanceToNonspace(¤t, end)) {
return JunkStringValue();
}
int middle_value = (1 << (overflow_bits_count - 1));
if (dropped_bits > middle_value) {
number++; // Rounding up.
} else if (dropped_bits == middle_value) {
// Rounding to even to consistency with decimals: half-way case rounds
// up if significant part is odd and down otherwise.
if ((number & 1) != 0 || !zero_tail) {
number++; // Rounding up.
}
}
// Rounding up may cause overflow.
if ((number & (static_cast<int64_t>(1) << 53)) != 0) {
exponent++;
number >>= 1;
}
break;
}
++current;
} while (current != end);
DCHECK(number < ((int64_t)1 << 53));
DCHECK(static_cast<int64_t>(static_cast<double>(number)) == number);
if (exponent == 0) {
if (negative) {
if (number == 0) return -0.0;
number = -number;
}
return static_cast<double>(number);
}
DCHECK_NE(number, 0);
return std::ldexp(static_cast<double>(negative ? -number : number), exponent);
}
namespace {
// Subclasses of StringToIntHelper get access to internal state:
enum class State { kRunning, kError, kJunk, kEmpty, kZero, kDone };
enum class Sign { kNegative, kPositive, kNone };
} // namespace
// ES6 18.2.5 parseInt(string, radix) (with NumberParseIntHelper subclass);
// and BigInt parsing cases from https://tc39.github.io/proposal-bigint/
// (with StringToBigIntHelper subclass).
template <typename LocalIsolate>
class StringToIntHelper {
public:
StringToIntHelper(LocalIsolate* isolate, Handle<String> subject, int radix)
: isolate_(isolate), subject_(subject), radix_(radix) {
DCHECK(subject->IsFlat());
}
// Used for the StringToBigInt operation.
StringToIntHelper(LocalIsolate* isolate, Handle<String> subject)
: isolate_(isolate), subject_(subject) {
DCHECK(subject->IsFlat());
}
// Used for parsing BigInt literals, where the input is a Zone-allocated
// buffer of one-byte digits, along with an optional radix prefix.
StringToIntHelper(LocalIsolate* isolate, const uint8_t* subject, int length)
: isolate_(isolate), raw_one_byte_subject_(subject), length_(length) {}
virtual ~StringToIntHelper() = default;
protected:
// Subclasses must implement these:
virtual void AllocateResult() = 0;
virtual void ResultMultiplyAdd(uint32_t multiplier, uint32_t part) = 0;
// Subclasses must call this to do all the work.
void ParseInt();
// Subclasses may override this.
virtual bool CheckTermination() { return false; }
virtual void HandleSpecialCases() {}
// Subclass constructors should call these for configuration before calling
// ParseInt().
void set_allow_binary_and_octal_prefixes() {
allow_binary_and_octal_prefixes_ = true;
}
void set_disallow_trailing_junk() { allow_trailing_junk_ = false; }
bool IsOneByte() const {
return raw_one_byte_subject_ != nullptr ||
String::IsOneByteRepresentationUnderneath(*subject_);
}
Vector<const uint8_t> GetOneByteVector() {
if (raw_one_byte_subject_ != nullptr) {
return Vector<const uint8_t>(raw_one_byte_subject_, length_);
}
DisallowHeapAllocation no_gc;
return subject_->GetFlatContent(no_gc).ToOneByteVector();
}
Vector<const uc16> GetTwoByteVector() {
DisallowHeapAllocation no_gc;
return subject_->GetFlatContent(no_gc).ToUC16Vector();
}
LocalIsolate* isolate() { return isolate_; }
int radix() { return radix_; }
int cursor() { return cursor_; }
int length() { return length_; }
bool negative() { return sign_ == Sign::kNegative; }
Sign sign() { return sign_; }
State state() { return state_; }
void set_state(State state) { state_ = state; }
private:
template <class Char>
void DetectRadixInternal(Char current, int length);
template <class Char>
bool ParseChunkInternal(Char start);
LocalIsolate* isolate_;
Handle<String> subject_;
const uint8_t* raw_one_byte_subject_ = nullptr;
int radix_ = 0;
int cursor_ = 0;
int length_ = 0;
Sign sign_ = Sign::kNone;
bool leading_zero_ = false;
bool allow_binary_and_octal_prefixes_ = false;
bool allow_trailing_junk_ = true;
State state_ = State::kRunning;
};
template <typename LocalIsolate>
void StringToIntHelper<LocalIsolate>::ParseInt() {
{
DisallowHeapAllocation no_gc;
if (IsOneByte()) {
Vector<const uint8_t> vector = GetOneByteVector();
DetectRadixInternal(vector.begin(), vector.length());
} else {
Vector<const uc16> vector = GetTwoByteVector();
DetectRadixInternal(vector.begin(), vector.length());
}
}
if (state_ != State::kRunning) return;
AllocateResult();
HandleSpecialCases();
if (state_ != State::kRunning) return;
do {
{
DisallowHeapAllocation no_gc;
if (IsOneByte()) {
Vector<const uint8_t> vector = GetOneByteVector();
DCHECK_EQ(length_, vector.length());
if (ParseChunkInternal(vector.begin())) {
break;
}
} else {
Vector<const uc16> vector = GetTwoByteVector();
DCHECK_EQ(length_, vector.length());
if (ParseChunkInternal(vector.begin())) {
break;
}
}
}
// The flat vector handle is temporarily released after parsing 10kb
// in order to invoke interrupts which may in turn invoke GC.
if (CheckTermination()) {
set_state(State::kError);
break;
}
} while (true);
DCHECK_NE(state_, State::kRunning);
}
template <typename LocalIsolate>
template <class Char>
void StringToIntHelper<LocalIsolate>::DetectRadixInternal(Char current,
int length) {
Char start = current;
length_ = length;
Char end = start + length;
if (!AdvanceToNonspace(¤t, end)) {
return set_state(State::kEmpty);
}
if (*current == '+') {
// Ignore leading sign; skip following spaces.
++current;
if (current == end) {
return set_state(State::kJunk);
}
sign_ = Sign::kPositive;
} else if (*current == '-') {
++current;
if (current == end) {
return set_state(State::kJunk);
}
sign_ = Sign::kNegative;
}
if (radix_ == 0) {
// Radix detection.
radix_ = 10;
if (*current == '0') {
++current;
if (current == end) return set_state(State::kZero);
if (*current == 'x' || *current == 'X') {
radix_ = 16;
++current;
if (current == end) return set_state(State::kJunk);
} else if (allow_binary_and_octal_prefixes_ &&
(*current == 'o' || *current == 'O')) {
radix_ = 8;
++current;
if (current == end) return set_state(State::kJunk);
} else if (allow_binary_and_octal_prefixes_ &&
(*current == 'b' || *current == 'B')) {
radix_ = 2;
++current;
if (current == end) return set_state(State::kJunk);
} else {
leading_zero_ = true;
}
}
} else if (radix_ == 16) {
if (*current == '0') {
// Allow "0x" prefix.
++current;
if (current == end) return set_state(State::kZero);
if (*current == 'x' || *current == 'X') {
++current;
if (current == end) return set_state(State::kJunk);
} else {
leading_zero_ = true;
}
}
}
// Skip leading zeros.
while (*current == '0') {
leading_zero_ = true;
++current;
if (current == end) return set_state(State::kZero);
}
if (!leading_zero_ && !isDigit(*current, radix_)) {
return set_state(State::kJunk);
}
DCHECK(radix_ >= 2 && radix_ <= 36);
STATIC_ASSERT(String::kMaxLength <= INT_MAX);
cursor_ = static_cast<int>(current - start);
}
template <typename LocalIsolate>
template <class Char>
bool StringToIntHelper<LocalIsolate>::ParseChunkInternal(Char start) {
const int kChunkSize = 10240;
Char current = start + cursor_;
Char end = start + length_;
Char break_pos = current + kChunkSize;
// The following code causes accumulating rounding error for numbers greater
// than ~2^56. It's explicitly allowed in the spec: "if R is not 2, 4, 8, 10,
// 16, or 32, then mathInt may be an implementation-dependent approximation to
// the mathematical integer value" (15.1.2.2).
int lim_0 = '0' + (radix_ < 10 ? radix_ : 10);
int lim_a = 'a' + (radix_ - 10);
int lim_A = 'A' + (radix_ - 10);
// NOTE: The code for computing the value may seem a bit complex at
// first glance. It is structured to use 32-bit multiply-and-add
// loops as long as possible to avoid losing precision.
bool done = false;
do {
// Parse the longest part of the string starting at {current}
// possible while keeping the multiplier, and thus the part
// itself, within 32 bits.
uint32_t part = 0, multiplier = 1;
while (true) {
uint32_t d;
if (*current >= '0' && *current < lim_0) {
d = *current - '0';
} else if (*current >= 'a' && *current < lim_a) {
d = *current - 'a' + 10;
} else if (*current >= 'A' && *current < lim_A) {
d = *current - 'A' + 10;
} else {
done = true;
break;
}
// Update the value of the part as long as the multiplier fits
// in 32 bits. When we can't guarantee that the next iteration
// will not overflow the multiplier, we stop parsing the part
// by leaving the loop.
const uint32_t kMaximumMultiplier = 0xFFFFFFFFU / 36;
uint32_t m = multiplier * static_cast<uint32_t>(radix_);
if (m > kMaximumMultiplier) break;
part = part * radix_ + d;
multiplier = m;
DCHECK(multiplier > part);
++current;
if (current == end) {
done = true;
break;
}
}
// Update the value and skip the part in the string.
ResultMultiplyAdd(multiplier, part);
// Set final state
if (done) {
if (!allow_trailing_junk_ && AdvanceToNonspace(¤t, end)) {
set_state(State::kJunk);
} else {
set_state(State::kDone);
}
return true;
}
} while (current < break_pos);
cursor_ = static_cast<int>(current - start);
return false;
}
class NumberParseIntHelper : public StringToIntHelper<Isolate> {
public:
NumberParseIntHelper(Isolate* isolate, Handle<String> string, int radix)
: StringToIntHelper(isolate, string, radix) {}
double GetResult() {
ParseInt();
switch (state()) {
case State::kJunk:
case State::kEmpty:
return JunkStringValue();
case State::kZero:
return SignedZero(negative());
case State::kDone:
return negative() ? -result_ : result_;
case State::kError:
case State::kRunning:
break;
}
UNREACHABLE();
}
protected:
void AllocateResult() override {}
void ResultMultiplyAdd(uint32_t multiplier, uint32_t part) override {
result_ = result_ * multiplier + part;
}
private:
void HandleSpecialCases() override {
bool is_power_of_two = base::bits::IsPowerOfTwo(radix());
if (!is_power_of_two && radix() != 10) return;
DisallowHeapAllocation no_gc;
if (IsOneByte()) {
Vector<const uint8_t> vector = GetOneByteVector();
DCHECK_EQ(length(), vector.length());
result_ = is_power_of_two ? HandlePowerOfTwoCase(vector.begin())
: HandleBaseTenCase(vector.begin());
} else {
Vector<const uc16> vector = GetTwoByteVector();
DCHECK_EQ(length(), vector.length());
result_ = is_power_of_two ? HandlePowerOfTwoCase(vector.begin())
: HandleBaseTenCase(vector.begin());
}
set_state(State::kDone);
}
template <class Char>
double HandlePowerOfTwoCase(Char start) {
Char current = start + cursor();
Char end = start + length();
const bool allow_trailing_junk = true;
// GetResult() will take care of the sign bit, so ignore it for now.
const bool negative = false;
switch (radix()) {
case 2:
return InternalStringToIntDouble<1>(current, end, negative,
allow_trailing_junk);
case 4:
return InternalStringToIntDouble<2>(current, end, negative,
allow_trailing_junk);
case 8:
return InternalStringToIntDouble<3>(current, end, negative,
allow_trailing_junk);
case 16:
return InternalStringToIntDouble<4>(current, end, negative,
allow_trailing_junk);
case 32:
return InternalStringToIntDouble<5>(current, end, negative,
allow_trailing_junk);
default:
UNREACHABLE();
}
}
template <class Char>
double HandleBaseTenCase(Char start) {
// Parsing with strtod.
Char current = start + cursor();
Char end = start + length();
const int kMaxSignificantDigits = 309; // Doubles are less than 1.8e308.
// The buffer may contain up to kMaxSignificantDigits + 1 digits and a zero
// end.
const int kBufferSize = kMaxSignificantDigits + 2;
char buffer[kBufferSize];
int buffer_pos = 0;
while (*current >= '0' && *current <= '9') {
if (buffer_pos <= kMaxSignificantDigits) {
// If the number has more than kMaxSignificantDigits it will be parsed
// as infinity.
DCHECK_LT(buffer_pos, kBufferSize);
buffer[buffer_pos++] = static_cast<char>(*current);
}
++current;
if (current == end) break;
}
SLOW_DCHECK(buffer_pos < kBufferSize);
buffer[buffer_pos] = '\0';
Vector<const char> buffer_vector(buffer, buffer_pos);
return Strtod(buffer_vector, 0);
}
double result_ = 0;
};
// Converts a string to a double value. Assumes the Iterator supports
// the following operations:
// 1. current == end (other ops are not allowed), current != end.
// 2. *current - gets the current character in the sequence.
// 3. ++current (advances the position).
template <class Iterator, class EndMark>
double InternalStringToDouble(Iterator current, EndMark end, int flags,
double empty_string_val) {
// To make sure that iterator dereferencing is valid the following
// convention is used:
// 1. Each '++current' statement is followed by check for equality to 'end'.
// 2. If AdvanceToNonspace returned false then current == end.
// 3. If 'current' becomes be equal to 'end' the function returns or goes to
// 'parsing_done'.
// 4. 'current' is not dereferenced after the 'parsing_done' label.
// 5. Code before 'parsing_done' may rely on 'current != end'.
if (!AdvanceToNonspace(¤t, end)) {
return empty_string_val;
}
const bool allow_trailing_junk = (flags & ALLOW_TRAILING_JUNK) != 0;
// Maximum number of significant digits in decimal representation.
// The longest possible double in decimal representation is
// (2^53 - 1) * 2 ^ -1074 that is (2 ^ 53 - 1) * 5 ^ 1074 / 10 ^ 1074
// (768 digits). If we parse a number whose first digits are equal to a
// mean of 2 adjacent doubles (that could have up to 769 digits) the result
// must be rounded to the bigger one unless the tail consists of zeros, so
// we don't need to preserve all the digits.
const int kMaxSignificantDigits = 772;
// The longest form of simplified number is: "-<significant digits>'.1eXXX\0".
const int kBufferSize = kMaxSignificantDigits + 10;
char buffer[kBufferSize];
int buffer_pos = 0;
// Exponent will be adjusted if insignificant digits of the integer part
// or insignificant leading zeros of the fractional part are dropped.
int exponent = 0;
int significant_digits = 0;
int insignificant_digits = 0;
bool nonzero_digit_dropped = false;
enum Sign { NONE, NEGATIVE, POSITIVE };
Sign sign = NONE;
if (*current == '+') {
// Ignore leading sign.
++current;
if (current == end) return JunkStringValue();
sign = POSITIVE;
} else if (*current == '-') {
++current;
if (current == end) return JunkStringValue();
sign = NEGATIVE;
}
static const char kInfinityString[] = "Infinity";
if (*current == kInfinityString[0]) {
if (!SubStringEquals(¤t, end, kInfinityString)) {
return JunkStringValue();
}
if (!allow_trailing_junk && AdvanceToNonspace(¤t, end)) {
return JunkStringValue();
}
DCHECK_EQ(buffer_pos, 0);
return (sign == NEGATIVE) ? -V8_INFINITY : V8_INFINITY;
}
bool leading_zero = false;
if (*current == '0') {
++current;
if (current == end) return SignedZero(sign == NEGATIVE);
leading_zero = true;
// It could be hexadecimal value.
if ((flags & ALLOW_HEX) && (*current == 'x' || *current == 'X')) {
++current;
if (current == end || !isDigit(*current, 16) || sign != NONE) {
return JunkStringValue(); // "0x".
}
return InternalStringToIntDouble<4>(current, end, false,
allow_trailing_junk);
// It could be an explicit octal value.
} else if ((flags & ALLOW_OCTAL) && (*current == 'o' || *current == 'O')) {
++current;
if (current == end || !isDigit(*current, 8) || sign != NONE) {
return JunkStringValue(); // "0o".
}
return InternalStringToIntDouble<3>(current, end, false,
allow_trailing_junk);
// It could be a binary value.
} else if ((flags & ALLOW_BINARY) && (*current == 'b' || *current == 'B')) {
++current;
if (current == end || !isBinaryDigit(*current) || sign != NONE) {
return JunkStringValue(); // "0b".
}
return InternalStringToIntDouble<1>(current, end, false,
allow_trailing_junk);
}
// Ignore leading zeros in the integer part.
while (*current == '0') {
++current;
if (current == end) return SignedZero(sign == NEGATIVE);
}
}
bool octal = leading_zero && (flags & ALLOW_IMPLICIT_OCTAL) != 0;
// Copy significant digits of the integer part (if any) to the buffer.
while (*current >= '0' && *current <= '9') {
if (significant_digits < kMaxSignificantDigits) {
DCHECK_LT(buffer_pos, kBufferSize);
buffer[buffer_pos++] = static_cast<char>(*current);
significant_digits++;
// Will later check if it's an octal in the buffer.
} else {
insignificant_digits++; // Move the digit into the exponential part.
nonzero_digit_dropped = nonzero_digit_dropped || *current != '0';
}
octal = octal && *current < '8';
++current;
if (current == end) goto parsing_done;
}
if (significant_digits == 0) {
octal = false;
}
if (*current == '.') {
if (octal && !allow_trailing_junk) return JunkStringValue();
if (octal) goto parsing_done;
++current;
if (current == end) {
if (significant_digits == 0 && !leading_zero) {
return JunkStringValue();
} else {
goto parsing_done;
}
}
if (significant_digits == 0) {
// octal = false;
// Integer part consists of 0 or is absent. Significant digits start after
// leading zeros (if any).
while (*current == '0') {
++current;
if (current == end) return SignedZero(sign == NEGATIVE);
exponent--; // Move this 0 into the exponent.
}
}
// There is a fractional part. We don't emit a '.', but adjust the exponent
// instead.
while (*current >= '0' && *current <= '9') {
if (significant_digits < kMaxSignificantDigits) {
DCHECK_LT(buffer_pos, kBufferSize);
buffer[buffer_pos++] = static_cast<char>(*current);
significant_digits++;
exponent--;
} else {
// Ignore insignificant digits in the fractional part.
nonzero_digit_dropped = nonzero_digit_dropped || *current != '0';
}
++current;
if (current == end) goto parsing_done;
}
}
if (!leading_zero && exponent == 0 && significant_digits == 0) {
// If leading_zeros is true then the string contains zeros.
// If exponent < 0 then string was [+-]\.0*...
// If significant_digits != 0 the string is not equal to 0.
// Otherwise there are no digits in the string.
return JunkStringValue();
}
// Parse exponential part.
if (*current == 'e' || *current == 'E') {
if (octal) return JunkStringValue();
++current;
if (current == end) {
if (allow_trailing_junk) {
goto parsing_done;
} else {
return JunkStringValue();
}
}
char sign = '+';
if (*current == '+' || *current == '-') {
sign = static_cast<char>(*current);
++current;
if (current == end) {
if (allow_trailing_junk) {
goto parsing_done;
} else {
return JunkStringValue();
}
}
}
if (current == end || *current < '0' || *current > '9') {
if (allow_trailing_junk) {
goto parsing_done;
} else {
return JunkStringValue();
}
}
const int max_exponent = INT_MAX / 2;
DCHECK(-max_exponent / 2 <= exponent && exponent <= max_exponent / 2);
int num = 0;
do {
// Check overflow.
int digit = *current - '0';
if (num >= max_exponent / 10 &&
!(num == max_exponent / 10 && digit <= max_exponent % 10)) {
num = max_exponent;
} else {
num = num * 10 + digit;
}
++current;
} while (current != end && *current >= '0' && *current <= '9');
exponent += (sign == '-' ? -num : num);
}
if (!allow_trailing_junk && AdvanceToNonspace(¤t, end)) {
return JunkStringValue();
}
parsing_done:
exponent += insignificant_digits;
if (octal) {
return InternalStringToIntDouble<3>(buffer, buffer + buffer_pos,
sign == NEGATIVE, allow_trailing_junk);
}
if (nonzero_digit_dropped) {
buffer[buffer_pos++] = '1';
exponent--;
}
SLOW_DCHECK(buffer_pos < kBufferSize);
buffer[buffer_pos] = '\0';
double converted = Strtod(Vector<const char>(buffer, buffer_pos), exponent);
return (sign == NEGATIVE) ? -converted : converted;
}
double StringToDouble(const char* str, int flags, double empty_string_val) {
// We use {OneByteVector} instead of {CStrVector} to avoid instantiating the
// InternalStringToDouble() template for {const char*} as well.
return StringToDouble(OneByteVector(str), flags, empty_string_val);
}
double StringToDouble(Vector<const uint8_t> str, int flags,
double empty_string_val) {
return InternalStringToDouble(str.begin(), str.end(), flags,
empty_string_val);
}
double StringToDouble(Vector<const uc16> str, int flags,
double empty_string_val) {
const uc16* end = str.begin() + str.length();
return InternalStringToDouble(str.begin(), end, flags, empty_string_val);
}
double StringToInt(Isolate* isolate, Handle<String> string, int radix) {
NumberParseIntHelper helper(isolate, string, radix);
return helper.GetResult();
}
template <typename LocalIsolate>
class StringToBigIntHelper : public StringToIntHelper<LocalIsolate> {
public:
enum class Behavior { kStringToBigInt, kLiteral };
// Used for StringToBigInt operation (BigInt constructor and == operator).
StringToBigIntHelper(LocalIsolate* isolate, Handle<String> string)
: StringToIntHelper<LocalIsolate>(isolate, string),
behavior_(Behavior::kStringToBigInt) {
this->set_allow_binary_and_octal_prefixes();
this->set_disallow_trailing_junk();
}
// Used for parsing BigInt literals, where the input is a buffer of
// one-byte ASCII digits, along with an optional radix prefix.
StringToBigIntHelper(LocalIsolate* isolate, const uint8_t* string, int length)
: StringToIntHelper<LocalIsolate>(isolate, string, length),
behavior_(Behavior::kLiteral) {
this->set_allow_binary_and_octal_prefixes();
}
MaybeHandle<BigInt> GetResult() {
this->ParseInt();
if (behavior_ == Behavior::kStringToBigInt && this->sign() != Sign::kNone &&
this->radix() != 10) {
return MaybeHandle<BigInt>();
}
if (this->state() == State::kEmpty) {
if (behavior_ == Behavior::kStringToBigInt) {
this->set_state(State::kZero);
} else {
UNREACHABLE();
}
}
switch (this->state()) {
case State::kJunk:
case State::kError:
return MaybeHandle<BigInt>();
case State::kZero:
return BigInt::Zero(this->isolate(), allocation_type());
case State::kDone:
return BigInt::Finalize<Isolate>(result_, this->negative());
case State::kEmpty:
case State::kRunning:
break;
}
UNREACHABLE();
}
protected:
void AllocateResult() override {
// We have to allocate a BigInt that's big enough to fit the result.
// Conseratively assume that all remaining digits are significant.
// Optimization opportunity: Would it makes sense to scan for trailing
// junk before allocating the result?
int charcount = this->length() - this->cursor();
MaybeHandle<FreshlyAllocatedBigInt> maybe =
BigInt::AllocateFor(this->isolate(), this->radix(), charcount,
kDontThrow, allocation_type());
if (!maybe.ToHandle(&result_)) {
this->set_state(State::kError);
}
}
void ResultMultiplyAdd(uint32_t multiplier, uint32_t part) override {
BigInt::InplaceMultiplyAdd(*result_, static_cast<uintptr_t>(multiplier),
static_cast<uintptr_t>(part));
}
bool CheckTermination() override;
AllocationType allocation_type() {
// For literals, we pretenure the allocated BigInt, since it's about
// to be stored in the interpreter's constants array.
return behavior_ == Behavior::kLiteral ? AllocationType::kOld
: AllocationType::kYoung;
}
private:
Handle<FreshlyAllocatedBigInt> result_;
Behavior behavior_;
};
template <typename LocalIsolate>
bool StringToBigIntHelper<LocalIsolate>::CheckTermination() {
return false;
}
template <>
bool StringToBigIntHelper<Isolate>::CheckTermination() {
StackLimitCheck interrupt_check(isolate());
return interrupt_check.InterruptRequested() &&
isolate()->stack_guard()->HandleInterrupts().IsException(isolate());
}
MaybeHandle<BigInt> StringToBigInt(Isolate* isolate, Handle<String> string) {
string = String::Flatten(isolate, string);
StringToBigIntHelper<Isolate> helper(isolate, string);
return helper.GetResult();
}
template <typename LocalIsolate>
MaybeHandle<BigInt> BigIntLiteral(LocalIsolate* isolate, const char* string) {
StringToBigIntHelper<LocalIsolate> helper(
isolate, reinterpret_cast<const uint8_t*>(string),
static_cast<int>(strlen(string)));
return helper.GetResult();
}
template EXPORT_TEMPLATE_DEFINE(V8_EXPORT_PRIVATE)
MaybeHandle<BigInt> BigIntLiteral(Isolate* isolate, const char* string);
template EXPORT_TEMPLATE_DEFINE(V8_EXPORT_PRIVATE)
MaybeHandle<BigInt> BigIntLiteral(LocalIsolate* isolate,
const char* string);
const char* DoubleToCString(double v, Vector<char> buffer) {
switch (FPCLASSIFY_NAMESPACE::fpclassify(v)) {
case FP_NAN:
return "NaN";
case FP_INFINITE:
return (v < 0.0 ? "-Infinity" : "Infinity");
case FP_ZERO:
return "0";
default: {
if (IsInt32Double(v)) {
// This will trigger if v is -0 and -0.0 is stringified to "0".
// (see ES section 7.1.12.1 #sec-tostring-applied-to-the-number-type)
return IntToCString(FastD2I(v), buffer);
}
SimpleStringBuilder builder(buffer.begin(), buffer.length());
int decimal_point;
int sign;
const int kV8DtoaBufferCapacity = kBase10MaximalLength + 1;
char decimal_rep[kV8DtoaBufferCapacity];
int length;
DoubleToAscii(v, DTOA_SHORTEST, 0,
Vector<char>(decimal_rep, kV8DtoaBufferCapacity), &sign,
&length, &decimal_point);
if (sign) builder.AddCharacter('-');
if (length <= decimal_point && decimal_point <= 21) {
// ECMA-262 section 9.8.1 step 6.
builder.AddString(decimal_rep);
builder.AddPadding('0', decimal_point - length);
} else if (0 < decimal_point && decimal_point <= 21) {
// ECMA-262 section 9.8.1 step 7.
builder.AddSubstring(decimal_rep, decimal_point);
builder.AddCharacter('.');
builder.AddString(decimal_rep + decimal_point);
} else if (decimal_point <= 0 && decimal_point > -6) {
// ECMA-262 section 9.8.1 step 8.
builder.AddString("0.");
builder.AddPadding('0', -decimal_point);
builder.AddString(decimal_rep);
} else {
// ECMA-262 section 9.8.1 step 9 and 10 combined.
builder.AddCharacter(decimal_rep[0]);
if (length != 1) {
builder.AddCharacter('.');
builder.AddString(decimal_rep + 1);
}
builder.AddCharacter('e');
builder.AddCharacter((decimal_point >= 0) ? '+' : '-');
int exponent = decimal_point - 1;
if (exponent < 0) exponent = -exponent;
builder.AddDecimalInteger(exponent);
}
return builder.Finalize();
}
}
}
const char* IntToCString(int n, Vector<char> buffer) {
bool negative = true;
if (n >= 0) {
n = -n;
negative = false;
}
// Build the string backwards from the least significant digit.
int i = buffer.length();
buffer[--i] = '\0';
do {
// We ensured n <= 0, so the subtraction does the right addition.
buffer[--i] = '0' - (n % 10);
n /= 10;
} while (n);
if (negative) buffer[--i] = '-';
return buffer.begin() + i;
}
char* DoubleToFixedCString(double value, int f) {
const int kMaxDigitsBeforePoint = 21;
const double kFirstNonFixed = 1e21;
DCHECK_GE(f, 0);
DCHECK_LE(f, kMaxFractionDigits);
bool negative = false;
double abs_value = value;
if (value < 0) {
abs_value = -value;
negative = true;
}
// If abs_value has more than kMaxDigitsBeforePoint digits before the point
// use the non-fixed conversion routine.
if (abs_value >= kFirstNonFixed) {
char arr[kMaxFractionDigits];
Vector<char> buffer(arr, arraysize(arr));
return StrDup(DoubleToCString(value, buffer));
}
// Find a sufficiently precise decimal representation of n.
int decimal_point;
int sign;
// Add space for the '\0' byte.
const int kDecimalRepCapacity =
kMaxDigitsBeforePoint + kMaxFractionDigits + 1;
char decimal_rep[kDecimalRepCapacity];
int decimal_rep_length;
DoubleToAscii(value, DTOA_FIXED, f,
Vector<char>(decimal_rep, kDecimalRepCapacity), &sign,
&decimal_rep_length, &decimal_point);
// Create a representation that is padded with zeros if needed.
int zero_prefix_length = 0;
int zero_postfix_length = 0;
if (decimal_point <= 0) {
zero_prefix_length = -decimal_point + 1;
decimal_point = 1;
}
if (zero_prefix_length + decimal_rep_length < decimal_point + f) {
zero_postfix_length =
decimal_point + f - decimal_rep_length - zero_prefix_length;
}
unsigned rep_length =
zero_prefix_length + decimal_rep_length + zero_postfix_length;
SimpleStringBuilder rep_builder(rep_length + 1);
rep_builder.AddPadding('0', zero_prefix_length);
rep_builder.AddString(decimal_rep);
rep_builder.AddPadding('0', zero_postfix_length);
char* rep = rep_builder.Finalize();
// Create the result string by appending a minus and putting in a
// decimal point if needed.
unsigned result_size = decimal_point + f + 2;
SimpleStringBuilder builder(result_size + 1);
if (negative) builder.AddCharacter('-');
builder.AddSubstring(rep, decimal_point);
if (f > 0) {
builder.AddCharacter('.');
builder.AddSubstring(rep + decimal_point, f);
}
DeleteArray(rep);
return builder.Finalize();
}
static char* CreateExponentialRepresentation(char* decimal_rep, int exponent,
bool negative,
int significant_digits) {
bool negative_exponent = false;
if (exponent < 0) {
negative_exponent = true;
exponent = -exponent;
}
// Leave room in the result for appending a minus, for a period, the
// letter 'e', a minus or a plus depending on the exponent, and a
// three digit exponent.
unsigned result_size = significant_digits + 7;
SimpleStringBuilder builder(result_size + 1);
if (negative) builder.AddCharacter('-');
builder.AddCharacter(decimal_rep[0]);
if (significant_digits != 1) {
builder.AddCharacter('.');
builder.AddString(decimal_rep + 1);
size_t rep_length = strlen(decimal_rep);
DCHECK_GE(significant_digits, rep_length);
builder.AddPadding('0', significant_digits - static_cast<int>(rep_length));
}
builder.AddCharacter('e');
builder.AddCharacter(negative_exponent ? '-' : '+');
builder.AddDecimalInteger(exponent);
return builder.Finalize();
}
char* DoubleToExponentialCString(double value, int f) {
// f might be -1 to signal that f was undefined in JavaScript.
DCHECK(f >= -1 && f <= kMaxFractionDigits);
bool negative = false;
if (value < 0) {
value = -value;
negative = true;
}
// Find a sufficiently precise decimal representation of n.
int decimal_point;
int sign;
// f corresponds to the digits after the point. There is always one digit
// before the point. The number of requested_digits equals hence f + 1.
// And we have to add one character for the null-terminator.
const int kV8DtoaBufferCapacity = kMaxFractionDigits + 1 + 1;
// Make sure that the buffer is big enough, even if we fall back to the
// shortest representation (which happens when f equals -1).
DCHECK_LE(kBase10MaximalLength, kMaxFractionDigits + 1);
char decimal_rep[kV8DtoaBufferCapacity];
int decimal_rep_length;
if (f == -1) {
DoubleToAscii(value, DTOA_SHORTEST, 0,
Vector<char>(decimal_rep, kV8DtoaBufferCapacity), &sign,
&decimal_rep_length, &decimal_point);
f = decimal_rep_length - 1;
} else {
DoubleToAscii(value, DTOA_PRECISION, f + 1,
Vector<char>(decimal_rep, kV8DtoaBufferCapacity), &sign,
&decimal_rep_length, &decimal_point);
}
DCHECK_GT(decimal_rep_length, 0);
DCHECK(decimal_rep_length <= f + 1);
int exponent = decimal_point - 1;
char* result =
CreateExponentialRepresentation(decimal_rep, exponent, negative, f + 1);
return result;
}
char* DoubleToPrecisionCString(double value, int p) {
const int kMinimalDigits = 1;
DCHECK(p >= kMinimalDigits && p <= kMaxFractionDigits);
USE(kMinimalDigits);
bool negative = false;
if (value < 0) {
value = -value;
negative = true;
}
// Find a sufficiently precise decimal representation of n.
int decimal_point;
int sign;
// Add one for the terminating null character.
const int kV8DtoaBufferCapacity = kMaxFractionDigits + 1;
char decimal_rep[kV8DtoaBufferCapacity];
int decimal_rep_length;
DoubleToAscii(value, DTOA_PRECISION, p,
Vector<char>(decimal_rep, kV8DtoaBufferCapacity), &sign,
&decimal_rep_length, &decimal_point);
DCHECK(decimal_rep_length <= p);
int exponent = decimal_point - 1;
char* result = nullptr;
if (exponent < -6 || exponent >= p) {
result =
CreateExponentialRepresentation(decimal_rep, exponent, negative, p);
} else {
// Use fixed notation.
//
// Leave room in the result for appending a minus, a period and in
// the case where decimal_point is not positive for a zero in
// front of the period.
unsigned result_size =
(decimal_point <= 0) ? -decimal_point + p + 3 : p + 2;
SimpleStringBuilder builder(result_size + 1);
if (negative) builder.AddCharacter('-');
if (decimal_point <= 0) {
builder.AddString("0.");
builder.AddPadding('0', -decimal_point);
builder.AddString(decimal_rep);
builder.AddPadding('0', p - decimal_rep_length);
} else {
const int m = Min(decimal_rep_length, decimal_point);
builder.AddSubstring(decimal_rep, m);
builder.AddPadding('0', decimal_point - decimal_rep_length);
if (decimal_point < p) {
builder.AddCharacter('.');
const int extra = negative ? 2 : 1;
if (decimal_rep_length > decimal_point) {
const size_t len = strlen(decimal_rep + decimal_point);
DCHECK_GE(kMaxInt, len);
const int n =
Min(static_cast<int>(len), p - (builder.position() - extra));
builder.AddSubstring(decimal_rep + decimal_point, n);
}
builder.AddPadding('0', extra + (p - builder.position()));
}
}
result = builder.Finalize();
}
return result;
}
char* DoubleToRadixCString(double value, int radix) {
DCHECK(radix >= 2 && radix <= 36);
DCHECK(std::isfinite(value));
DCHECK_NE(0.0, value);
// Character array used for conversion.
static const char chars[] = "0123456789abcdefghijklmnopqrstuvwxyz";
// Temporary buffer for the result. We start with the decimal point in the
// middle and write to the left for the integer part and to the right for the
// fractional part. 1024 characters for the exponent and 52 for the mantissa
// either way, with additional space for sign, decimal point and string
// termination should be sufficient.
static const int kBufferSize = 2200;
char buffer[kBufferSize];
int integer_cursor = kBufferSize / 2;
int fraction_cursor = integer_cursor;
bool negative = value < 0;
if (negative) value = -value;
// Split the value into an integer part and a fractional part.
double integer = std::floor(value);
double fraction = value - integer;
// We only compute fractional digits up to the input double's precision.
double delta = 0.5 * (Double(value).NextDouble() - value);
delta = std::max(Double(0.0).NextDouble(), delta);
DCHECK_GT(delta, 0.0);
if (fraction >= delta) {
// Insert decimal point.
buffer[fraction_cursor++] = '.';
do {
// Shift up by one digit.
fraction *= radix;
delta *= radix;
// Write digit.
int digit = static_cast<int>(fraction);
buffer[fraction_cursor++] = chars[digit];
// Calculate remainder.
fraction -= digit;
// Round to even.
if (fraction > 0.5 || (fraction == 0.5 && (digit & 1))) {
if (fraction + delta > 1) {
// We need to back trace already written digits in case of carry-over.
while (true) {
fraction_cursor--;
if (fraction_cursor == kBufferSize / 2) {
CHECK_EQ('.', buffer[fraction_cursor]);
// Carry over to the integer part.
integer += 1;
break;
}
char c = buffer[fraction_cursor];
// Reconstruct digit.
int digit = c > '9' ? (c - 'a' + 10) : (c - '0');
if (digit + 1 < radix) {
buffer[fraction_cursor++] = chars[digit + 1];
break;
}
}
break;
}
}
} while (fraction >= delta);
}
// Compute integer digits. Fill unrepresented digits with zero.
while (Double(integer / radix).Exponent() > 0) {
integer /= radix;
buffer[--integer_cursor] = '0';
}
do {
double remainder = Modulo(integer, radix);
buffer[--integer_cursor] = chars[static_cast<int>(remainder)];
integer = (integer - remainder) / radix;
} while (integer > 0);
// Add sign and terminate string.
if (negative) buffer[--integer_cursor] = '-';
buffer[fraction_cursor++] = '\0';
DCHECK_LT(fraction_cursor, kBufferSize);
DCHECK_LE(0, integer_cursor);
// Allocate new string as return value.
char* result = NewArray<char>(fraction_cursor - integer_cursor);
memcpy(result, buffer + integer_cursor, fraction_cursor - integer_cursor);
return result;
}
// ES6 18.2.4 parseFloat(string)
double StringToDouble(Isolate* isolate, Handle<String> string, int flags,
double empty_string_val) {
Handle<String> flattened = String::Flatten(isolate, string);
{
DisallowHeapAllocation no_gc;
String::FlatContent flat = flattened->GetFlatContent(no_gc);
DCHECK(flat.IsFlat());
if (flat.IsOneByte()) {
return StringToDouble(flat.ToOneByteVector(), flags, empty_string_val);
} else {
return StringToDouble(flat.ToUC16Vector(), flags, empty_string_val);
}
}
}
bool IsSpecialIndex(String string) {
// Max length of canonical double: -X.XXXXXXXXXXXXXXXXX-eXXX
const int kBufferSize = 24;
const int length = string.length();
if (length == 0 || length > kBufferSize) return false;
uint16_t buffer[kBufferSize];
String::WriteToFlat(string, buffer, 0, length);
// If the first char is not a digit or a '-' or we can't match 'NaN' or
// '(-)Infinity', bailout immediately.
int offset = 0;
if (!IsDecimalDigit(buffer[0])) {
if (buffer[0] == '-') {
if (length == 1) return false; // Just '-' is bad.
if (!IsDecimalDigit(buffer[1])) {
if (buffer[1] == 'I' && length == 9) {
// Allow matching of '-Infinity' below.
} else {
return false;
}
}
offset++;
} else if (buffer[0] == 'I' && length == 8) {
// Allow matching of 'Infinity' below.
} else if (buffer[0] == 'N' && length == 3) {
// Match NaN.
return buffer[1] == 'a' && buffer[2] == 'N';
} else {
return false;
}
}
// Expected fast path: key is an integer.
static const int kRepresentableIntegerLength = 15; // (-)XXXXXXXXXXXXXXX
if (length - offset <= kRepresentableIntegerLength) {
const int initial_offset = offset;
bool matches = true;
for (; offset < length; offset++) {
matches &= IsDecimalDigit(buffer[offset]);
}
if (matches) {
// Match 0 and -0.
if (buffer[initial_offset] == '0') return initial_offset == length - 1;
return true;
}
}
// Slow path: test DoubleToString(StringToDouble(string)) == string.
Vector<const uint16_t> vector(buffer, length);
double d = StringToDouble(vector, NO_FLAGS);
if (std::isnan(d)) return false;
// Compute reverse string.
char reverse_buffer[kBufferSize + 1]; // Result will be /0 terminated.
Vector<char> reverse_vector(reverse_buffer, arraysize(reverse_buffer));
const char* reverse_string = DoubleToCString(d, reverse_vector);
for (int i = 0; i < length; ++i) {
if (static_cast<uint16_t>(reverse_string[i]) != buffer[i]) return false;
}
return true;
}
} // namespace internal
} // namespace v8
#undef FPCLASSIFY_NAMESPACE
| 32.755416 | 80 | 0.632283 | [
"vector"
] |
142ce23f4a7483e0df6deb250d5b12574fb8d6c4 | 3,215 | cpp | C++ | trainings/2015-08-06-Shanghai-2004/J.cpp | HcPlu/acm-icpc | ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8 | [
"MIT"
] | 9 | 2017-10-07T13:35:45.000Z | 2021-06-07T17:36:55.000Z | trainings/2015-08-06-Shanghai-2004/J.cpp | zhijian-liu/acm-icpc | ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8 | [
"MIT"
] | null | null | null | trainings/2015-08-06-Shanghai-2004/J.cpp | zhijian-liu/acm-icpc | ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8 | [
"MIT"
] | 3 | 2018-04-24T05:27:21.000Z | 2019-04-25T06:06:00.000Z | #include <cstdio>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
namespace mf {
const int N = 1500, M = 1010000;
struct EdgeList {
int size;
int last[N];
int succ[M], other[M], flow[M];
void clear(int n) {
size = 0;
fill(last, last + n, -1);
}
void add(int x, int y, int c) {
succ[size] = last[x];
last[x] = size;
other[size] = y;
flow[size++] = c;
}
} e;
int n, source, target;
int dist[N], curr[N];
void add(int x, int y, int c) {
e.add(x, y, c);
e.add(y, x, 0);
}
bool bfs() {
vector<int> queue;
for (int i = 0; i < n; i++) {
curr[i] = e.last[i];
dist[i] = -1;
}
queue.push_back(target);
dist[target] = 0;
for (int head = 0; head < (int)queue.size(); ++head) {
int x = queue[head];
for (int i = e.last[x]; ~i; i = e.succ[i]) {
int y = e.other[i];
if (e.flow[i ^ 1] && dist[y] == -1) {
dist[y] = dist[x] + 1;
queue.push_back(y);
}
}
}
return ~dist[source];
}
int dfs(int x, int ans) {
if (x == target) {
return ans;
}
int delta = ans;
for (int &i = curr[x]; ~i; i = e.succ[i]) {
int y = e.other[i];
if (e.flow[i] && dist[x] == dist[y] + 1) {
int num = dfs(y, min(e.flow[i], delta));
e.flow[i] -= num;
e.flow[i ^ 1] += num;
if ((delta -= num) == 0) {
break;
}
}
}
return ans - delta;
}
int solve() {
int ans = 0;
for (; bfs(); ans += dfs(source, INT_MAX)) {
}
return ans;
}
void clear() {
e.clear(n);
}
}
int n, m, cnt = 0;
pair<int, int> t[500004];
char buffer[11111];
bool check(int x) {
mf::n = n + m + 2;
mf::clear();
mf::source = 0;
mf::target = n + m + 1;
for (int i = 1; i <= m; i++) {
mf::add(0, i, x);
}
for (int i = 1; i <= cnt; i++) {
mf::add(t[i].second, t[i].first + m, 1);
}
for (int i = 1; i <= n; i++) {
mf::add(i + m, mf::target, 1);
}
int t = mf::solve();
return t == n;
}
int main() {
scanf("%d%d", &n, &m);
while (n != 0 || m != 0) {
gets(buffer);
cnt = 0;
for (int i = 1; i <= n; i++) {
static char buffer[11111];
gets(buffer);
stringstream os(buffer);
os >> buffer;
for (int num; os >> num; t[++cnt] = make_pair(i, num + 1)) {
}
}
int left = 1, right = n;
int ans = 0;
while (left <= right) {
int mid = left + right >> 1;
if (check(mid)) {
ans = mid, right = mid - 1;
} else {
left = mid + 1;
}
}
printf("%d\n", ans);
scanf("%d%d", &n, &m);
}
return 0;
} | 22.801418 | 72 | 0.376361 | [
"vector"
] |
28a2c8ace6903dbaba3968b5ab35f00fc3761d0b | 910 | hpp | C++ | catkin_ws/src/localization/include/localization/fake_scan.hpp | wpi-arn-spring-2019/Turtlebot-3-Navigation | c02dbe75de2d4f2fc31d6c2f4873d56f0927a286 | [
"BSD-3-Clause"
] | null | null | null | catkin_ws/src/localization/include/localization/fake_scan.hpp | wpi-arn-spring-2019/Turtlebot-3-Navigation | c02dbe75de2d4f2fc31d6c2f4873d56f0927a286 | [
"BSD-3-Clause"
] | null | null | null | catkin_ws/src/localization/include/localization/fake_scan.hpp | wpi-arn-spring-2019/Turtlebot-3-Navigation | c02dbe75de2d4f2fc31d6c2f4873d56f0927a286 | [
"BSD-3-Clause"
] | 2 | 2019-07-06T04:04:09.000Z | 2019-12-17T01:46:34.000Z | #pragma once
#include <ros/ros.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <nav_msgs/OccupancyGrid.h>
#include <sensor_msgs/LaserScan.h>
#include <tf/tf.h>
#include <tf/transform_broadcaster.h>
#include <point.hpp>
namespace Turtlebot
{
class FakeScan
{
public:
FakeScan(const nav_msgs::OccupancyGrid &map, const sensor_msgs::LaserScan &scan) : m_map(map), m_scan(scan){}
~FakeScan(){}
const sensor_msgs::LaserScan getFakeScan(const geometry_msgs::PoseWithCovarianceStamped &pose);
private:
void convertMatrix();
const double laserThrower(const geometry_msgs::PoseWithCovarianceStamped &pose, const float &inc) const;
const int getLocation(const Point &pt) const;
void writeScan(const double &dist, sensor_msgs::LaserScan &scan);
std::vector<std::vector<int>> m_matrix_map;
nav_msgs::OccupancyGrid m_map;
sensor_msgs::LaserScan m_scan;
};
}
| 26 | 113 | 0.749451 | [
"vector"
] |
28a7b820af7803ebd548dec86e5e2d0344bf6e49 | 1,720 | cpp | C++ | src/fontTexture.cpp | goibon/Achluophobia | 6b8b8627dd98dddd76e586a1fa86b98c24938861 | [
"MIT"
] | null | null | null | src/fontTexture.cpp | goibon/Achluophobia | 6b8b8627dd98dddd76e586a1fa86b98c24938861 | [
"MIT"
] | null | null | null | src/fontTexture.cpp | goibon/Achluophobia | 6b8b8627dd98dddd76e586a1fa86b98c24938861 | [
"MIT"
] | null | null | null | #include "fontTexture.hpp"
#include <SDL_ttf.h>
FontTexture::FontTexture(int width, int height, TTF_Font* font) : Texture(width, height)
{
mFont = font;
}
void FontTexture::createTextureFromSurface(SDL_Renderer* renderer, SDL_Surface* surface)
{
//Create texture from surface pixels
mTexture = SDL_CreateTextureFromSurface(renderer, surface);
if(mTexture == NULL)
{
printf("Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError());
}
else
{
//Get image dimensions
mWidth = surface->w;
mHeight = surface->h;
}
//Get rid of old surface
SDL_FreeSurface(surface);
}
bool FontTexture::loadFromFile(std::string text, SDL_Renderer* renderer, SDL_Color textColor)
{
//Get rid of preexisting texture
free();
//Success flag
bool success = true;
//Render text surface
SDL_Surface* textSurface = TTF_RenderText_Blended( mFont, text.c_str(), textColor);
if(textSurface == NULL)
{
printf("Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError());
}
else
{
createTextureFromSurface(renderer, textSurface);
}
//Return success
return mTexture != NULL;
}
bool FontTexture::loadFromFile(std::string text, SDL_Renderer* renderer, SDL_Color textColor, SDL_Color backgroundColor)
{
//Get rid of preexisting texture
free();
//Success flag
bool success = true;
//Render text surface
SDL_Surface* textSurface = TTF_RenderText_Shaded( mFont, text.c_str(), textColor, backgroundColor );
if(textSurface == NULL)
{
printf("Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError());
}
else
{
createTextureFromSurface(renderer, textSurface);
}
//Return success
return mTexture != NULL;
}
| 24.571429 | 120 | 0.709302 | [
"render"
] |
28a87ae2b112f3a3269bb67294d478e3eab2023f | 8,809 | hpp | C++ | src/batched/KokkosBatched_Vector_SIMD_Math.hpp | dialecticDolt/kokkos-kernels | 00189c0be23a70979aeaa162f0abd4c0e4d1c479 | [
"BSD-3-Clause"
] | 156 | 2017-03-01T23:38:10.000Z | 2022-03-27T21:28:03.000Z | src/batched/KokkosBatched_Vector_SIMD_Math.hpp | dialecticDolt/kokkos-kernels | 00189c0be23a70979aeaa162f0abd4c0e4d1c479 | [
"BSD-3-Clause"
] | 1,257 | 2017-03-03T15:25:16.000Z | 2022-03-31T19:46:09.000Z | src/batched/KokkosBatched_Vector_SIMD_Math.hpp | dialecticDolt/kokkos-kernels | 00189c0be23a70979aeaa162f0abd4c0e4d1c479 | [
"BSD-3-Clause"
] | 76 | 2017-03-01T17:03:59.000Z | 2022-03-03T21:04:41.000Z | #ifndef __KOKKOSBATCHED_VECTOR_SIMD_MATH_HPP__
#define __KOKKOSBATCHED_VECTOR_SIMD_MATH_HPP__
/// \author Kyungjoo Kim (kyukim@sandia.gov)
#include "Kokkos_Complex.hpp"
namespace KokkosBatched {
//#define KOKKOSKERNELS_SIMD_MATH_RETURN_TYPE typename std::enable_if<std::is_same<Kokkos::Impl::ActiveExecutionMemorySpace,Kokkos::HostSpace>::value,Vector<SIMD<T>,l> >::type
#define KOKKOSKERNELS_SIMD_MATH_RETURN_TYPE(T,l) Vector< SIMD< T >, l >
#define KOKKOSKERNELS_SIMD_MATH_RETURN_FLOAT_TYPE(T,l) typename std::enable_if<!std::is_integral< T >::value,Vector<SIMD< T >,l> >::type
/// simd
template<typename T, int l>
KOKKOS_INLINE_FUNCTION
static
KOKKOSKERNELS_SIMD_MATH_RETURN_TYPE(T,l)
sqrt(const Vector<SIMD<T>,l> &a) {
typedef Kokkos::Details::ArithTraits<T> ats;
Vector<SIMD<T>,l> r_val;
#if defined( KOKKOS_ENABLE_PRAGMA_IVDEP )
#pragma ivdep
#endif
#if defined( KOKKOS_ENABLE_PRAGMA_VECTOR )
#pragma vector always
#endif
for (int i=0;i<l;++i)
r_val[i] = ats::sqrt(a[i]);
return r_val;
}
template<typename T, int l>
KOKKOS_INLINE_FUNCTION
static
KOKKOSKERNELS_SIMD_MATH_RETURN_TYPE(T,l)
cbrt(const Vector<SIMD<T>,l> &a) {
typedef Kokkos::Details::ArithTraits<T> ats;
Vector<SIMD<T>,l> r_val;
#if defined( KOKKOS_ENABLE_PRAGMA_IVDEP )
#pragma ivdep
#endif
#if defined( KOKKOS_ENABLE_PRAGMA_VECTOR )
#pragma vector always
#endif
for (int i=0;i<l;++i)
r_val[i] = ats::cbrt(a[i]);
return r_val;
}
template<typename T, int l>
KOKKOS_INLINE_FUNCTION
static
KOKKOSKERNELS_SIMD_MATH_RETURN_TYPE(T,l)
log(const Vector<SIMD<T>,l> &a) {
typedef Kokkos::Details::ArithTraits<T> ats;
Vector<SIMD<T>,l> r_val;
#if defined( KOKKOS_ENABLE_PRAGMA_IVDEP )
#pragma ivdep
#endif
#if defined( KOKKOS_ENABLE_PRAGMA_VECTOR )
#pragma vector always
#endif
for (int i=0;i<l;++i)
r_val[i] = ats::log(a[i]);
return r_val;
}
template<typename T, int l>
KOKKOS_INLINE_FUNCTION
static
KOKKOSKERNELS_SIMD_MATH_RETURN_TYPE(T,l)
log10(const Vector<SIMD<T>,l> &a) {
typedef Kokkos::Details::ArithTraits<T> ats;
Vector<SIMD<T>,l> r_val;
#if defined( KOKKOS_ENABLE_PRAGMA_IVDEP )
#pragma ivdep
#endif
#if defined( KOKKOS_ENABLE_PRAGMA_VECTOR )
#pragma vector always
#endif
for (int i=0;i<l;++i)
r_val[i] = ats::log10(a[i]);
return r_val;
}
template<typename T, int l>
KOKKOS_INLINE_FUNCTION
static
KOKKOSKERNELS_SIMD_MATH_RETURN_TYPE(T,l)
exp(const Vector<SIMD<T>,l> &a) {
typedef Kokkos::Details::ArithTraits<T> ats;
Vector<SIMD<T>,l> r_val;
#if defined( KOKKOS_ENABLE_PRAGMA_IVDEP )
#pragma ivdep
#endif
#if defined( KOKKOS_ENABLE_PRAGMA_VECTOR )
#pragma vector always
#endif
for (int i=0;i<l;++i)
r_val[i] = ats::exp(a[i]);
return r_val;
}
template<typename T0, typename T1, int l>
KOKKOS_INLINE_FUNCTION
static
KOKKOSKERNELS_SIMD_MATH_RETURN_TYPE(T0,l)
pow(const Vector<SIMD<T0>,l> &a, const Vector<SIMD<T1>,l> &b) {
typedef Kokkos::Details::ArithTraits<T0> ats;
Vector<SIMD<T0>,l> r_val;
#if defined( KOKKOS_ENABLE_PRAGMA_IVDEP )
#pragma ivdep
#endif
#if defined( KOKKOS_ENABLE_PRAGMA_VECTOR )
#pragma vector always
#endif
for (int i=0;i<l;++i)
r_val[i] = ats::pow(a[i], b[i]);
return r_val;
}
template<typename T0, typename T1, int l>
KOKKOS_INLINE_FUNCTION
static
KOKKOSKERNELS_SIMD_MATH_RETURN_TYPE(T0,l)
pow(const T0 &a, const Vector<SIMD<T1>,l> &b) {
return pow(Vector<SIMD<T0>,l>(a), b);
}
template<typename T0, typename T1, int l>
KOKKOS_INLINE_FUNCTION
static
KOKKOSKERNELS_SIMD_MATH_RETURN_TYPE(T0,l)
pow(const Vector<SIMD<T0>,l> &a, const T1 &b) {
return pow(a, Vector<SIMD<T1>,l>(b));
}
template<typename T, int l>
KOKKOS_INLINE_FUNCTION
static
KOKKOSKERNELS_SIMD_MATH_RETURN_FLOAT_TYPE(T,l)
sin(const Vector<SIMD<T>,l> &a) {
typedef Kokkos::Details::ArithTraits<T> ats;
Vector<SIMD<T>,l> r_val;
#if defined( KOKKOS_ENABLE_PRAGMA_IVDEP )
#pragma ivdep
#endif
#if defined( KOKKOS_ENABLE_PRAGMA_VECTOR )
#pragma vector always
#endif
for (int i=0;i<l;++i)
r_val[i] = ats::sin(a[i]);
return r_val;
}
template<typename T, int l>
KOKKOS_INLINE_FUNCTION
static
KOKKOSKERNELS_SIMD_MATH_RETURN_FLOAT_TYPE(T,l)
cos(const Vector<SIMD<T>,l> &a) {
typedef Kokkos::Details::ArithTraits<T> ats;
Vector<SIMD<T>,l> r_val;
#if defined( KOKKOS_ENABLE_PRAGMA_IVDEP )
#pragma ivdep
#endif
#if defined( KOKKOS_ENABLE_PRAGMA_VECTOR )
#pragma vector always
#endif
for (int i=0;i<l;++i)
r_val[i] = ats::cos(a[i]);
return r_val;
}
template<typename T, int l>
KOKKOS_INLINE_FUNCTION
static
KOKKOSKERNELS_SIMD_MATH_RETURN_FLOAT_TYPE(T,l)
tan(const Vector<SIMD<T>,l> &a) {
typedef Kokkos::Details::ArithTraits<T> ats;
Vector<SIMD<T>,l> r_val;
#if defined( KOKKOS_ENABLE_PRAGMA_IVDEP )
#pragma ivdep
#endif
#if defined( KOKKOS_ENABLE_PRAGMA_VECTOR )
#pragma vector always
#endif
for (int i=0;i<l;++i)
r_val[i] = ats::tan(a[i]);
return r_val;
}
template<typename T, int l>
KOKKOS_INLINE_FUNCTION
static
KOKKOSKERNELS_SIMD_MATH_RETURN_FLOAT_TYPE(T,l)
sinh(const Vector<SIMD<T>,l> &a) {
typedef Kokkos::Details::ArithTraits<T> ats;
Vector<SIMD<T>,l> r_val;
#if defined( KOKKOS_ENABLE_PRAGMA_IVDEP )
#pragma ivdep
#endif
#if defined( KOKKOS_ENABLE_PRAGMA_VECTOR )
#pragma vector always
#endif
for (int i=0;i<l;++i)
r_val[i] = ats::sinh(a[i]);
return r_val;
}
template<typename T, int l>
KOKKOS_INLINE_FUNCTION
static
KOKKOSKERNELS_SIMD_MATH_RETURN_FLOAT_TYPE(T,l)
cosh(const Vector<SIMD<T>,l> &a) {
typedef Kokkos::Details::ArithTraits<T> ats;
Vector<SIMD<T>,l> r_val;
#if defined( KOKKOS_ENABLE_PRAGMA_IVDEP )
#pragma ivdep
#endif
#if defined( KOKKOS_ENABLE_PRAGMA_VECTOR )
#pragma vector always
#endif
for (int i=0;i<l;++i)
r_val[i] = ats::cosh(a[i]);
return r_val;
}
template<typename T, int l>
KOKKOS_INLINE_FUNCTION
static
KOKKOSKERNELS_SIMD_MATH_RETURN_FLOAT_TYPE(T,l)
tanh(const Vector<SIMD<T>,l> &a) {
typedef Kokkos::Details::ArithTraits<T> ats;
Vector<SIMD<T>,l> r_val;
#if defined( KOKKOS_ENABLE_PRAGMA_IVDEP )
#pragma ivdep
#endif
#if defined( KOKKOS_ENABLE_PRAGMA_VECTOR )
#pragma vector always
#endif
for (int i=0;i<l;++i)
r_val[i] = ats::tanh(a[i]);
return r_val;
}
template<typename T, int l>
KOKKOS_INLINE_FUNCTION
static
KOKKOSKERNELS_SIMD_MATH_RETURN_FLOAT_TYPE(T,l)
asin(const Vector<SIMD<T>,l> &a) {
typedef Kokkos::Details::ArithTraits<T> ats;
Vector<SIMD<T>,l> r_val;
#if defined( KOKKOS_ENABLE_PRAGMA_IVDEP )
#pragma ivdep
#endif
#if defined( KOKKOS_ENABLE_PRAGMA_VECTOR )
#pragma vector always
#endif
for (int i=0;i<l;++i)
r_val[i] = ats::asin(a[i]);
return r_val;
}
template<typename T, int l>
KOKKOS_INLINE_FUNCTION
static
KOKKOSKERNELS_SIMD_MATH_RETURN_FLOAT_TYPE(T,l)
acos(const Vector<SIMD<T>,l> &a) {
typedef Kokkos::Details::ArithTraits<T> ats;
Vector<SIMD<T>,l> r_val;
#if defined( KOKKOS_ENABLE_PRAGMA_IVDEP )
#pragma ivdep
#endif
#if defined( KOKKOS_ENABLE_PRAGMA_VECTOR )
#pragma vector always
#endif
for (int i=0;i<l;++i)
r_val[i] = ats::acos(a[i]);
return r_val;
}
template<typename T, int l>
KOKKOS_INLINE_FUNCTION
static
KOKKOSKERNELS_SIMD_MATH_RETURN_FLOAT_TYPE(T,l)
atan(const Vector<SIMD<T>,l> &a) {
typedef Kokkos::Details::ArithTraits<T> ats;
Vector<SIMD<T>,l> r_val;
#if defined( KOKKOS_ENABLE_PRAGMA_IVDEP )
#pragma ivdep
#endif
#if defined( KOKKOS_ENABLE_PRAGMA_VECTOR )
#pragma vector always
#endif
for (int i=0;i<l;++i)
r_val[i] = ats::atan(a[i]);
return r_val;
}
template<typename T, int l>
KOKKOS_INLINE_FUNCTION
static
KOKKOSKERNELS_SIMD_MATH_RETURN_FLOAT_TYPE(T,l)
atan2(const Vector<SIMD<T>,l> &a, const Vector<SIMD<T>,l> &b) {
//typedef Kokkos::Details::ArithTraits<T> ats;
Vector<SIMD<T>,l> r_val;
#if defined( KOKKOS_ENABLE_PRAGMA_IVDEP )
#pragma ivdep
#endif
#if defined( KOKKOS_ENABLE_PRAGMA_VECTOR )
#pragma vector always
#endif
for (int i=0;i<l;++i)
r_val[i] = std::atan2(a[i], b[i]);
return r_val;
}
template<typename T, int l>
KOKKOS_INLINE_FUNCTION
static
KOKKOSKERNELS_SIMD_MATH_RETURN_FLOAT_TYPE(T,l)
atan2(const T &a, const Vector<SIMD<T>,l> &b) {
return atan2(Vector<SIMD<T>,l>(a), b);
}
template<typename T, int l>
KOKKOS_INLINE_FUNCTION
static
KOKKOSKERNELS_SIMD_MATH_RETURN_FLOAT_TYPE(T,l)
atan2(const Vector<SIMD<T>,l> &a, const T &b) {
return atan2(a, Vector<SIMD<T>,l>(b));
}
#undef KOKKOSKERNELS_SIMD_MATH_RETURN_TYPE
#undef KOKKOSKERNELS_SIMD_MATH_RETURN_FLOAT_TYPE
}
#endif
| 24.606145 | 177 | 0.701782 | [
"vector"
] |
28a9c195cd187ac3970dca77fe8fb32620eacffe | 3,385 | cpp | C++ | Userland/Libraries/LibC/termcap.cpp | shubhdev/serenity | 9321d9d83d366ad4cf686c856063ff9ac97c18a4 | [
"BSD-2-Clause"
] | 4 | 2021-02-23T05:35:25.000Z | 2021-06-08T06:11:06.000Z | Userland/Libraries/LibC/termcap.cpp | shubhdev/serenity | 9321d9d83d366ad4cf686c856063ff9ac97c18a4 | [
"BSD-2-Clause"
] | 4 | 2021-04-27T20:44:44.000Z | 2021-06-30T18:07:10.000Z | Userland/Libraries/LibC/termcap.cpp | shubhdev/serenity | 9321d9d83d366ad4cf686c856063ff9ac97c18a4 | [
"BSD-2-Clause"
] | 1 | 2021-06-05T16:58:05.000Z | 2021-06-05T16:58:05.000Z | /*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/Debug.h>
#include <AK/HashMap.h>
#include <AK/String.h>
#include <AK/Vector.h>
#include <assert.h>
#include <string.h>
#include <termcap.h>
extern "C" {
char PC;
char* UP;
char* BC;
int tgetent([[maybe_unused]] char* bp, [[maybe_unused]] const char* name)
{
warnln_if(TERMCAP_DEBUG, "tgetent: bp={:p}, name='{}'", bp, name);
PC = '\0';
BC = const_cast<char*>("\033[D");
UP = const_cast<char*>("\033[A");
return 1;
}
static HashMap<String, const char*>* caps = nullptr;
static void ensure_caps()
{
if (caps)
return;
caps = new HashMap<String, const char*>;
caps->set("DC", "\033[%p1%dP");
caps->set("IC", "\033[%p1%d@");
caps->set("ce", "\033[K");
caps->set("cl", "\033[H\033[J");
caps->set("cr", "\015");
caps->set("dc", "\033[P");
caps->set("ei", "");
caps->set("ic", "");
caps->set("im", "");
caps->set("kd", "\033[B");
caps->set("kl", "\033[D");
caps->set("kr", "\033[C");
caps->set("ku", "\033[A");
caps->set("ks", "");
caps->set("ke", "");
caps->set("le", "\033[D");
caps->set("mm", "");
caps->set("mo", "");
caps->set("pc", "");
caps->set("up", "\033[A");
caps->set("vb", "");
caps->set("am", "");
caps->set("@7", "");
caps->set("kH", "");
caps->set("kI", "\033[L");
caps->set("kh", "\033[H");
caps->set("vs", "");
caps->set("ve", "");
caps->set("E3", "");
caps->set("kD", "");
caps->set("nd", "\033[C");
caps->set("co", "80");
caps->set("li", "25");
}
// Unfortunately, tgetstr() doesn't accept a size argument for the buffer
// pointed to by area, so we have to use bare strcpy().
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
char* tgetstr(const char* id, char** area)
{
ensure_caps();
warnln_if(TERMCAP_DEBUG, "tgetstr: id='{}'", id);
auto it = caps->find(id);
if (it != caps->end()) {
char* ret = *area;
const char* val = (*it).value;
strcpy(*area, val);
*area += strlen(val) + 1;
return ret;
}
warnln_if(TERMCAP_DEBUG, "tgetstr: missing cap id='{}'", id);
return nullptr;
}
#pragma GCC diagnostic pop
int tgetflag([[maybe_unused]] const char* id)
{
warnln_if(TERMCAP_DEBUG, "tgetflag: '{}'", id);
auto it = caps->find(id);
if (it != caps->end())
return 1;
return 0;
}
int tgetnum(const char* id)
{
warnln_if(TERMCAP_DEBUG, "tgetnum: '{}'", id);
auto it = caps->find(id);
if (it != caps->end())
return atoi((*it).value);
return -1;
}
static Vector<char> s_tgoto_buffer;
char* tgoto([[maybe_unused]] const char* cap, [[maybe_unused]] int col, [[maybe_unused]] int row)
{
auto cap_str = String(cap);
cap_str.replace("%p1%d", String::number(col));
cap_str.replace("%p2%d", String::number(row));
s_tgoto_buffer.clear_with_capacity();
s_tgoto_buffer.ensure_capacity(cap_str.length());
(void)cap_str.copy_characters_to_buffer(s_tgoto_buffer.data(), cap_str.length());
return s_tgoto_buffer.data();
}
int tputs(const char* str, [[maybe_unused]] int affcnt, int (*putc)(int))
{
size_t len = strlen(str);
for (size_t i = 0; i < len; ++i)
putc(str[i]);
return 0;
}
}
| 25.074074 | 97 | 0.560118 | [
"vector"
] |
28aae6712ff77798ddb7e8d78e0e81577ba280a4 | 6,816 | cxx | C++ | Testing/Code/BasicFilters/itkBloxCoreAtomTest.cxx | kiranhs/ITKv4FEM-Kiran | 0e4ab3b61b5fc4c736f04a73dd19e41390f20152 | [
"BSD-3-Clause"
] | 1 | 2018-04-15T13:32:43.000Z | 2018-04-15T13:32:43.000Z | Testing/Code/BasicFilters/itkBloxCoreAtomTest.cxx | kiranhs/ITKv4FEM-Kiran | 0e4ab3b61b5fc4c736f04a73dd19e41390f20152 | [
"BSD-3-Clause"
] | null | null | null | Testing/Code/BasicFilters/itkBloxCoreAtomTest.cxx | kiranhs/ITKv4FEM-Kiran | 0e4ab3b61b5fc4c736f04a73dd19e41390f20152 | [
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkBloxCoreAtomTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <stdio.h>
// Native ITK stuff
#include "itkSize.h"
#include "itkIndex.h"
#include "itkImage.h"
#include "itkImageRegionIterator.h"
#include "itkPoint.h"
// Blox stuff
#include "itkBloxBoundaryPointImage.h"
#include "itkBloxCoreAtomImage.h"
#include "itkGradientImageToBloxBoundaryPointImageFilter.h"
#include "itkBloxBoundaryPointToCoreAtomImageFilter.h"
// Spatial function stuff
#include "itkSphereSpatialFunction.h"
#include "itkFloodFilledSpatialFunctionConditionalIterator.h"
// DOG gradient related stuff
#include "itkBinomialBlurImageFilter.h"
#include "itkDifferenceOfGaussiansGradientImageFilter.h"
// Main for testing BloxImage/BloxPixel storage
int itkBloxCoreAtomTest(int, char* [] )
{
const unsigned int dim = 3;
// Image typedef
typedef itk::Image< unsigned char, dim > ImageType;
//-----------------Create a new input image--------------------
// Image size and spacing parameters
ImageType::SizeValueType sourceImageSize[] = { 20,20,20 };
ImageType::SpacingValueType sourceImageSpacing[] = { 1.0,1.0,1.0 };
ImageType::PointValueType sourceImageOrigin[] = { 0,0,0 };
// Creates the sourceImage (but doesn't set the size or allocate memory)
ImageType::Pointer sourceImage = ImageType::New();
sourceImage->SetOrigin(sourceImageOrigin);
sourceImage->SetSpacing(sourceImageSpacing);
printf("New sourceImage created\n");
//-----The following block allocates the sourceImage-----
// Create a size object native to the sourceImage type
ImageType::SizeType sourceImageSizeObject;
// Set the size object to the array defined earlier
sourceImageSizeObject.SetSize( sourceImageSize );
// Create a region object native to the sourceImage type
ImageType::RegionType largestPossibleRegion;
// Resize the region
largestPossibleRegion.SetSize( sourceImageSizeObject );
// Set the largest legal region size (i.e. the size of the whole sourceImage) to what we just defined
sourceImage->SetLargestPossibleRegion( largestPossibleRegion );
// Set the buffered region
sourceImage->SetBufferedRegion( largestPossibleRegion );
// Set the requested region
sourceImage->SetRequestedRegion( largestPossibleRegion );
// Now allocate memory for the sourceImage
sourceImage->Allocate();
printf("New sourceImage allocated\n");
// Initialize the image to hold all 0's
itk::ImageRegionIterator<ImageType> it =
itk::ImageRegionIterator<ImageType>(sourceImage, largestPossibleRegion);
for(it.GoToBegin(); !it.IsAtEnd(); ++it)
{
it.Set(0);
}
//---------Create and initialize a spatial function-----------
typedef itk::SphereSpatialFunction<dim> FunctionType;
typedef FunctionType::InputType FunctionPositionType;
// Create and initialize a new sphere function
FunctionType::Pointer spatialFunc = FunctionType::New();
spatialFunc->SetRadius( 5 );
FunctionPositionType center;
center[0]=10;
center[1]=10;
center[2]=10;
spatialFunc->SetCenter(center);
printf("Sphere spatial function created\n");
//---------Create and initialize a spatial function iterator-----------
ImageType::IndexType seedPos;
const ImageType::IndexValueType pos[] = {10,10,10};
seedPos.SetIndex(pos);
typedef itk::FloodFilledSpatialFunctionConditionalIterator
<ImageType, FunctionType> ItType;
ItType sfi = ItType(sourceImage, spatialFunc, seedPos);
// Iterate through the entire image and set interior pixels to 255
for( ; !( sfi.IsAtEnd() ); ++sfi)
{
sfi.Set(255);
}
printf("Spatial function iterator created, sphere drawn\n");
//--------------------Do blurring and edge detection----------------
typedef ImageType OutputType;
// Create a binomial blur filter
itk::BinomialBlurImageFilter<ImageType, OutputType>::Pointer binfilter;
binfilter = itk::BinomialBlurImageFilter<ImageType, OutputType>::New();
sourceImage->SetRequestedRegion(sourceImage->GetLargestPossibleRegion() );
// Set filter parameters
binfilter->SetInput(sourceImage);
binfilter->SetRepetitions(4);
// Set up the output of the filter
ImageType::Pointer blurredImage = binfilter->GetOutput();
// Create a differennce of gaussians gradient filter
typedef itk::DifferenceOfGaussiansGradientImageFilter<OutputType,
double> DOGFilterType;
DOGFilterType::Pointer DOGFilter = DOGFilterType::New();
// We're filtering the output of the binomial filter
DOGFilter->SetInput(blurredImage);
// Get the output of the gradient filter
DOGFilterType::TOutputImage::Pointer gradientImage = DOGFilter->GetOutput();
//------------------------Blox Boundary Point Analysis-------------------------
typedef itk::GradientImageToBloxBoundaryPointImageFilter<DOGFilterType::TOutputImage> TBPFilter;
typedef TBPFilter::TOutputImage BloxBPImageType;
TBPFilter::Pointer bpFilter= TBPFilter::New();
bpFilter->SetInput( DOGFilter->GetOutput() );
BloxBPImageType::Pointer bloxBoundaryPointImage = bpFilter->GetOutput();
bpFilter->Update();
//----------------------Find core atoms-------------------------
typedef itk::BloxCoreAtomImage<dim> CoreAtomType;
CoreAtomType::Pointer coreAtomImage = CoreAtomType::New();
typedef itk::BloxBoundaryPointToCoreAtomImageFilter<dim> TCAFilter;
typedef TCAFilter::TOutputImage BloxCAImageType;
TCAFilter::Pointer caFilter = TCAFilter::New();
caFilter->SetInput(bloxBoundaryPointImage);
caFilter->SetDistanceMin(8.0);
caFilter->SetDistanceMax(12.0);
caFilter->SetEpsilon(0.05);
caFilter->SetPolarity(0);
BloxCAImageType::Pointer bloxCoreAtomImage = caFilter->GetOutput();
caFilter->Update();
// Test the macros in the image
bloxCoreAtomImage->GetMedialNodeCount();
bloxCoreAtomImage->GetNodePointerList();
//--------------------Analyze core atom population---------------------
std::cout << "Performing Eigenanalysis\n";
bloxCoreAtomImage->DoEigenanalysis();
//--------------------------Run voting test-----------------------------
std::cout << "Doing core atom voting\n";
bloxCoreAtomImage->DoCoreAtomVoting();
return EXIT_SUCCESS;
}
| 33.087379 | 103 | 0.702171 | [
"object"
] |
28ab49bb1c284592df2a04585e2347560f0e14ff | 254 | cc | C++ | Part-II/Ch11/11.3.2/11.22.cc | RingZEROtlf/Cpp-Primer | bde40534eeca733350825c41f268415fdccb1cc3 | [
"MIT"
] | 1 | 2021-09-23T13:13:12.000Z | 2021-09-23T13:13:12.000Z | Part-II/Ch11/11.3.2/11.22.cc | RingZEROtlf/Cpp-Primer | bde40534eeca733350825c41f268415fdccb1cc3 | [
"MIT"
] | null | null | null | Part-II/Ch11/11.3.2/11.22.cc | RingZEROtlf/Cpp-Primer | bde40534eeca733350825c41f268415fdccb1cc3 | [
"MIT"
] | null | null | null | #include <map>
#include <string>
#include <vector>
#include <utility>
using namespace std;
int main()
{
map<string, vector<int>> mmap;
pair<string, vector<int>> argument;
pair<map<string, vector<int>>::iterator, bool> result;
return 0;
} | 19.538462 | 58 | 0.669291 | [
"vector"
] |
28ab616a9d3eb27387984d88db051776603e0054 | 24,323 | cpp | C++ | Extensions/VIW/VSTI/VSTInstrument.cpp | bach5000/XRS | 8b9169f8d52a441ddca87415963ea2fcfced1884 | [
"MIT"
] | null | null | null | Extensions/VIW/VSTI/VSTInstrument.cpp | bach5000/XRS | 8b9169f8d52a441ddca87415963ea2fcfced1884 | [
"MIT"
] | null | null | null | Extensions/VIW/VSTI/VSTInstrument.cpp | bach5000/XRS | 8b9169f8d52a441ddca87415963ea2fcfced1884 | [
"MIT"
] | null | null | null | /*
VSTInstrument.cpp
by Georges-Edouard Berenger
© 2000, Steinberg Soft- und Hard GmbH, All Rights Reserved.
*/
#ifndef _VSTINSTRUMENT_H_
#include "VSTInstrument.h"
#endif
/*#ifndef _VSTSOUND_H_
#include "VSTSound.h"
#endif*/
/*#ifndef _VSTSOUND_CONFIGURE_H_
#include "VSTSoundConfigure.h"
#endif*/
#include "ListView.h"
#include <MidiRoster.h>
#include "stdio.h"
#include "stdlib.h"
#include "OS.h"
#include <MidiProducer.h>
#include "SupportKit.h"
#include "VSTSoundConfigure.h"
#include "Node.h"
#include "Mime.h"
#include "Message.h"
#include "Path.h"
//static void load_plug_ins (const char *path, BList& list);
const int kDefaultBlockSize = 4096;
const int kDefaultFrameRate = 44100;
const int kAdapterVersion = 0x0100;
BMessage *info;
VstTimeInfo time_info;
int bpm;
int bpm_change;
VSTInstrumentPlugin::VSTInstrumentPlugin (const char *filename) :
fSampleRate (kDefaultFrameRate), fBlockSize (kDefaultBlockSize), fIdleSem (-1)
{
//fImage = load_add_on (fFactory->fAddonPath.String ());
fImage = load_add_on (filename);
if (fImage > 0)
{
AEffect * (*main_plugin) (audioMasterCallback audioMaster);
if (get_image_symbol (fImage, "main_plugin", B_SYMBOL_TYPE_TEXT, (void**) &main_plugin) == B_OK)
{
fEffect = (*main_plugin) (&audioMaster);
if (fEffect && fEffect->magic == kEffectMagic)
{
fLastFilter =(uint32) system_time ();
Register (this, fEffect);
// set up the plugin
fEffect->dispatcher (fEffect, effOpen, 0, 0, 0, 0.);
fEffect->dispatcher (fEffect,effSetProgram , 0, 0, NULL, 0.f);
fEffect->dispatcher (fEffect, effSetSampleRate, 0, 0, 0, float (fSampleRate));
fEffect->dispatcher (fEffect, effSetBlockSize, 0, kDefaultBlockSize, 0, 0.);
fEffect->dispatcher (fEffect, effMainsChanged, 0, 1, 0, 0.); // turn on
// VSTEVENTS
wme=new VstMidiEvent();
wme->type=kVstMidiType;
wme->byteSize=24;
wme->deltaFrames=0;
wme->noteLength=0;
wme->noteOffset=0;
wms=new VstMidiEvent();
wms->type=kVstMidiType;
wms->byteSize=24;
wms->deltaFrames=0;
wms->noteLength=0;
wms->noteOffset=0;
we=new VstEvents();
we->numEvents=2;
we->events[0]=(VstEvent*)wms;
we->events[1]=(VstEvent*)wme;
bpm_change=true;
name.SetTo(BPath(filename).Leaf());
return;
}
// plugin is not ok. Leak rather than take a risk to crash...
}
/*else
fprintf (stderr, "entry point not found in the plugin\n");*/
unload_add_on (fImage);
fImage = 0;
}
/*else
fprintf (stderr, "The addon could not be loaded: %s\n", strerror (fImage));*/
}
void
VSTInstrumentPlugin::setBPM(int y)
{
bpm=y;
memset(&time_info, 0, sizeof(time_info));
time_info.samplePos = 0;
time_info.sampleRate = 44100;
time_info.flags |= kVstTempoValid;
time_info.tempo = bpm;
bpm_change=true;
}
VSTInstrumentPlugin::~VSTInstrumentPlugin ()
{
//printf("Deleting VST..\n");
if (fImage > 0)
{
// terminate the idle thread if necessary
sem_info sinfo;
if (fIdleSem != -1 && get_sem_info (fIdleSem, &sinfo) == B_OK)
{
delete_sem (fIdleSem);
status_t r;
wait_for_thread (fIdleThread, &r);
}
// stop midi input if necessary
//QUI-QUI
/*
if (fMidiConsumer)
{
// puts ("Closing midi consumer");
sem_id finish = fMidiConsumer->Finish ();
acquire_sem_etc (finish, 1, B_RELATIVE_TIMEOUT, 1000000);
// printf ("result: %s\n", strerror (r));
}*/
fEffect->dispatcher (fEffect, effClose, 0, 0, 0, 0.);
Unregister (fEffect);
unload_add_on (fImage);
}
}
// Idle thread's entry point.
static long idle_thread_start (void *arg)
{
VSTInstrumentPlugin * plugin = (VSTInstrumentPlugin*) arg;
plugin->IdleLoop ();
return B_OK;
}
long VSTInstrumentPlugin::NeedIdle ()
{
// printf ("Idle needed for %s\n", fFactory->fName.String ());
sem_info sinfo;
if (fIdleSem == -1 || get_sem_info (fIdleSem, &sinfo) != B_OK)
{
// puts ("Creating Idle thread");
fIdleSem = create_sem (0, "VST plugin Idle Semaphore");
resume_thread (fIdleThread = spawn_thread (idle_thread_start, "VST Plugin Idle", B_NORMAL_PRIORITY, this));
}
return 1;
}
void VSTInstrumentPlugin::IdleLoop ()
{
// Note this common BeOS use of a semaphore to control timing & live of a user level timer.
// The timer will try to acquire the semaphore. In "normal" cases, it will time out
// and will then do its timer's work (in that case call the plugin idle call).
// When the timer has to be destroyed, then the semaphore is simply deleted.
// The acquisition of the semaphore fails, and the timer knows it has to die.
// This allows very compact, efficient & clean code.
// puts ("Idle Thread created!");
bigtime_t nextIdle = system_time ();
while (acquire_sem_etc (fIdleSem, 1, B_ABSOLUTE_TIMEOUT, nextIdle) == B_TIMED_OUT)
{
nextIdle += 10000; // idle every 10 ms.
if (!fEffect->dispatcher (fEffect, effIdle, 0, 0, 0, 0))
{
// The plugin says that no more idle is needed!
// printf ("Idle no longer needed!\n");
delete_sem (fIdleSem);
fIdleSem = -1;
return;
}
}
// printf ("Idle thread gone!\n");
}
long VSTInstrumentPlugin::WantMidi ()
{
//QUI--QUI
/*
if (fMidiConsumer == 0)
{
fMidiConsumer = new MIDI_consumer (this);
if (fMidiPortName.Length () < 1)
first_producer_name (fMidiPortName);
if (fMidiPortName.Length () > 0)
fMidiConsumer->SetSource (fMidiPortName.String ());
}*/
return 1;
}
void VSTInstrumentPlugin::SetMidiProducer (int32 id)
{ //QUI__QUI
/*BMidiProducer * producer = BMidiRoster::FindProducer (id);
if (producer)
fMidiPortName = producer->Name ();
else
fMidiPortName = "";
//if (producer && fMidiConsumer)
// fMidiConsumer->SetSource (producer);
else if (producer)
producer->Release ();*/
}
const char * VSTInstrumentPlugin::GetMidiProducerName ()
{
//return fMidiPortName.String ();
return "XRSBeta";
//time
}
status_t VSTInstrumentPlugin::FilterFloat (float **input, float **output, int32 framecount, void *info)
{
fLastFilter = (uint32) system_time ();
// value set by default. VST plugin need to know how big the buffer
// *might* be, that is, the upper limit of framecount...
if (framecount > fBlockSize)
{
// with SoundPlay, this should happen only once when the plugin is first used...
fEffect->dispatcher (fEffect, effMainsChanged, 0, 0, 0, 0.); // turn off
fEffect->dispatcher (fEffect, effSetBlockSize, 0, framecount, 0, 0.);
fEffect->dispatcher (fEffect, effMainsChanged, 0, 1, 0, 0.); // turn on
fBlockSize = framecount;
}
if (fEffect->flags & effFlagsIsSynth)
{
// VST instruments add their audio to the audio stream...
memcpy (output[0], input[0], sizeof (float) * framecount);
memcpy (output[1], input[1], sizeof (float) * framecount);
float* outputs[VST_INSTRUMENTS_MAX_OUTPUT];
for (int out = 0; out < fEffect->numOutputs; out++)
outputs[out] = output[out % 2];
// Qui mi sa che possiamo sparargli dentro gli eventi..
// process..
fEffect->process (fEffect, input, outputs, framecount);
//printf("VST Instrument working..\n");
}
// "normal" plugins
else if (fEffect->flags & effFlagsCanReplacing)
{
if (fEffect->numOutputs < 2)
memcpy (output[1], input[1], sizeof (float) * framecount);
fEffect->processReplacing (fEffect, input, output, framecount);
}
else
{
memset (output[0], 0, sizeof (float) * framecount);
if (fEffect->numOutputs < 2)
memcpy (output[1], input[1], sizeof (float) * framecount);
else
memset (output[1], 0, sizeof (float) * framecount);
fEffect->process (fEffect, input, output, framecount);
//printf("case c\n");
}
//printf("ci provo %ld \n",fBlockSize);
return B_OK;
}
void
VSTInstrumentPlugin::StopAll()
{
// B0 Channel Mode Message (on channel 1)
wms->midiData[2]=0x00; //
wms->midiData[1]=(char)123; // Message: AllNoteOff
wms->midiData[0]=0xB0; //
wme->midiData[2]=0x00; //
wme->midiData[1]=0x00; //(char)120; // Message:: AllSoundsOff
wme->midiData[0]=0x00; //0xB0; //
((AudioEffectX*)fEffect->object)->processEvents(we); //Send them!!
((AudioEffectX*)fEffect->object)->resume();
}
void
VSTInstrumentPlugin::SendNote(long note,float vel )
{
//wme->midiData[3]=0;
if(wme->midiData[0]!=0x00){
wms->midiData[2]=wme->midiData[2]; //Volume = 0x7f=255=MAX;
wms->midiData[1]=wme->midiData[1]; //
wms->midiData[0]=0x80; // noteoff of the previus note
}
long v=(long)(vel*255.);
wme->midiData[2]=v; //Volume = 0x7f=255=MAX;
wme->midiData[1]=(char)note; //
wme->midiData[0]=0x90; //note_on on the first channel (0);
// use 0x80 for note_off on the first channel (0);
AudioEffectX* p ;
p= (AudioEffectX*)fEffect->object;
p->processEvents(we);
}
BView * VSTInstrumentPlugin::Configure ()
{
return (new VSTConfigureView(this));
}
void VSTInstrumentPlugin::SetConfig (BMessage *config)
{ // BMessage -> plugin
const float * params;
const void * chunk;
ssize_t size;
int32 currentProgram;
if (config->FindInt32 ("current", ¤tProgram) == B_OK)
{
if (fEffect->flags & effFlagsProgramChunks)
{
int prog = 0;
const char * name;
while (config->FindData ("chunk", B_RAW_TYPE, prog, &chunk, &size) == B_OK
&& config->FindString ("name", prog, &name) == B_OK
&& prog < fEffect->numPrograms)
{
fEffect->dispatcher (fEffect, effSetProgram, 0, prog++, 0, 0.f);
fEffect->dispatcher (fEffect, effSetProgramName, 0, 0, (char*) name, 0);
fEffect->dispatcher (fEffect, effSetChunk, 0, size, (void*) chunk, 0.f);
}
}
else
{
int prog = 0;
const char * name;
while (config->FindData ("floats", B_RAW_TYPE, prog, (const void **) ¶ms, &size) == B_OK
&& config->FindString ("name", prog, &name) == B_OK
&& prog < fEffect->numPrograms)
{
fEffect->dispatcher (fEffect, effSetProgram, 0, prog++, 0, 0.f);
fEffect->dispatcher (fEffect, effSetProgramName, 0, 0, (char*) name, 0);
int count = size / sizeof (float);
for (int p = 0; p < count; p++)
{
fEffect->setParameter (fEffect, p, params[p]);
}
}
}
fEffect->dispatcher (fEffect, effSetProgram, 0, currentProgram, 0, 0.f);
}
//QUI__QUI
//if (config->FindString ("midi", &fMidiPortName) != B_OK)
// first_producer_name (fMidiPortName);
//else if (fMidiConsumer)
// fMidiConsumer->SetSource (fMidiPortName.String ());
}
void VSTInstrumentPlugin::GetConfig (BMessage *config)
{ // plugin -> BMessage
int32 currentProgram = fEffect->dispatcher (fEffect, effGetProgram, 0, 0, 0, 0.f);
if (fEffect->flags & effFlagsProgramChunks)
{
void * chunk;
ssize_t size;
int progCount = fEffect->numPrograms;
config->MakeEmpty ();
char name[32];
for (int prog = 0; prog < progCount; prog++)
{
fEffect->dispatcher (fEffect, effSetProgram, 0, prog, 0, 0.f);
size = fEffect->dispatcher (fEffect, effGetChunk, 0, 0, &chunk, 0.f);
config->AddData ("chunk", B_RAW_TYPE, chunk, size);
fEffect->dispatcher (fEffect, effGetProgramName, 0, 0, name, 0);
config->AddString ("name", name);
}
}
else
{
int count = fEffect->numParams;
int progCount = fEffect->numPrograms;
if (count > 0)
{
char name[32];
float * params = new float[count];
config->MakeEmpty ();
for (int prog = 0; prog < progCount; prog++)
{
fEffect->dispatcher (fEffect, effSetProgram, 0, prog, 0, 0.f);
for (int p = 0; p < count; p++)
params[p] = fEffect->getParameter (fEffect, p);
config->AddData ("floats", B_RAW_TYPE, params, count * sizeof (float));
fEffect->dispatcher (fEffect, effGetProgramName, 0, 0, name, 0);
config->AddString ("name", name);
}
delete[] params;
}
}
config->AddInt32 ("current", currentProgram);
fEffect->dispatcher (fEffect, effSetProgram, 0, currentProgram, 0, 0.f);
//if (fMidiPortName.Length () > 0)
// config->AddString ("midi", fMidiPortName);
}
/*
VST plugin will make request to the host by calling the audioMaster function.
This function needs to know which plugin is doing the request, therefore, there is
this "register" which monitors which VST plugin is active.
*/
void VSTInstrumentPlugin::Register (VSTInstrumentPlugin * plugin, AEffect * effect)
{
fLock.Lock ();
int index = 0;
while (index < fPairsCount && fPairs[index].effect != NULL)
index++;
if (index >= fPairsCount)
{
int newCount = fPairsCount + 10;
if (fPairsCount > 0)
fPairs = (effectPluginPair*) realloc (fPairs, sizeof (effectPluginPair) * newCount);
else
fPairs = (effectPluginPair*) malloc (sizeof (effectPluginPair) * newCount);
while (fPairsCount < newCount)
fPairs[fPairsCount++].effect = NULL;
}
fPairs[index].effect = effect;
fPairs[index].plugin = plugin;
fLock.Unlock ();
}
void VSTInstrumentPlugin::Unregister (AEffect * effect)
{
fLock.Lock ();
int index = 0;
while (index < fPairsCount)
{
if (fPairs[index].effect == effect)
{
fPairs[index].effect = NULL;
break;
}
index++;
}
fLock.Unlock ();
}
VSTInstrumentPlugin * VSTInstrumentPlugin::Identify (AEffect * effect)
{
fLock.Lock ();
int index = 0;
VSTInstrumentPlugin * plugin = NULL;
while (index < fPairsCount)
{
if (fPairs[index].effect == effect)
{
plugin = fPairs[index].plugin;
break;
}
index++;
}
/*if (plugin)
printf ("Identified plugin \n");
else
puts ("could not identify a plugin");*/
fLock.Unlock ();
return plugin;
}
effectPluginPair * VSTInstrumentPlugin::fPairs = NULL;
int VSTInstrumentPlugin::fPairsCount = 0;
BLocker VSTInstrumentPlugin::fLock;
void certify_fEffect (AEffect * fEffect)
{
//printf ("Testing fEffect %x\n", int (fEffect));
if (fEffect->magic == 'VstP')
puts ("Magic ok");
/*else
printf ("Magic not ok: %x\n", int (fEffect->magic));*/
//printf ("Progs: %d Params: %d Inputs: %d Outputs: %d\n", int (fEffect->numPrograms), int (fEffect->numParams), int (fEffect->numInputs), int (fEffect->numOutputs));
}
/*
VST plugins may talk to the host for a number of reasons.
This call is the main entry point for plug-in -> host calls.
*/
long audioMaster (AEffect *eff, long opCode, long index, long value, void *ptr, float opt)
{
long ret = 0;
VstTimeInfo *a;
switch (opCode)
{
//---------------------------
case audioMasterAutomate:
break;
//---------------------------
case audioMasterVersion:
ret = 1;
break;
//---------------------------
case audioMasterCurrentId:
break;
//---------------------------
case audioMasterIdle:
// no need to idle a BeOS host (normaly).
break;
//---------------------------
case audioMasterPinConnected:
break;
//---------------------------
case audioMasterPinConnected+1:// audioMasterMapAsioPorts:
break;
//----------------------------------------------------------------------
// VSTSDK 2.0
//---------------------------
case audioMasterWantMidi:
{
/*VSTInstrumentPlugin * plugin = VSTInstrumentPlugin::Identify (eff);
if (plugin)
ret = plugin->WantMidi ();*/
//printf("A Want Midi Request has been send..\n");
break;
}
//---------------------------
case audioMasterGetTime: // returns const VstTimeInfo* (or 0 if not supported)
// <value> should contain a mask indicating which fields are required
// (see valid masks above), as some items may require extensive
// conversions
//if ((value & kVstTempoValid) && bpm_change)
//{
time_info.flags |= kVstTempoValid;
time_info.tempo = bpm;
ret=(long)&time_info;
//bpm_change=false;
//}
//ret= (long)&time_info ;
break;
//---------------------------
case audioMasterProcessEvents: // VstEvents* in <ptr>
printf("VstEvents send to the host...\n");
break;
//---------------------------
case audioMasterSetTime: // VstTimenfo* in <ptr>, filter in <value>, not supported
a=(VstTimeInfo*)ptr;
break;
//---------------------------
case audioMasterTempoAt: // returns tempo (in bpm * 10000) at sample frame location passed in <value>
ret=bpm*10000;
break;
//---------------------------
// parameters
case audioMasterGetNumAutomatableParameters:
break;
//---------------------------
case audioMasterGetParameterQuantization: // returns the integer value for +1.0 representation,
// or 1 if full single float precision is maintained
// in automation. parameter index in <value> (-1: all, any)
break;
//---------------------------
// connections, configuration
case audioMasterIOChanged: // numInputs and/or numOutputs has changed
break;
//---------------------------
case audioMasterNeedIdle: // plug needs idle calls (outside its editor window)
{
VSTInstrumentPlugin * plugin = VSTInstrumentPlugin::Identify (eff);
if (plugin)
ret = plugin->NeedIdle ();
break;
}
//---------------------------
case audioMasterGetSampleRate:
{
VSTInstrumentPlugin * plugin = VSTInstrumentPlugin::Identify (eff);
if (plugin)
ret = plugin->GetSampleRate ();
else
ret = kDefaultFrameRate;
break;
}
//---------------------------
case audioMasterGetBlockSize:
{
VSTInstrumentPlugin * plugin = VSTInstrumentPlugin::Identify (eff);
if (plugin)
ret = plugin->GetBlockSize ();
else
ret = kDefaultBlockSize;
break;
}
//---------------------------
case audioMasterGetInputLatency:
break;
//---------------------------
case audioMasterGetOutputLatency:
break;
//---------------------------
case audioMasterGetPreviousPlug: // input pin in <value> (-1: first to come), returns cEffect*
break;
//---------------------------
case audioMasterGetNextPlug: // output pin in <value> (-1: first to come), returns cEffect*
break;
//---------------------------
// realtime info
case audioMasterWillReplaceOrAccumulate: // returns: 0: not supported, 1: replace, 2: accumulate
break;
//---------------------------
case audioMasterGetCurrentProcessLevel: // returns: 0: not supported,
// 1: currently in user thread (gui)
ret=1; // 2: currently in audio thread (where process is called)
// 3: currently in 'sequencer' thread (midi, timer etc)
// 4: currently offline processing and thus in user thread
// other: not defined, but probably pre-empting user thread.
break;
//---------------------------
case audioMasterGetAutomationState: // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
break;
//---------------------------
// offline
case audioMasterOfflineStart:
case audioMasterOfflineRead: // ptr points to offline structure, see below. return 0: error, 1 ok
case audioMasterOfflineWrite: // same as read
case audioMasterOfflineGetCurrentPass:
case audioMasterOfflineGetCurrentMetaPass:
break;
//---------------------------
// other
case audioMasterSetOutputSampleRate: // for variable i/o, sample rate in <opt>
break;
//---------------------------
case audioMasterGetSpeakerArrangement: // (long)input in <value>, output in <ptr>
break;
//---------------------------
case audioMasterGetVendorString: // fills <ptr> with a string identifying the vendor (max 64 char)
if (ptr)
{
strcpy ((char*)ptr, "Anzani Andrea");
ret = 1;
}
break;
//---------------------------
case audioMasterGetProductString: // fills <ptr> with a string with product name (max 64 char)
if (ptr)
{
strcpy ((char*)ptr, "XRS");
ret = 1;
}
break;
//---------------------------
case audioMasterGetVendorVersion: // returns vendor-specific version
ret = kAdapterVersion;
break;
//---------------------------
case audioMasterSetIcon: // void* in <ptr>, format not defined yet
break;
//---------------------------
case audioMasterCanDo: // string in ptr, see below
{
char* text = (char*)ptr;
//printf ("audioMasterCanDo? %s\n", text);
if (
!strcmp (text, "sendVstEvents") ||
// !strcmp (text, "sendVstMidiEvent") ||
!strcmp (text, "sendVstTimeInfo") ||
!strcmp (text, "receiveVstEvents") ||
// !strcmp (text, "receiveVstMidiEvent") ||
!strcmp (text, "supplyIdle"))
ret = 1;
break;
}
//---------------------------
case audioMasterGetLanguage: // see enum
ret = kVstLangEnglish;
break;
//---------------------------
case audioMasterSizeWindow: // index: width, value: height
break;
//---------------------------
case audioMasterVendorSpecific: // no definition, vendor specific handling
break;
//---------------------------
case audioMasterOpenWindow: // returns platform specific ptr
case audioMasterCloseWindow: // close window, platform specific handle in <ptr>
break;
//---------------------------
case audioMasterGetDirectory: // get plug directory, FSSpec on MAC, else char pointer
{
VSTInstrumentPlugin * plugin = VSTInstrumentPlugin::Identify (eff);
if (plugin)
//QUI--QUI ret = (long) plugin->fFactory->fFolderPath.String ();
printf("Ops.. i don't know where is plug-in directory..\n");
break;
}
case audioMasterUpdateDisplay: // something has changed, update 'multi-fx' display
bpm_change=true;
break;
}
return ret;
}
void VSTInstrumentPlugin::load_plug_ins (const char *rootdir, BListView *list,int line)
{
DIR* dir = opendir (rootdir);
if (dir)
{
struct dirent * entry = readdir (dir);
while (entry)
{
if (strcmp (entry->d_name, ".") != 0 && strcmp (entry->d_name, "..") != 0)
{
char path[PATH_MAX];
strcpy (path, rootdir);
strcat (path, "/");
strcat (path, entry->d_name);
struct stat st;
if (stat (path, &st) == 0)
{
if (S_ISREG (st.st_mode))
{
BNode node (path);
char type[B_MIME_TYPE_LENGTH];
if (node.InitCheck () == B_OK
&& node.ReadAttr ("BEOS:TYPE", B_MIME_STRING_TYPE, 0, type, B_MIME_TYPE_LENGTH) > 0
&& strcmp (type, B_APP_MIME_TYPE) == 0) {
// To help debugging if a crash occurs...
//printf ("Loading \"%s\" as an addon... ", path);
fflush (stdout);
char name[B_OS_NAME_LENGTH];
strncpy (name, entry->d_name, B_OS_NAME_LENGTH);
rename_thread (find_thread (NULL), name);
// an executable has been found. Try to load it as a VST plugin
image_id vstaddon = load_add_on (path);
if (vstaddon > 0)
{ // the file is indeed an addon, but is it a VST plugin?
//printf ("OK! VST Plugin?... ");
fflush (stdout);
AEffect * effect;
AEffect * (*main_plugin) (audioMasterCallback audioMaster);
if (get_image_symbol (vstaddon, "main_plugin", B_SYMBOL_TYPE_TEXT, (void**) &main_plugin) == B_OK)
{ // Chances are now that this is a VST plugin, but is it supported?...
//printf ("Yes!\n");
effect = (*main_plugin) (&audioMaster);
if (effect && effect->magic == kEffectMagic)
{
if (
#if VST_INSTRUMENTS
(((effect->flags & effFlagsIsSynth) && effect->numOutputs <= VST_INSTRUMENTS_MAX_OUTPUT) || // for VST Instruments
(effect->numOutputs <= 2)) // "normal" plugins
#else
// VST Instrument not allowed
(effect->flags & effFlagsIsSynth) == 0
&& effect->numOutputs <= 2
#endif
//&& effect->dispatcher (effect, effGetVstVersion, 0, 0, 0, 0) >= 1
&& effect->numInputs <= 2)
{
effect->dispatcher (effect, effOpen, 0, 0, 0, 0.);
// the VST plugin has been opened. Now we can create the "PluginFactory" object.
info=new BMessage('VST');
info->AddInt16("vst_line",line);
info->AddString("vst_name",entry->d_name);
//list->AddItem (new BMenuItem(entry->d_name,info));
list->AddItem (new BStringItem(entry->d_name));
//printf("Vst : %s\n",entry->d_name);
//unload_add_on (vstaddon);
}
effect->dispatcher (effect, effClose, 0, 0, 0, 0.);
}
}// else
//printf ("No!\n");
unload_add_on (vstaddon);
} //else
//printf ("Not an addon!\n");
}
}
else if (S_ISDIR (st.st_mode))
load_plug_ins (path, list,line);
}
}
entry = readdir (dir);
}
closedir (dir);
}
// Add
}
| 28.086605 | 167 | 0.619496 | [
"object"
] |
28abd6b1f726dc3c734a657b2988e7692b11d088 | 56,380 | cpp | C++ | src/core/environ/win32/WindowFormUnit.cpp | weimingtom/krkrz110_fork | dda1177f75428e030853c0de237076986818fa65 | [
"BSD-3-Clause"
] | 1 | 2019-05-16T09:30:11.000Z | 2019-05-16T09:30:11.000Z | src/core/environ/win32/WindowFormUnit.cpp | weimingtom/krkrz110_fork | dda1177f75428e030853c0de237076986818fa65 | [
"BSD-3-Clause"
] | null | null | null | src/core/environ/win32/WindowFormUnit.cpp | weimingtom/krkrz110_fork | dda1177f75428e030853c0de237076986818fa65 | [
"BSD-3-Clause"
] | null | null | null |
#include "tjsCommHead.h"
#define DIRECTDRAW_VERSION 0x0300
#include <ddraw.h>
#include <dbt.h> // for WM_DEVICECHANGE
#include <algorithm>
#include "WindowFormUnit.h"
#include "WindowImpl.h"
#include "EventIntf.h"
#include "ComplexRect.h"
#include "LayerBitmapIntf.h"
#include "tjsArray.h"
#include "StorageIntf.h"
#include "MsgIntf.h"
#include "SystemControl.h"
#include "SysInitIntf.h"
#include "PluginImpl.h"
#include "Random.h"
#include "SystemImpl.h"
#include "DInputMgn.h"
#include "tvpinputdefs.h"
#include "Application.h"
#include "TVPSysFont.h"
#include "TickCount.h"
#include "WindowsUtil.h"
#include "CompatibleNativeFuncs.h"
tjs_uint32 TVP_TShiftState_To_uint32(TShiftState state) {
tjs_uint32 result = 0;
if( state & MK_SHIFT ) {
result |= ssShift;
}
if( state & MK_CONTROL ) {
result |= ssCtrl;
}
if( state & MK_ALT ) {
result |= ssAlt;
}
return result;
}
TShiftState TVP_TShiftState_From_uint32(tjs_uint32 state){
TShiftState result = 0;
if( state & ssShift ) {
result |= MK_SHIFT;
}
if( state & ssCtrl ) {
result |= MK_CONTROL;
}
if( state & ssAlt ) {
result |= MK_ALT;
}
return result;
}
tTVPMouseButton TVP_TMouseButton_To_tTVPMouseButton(int button) {
return (tTVPMouseButton)button;
}
//---------------------------------------------------------------------------
// Modal Window List
//---------------------------------------------------------------------------
// modal window list is used to ensure modal window accessibility when
// the system is full-screened,
std::vector<TTVPWindowForm *> TVPModalWindowList;
//---------------------------------------------------------------------------
static void TVPAddModalWindow(TTVPWindowForm * window)
{
std::vector<TTVPWindowForm *>::iterator i;
i = std::find(TVPModalWindowList.begin(), TVPModalWindowList.end(), window);
if(i == TVPModalWindowList.end())
TVPModalWindowList.push_back(window);
}
//---------------------------------------------------------------------------
static void TVPRemoveModalWindow(TTVPWindowForm *window)
{
std::vector<TTVPWindowForm *>::iterator i;
i = std::find(TVPModalWindowList.begin(), TVPModalWindowList.end(), window);
if(i != TVPModalWindowList.end())
TVPModalWindowList.erase(i);
}
//---------------------------------------------------------------------------
#include "DebugIntf.h"
void TVPShowModalAtAppActivate()
{
// called when the application is activated
if(TVPFullScreenedWindow != NULL)
{
// any window is full-screened
::ShowWindow(TVPFullScreenedWindow->GetHandle(), SW_RESTORE); // restore the window
// send message which brings modal windows to front
std::vector<TTVPWindowForm *>::iterator i;
for(i = TVPModalWindowList.begin(); i != TVPModalWindowList.end(); i++)
(*i)->InvokeShowVisible();
for(i = TVPModalWindowList.begin(); i != TVPModalWindowList.end(); i++)
(*i)->InvokeShowTop();
}
}
//---------------------------------------------------------------------------
HDWP TVPShowModalAtTimer(HDWP hdwp)
{
// called every 4 seconds, to ensure the modal window visible
if(TVPFullScreenedWindow != NULL)
{
// send message which brings modal windows to front
std::vector<TTVPWindowForm *>::iterator i;
for(i = TVPModalWindowList.begin(); i != TVPModalWindowList.end(); i++)
hdwp = (*i)->ShowTop(hdwp);
}
return hdwp;
}
//---------------------------------------------------------------------------
void TVPHideModalAtAppDeactivate()
{
// called when the application is deactivated
if(TVPFullScreenedWindow != NULL)
{
// any window is full-screened
// hide modal windows
std::vector<TTVPWindowForm *>::iterator i;
for(i = TVPModalWindowList.begin(); i != TVPModalWindowList.end(); i++)
(*i)->SetVisible( false );
}
// hide also popups
TTVPWindowForm::DeliverPopupHide();
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// Window/Bitmap options
//---------------------------------------------------------------------------
static bool TVPWindowOptionsInit = false;
static bool TVPControlImeState = true;
//---------------------------------------------------------------------------
void TVPInitWindowOptions()
{
// initialize various options around window/graphics
if(TVPWindowOptionsInit) return;
tTJSVariant val;
if(TVPGetCommandLine(TJS_W("-wheel"), &val) )
{
ttstr str(val);
if(str == TJS_W("dinput"))
TVPWheelDetectionType = wdtDirectInput;
else if(str == TJS_W("message"))
TVPWheelDetectionType = wdtWindowMessage;
else
TVPWheelDetectionType = wdtNone;
}
#ifndef DISABLE_EMBEDDED_GAME_PAD
if(TVPGetCommandLine(TJS_W("-joypad"), &val) )
{
ttstr str(val);
if(str == TJS_W("dinput"))
TVPJoyPadDetectionType = jdtDirectInput;
else
TVPJoyPadDetectionType = jdtNone;
}
#endif
if(TVPGetCommandLine(TJS_W("-controlime"), &val) )
{
ttstr str(val);
if(str == TJS_W("no"))
TVPControlImeState = false;
}
TVPWindowOptionsInit = true;
}
//---------------------------------------------------------------------------
TTVPWindowForm::TTVPWindowForm( tTVPApplication* app, tTJSNI_Window* ni, tTJSNI_Window* parent ) : tTVPWindow(), CurrentMouseCursor(crDefault), touch_points_(this),
LayerLeft(0), LayerTop(0), LayerWidth(32), LayerHeight(32),
LastMouseDownX(0), LastMouseDownY(0),
HintX(0), HintY(0), HintTimer(NULL), HintDelay(TVP_TOOLTIP_SHOW_DELAY), LastHintSender(NULL),
FullScreenDestRect(0,0,0,0) {
HWND hParent = NULL;
if( parent ) hParent = parent->GetSurfaceWindowHandle();
CreateWnd( L"TVPMainWindow", Application->GetTitle(), 10, 10, hParent );
TVPInitWindowOptions();
// initialize members
TJSNativeInstance = ni;
app->AddWindow(this);
NextSetWindowHandleToDrawDevice = true;
LastSentDrawDeviceDestRect.clear();
in_mode_ = false;
Focusable = true;
Closing = false;
ProgramClosing = false;
modal_result_ = 0;
InnerWidthSave = GetInnerWidth();
InnerHeightSave = GetInnerHeight();
AttentionPointEnabled = false;
AttentionPoint.x = 0;
AttentionPoint.y = 0;
AttentionFont = new tTVPSysFont();
ZoomDenom = ActualZoomDenom = 1;
ZoomNumer = ActualZoomNumer = 1;
DefaultImeMode = imClose;
LastSetImeMode = imClose;
::PostMessage( GetHandle(), TVP_WM_ACQUIREIMECONTROL, 0, 0);
UseMouseKey = false;
TrapKeys = false;
CanReceiveTrappedKeys = false;
InReceivingTrappedKeys = false;
MouseKeyXAccel = 0;
MouseKeyYAccel = 0;
LastMouseMoved = false;
MouseLeftButtonEmulatedPushed = false;
MouseRightButtonEmulatedPushed = false;
LastMouseMovedPos.x = 0;
LastMouseMovedPos.y = 0;
MouseCursorState = mcsVisible;
ForceMouseCursorVisible = false;
CurrentMouseCursor = crDefault;
DIWheelDevice = NULL;
#ifndef DISABLE_EMBEDDED_GAME_PAD
DIPadDevice = NULL;
#endif
ReloadDevice = false;
ReloadDeviceTick = 0;
LastRecheckInputStateSent = 0;
SetBorderStyle( bsSizeable );
DisplayOrientation = orientUnknown;
DisplayRotate = -1;
}
TTVPWindowForm::~TTVPWindowForm() {
if( HintTimer ) {
delete HintTimer;
HintTimer = NULL;
}
if( AttentionFont ) {
delete AttentionFont;
AttentionFont = NULL;
}
if( DIWheelDevice ) {
delete DIWheelDevice;
DIWheelDevice = NULL;
}
#ifndef DISABLE_EMBEDDED_GAME_PAD
if( DIPadDevice ) {
delete DIPadDevice;
DIPadDevice = NULL;
}
#endif
Application->RemoveWindow( this );
}
void TTVPWindowForm::OnDestroy() {
CallWindowDetach(true);
CleanupFullScreen();
TJSNativeInstance = NULL;
TVPRemoveModalWindow(this);
FreeDirectInputDevice();
if( AttentionFont ) {
delete AttentionFont, AttentionFont = NULL;
}
tjs_int count = WindowMessageReceivers.GetCount();
for(tjs_int i = 0 ; i < count; i++)
{
tTVPMessageReceiverRecord * item = WindowMessageReceivers[i];
if(!item) continue;
delete item;
WindowMessageReceivers.Remove(i);
}
Application->RemoveWindow(this);
tTVPWindow::OnDestroy();
}
void TTVPWindowForm::CleanupFullScreen() {
// called at destruction
if(TVPFullScreenedWindow != this) return;
TVPFullScreenedWindow = NULL;
}
tjs_uint32 TVPGetCurrentShiftKeyState() {
tjs_uint32 f = 0;
if(TVPGetAsyncKeyState(VK_SHIFT)) f += TVP_SS_SHIFT;
if(TVPGetAsyncKeyState(VK_MENU)) f += TVP_SS_ALT;
if(TVPGetAsyncKeyState(VK_CONTROL)) f += TVP_SS_CTRL;
if(TVPGetAsyncKeyState(VK_LBUTTON)) f += TVP_SS_LEFT;
if(TVPGetAsyncKeyState(VK_RBUTTON)) f += TVP_SS_RIGHT;
if(TVPGetAsyncKeyState(VK_MBUTTON)) f += TVP_SS_MIDDLE;
return f;
}
TTVPWindowForm * TVPFullScreenedWindow;
enum {
CM_BASE = 0xB000,
CM_MOUSEENTER = CM_BASE + 19,
CM_MOUSELEAVE = CM_BASE + 20,
};
bool TTVPWindowForm::FindKeyTrapper(LRESULT &result, UINT msg, WPARAM wparam, LPARAM lparam) {
// find most recent "trapKeys = true" window.
tjs_int count = TVPGetWindowCount();
for( tjs_int i = count - 1; i >= 0; i-- ) {
tTJSNI_Window * win = TVPGetWindowListAt(i);
if( win ) {
TTVPWindowForm * form = win->GetForm();
if( form ) {
if( form->TrapKeys && form->GetVisible() ) {
// found
return form->ProcessTrappedKeyMessage(result, msg, wparam, lparam);
}
}
}
}
// not found
return false;
}
bool TTVPWindowForm::ProcessTrappedKeyMessage(LRESULT &result, UINT msg, WPARAM wparam, LPARAM lparam) {
// perform key message
if( msg == WM_KEYDOWN ) {
CanReceiveTrappedKeys = true;
// to prevent receiving a key, which is pushed when the window is just created
}
if( CanReceiveTrappedKeys ) {
InReceivingTrappedKeys = true;
result = tTVPWindow::Proc( GetHandle(), msg, wparam, lparam );
InReceivingTrappedKeys = false;
}
if( msg == WM_KEYUP ) {
CanReceiveTrappedKeys = true;
}
return true;
}
LRESULT WINAPI TTVPWindowForm::Proc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {
tTVPWindowMessage Message;
Message.LParam = lParam;
Message.WParam = wParam;
Message.Msg = msg;
Message.Result = 0;
if( DeliverMessageToReceiver( Message) ) return Message.Result;
if( Message.Msg == WM_SYSCOMMAND ) {
long subcom = Message.WParam & 0xfff0;
bool ismain = false;
if( TJSNativeInstance ) ismain = TJSNativeInstance->IsMainWindow();
if( ismain ) {
if( subcom == SC_MINIMIZE && !Application->IsIconic() ) {
Application->Minimize();
return 0;
}
if(subcom == SC_RESTORE && Application->IsIconic() ) {
Application->Restore();
return 0;
}
}
} else if(!InReceivingTrappedKeys // to prevent infinite recursive call
&& Message.Msg >= WM_KEYFIRST && Message.Msg <= WM_KEYLAST ) {
// hide popups when alt key is pressed
if(Message.Msg == WM_SYSKEYDOWN && !CanSendPopupHide())
DeliverPopupHide();
// drain message to key trapping window
LRESULT res;
if(FindKeyTrapper(res, Message.Msg, Message.WParam, Message.LParam)) {
Message.Result = res;
return res;
}
}
switch( msg ) {
case TVP_WM_SHOWVISIBLE:
WMShowVisible();
return 0;
case TVP_WM_SHOWTOP:
WMShowTop(wParam);
return 0;
case TVP_WM_RETRIEVEFOCUS:
WMRetrieveFocus();
return 0;
case TVP_WM_ACQUIREIMECONTROL:
WMAcquireImeControl();
return 0;
default:
return tTVPWindow::Proc( hWnd, msg, wParam, lParam );
}
}
void TTVPWindowForm::WMShowVisible() {
SetVisible(true);
}
void TTVPWindowForm::WMShowTop( WPARAM wParam ) {
if( GetVisible() ) {
::SetWindowPos( GetHandle(), HWND_TOPMOST, 0, 0, 0, 0, SWP_NOACTIVATE|SWP_NOMOVE|SWP_NOREPOSITION|SWP_NOSIZE|SWP_SHOWWINDOW);
}
}
void TTVPWindowForm::WMRetrieveFocus() {
Application->BringToFront();
SetFocus( GetHandle() );
}
void TTVPWindowForm::WMAcquireImeControl() {
AcquireImeControl();
}
bool TTVPWindowForm::GetFormEnabled() {
return TRUE == ::IsWindowEnabled(GetHandle());
}
void TTVPWindowForm::TickBeat(){
// called every 50ms intervally
DWORD tickcount = static_cast<DWORD>(TVPGetTickCount());
bool focused = HasFocus();
// mouse key
if(UseMouseKey && focused) {
GenerateMouseEvent(false, false, false, false);
}
// device reload
if( ReloadDevice && (int)(tickcount - ReloadDeviceTick) > 0) {
ReloadDevice = false;
FreeDirectInputDevice();
CreateDirectInputDevice();
}
// wheel rotation detection
tjs_uint32 shift = TVPGetCurrentShiftKeyState();
if( TVPWheelDetectionType == wdtDirectInput ) {
CreateDirectInputDevice();
if( focused && TJSNativeInstance && DIWheelDevice ) {
tjs_int delta = DIWheelDevice->GetWheelDelta();
if( delta ) {
POINT origin = {0,0};
::ClientToScreen( GetHandle(), &origin );
POINT mp = {0, 0};
::GetCursorPos(&mp);
tjs_int x = mp.x - origin.x;
tjs_int y = mp.y - origin.y;
TranslateWindowToDrawArea( x, y);
TVPPostInputEvent(new tTVPOnMouseWheelInputEvent(TJSNativeInstance, shift, delta, x, y));
}
}
}
#ifndef DISABLE_EMBEDDED_GAME_PAD
// pad detection
if( TVPJoyPadDetectionType == jdtDirectInput ) {
CreateDirectInputDevice();
if( DIPadDevice && TJSNativeInstance ) {
if( focused )
DIPadDevice->UpdateWithCurrentState();
else
DIPadDevice->UpdateWithSuspendedState();
const std::vector<WORD> & uppedkeys = DIPadDevice->GetUppedKeys();
const std::vector<WORD> & downedkeys = DIPadDevice->GetDownedKeys();
const std::vector<WORD> & repeatkeys = DIPadDevice->GetRepeatKeys();
std::vector<WORD>::const_iterator i;
// for upped pad buttons
for(i = uppedkeys.begin(); i != uppedkeys.end(); i++) {
InternalKeyUp(*i, shift);
}
// for downed pad buttons
for(i = downedkeys.begin(); i != downedkeys.end(); i++) {
InternalKeyDown(*i, shift);
}
// for repeated pad buttons
for(i = repeatkeys.begin(); i != repeatkeys.end(); i++) {
InternalKeyDown(*i, shift|TVP_SS_REPEAT);
}
}
}
#endif
// check RecheckInputState
if( tickcount - LastRecheckInputStateSent > 1000 ) {
LastRecheckInputStateSent = tickcount;
if(TJSNativeInstance) TJSNativeInstance->RecheckInputState();
}
}
bool TTVPWindowForm::GetWindowActive() {
return ::GetForegroundWindow() == GetHandle();
}
void TTVPWindowForm::SetDrawDeviceDestRect()
{
tTVPRect destrect;
tjs_int w = MulDiv(LayerWidth, ActualZoomNumer, ActualZoomDenom);
tjs_int h = MulDiv(LayerHeight, ActualZoomNumer, ActualZoomDenom);
if( w < 1 ) w = 1;
if( h < 1 ) h = 1;
if( GetFullScreenMode() ) {
destrect.left = FullScreenDestRect.left;
destrect.top = FullScreenDestRect.top;
destrect.right = destrect.left + w;
destrect.bottom = destrect.top + h;
} else {
destrect.left = destrect.top = 0;
destrect.right = w;
destrect.bottom = h;
}
if( LastSentDrawDeviceDestRect != destrect ) {
if( TJSNativeInstance ) {
if( GetFullScreenMode() ) {
TJSNativeInstance->GetDrawDevice()->SetClipRectangle(FullScreenDestRect);
} else {
TJSNativeInstance->GetDrawDevice()->SetClipRectangle(destrect);
}
TJSNativeInstance->GetDrawDevice()->SetDestRectangle(destrect);
}
LastSentDrawDeviceDestRect = destrect;
}
}
void TTVPWindowForm::OnPaint() {
// a painting event
if( NextSetWindowHandleToDrawDevice ) {
bool ismain = false;
if( TJSNativeInstance ) ismain = TJSNativeInstance->IsMainWindow();
if( TJSNativeInstance ) TJSNativeInstance->GetDrawDevice()->SetTargetWindow( GetHandle(), ismain);
NextSetWindowHandleToDrawDevice = false;
}
SetDrawDeviceDestRect();
if( TJSNativeInstance ) {
tTVPRect r;
GetClientRect( r );
TJSNativeInstance->NotifyWindowExposureToLayer(r);
}
}
void TTVPWindowForm::SetUseMouseKey( bool b ) {
UseMouseKey = b;
if( b ) {
MouseLeftButtonEmulatedPushed = false;
MouseRightButtonEmulatedPushed = false;
LastMouseKeyTick = GetTickCount();
} else {
if(MouseLeftButtonEmulatedPushed) {
MouseLeftButtonEmulatedPushed = false;
OnMouseUp( mbLeft, 0, LastMouseMovedPos.x, LastMouseMovedPos.y);
}
if(MouseRightButtonEmulatedPushed) {
MouseRightButtonEmulatedPushed = false;
OnMouseUp( mbRight, 0, LastMouseMovedPos.x, LastMouseMovedPos.y);
}
}
}
bool TTVPWindowForm::GetUseMouseKey() const {
return UseMouseKey;
}
void TTVPWindowForm::SetTrapKey(bool b) {
TrapKeys = b;
if( TrapKeys ) {
// reset CanReceiveTrappedKeys and InReceivingTrappedKeys
CanReceiveTrappedKeys = false;
InReceivingTrappedKeys = false;
// note that SetTrapKey can be called while the key trapping is processing.
}
}
bool TTVPWindowForm::GetTrapKey() const {
return TrapKeys;
}
void TTVPWindowForm::SetMaskRegion(HRGN threshold)
{
::SetWindowRgn(GetHandle(), threshold, GetVisible() ? TRUE : FALSE );
}
void TTVPWindowForm::RemoveMaskRegion()
{
::SetWindowRgn(GetHandle(), NULL, GetVisible() ? TRUE : FALSE );
}
void TTVPWindowForm::HideMouseCursor() {
// hide mouse cursor temporarily
SetMouseCursorState(mcsTempHidden);
}
void TTVPWindowForm::SetMouseCursorState(tTVPMouseCursorState mcs) {
if(MouseCursorState == mcsVisible && mcs != mcsVisible) {
// formerly visible and newly invisible
if(!ForceMouseCursorVisible) SetMouseCursorVisibleState(false);
} else if(MouseCursorState != mcsVisible && mcs == mcsVisible) {
// formerly invisible and newly visible
if(!ForceMouseCursorVisible) SetMouseCursorVisibleState(true);
}
if(MouseCursorState != mcs && mcs == mcsTempHidden) {
POINT pt;
::GetCursorPos(&pt);
LastMouseScreenX = pt.x;
LastMouseScreenY = pt.y;
}
MouseCursorState = mcs;
}
void TTVPWindowForm::RestoreMouseCursor() {
// restore mouse cursor hidden by HideMouseCursor
if( MouseCursorState == mcsTempHidden ) {
POINT pt;
::GetCursorPos(&pt);
if( LastMouseScreenX != pt.x || LastMouseScreenY != pt.y ) {
SetMouseCursorState(mcsVisible);
}
}
}
void TTVPWindowForm::SetMouseCursorVisibleState(bool b) {
// set mouse cursor visible state
// this does not look MouseCursorState
if(b)
SetMouseCursorToWindow( CurrentMouseCursor );
else
SetMouseCursorToWindow( MouseCursor(crNone) );
}
void TTVPWindowForm::SetForceMouseCursorVisible(bool s) {
if(ForceMouseCursorVisible != s) {
if(s) {
// force visible mode
// the cursor is to be fixed in crDefault
SetMouseCursorToWindow( MouseCursor(crDefault) );
} else {
// normal mode
// restore normal cursor
SetMouseCursorVisibleState(MouseCursorState == mcsVisible);
}
ForceMouseCursorVisible = s;
}
}
void TTVPWindowForm::SetMouseCursorToWindow( MouseCursor& cursor ) {
cursor.SetCursor();
}
//---------------------------------------------------------------------------
void TTVPWindowForm::SetFocusable(bool b)
{
// set focusable state to 'b'.
// note that currently focused window does not automatically unfocus by
// setting false to this flag.
Focusable = b;
}
//---------------------------------------------------------------------------
void TTVPWindowForm::InternalSetPaintBoxSize() {
SetDrawDeviceDestRect();
}
void TTVPWindowForm::AdjustNumerAndDenom(tjs_int &n, tjs_int &d){
tjs_int a = n;
tjs_int b = d;
while( b ) {
tjs_int t = b;
b = a % b;
a = t;
}
n = n / a;
d = d / a;
}
void TTVPWindowForm::SetZoom( tjs_int numer, tjs_int denom, bool set_logical ) {
bool ischanged = false;
// set layer zooming factor;
// the zooming factor is passed in numerator/denoiminator style.
// we must find GCM to optimize numer/denium via Euclidean algorithm.
AdjustNumerAndDenom(numer, denom);
if( set_logical ) {
if( ZoomNumer != numer || ZoomDenom != denom ) {
ischanged = true;
}
ZoomNumer = numer;
ZoomDenom = denom;
}
if( !GetFullScreenMode() ) {
// in fullscreen mode, zooming factor is controlled by the system
ActualZoomDenom = denom;
ActualZoomNumer = numer;
}
InternalSetPaintBoxSize();
if( ischanged ) ::InvalidateRect( GetHandle(), NULL, FALSE );
}
void TTVPWindowForm::SetFullScreenMode( bool b ) {
// note that we should not change the display mode when showing overlay videos.
CallFullScreenChanging(); // notify to plugin
try {
if(TJSNativeInstance) TJSNativeInstance->DetachVideoOverlay();
// due to re-create window (but current implementation may not re-create the window)
if( b ) {
if(TVPFullScreenedWindow == this) return;
if(TVPFullScreenedWindow) TVPFullScreenedWindow->SetFullScreenMode(false);
// save position and size
OrgLeft = GetLeft();
OrgTop = GetTop();
OrgWidth = GetWidth();
OrgHeight = GetHeight();
// determin desired full screen size
tjs_int desired_fs_w = GetInnerWidth();
tjs_int desired_fs_h = GetInnerHeight();
OrgClientWidth = desired_fs_w;
OrgClientHeight = desired_fs_h;
// set BorderStyle
OrgStyle = ::GetWindowLong(GetHandle(), GWL_STYLE);
OrgExStyle = ::GetWindowLong(GetHandle(), GWL_EXSTYLE);
::SetWindowLong( GetHandle(), GWL_STYLE, WS_POPUP | WS_VISIBLE);
// try to switch to fullscreen
try {
if(TJSNativeInstance) TVPSwitchToFullScreen( GetHandle(), desired_fs_w, desired_fs_h, TJSNativeInstance->GetDrawDevice() );
} catch(...) {
SetFullScreenMode(false);
return;
}
::SetWindowLong( GetHandle(), GWL_STYLE, WS_POPUP | WS_VISIBLE | WS_CLIPCHILDREN);
// get resulted screen size
tjs_int fs_w = TVPFullScreenMode.Width;
tjs_int fs_h = TVPFullScreenMode.Height;
// determine fullscreen zoom factor and client size
int sb_w, sb_h, zoom_d, zoom_n;
zoom_d = TVPFullScreenMode.ZoomDenom;
zoom_n = TVPFullScreenMode.ZoomNumer;
sb_w = desired_fs_w * zoom_n / zoom_d;
sb_h = desired_fs_h * zoom_n / zoom_d;
FullScreenDestRect.set_size( sb_w, sb_h );
FullScreenDestRect.set_offsets( (fs_w - sb_w)/2, (fs_h - sb_h)/2 );
SetZoom(zoom_n, zoom_d, false);
// indicate fullscreen state
TVPFullScreenedWindow = this;
// reset window size
HMONITOR hMonitor = ::MonitorFromWindow( GetHandle(), MONITOR_DEFAULTTOPRIMARY );
MONITORINFO mi = {sizeof(MONITORINFO)};
int ml = 0, mt = 0;
if( ::GetMonitorInfo( hMonitor, &mi ) ) {
ml = mi.rcMonitor.left;
mt = mi.rcMonitor.top;
}
SetBounds( ml, mt, fs_w, fs_h );
SetInnerSize( fs_w, fs_h );
// re-adjust video rect
if(TJSNativeInstance) TJSNativeInstance->ReadjustVideoRect();
// activate self
BringToFront();
::SetFocus(GetHandle());
// activate self (again)
::SetWindowPos( GetHandle(), HWND_TOP, 0, 0, 0, 0, SWP_NOACTIVATE|SWP_NOMOVE|SWP_NOREPOSITION|SWP_NOSIZE|SWP_SHOWWINDOW );
} else {
if(TVPFullScreenedWindow != this) return;
SetBounds(OrgLeft, OrgTop, OrgWidth, OrgHeight);
// revert from fullscreen
if(TJSNativeInstance) TVPRevertFromFullScreen( GetHandle(), OrgClientWidth, OrgClientHeight, TJSNativeInstance->GetDrawDevice() );
TVPFullScreenedWindow = NULL;
FullScreenDestRect.set_offsets( 0, 0 );
// revert zooming factor
ActualZoomDenom = ZoomDenom;
ActualZoomNumer = ZoomNumer;
SetZoom(ZoomNumer, ZoomDenom); // reset zoom factor
// set BorderStyle
SetWindowLong(GetHandle(), GWL_STYLE, OrgStyle);
SetWindowLong(GetHandle(), GWL_EXSTYLE, OrgExStyle);
// revert the position and size
SetBounds(OrgLeft, OrgTop, OrgWidth, OrgHeight);
SetInnerSize( OrgClientWidth, OrgClientHeight );
::SetWindowPos( GetHandle(), HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOACTIVATE|SWP_NOMOVE|SWP_NOREPOSITION|SWP_NOSIZE|SWP_SHOWWINDOW );
// re-adjust video rect
if(TJSNativeInstance) TJSNativeInstance->ReadjustVideoRect();
}
} catch(...) {
CallFullScreenChanged();
throw;
}
CallFullScreenChanged();
CurrentMouseCursor.SetCursor();
}
bool TTVPWindowForm::GetFullScreenMode() const {
return TVPFullScreenedWindow == this;
}
//---------------------------------------------------------------------------
void TTVPWindowForm::CallWindowDetach(bool close) {
if( TJSNativeInstance ) TJSNativeInstance->GetDrawDevice()->SetTargetWindow( NULL, false );
tTVPWindowMessage msg;
msg.Msg = TVP_WM_DETACH;
msg.LParam = 0;
msg.WParam = close ? 1 : 0;
msg.Result = 0;
DeliverMessageToReceiver(msg);
}
//---------------------------------------------------------------------------
void TTVPWindowForm::CallWindowAttach() {
NextSetWindowHandleToDrawDevice = true;
LastSentDrawDeviceDestRect.clear();
tTVPWindowMessage msg;
msg.Msg = TVP_WM_ATTACH;
msg.LParam = reinterpret_cast<int>(GetWindowHandleForPlugin());
msg.WParam = 0;
msg.Result = 0;
DeliverMessageToReceiver(msg);
}
//---------------------------------------------------------------------------
void TTVPWindowForm::CallFullScreenChanged() {
LastSentDrawDeviceDestRect.clear();
::InvalidateRect( GetHandle(), NULL, FALSE );
tTVPWindowMessage msg;
msg.Msg = TVP_WM_FULLSCREEN_CHANGED;
msg.LParam = 0;
msg.WParam = 0;
msg.Result = 0;
DeliverMessageToReceiver(msg);
}
//---------------------------------------------------------------------------
void TTVPWindowForm::CallFullScreenChanging() {
tTVPWindowMessage msg;
msg.Msg = TVP_WM_FULLSCREEN_CHANGING;
msg.LParam = reinterpret_cast<int>(GetWindowHandleForPlugin());
msg.WParam = 0;
msg.Result = 0;
DeliverMessageToReceiver(msg);
}
bool TTVPWindowForm::InternalDeliverMessageToReceiver(tTVPWindowMessage &msg) {
if( !TJSNativeInstance ) return false;
if( TVPPluginUnloadedAtSystemExit ) return false;
tObjectListSafeLockHolder<tTVPMessageReceiverRecord> holder(WindowMessageReceivers);
tjs_int count = WindowMessageReceivers.GetSafeLockedObjectCount();
bool block = false;
for( tjs_int i = 0; i < count; i++ ) {
tTVPMessageReceiverRecord *item = WindowMessageReceivers.GetSafeLockedObjectAt(i);
if(!item) continue;
bool b = item->Deliver(&msg);
block = block || b;
}
return block;
}
void TTVPWindowForm::UpdateWindow(tTVPUpdateType type ) {
if( TJSNativeInstance ) {
tTVPRect r;
r.left = 0;
r.top = 0;
r.right = LayerWidth;
r.bottom = LayerHeight;
TJSNativeInstance->NotifyWindowExposureToLayer(r);
TVPDeliverWindowUpdateEvents();
}
}
void TTVPWindowForm::ShowWindowAsModal() {
// TODO: what's modalwindowlist ?
modal_result_ = 0;
TVPAddModalWindow(this); // add to modal window list
try {
ShowModal();
} catch(...) {
TVPRemoveModalWindow(this);
throw;
}
TVPRemoveModalWindow(this);
}
//---------------------------------------------------------------------------
void TTVPWindowForm::SetVisibleFromScript(bool b)
{
if(Focusable) {
SetVisible( b );
} else {
if( !GetVisible() ) {
// just show window, not activate
SetWindowPos(GetHandle(), GetStayOnTop()?HWND_TOPMOST:HWND_TOP, 0, 0, 0, 0, SWP_NOACTIVATE|SWP_NOMOVE|SWP_NOSIZE|SWP_SHOWWINDOW);
SetVisible( true );
} else {
SetVisible( false );
}
}
}
void TTVPWindowForm::RegisterWindowMessageReceiver(tTVPWMRRegMode mode, void * proc, const void *userdata) {
if( mode == wrmRegister ) {
// register
tjs_int count = WindowMessageReceivers.GetCount();
tjs_int i;
for(i = 0 ; i < count; i++) {
tTVPMessageReceiverRecord *item = WindowMessageReceivers[i];
if(!item) continue;
if((void*)item->Proc == proc) break; // have already registered
}
if(i == count) {
// not have registered
tTVPMessageReceiverRecord *item = new tTVPMessageReceiverRecord();
item->Proc = (tTVPWindowMessageReceiver)proc;
item->UserData = userdata;
WindowMessageReceivers.Add(item);
}
} else if(mode == wrmUnregister) {
// unregister
tjs_int count = WindowMessageReceivers.GetCount();
for(tjs_int i = 0 ; i < count; i++) {
tTVPMessageReceiverRecord *item = WindowMessageReceivers[i];
if(!item) continue;
if((void*)item->Proc == proc) {
// found
WindowMessageReceivers.Remove(i);
delete item;
}
}
WindowMessageReceivers.Compact();
}
}
void TTVPWindowForm::OnClose( CloseAction& action ) {
if(modal_result_ == 0)
action = caNone;
else
action = caHide;
if( ProgramClosing ) {
if( TJSNativeInstance ) {
if( TJSNativeInstance->IsMainWindow() ) {
// this is the main window
} else {
// not the main window
action = caFree;
}
if( TVPFullScreenedWindow != this ) {
// if this is not a fullscreened window
SetVisible( false );
}
iTJSDispatch2 * obj = TJSNativeInstance->GetOwnerNoAddRef();
TJSNativeInstance->NotifyWindowClose();
obj->Invalidate(0, NULL, NULL, obj);
TJSNativeInstance = NULL;
}
}
}
bool TTVPWindowForm::OnCloseQuery() {
// closing actions are 3 patterns;
// 1. closing action by the user
// 2. "close" method
// 3. object invalidation
if( TVPGetBreathing() ) {
return false;
}
// the default event handler will invalidate this object when an onCloseQuery
// event reaches the handler.
if(TJSNativeInstance && (modal_result_ == 0 ||
modal_result_ == mrCancel/* mrCancel=when close button is pushed in modal window */ )) {
iTJSDispatch2 * obj = TJSNativeInstance->GetOwnerNoAddRef();
if(obj) {
tTJSVariant arg[1] = {true};
static ttstr eventname(TJS_W("onCloseQuery"));
if(!ProgramClosing) {
// close action does not happen immediately
if(TJSNativeInstance) {
TVPPostInputEvent( new tTVPOnCloseInputEvent(TJSNativeInstance) );
}
Closing = true; // waiting closing...
TVPSystemControl->NotifyCloseClicked();
return false;
} else {
CanCloseWork = true;
TVPPostEvent(obj, obj, eventname, 0, TVP_EPT_IMMEDIATE, 1, arg);
// this event happens immediately
// and does not return until done
return CanCloseWork; // CanCloseWork is set by the event handler
}
} else {
return true;
}
} else {
return true;
}
}
void TTVPWindowForm::Close() {
// closing action by "close" method
if( Closing ) return; // already waiting closing...
ProgramClosing = true;
try {
tTVPWindow::Close();
} catch(...) {
ProgramClosing = false;
throw;
}
ProgramClosing = false;
}
void TTVPWindowForm::InvalidateClose() {
// closing action by object invalidation;
// this will not cause any user confirmation of closing the window.
TJSNativeInstance = NULL;
SetVisible( false );
BOOL ret = ::DestroyWindow( GetHandle() );
if( ret == FALSE ) {
TVPThrowWindowsErrorException();
}
delete this;
}
void TTVPWindowForm::OnCloseQueryCalled( bool b ) {
// closing is allowed by onCloseQuery event handler
if( !ProgramClosing ) {
// closing action by the user
if( b ) {
if( in_mode_ )
modal_result_ = 1; // when modal
else
SetVisible( false ); // just hide
Closing = false;
if( TJSNativeInstance ) {
if( TJSNativeInstance->IsMainWindow() ) {
// this is the main window
iTJSDispatch2 * obj = TJSNativeInstance->GetOwnerNoAddRef();
obj->Invalidate(0, NULL, NULL, obj);
// TJSNativeInstance = NULL; // この段階では既にthisが削除されているため、メンバーへアクセスしてはいけない
}
} else {
delete this;
}
} else {
Closing = false;
}
} else {
// closing action by the program
CanCloseWork = b;
}
}
void TTVPWindowForm::SendCloseMessage() {
::PostMessage(GetHandle(), WM_CLOSE, 0, 0);
}
void TTVPWindowForm::ZoomRectangle( tjs_int& left, tjs_int& top, tjs_int& right, tjs_int& bottom) {
left = MulDiv(left , ActualZoomNumer, ActualZoomDenom);
top = MulDiv(top , ActualZoomNumer, ActualZoomDenom);
right = MulDiv(right , ActualZoomNumer, ActualZoomDenom);
bottom = MulDiv(bottom, ActualZoomNumer, ActualZoomDenom);
}
void TTVPWindowForm::GetVideoOffset(tjs_int &ofsx, tjs_int &ofsy) {
if( GetFullScreenMode() ) {
ofsx = FullScreenDestRect.left;
ofsy = FullScreenDestRect.top;
} else {
ofsx = 0;
ofsy = 0;
}
}
/*
HWND TTVPWindowForm::GetSurfaceWindowHandle() {
return GetHandle();
}
HWND TTVPWindowForm::GetWindowHandle(tjs_int &ofsx, tjs_int &ofsy) {
RECT rt;
::GetWindowRect( GetHandle(), &rt );
POINT pt = { rt.left, rt.top };
ScreenToClient( GetHandle(), &pt );
ofsx = -pt.x;
ofsy = -pt.y;
return GetHandle();
}
HWND TTVPWindowForm::GetWindowHandleForPlugin() {
return GetHandle();
}
*/
void TTVPWindowForm::ResetDrawDevice() {
NextSetWindowHandleToDrawDevice = true;
LastSentDrawDeviceDestRect.clear();
::InvalidateRect( GetHandle(), NULL, FALSE );
}
void TTVPWindowForm::InternalKeyUp(WORD key, tjs_uint32 shift) {
DWORD tick = GetTickCount();
TVPPushEnvironNoise(&tick, sizeof(tick));
TVPPushEnvironNoise(&key, sizeof(key));
TVPPushEnvironNoise(&shift, sizeof(shift));
if( TJSNativeInstance ) {
if( UseMouseKey /*&& PaintBox*/ ) {
if( key == VK_RETURN || key == VK_SPACE || key == VK_ESCAPE || key == VK_PAD1 || key == VK_PAD2) {
POINT p;
::GetCursorPos(&p);
::ScreenToClient( GetHandle(), &p );
if( p.x >= 0 && p.y >= 0 && p.x < GetInnerWidth() && p.y < GetInnerHeight() ) {
if( key == VK_RETURN || key == VK_SPACE || key == VK_PAD1 ) {
OnMouseClick( mbLeft, 0, p.x, p.y );
MouseLeftButtonEmulatedPushed = false;
OnMouseUp( mbLeft, 0, p.x, p.y );
}
if( key == VK_ESCAPE || key == VK_PAD2 ) {
MouseRightButtonEmulatedPushed = false;
OnMouseUp( mbRight, 0, p.x, p.y );
}
}
return;
}
}
TVPPostInputEvent(new tTVPOnKeyUpInputEvent(TJSNativeInstance, key, shift));
}
}
void TTVPWindowForm::InternalKeyDown(WORD key, tjs_uint32 shift) {
DWORD tick = GetTickCount();
TVPPushEnvironNoise(&tick, sizeof(tick));
TVPPushEnvironNoise(&key, sizeof(key));
TVPPushEnvironNoise(&shift, sizeof(shift));
if( TJSNativeInstance ) {
if(UseMouseKey /*&& PaintBox*/ ) {
if(key == VK_RETURN || key == VK_SPACE || key == VK_ESCAPE || key == VK_PAD1 || key == VK_PAD2) {
POINT p;
::GetCursorPos(&p);
::ScreenToClient( GetHandle(), &p );
if( p.x >= 0 && p.y >= 0 && p.x < GetInnerWidth() && p.y < GetInnerHeight() ) {
if( key == VK_RETURN || key == VK_SPACE || key == VK_PAD1 ) {
MouseLeftButtonEmulatedPushed = true;
OnMouseDown( mbLeft, 0, p.x, p.y );
}
if(key == VK_ESCAPE || key == VK_PAD2) {
MouseRightButtonEmulatedPushed = true;
OnMouseDown( mbLeft, 0, p.x, p.y );
}
}
return;
}
switch(key) {
case VK_LEFT:
case VK_PADLEFT:
if( MouseKeyXAccel == 0 && MouseKeyYAccel == 0 ) {
GenerateMouseEvent(true, false, false, false);
LastMouseKeyTick = GetTickCount() + 100;
}
return;
case VK_RIGHT:
case VK_PADRIGHT:
if(MouseKeyXAccel == 0 && MouseKeyYAccel == 0)
{
GenerateMouseEvent(false, true, false, false);
LastMouseKeyTick = GetTickCount() + 100;
}
return;
case VK_UP:
case VK_PADUP:
if(MouseKeyXAccel == 0 && MouseKeyYAccel == 0)
{
GenerateMouseEvent(false, false, true, false);
LastMouseKeyTick = GetTickCount() + 100;
}
return;
case VK_DOWN:
case VK_PADDOWN:
if(MouseKeyXAccel == 0 && MouseKeyYAccel == 0)
{
GenerateMouseEvent(false, false, false, true);
LastMouseKeyTick = GetTickCount() + 100;
}
return;
}
}
TVPPostInputEvent(new tTVPOnKeyDownInputEvent(TJSNativeInstance, key, shift));
}
}
void TTVPWindowForm::GenerateMouseEvent(bool fl, bool fr, bool fu, bool fd) {
if( !fl && !fr && !fu && !fd ) {
if(GetTickCount() - 45 < LastMouseKeyTick) return;
}
bool shift = 0!=(GetAsyncKeyState(VK_SHIFT) & 0x8000);
bool left = fl || GetAsyncKeyState(VK_LEFT) & 0x8000 || TVPGetJoyPadAsyncState(VK_PADLEFT, true);
bool right = fr || GetAsyncKeyState(VK_RIGHT) & 0x8000 || TVPGetJoyPadAsyncState(VK_PADRIGHT, true);
bool up = fu || GetAsyncKeyState(VK_UP) & 0x8000 || TVPGetJoyPadAsyncState(VK_PADUP, true);
bool down = fd || GetAsyncKeyState(VK_DOWN) & 0x8000 || TVPGetJoyPadAsyncState(VK_PADDOWN, true);
DWORD flags = 0;
if(left || right || up || down) flags |= MOUSEEVENTF_MOVE;
if(!right && !left && !up && !down) {
LastMouseMoved = false;
MouseKeyXAccel = MouseKeyYAccel = 0;
}
if(!shift) {
if(!right && left && MouseKeyXAccel > 0) MouseKeyXAccel = -0;
if(!left && right && MouseKeyXAccel < 0) MouseKeyXAccel = 0;
if(!down && up && MouseKeyYAccel > 0) MouseKeyYAccel = -0;
if(!up && down && MouseKeyYAccel < 0) MouseKeyYAccel = 0;
} else {
if(left) MouseKeyXAccel = -TVP_MOUSE_SHIFT_ACCEL;
if(right) MouseKeyXAccel = TVP_MOUSE_SHIFT_ACCEL;
if(up) MouseKeyYAccel = -TVP_MOUSE_SHIFT_ACCEL;
if(down) MouseKeyYAccel = TVP_MOUSE_SHIFT_ACCEL;
}
if(right || left || up || down) {
if(left) if(MouseKeyXAccel > -TVP_MOUSE_MAX_ACCEL)
MouseKeyXAccel = MouseKeyXAccel?MouseKeyXAccel - 2:-2;
if(right) if(MouseKeyXAccel < TVP_MOUSE_MAX_ACCEL)
MouseKeyXAccel = MouseKeyXAccel?MouseKeyXAccel + 2:+2;
if(!left && !right) {
if(MouseKeyXAccel > 0) MouseKeyXAccel--;
else if(MouseKeyXAccel < 0) MouseKeyXAccel++;
}
if(up) if(MouseKeyYAccel > -TVP_MOUSE_MAX_ACCEL)
MouseKeyYAccel = MouseKeyYAccel?MouseKeyYAccel - 2:-2;
if(down) if(MouseKeyYAccel < TVP_MOUSE_MAX_ACCEL)
MouseKeyYAccel = MouseKeyYAccel?MouseKeyYAccel + 2:+2;
if(!up && !down) {
if(MouseKeyYAccel > 0) MouseKeyYAccel--;
else if(MouseKeyYAccel < 0) MouseKeyYAccel++;
}
}
if(flags) {
POINT pt;
if(::GetCursorPos(&pt)) {
::SetCursorPos( pt.x + (MouseKeyXAccel>>1), pt.y + (MouseKeyYAccel>>1));
}
LastMouseMoved = true;
}
LastMouseKeyTick = GetTickCount();
}
void TTVPWindowForm::SetPaintBoxSize(tjs_int w, tjs_int h) {
LayerWidth = w;
LayerHeight = h;
InternalSetPaintBoxSize();
}
void TTVPWindowForm::SetDefaultMouseCursor() {
if( !CurrentMouseCursor.IsCurrentCursor(crDefault ) ) {
if( MouseCursorState == mcsVisible && !ForceMouseCursorVisible ) {
SetMouseCursorToWindow(MouseCursor(crDefault));
}
}
CurrentMouseCursor.SetCursorIndex(crDefault);
}
void TTVPWindowForm::SetMouseCursor( tjs_int handle ) {
if( !CurrentMouseCursor.IsCurrentCursor(handle ) ) {
if(MouseCursorState == mcsVisible && !ForceMouseCursorVisible) {
SetMouseCursorToWindow( MouseCursor(handle) );
}
}
CurrentMouseCursor.SetCursorIndex(handle);
}
/**
* クライアント領域座標からウィンドウ領域座標へ変換する
*/
void TTVPWindowForm::OffsetClientPoint( int &x, int &y ) {
POINT origin = {0,0};
::ClientToScreen( GetHandle(), &origin );
x = -origin.x;
y = -origin.y;
}
void TTVPWindowForm::GetCursorPos(tjs_int &x, tjs_int &y) {
// get mouse cursor position in client
POINT origin = {0,0};
::ClientToScreen( GetHandle(), &origin );
POINT mp = {0, 0};
::GetCursorPos(&mp);
x = mp.x - origin.x;
y = mp.y - origin.y;
}
void TTVPWindowForm::SetCursorPos(tjs_int x, tjs_int y) {
TranslateDrawAreaToWindow( x, y );
POINT pt = {x,y};
::ClientToScreen( GetHandle(), &pt );
::SetCursorPos(pt.x, pt.y);
LastMouseScreenX = LastMouseScreenY = -1; // force to display mouse cursor
RestoreMouseCursor();
}
void TTVPWindowForm::SetHintText(iTJSDispatch2* sender, const ttstr &text ) {
bool updatetext = HintMessage != text;
if( updatetext && text.IsEmpty() != true ) {
HintMessage.Clear();
UpdateHint();
}
HintMessage = text;
POINT p;
::GetCursorPos(&p);
::ScreenToClient( GetHandle(), &p );
HintX = p.x;
HintY = p.y;
if( HintTimer ) HintTimer->SetEnabled(false);
if( text.IsEmpty() ) {
if( HintTimer ) HintTimer->SetEnabled(false);
UpdateHint();
} else {
if( LastHintSender != sender || updatetext ) {
if( HintDelay > 0 ) {
if( HintTimer == NULL ) {
HintTimer = new TVPTimer();
HintTimer->SetOnTimerHandler( this, &TTVPWindowForm::UpdateHint );
}
HintTimer->SetEnabled(false);
HintTimer->SetInterval( HintDelay );
HintTimer->SetEnabled(true);
} else if( HintDelay == 0 ) {
UpdateHint();
}
}
}
LastHintSender = sender;
}
void TTVPWindowForm::UpdateHint() {
if(TJSNativeInstance) {
TVPPostInputEvent( new tTVPOnHintChangeInputEvent(TJSNativeInstance, HintMessage, HintX, HintY, HintMessage.IsEmpty()==false ));
}
if( HintTimer ) HintTimer->SetEnabled(false);
}
void TTVPWindowForm::UnacquireImeControl() {
if( TVPControlImeState ) {
GetIME()->Reset();
}
}
TTVPWindowForm * TTVPWindowForm::GetKeyTrapperWindow() {
// find most recent "trapKeys = true" window and return it.
// returnts "this" window if there is no trapping window.
tjs_int count = TVPGetWindowCount();
for( tjs_int i = count - 1; i >= 0; i-- ) {
tTJSNI_Window * win = TVPGetWindowListAt(i);
if( win ) {
TTVPWindowForm * form = win->GetForm();
if( form && form != this ) {
if( form->TrapKeys && form->GetVisible() ) {
// found
return form;
}
}
}
}
return this;
}
int TTVPWindowForm::ConvertImeMode( tTVPImeMode mode ) {
switch( mode ) {
case ::imDisable : return ImeControl::ModeClose ; // (*)
case ::imClose : return ImeControl::ModeClose ;
case ::imOpen : return ImeControl::ModeOpen ;
case ::imDontCare : return ImeControl::ModeDontCare;
case ::imSAlpha : return ImeControl::ModeSAlpha ;
case ::imAlpha : return ImeControl::ModeAlpha ;
case ::imHira : return ImeControl::ModeHira ;
case ::imSKata : return ImeControl::ModeSKata ;
case ::imKata : return ImeControl::ModeKata ;
case ::imChinese : return ImeControl::ModeChinese ;
case ::imSHanguel : return ImeControl::ModeSHanguel;
case ::imHanguel : return ImeControl::ModeHanguel ;
}
return ImeControl::ModeDontCare;
}
void TTVPWindowForm::AcquireImeControl() {
if( HasFocus() ) {
// find key trapper window ...
TTVPWindowForm * trapper = GetKeyTrapperWindow();
// force to access protected some methods.
// much nasty way ...
if( TVPControlImeState ) {
GetIME()->Reset();
tTVPImeMode newmode = trapper->LastSetImeMode;
if( GetIME()->IsEnableThisLocale() )
GetIME()->Enable();
GetIME()->SetIme(ConvertImeMode(newmode));
}
if( trapper->AttentionPointEnabled ) {
::SetCaretPos( trapper->AttentionPoint.x, trapper->AttentionPoint.y );
if( trapper == this ) {
GetIME()->SetCompositionWindow( AttentionPoint.x, AttentionPoint.y );
GetIME()->SetCompositionFont( AttentionFont);
} else {
// disable IMM composition window
GetIME()->Disable();
}
}
}
}
void TTVPWindowForm::SetImeMode(tTVPImeMode mode) {
LastSetImeMode = mode;
AcquireImeControl();
}
void TTVPWindowForm::SetDefaultImeMode(tTVPImeMode mode, bool reset) {
DefaultImeMode = mode;
if(reset) ResetImeMode();
}
void TTVPWindowForm::ResetImeMode() {
SetImeMode(DefaultImeMode);
}
void TTVPWindowForm::SetAttentionPoint(tjs_int left, tjs_int top, const tTVPFont * font) {
TranslateDrawAreaToWindow( left, top );
// set attention point information
AttentionPoint.x = left;
AttentionPoint.y = top;
AttentionPointEnabled = true;
if( font ) {
AttentionFont->Assign(*font);
} else {
tTVPSysFont * default_font = new tTVPSysFont();
AttentionFont->Assign(default_font);
delete default_font;
}
AcquireImeControl();
}
void TTVPWindowForm::DisableAttentionPoint() {
AttentionPointEnabled = false;
}
void TTVPWindowForm::CreateDirectInputDevice() {
if( !DIWheelDevice ) DIWheelDevice = new tTVPWheelDirectInputDevice(GetHandle());
#ifndef DISABLE_EMBEDDED_GAME_PAD
if( !DIPadDevice ) DIPadDevice = new tTVPPadDirectInputDevice(GetHandle());
#endif
}
void TTVPWindowForm::FreeDirectInputDevice() {
if( DIWheelDevice ) {
delete DIWheelDevice;
DIWheelDevice = NULL;
}
#ifndef DISABLE_EMBEDDED_GAME_PAD
if( DIPadDevice ) {
delete DIPadDevice;
DIPadDevice = NULL;
}
#endif
}
void TTVPWindowForm::OnKeyDown( WORD vk, int shift, int repeat, bool prevkeystate ) {
if(TJSNativeInstance) {
tjs_uint32 s = TVP_TShiftState_To_uint32( shift );
s |= GetMouseButtonState();
if( prevkeystate && repeat > 0 ) s |= TVP_SS_REPEAT;
InternalKeyDown( vk, s );
}
}
void TTVPWindowForm::OnKeyUp( WORD vk, int shift ) {
tjs_uint32 s = TVP_TShiftState_To_uint32(shift);
s |= GetMouseButtonState();
InternalKeyUp(vk, s );
}
void TTVPWindowForm::OnKeyPress( WORD vk, int repeat, bool prevkeystate, bool convertkey ) {
if( TJSNativeInstance && vk ) {
if(UseMouseKey && (vk == 0x1b || vk == 13 || vk == 32)) return;
// UNICODE なのでそのまま渡してしまう
TVPPostInputEvent(new tTVPOnKeyPressInputEvent(TJSNativeInstance, vk));
}
}
void TTVPWindowForm::TranslateWindowToDrawArea(int &x, int &y) {
if( GetFullScreenMode() ) {
x -= FullScreenDestRect.left;
y -= FullScreenDestRect.top;
}
}
void TTVPWindowForm::TranslateWindowToDrawArea(double&x, double &y) {
if( GetFullScreenMode() ) {
x -= FullScreenDestRect.left;
y -= FullScreenDestRect.top;
}
}
void TTVPWindowForm::TranslateDrawAreaToWindow(int &x, int &y) {
if( GetFullScreenMode() ) {
x += FullScreenDestRect.left;
y += FullScreenDestRect.top;
}
}
void TTVPWindowForm::FirePopupHide() {
// fire "onPopupHide" event
if(!CanSendPopupHide()) return;
if(!GetVisible()) return;
TVPPostInputEvent( new tTVPOnPopupHideInputEvent(TJSNativeInstance) );
}
void TTVPWindowForm::DeliverPopupHide() {
// deliver onPopupHide event to unfocusable windows
tjs_int count = TVPGetWindowCount();
for( tjs_int i = count - 1; i >= 0; i-- ) {
tTJSNI_Window * win = TVPGetWindowListAt(i);
if( win ){
TTVPWindowForm * form = win->GetForm();
if( form ) {
form->FirePopupHide();
}
}
}
}
void TTVPWindowForm::SetEnableTouch( bool b ) {
if( b != GetEnableTouch() ) {
if( procRegisterTouchWindow && procUnregisterTouchWindow ) {
int value= ::GetSystemMetrics( SM_DIGITIZER );
if( (value & NID_READY ) == NID_READY ) {
if( b ) {
procRegisterTouchWindow( GetHandle(), REGISTER_TOUCH_FLAG );
} else {
procUnregisterTouchWindow( GetHandle() );
}
}
}
}
}
bool TTVPWindowForm::GetEnableTouch() const {
if( procIsTouchWindow ) {
BOOL ret = procIsTouchWindow( GetHandle(), NULL );
return ret != 0;
}
return false;
}
void TTVPWindowForm::InvokeShowVisible() {
// this posts window message which invokes WMShowVisible
::PostMessage( GetHandle(), TVP_WM_SHOWVISIBLE, 0, 0);
}
//---------------------------------------------------------------------------
void TTVPWindowForm::InvokeShowTop(bool activate) {
// this posts window message which invokes WMShowTop
::PostMessage( GetHandle(), TVP_WM_SHOWTOP, activate ? 1:0, 0);
}
//---------------------------------------------------------------------------
HDWP TTVPWindowForm::ShowTop(HDWP hdwp) {
if( GetVisible() ) {
hdwp = ::DeferWindowPos(hdwp, GetHandle(), HWND_TOPMOST, 0, 0, 0, 0,
SWP_NOACTIVATE|SWP_NOMOVE|SWP_NOREPOSITION|
SWP_NOSIZE|WM_SHOWWINDOW);
}
return hdwp;
}
void TTVPWindowForm::OnMouseMove( int shift, int x, int y ) {
TranslateWindowToDrawArea(x, y);
MouseVelocityTracker.addMovement( TVPGetRoughTickCount32(), (float)x, (float)y );
if( TJSNativeInstance ) {
tjs_uint32 s = TVP_TShiftState_To_uint32(shift);
s |= GetMouseButtonState();
TVPPostInputEvent( new tTVPOnMouseMoveInputEvent(TJSNativeInstance, x, y, s), TVP_EPT_DISCARDABLE );
}
RestoreMouseCursor();
int pos = (y << 16) + x;
TVPPushEnvironNoise(&pos, sizeof(pos));
LastMouseMovedPos.x = x;
LastMouseMovedPos.y = y;
}
void TTVPWindowForm::OnMouseDown( int button, int shift, int x, int y ) {
if( !CanSendPopupHide() ) DeliverPopupHide();
TranslateWindowToDrawArea( x, y);
SetMouseCapture();
MouseVelocityTracker.addMovement( TVPGetRoughTickCount32(), (float)x, (float)y );
LastMouseDownX = x;
LastMouseDownY = y;
if(TJSNativeInstance) {
tjs_uint32 s = TVP_TShiftState_To_uint32(shift);
s |= GetMouseButtonState();
tTVPMouseButton b = TVP_TMouseButton_To_tTVPMouseButton(button);
TVPPostInputEvent( new tTVPOnMouseDownInputEvent(TJSNativeInstance, x, y, b, s));
}
}
void TTVPWindowForm::OnMouseUp( int button, int shift, int x, int y ) {
TranslateWindowToDrawArea(x, y);
ReleaseMouseCapture();
MouseVelocityTracker.addMovement( TVPGetRoughTickCount32(), (float)x, (float)y );
if(TJSNativeInstance) {
tjs_uint32 s = TVP_TShiftState_To_uint32(shift);
s |= GetMouseButtonState();
tTVPMouseButton b = TVP_TMouseButton_To_tTVPMouseButton(button);
TVPPostInputEvent( new tTVPOnMouseUpInputEvent(TJSNativeInstance, x, y, b, s));
}
}
void TTVPWindowForm::OnMouseDoubleClick( int button, int x, int y ) {
// fire double click event
if( TJSNativeInstance ) {
TVPPostInputEvent( new tTVPOnDoubleClickInputEvent(TJSNativeInstance, LastMouseDownX, LastMouseDownY));
}
}
void TTVPWindowForm::OnMouseClick( int button, int shift, int x, int y ) {
// fire click event
if( TJSNativeInstance ) {
TVPPostInputEvent( new tTVPOnClickInputEvent(TJSNativeInstance, LastMouseDownX, LastMouseDownY));
}
}
void TTVPWindowForm::OnMouseWheel( int delta, int shift, int x, int y ) {
TranslateWindowToDrawArea( x, y);
if( TVPWheelDetectionType == wdtWindowMessage ) {
// wheel
if( TJSNativeInstance ) {
tjs_uint32 s = TVP_TShiftState_To_uint32(shift);
s |= GetMouseButtonState();
TVPPostInputEvent(new tTVPOnMouseWheelInputEvent(TJSNativeInstance, s, delta, x, y));
}
}
}
void TTVPWindowForm::OnTouchDown( double x, double y, double cx, double cy, DWORD id, DWORD tick ) {
TranslateWindowToDrawArea(x, y);
TouchVelocityTracker.start( id );
TouchVelocityTracker.update( id, tick, (float)x, (float)y );
if(TJSNativeInstance) {
TVPPostInputEvent( new tTVPOnTouchDownInputEvent(TJSNativeInstance, x, y, cx, cy, id));
}
touch_points_.TouchDown( x, y ,cx, cy, id, tick );
}
void TTVPWindowForm::OnTouchMove( double x, double y, double cx, double cy, DWORD id, DWORD tick ) {
TranslateWindowToDrawArea( x, y);
TouchVelocityTracker.update( id, tick, (float)x, (float)y );
if(TJSNativeInstance) {
TVPPostInputEvent( new tTVPOnTouchMoveInputEvent(TJSNativeInstance, x, y, cx, cy, id));
}
touch_points_.TouchMove( x, y, cx, cy, id, tick );
}
void TTVPWindowForm::OnTouchUp( double x, double y, double cx, double cy, DWORD id, DWORD tick ) {
TranslateWindowToDrawArea( x, y);
TouchVelocityTracker.update( id, tick, (float)x, (float)y );
if(TJSNativeInstance) {
TVPPostInputEvent( new tTVPOnTouchUpInputEvent(TJSNativeInstance, x, y, cx, cy, id));
}
touch_points_.TouchUp( x, y, cx, cy, id, tick );
TouchVelocityTracker.end( id );
}
void TTVPWindowForm::OnTouchScaling( double startdist, double currentdist, double cx, double cy, int flag ) {
if(TJSNativeInstance) {
TVPPostInputEvent( new tTVPOnTouchScalingInputEvent(TJSNativeInstance, startdist, currentdist, cx, cy, flag ));
}
}
void TTVPWindowForm::OnTouchRotate( double startangle, double currentangle, double distance, double cx, double cy, int flag ) {
if(TJSNativeInstance) {
TVPPostInputEvent( new tTVPOnTouchRotateInputEvent(TJSNativeInstance, startangle, currentangle, distance, cx, cy, flag));
}
}
void TTVPWindowForm::OnMultiTouch() {
if( TJSNativeInstance ) {
TVPPostInputEvent( new tTVPOnMultiTouchInputEvent(TJSNativeInstance) );
}
}
void TTVPWindowForm::OnTouchSequenceStart() {
// 何もしない
}
void TTVPWindowForm::OnTouchSequenceEnd() {
}
void TTVPWindowForm::OnActive( HWND preactive ) {
if( TVPFullScreenedWindow == this )
TVPShowModalAtAppActivate();
Application->OnActivate( GetHandle() );
}
void TTVPWindowForm::OnDeactive( HWND postactive ) {
if( TJSNativeInstance ) {
TVPPostInputEvent( new tTVPOnReleaseCaptureInputEvent(TJSNativeInstance) );
}
Application->OnDeactivate( GetHandle() );
}
void TTVPWindowForm::OnMove( int x, int y ) {
if(TJSNativeInstance) {
TJSNativeInstance->WindowMoved();
}
}
void TTVPWindowForm::OnResize( int state, int w, int h ) {
if( state == SIZE_MINIMIZED || state == SIZE_MAXSHOW || state == SIZE_MAXHIDE ) return;
// state == SIZE_RESTORED, SIZE_MAXIMIZED,
// on resize
if(TJSNativeInstance) {
// here specifies TVP_EPT_REMOVE_POST, to remove redundant onResize events.
TVPPostInputEvent( new tTVPOnResizeInputEvent(TJSNativeInstance), TVP_EPT_REMOVE_POST );
}
}
void TTVPWindowForm::OnDropFile( HDROP hDrop ) {
wchar_t filename[MAX_PATH];
tjs_int filecount= ::DragQueryFile(hDrop, 0xFFFFFFFF, NULL, MAX_PATH);
iTJSDispatch2 * array = TJSCreateArrayObject();
try {
tjs_int count = 0;
for( tjs_int i = filecount-1; i>=0; i-- ) {
::DragQueryFile( hDrop, i, filename, MAX_PATH );
WIN32_FIND_DATA fd;
HANDLE h;
// existence checking
if((h = ::FindFirstFile(filename, &fd)) != INVALID_HANDLE_VALUE) {
::FindClose(h);
tTJSVariant val = TVPNormalizeStorageName(ttstr(filename));
// push into array
array->PropSetByNum(TJS_MEMBERENSURE|TJS_IGNOREPROP, count++, &val, array);
}
}
::DragFinish(hDrop);
tTJSVariant arg(array, array);
TVPPostInputEvent( new tTVPOnFileDropInputEvent(TJSNativeInstance, arg));
} catch(...) {
array->Release();
throw;
}
array->Release();
}
int TTVPWindowForm::OnMouseActivate( HWND hTopLevelParentWnd, WORD hitTestCode, WORD MouseMsg ) {
if(!Focusable) {
// override default action (which activates the window)
if( hitTestCode == HTCLIENT )
return MA_NOACTIVATE;
else
return MA_NOACTIVATEANDEAT;
} else {
return MA_ACTIVATE;
}
}
void TTVPWindowForm::OnEnable( bool enabled ) {
// enabled status has changed
if(TJSNativeInstance) {
TVPPostInputEvent( new tTVPOnReleaseCaptureInputEvent(TJSNativeInstance));
}
}
void TTVPWindowForm::OnDeviceChange( int event, void *data ) {
if( event == DBT_DEVNODES_CHANGED ) {
// reload DInput device
ReloadDevice = true; // to reload device
ReloadDeviceTick = GetTickCount() + 4000; // reload at 4secs later
}
}
void TTVPWindowForm::OnNonClientMouseDown( int button, int hittest, int x, int y ) {
if(!CanSendPopupHide()) {
DeliverPopupHide();
}
}
void TTVPWindowForm::OnMouseEnter() {
// mouse entered in client area
if( MouseCursorState == mcsVisible ) {
CurrentMouseCursor.SetCursor();
} else {
SetMouseCursorToWindow( MouseCursor(crNone) );
}
DWORD tick = GetTickCount();
TVPPushEnvironNoise(&tick, sizeof(tick));
MouseVelocityTracker.clear();
if(TJSNativeInstance) {
TVPPostInputEvent(new tTVPOnMouseEnterInputEvent(TJSNativeInstance));
}
}
void TTVPWindowForm::OnMouseLeave() {
SetMouseCursorToWindow( MouseCursor(crDefault) );
// mouse leaved from client area
DWORD tick = GetTickCount();
TVPPushEnvironNoise(&tick, sizeof(tick));
if(TJSNativeInstance) {
TVPPostInputEvent( new tTVPOnMouseOutOfWindowInputEvent(TJSNativeInstance));
TVPPostInputEvent( new tTVPOnMouseLeaveInputEvent(TJSNativeInstance));
}
}
void TTVPWindowForm::OnShow( int status ) {
::DragAcceptFiles( GetHandle(), TRUE );
::PostMessage( GetHandle(), TVP_WM_ACQUIREIMECONTROL, 0, 0);
}
void TTVPWindowForm::OnHide( int status ) {
}
void TTVPWindowForm::OnFocus(HWND hFocusLostWnd) {
::PostMessage( GetHandle(), TVP_WM_ACQUIREIMECONTROL, 0, 0);
::CreateCaret( GetHandle(), NULL, 1, 1);
#ifndef DISABLE_EMBEDDED_GAME_PAD
if(DIPadDevice && TJSNativeInstance ) DIPadDevice->WindowActivated();
#endif
if(TJSNativeInstance) TJSNativeInstance->FireOnActivate(true);
}
void TTVPWindowForm::OnFocusLost(HWND hFocusingWnd) {
DestroyCaret();
UnacquireImeControl();
#ifndef DISABLE_EMBEDDED_GAME_PAD
if(DIPadDevice && TJSNativeInstance ) DIPadDevice->WindowDeactivated();
#endif
if(TJSNativeInstance) TJSNativeInstance->FireOnActivate(false);
}
void TTVPWindowForm::UpdateOrientation() {
if( DisplayOrientation == orientUnknown || DisplayRotate < 0 ) {
int orient, rot;
if( GetOrientation( orient, rot ) ) {
if( DisplayOrientation != orient || DisplayRotate != rot ) {
DisplayOrientation = orient;
DisplayRotate = rot;
}
}
}
}
bool TTVPWindowForm::GetOrientation( int& orientation, int& rotate ) const {
DEVMODE mode = {0};
mode.dmSize = sizeof(DEVMODE);
mode.dmDriverExtra = 0;
mode.dmFields |= DM_DISPLAYORIENTATION | DM_PELSWIDTH | DM_PELSHEIGHT;
BOOL ret = ::EnumDisplaySettingsEx( NULL, ENUM_CURRENT_SETTINGS, &mode, EDS_ROTATEDMODE );
if( ret ) {
if( mode.dmPelsWidth > mode.dmPelsHeight ) {
orientation = orientLandscape;
} else if( mode.dmPelsWidth < mode.dmPelsHeight ) {
orientation = orientPortrait;
} else {
orientation = orientUnknown;
}
/* dmDisplayOrientation と共有(unionなので)されているので、以下では取得できない
if( mode.dmOrientation == DMORIENT_PORTRAIT ) { // 横
orientation = orientPortrait;
} else if( mode.dmOrientation == DMORIENT_LANDSCAPE ) { // 縦
orientation = orientLandscape;
} else { // unknown
orientation = orientUnknown;
}
*/
switch( mode.dmDisplayOrientation ) {
case DMDO_DEFAULT:
rotate = 0;
break;
case DMDO_90:
rotate = 90;
break;
case DMDO_180:
rotate = 180;
break;
case DMDO_270:
rotate = 270;
break;
default:
rotate = -1;
}
}
return ret != FALSE;
}
void TTVPWindowForm::OnDisplayChange( DWORD bpp, WORD hres, WORD vres ) {
int orient;
int rot;
if( GetOrientation( orient, rot ) ) {
if( DisplayOrientation != orient || DisplayRotate != rot ) {
DisplayOrientation = orient;
DisplayRotate = rot;
OnDisplayRotate( orient, rot, bpp, hres, vres );
}
}
}
void TTVPWindowForm::OnDisplayRotate( int orientation, int rotate, int bpp, int hresolution, int vresolution ) {
if(TJSNativeInstance) {
TVPPostInputEvent( new tTVPOnDisplayRotateInputEvent(TJSNativeInstance, orientation, rotate, bpp, hresolution, vresolution));
}
}
| 29.425887 | 164 | 0.690032 | [
"object",
"vector"
] |
28ac577a4184a13dfda4dc7a40861a3bf3a26c26 | 5,705 | cpp | C++ | Examples/ExampleCreateProfileTypes/CreateAll.cpp | scaredyfish/MPCDI | 1ddbc9abf99d39d4464afa2005934c325443cf28 | [
"BSD-3-Clause"
] | 3 | 2021-03-09T01:57:37.000Z | 2021-05-07T08:40:41.000Z | Examples/ExampleCreateProfileTypes/CreateAll.cpp | scaredyfish/MPCDI | 1ddbc9abf99d39d4464afa2005934c325443cf28 | [
"BSD-3-Clause"
] | 1 | 2021-06-01T07:52:36.000Z | 2021-06-03T00:54:49.000Z | Examples/ExampleCreateProfileTypes/CreateAll.cpp | scaredyfish/MPCDI | 1ddbc9abf99d39d4464afa2005934c325443cf28 | [
"BSD-3-Clause"
] | 4 | 2020-06-22T14:14:15.000Z | 2021-11-11T14:34:42.000Z | /* =========================================================================
Program: MPCDI Library
Language: C++
Date: $Date: 2012-02-08 11:39:41 -0500 (Wed, 08 Feb 2012) $
Version: $Revision: 18341 $
Copyright (c) 2013 Scalable Display Technologies, Inc.
All Rights Reserved.
The MPCDI Library is distributed under the BSD license.
Please see License.txt distributed with this package.
===================================================================auto== */
// .NAME CreateAll - Create one of each of the 4 MPCDI types
// .SECTION Description
//
// .AUTHOR Scalable Display Technologies, Inc.
//
#include "mpcdiWriter.h"
#include "mpcdiCreateProfile.h"
#include "CreateSampleData.h"
#include <iostream>
#define DO_PAUSE
#ifdef DO_PAUSE
# define PAUSE {std::cout<< "Press enter to continue....";std::cin.ignore();}
#else
# definE PAUSE
#endif
/* ====================================================================== */
mpcdi::MPCDI_Error CreateExample2DMedia(mpcdi::Profile *&profile);
mpcdi::MPCDI_Error CreateExample3DSimulation(mpcdi::Profile *&profile);
mpcdi::MPCDI_Error CreateExampleAdvanced3D(mpcdi::Profile *&profile);
mpcdi::MPCDI_Error CreateExampleShaderLamp(mpcdi::Profile *&profile);
mpcdi::MPCDI_Error Write(mpcdi::Profile *Profile,const std::string &FileName);
/* ====================================================================== */
int main( int argc, const char ** argv )
{
mpcdi::Profile *Profile = NULL;
if (MPCDI_FAILED(CreateExample2DMedia(Profile)))
{
std::cout << "Failed to Create 2D Media Profile" << std::endl;
PAUSE;
return mpcdi::MPCDI_FAILURE;
}
std::cout << "Created 2D Media Profile" << std::endl;
MPCDI_FAIL_RET(Write(Profile,"Media2D.mpcdi"));
if (Profile != NULL) { delete Profile; Profile = NULL; }
if (MPCDI_FAILED(CreateExample3DSimulation(Profile)))
{
std::cout << "Failed to Create 3D Simulation Profile" << std::endl;
PAUSE;
return mpcdi::MPCDI_FAILURE;
}
std::cout << "Created 3D Simulation Profile" << std::endl;
MPCDI_FAIL_RET(Write(Profile,"Sim3D.mpcdi"));
if (Profile != NULL) { delete Profile; Profile = NULL; }
if (MPCDI_FAILED(CreateExampleShaderLamp(Profile)))
{
std::cout << "Failed to Create Shader Lamp Profile" << std::endl;
PAUSE;
return mpcdi::MPCDI_FAILURE;
}
std::cout << "Created Shader Lamp Profile" << std::endl;
MPCDI_FAIL_RET(Write(Profile,"ShaderLamp.mpcdi"));
if (Profile != NULL) { delete Profile; Profile = NULL; }
if (MPCDI_FAILED(CreateExampleAdvanced3D(Profile)))
{
std::cout << "Failed to Create Advancde 3D Profile" << std::endl;
PAUSE;
return mpcdi::MPCDI_FAILURE;
}
std::cout << "Created Advanced 3D Profile" << std::endl;
MPCDI_FAIL_RET(Write(Profile,"Advanced3D.mpcdi"));
if (Profile != NULL) { delete Profile; Profile = NULL; }
std::cout << "4 Files Written to Disk." << std::endl;
PAUSE;
return mpcdi::MPCDI_SUCCESS;
}
/* ====================================================================== */
mpcdi::MPCDI_Error Write(mpcdi::Profile *Profile, const std::string &FileName)
{
mpcdi::Writer *writer = mpcdi::Writer::CreateWriter();
mpcdi::MPCDI_Error mpcdi_err = writer->Write(FileName, *Profile);
delete writer;
return mpcdi_err;
}
/* ====================================================================== */
// This is for all of the different profiles.
mpcdi::MPCDI_Error FillInCreatorCommonData(
mpcdi::CreateProfile &ProfileCreator,
const unsigned int &xRes,
const unsigned int &yRes)
{
std::string newBufferId = "buffer1";
std::string newRegionId = "proj1";
mpcdi::ComponentDepth COMPONENT_DEPTH=mpcdi::CD_THREE;
// This next line is optional, 1 is the lowest, so it does not
// do anything really.
ProfileCreator.SetLevel(1);
MPCDI_FAIL_RET(ProfileCreator.CreateNewBuffer(newBufferId));
MPCDI_FAIL_RET(ProfileCreator.CreateNewRegion(newBufferId,newRegionId));
mpcdi::Buffer *buffer = ProfileCreator.GetBuffer(newBufferId);
buffer->SetXresolution(xRes);
buffer->SetYresolution(yRes);
mpcdi::Region *region = ProfileCreator.GetRegion(buffer,newRegionId);
region->SetResolution(xRes,yRes);
region->SetSize(0.9f,0.92f); /* needs to be set but not relevant for this sample */
region->SetX(0.01f);
region->SetY(0.07f);
MPCDI_FAIL_RET(ProfileCreator.CreateAlphaMap(region,
xRes,
yRes,
COMPONENT_DEPTH));
ProfileCreator.SetGammaEmbedded(region,2.2);
MPCDI_FAIL_RET(ProfileCreator.CreateBetaMap(region,
100,100,mpcdi::CD_ONE));
MPCDI_FAIL_RET(ProfileCreator.CreateGeometryWarpFile(region,
xRes,yRes));
// Fill in the data.
mpcdi::AlphaMap *alphaMap = ProfileCreator.GetAlphaMap(region);
for (unsigned int c=0;c<(unsigned int)COMPONENT_DEPTH;c++)
{
DrawRectangle(alphaMap,255,xRes/2,yRes/2,c,
xRes/4+xRes/(1+COMPONENT_DEPTH)*c,
yRes/4+yRes/(1+COMPONENT_DEPTH)*c);
}
// Fill in the data.
mpcdi::BetaMap *betaMap = ProfileCreator.GetBetaMap(region);
mpcdi::GeometryWarpFile *geometryWarpFile =
ProfileCreator.GetGeometryWarpFile(region);
DrawGradientInPFM(geometryWarpFile,0,0,xRes,yRes);
DrawRectangleInPFM(geometryWarpFile,0,0,0,xRes/5,yRes/5);
return mpcdi::MPCDI_SUCCESS;
}
/* ====================================================================== */
| 35.216049 | 85 | 0.601753 | [
"3d"
] |
28af2ff76ecb37d2d49b28b27cbac81af9076dc6 | 20,750 | cpp | C++ | src/mnemonics/electrum-words.cpp | cryptoseyed/ryo-currency | 362ed1b70c82c06a27131aeb1f9ec456df29b8e5 | [
"BSD-3-Clause"
] | null | null | null | src/mnemonics/electrum-words.cpp | cryptoseyed/ryo-currency | 362ed1b70c82c06a27131aeb1f9ec456df29b8e5 | [
"BSD-3-Clause"
] | null | null | null | src/mnemonics/electrum-words.cpp | cryptoseyed/ryo-currency | 362ed1b70c82c06a27131aeb1f9ec456df29b8e5 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2018, Ryo Currency Project
// Portions copyright (c) 2014-2018, The Monero Project
//
// Portions of this file are available under BSD-3 license. Please see ORIGINAL-LICENSE for details
// All rights reserved.
//
// Authors and copyright holders give permission for following:
//
// 1. Redistribution and use in source and binary forms WITHOUT modification.
//
// 2. Modification of the source form for your own personal use.
//
// As long as the following conditions are met:
//
// 3. You must not distribute modified copies of the work to third parties. This includes
// posting the work online, or hosting copies of the modified work for download.
//
// 4. Any derivative version of this work is also covered by this license, including point 8.
//
// 5. Neither the name of the copyright holders nor the names of the authors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// 6. You agree that this licence is governed by and shall be construed in accordance
// with the laws of England and Wales.
//
// 7. You agree to submit all disputes arising out of or in connection with this licence
// to the exclusive jurisdiction of the Courts of England and Wales.
//
// Authors and copyright holders agree that:
//
// 8. This licence expires and the work covered by it is released into the
// public domain on 1st of February 2019
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/*!
* \file electrum-words.cpp
*
* \brief Mnemonic seed generation and wallet restoration from them.
*
* This file and its header file are for translating Electrum-style word lists
* into their equivalent byte representations for cross-compatibility with
* that method of "backing up" one's wallet keys.
*/
#include "mnemonics/electrum-words.h"
#include "crypto/crypto.h" // for declaration of crypto::secret_key
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/crc.hpp>
#include <boost/filesystem.hpp>
#include <boost/locale.hpp>
#include "common/boost_locale.hpp"
#include <cassert>
#include <cstdint>
#include <fstream>
#include <map>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <vector>
#include "chinese_simplified.h"
#include "dutch.h"
#include "english.h"
#include "esperanto.h"
#include "french.h"
#include "german.h"
#include "italian.h"
#include "japanese.h"
#include "language_base.h"
#include "lojban.h"
#include "portuguese.h"
#include "russian.h"
#include "singleton.h"
#include "spanish.h"
/*!
* \namespace crypto
*
* \brief crypto namespace.
*/
namespace crypto
{
// Polynomial chosen using https://users.ece.cmu.edu/~koopman/crc/
// Params width=12 poly=0x987 init=0x000 refin=false refout=false xorout=0x000 check=0xf1a residue=0x000
const uint16_t crc12_table[256] = {
0x000, 0x987, 0xa89, 0x30e, 0xc95, 0x512, 0x61c, 0xf9b, 0x0ad, 0x92a, 0xa24, 0x3a3, 0xc38, 0x5bf, 0x6b1, 0xf36,
0x15a, 0x8dd, 0xbd3, 0x254, 0xdcf, 0x448, 0x746, 0xec1, 0x1f7, 0x870, 0xb7e, 0x2f9, 0xd62, 0x4e5, 0x7eb, 0xe6c,
0x2b4, 0xb33, 0x83d, 0x1ba, 0xe21, 0x7a6, 0x4a8, 0xd2f, 0x219, 0xb9e, 0x890, 0x117, 0xe8c, 0x70b, 0x405, 0xd82,
0x3ee, 0xa69, 0x967, 0x0e0, 0xf7b, 0x6fc, 0x5f2, 0xc75, 0x343, 0xac4, 0x9ca, 0x04d, 0xfd6, 0x651, 0x55f, 0xcd8,
0x568, 0xcef, 0xfe1, 0x666, 0x9fd, 0x07a, 0x374, 0xaf3, 0x5c5, 0xc42, 0xf4c, 0x6cb, 0x950, 0x0d7, 0x3d9, 0xa5e,
0x432, 0xdb5, 0xebb, 0x73c, 0x8a7, 0x120, 0x22e, 0xba9, 0x49f, 0xd18, 0xe16, 0x791, 0x80a, 0x18d, 0x283, 0xb04,
0x7dc, 0xe5b, 0xd55, 0x4d2, 0xb49, 0x2ce, 0x1c0, 0x847, 0x771, 0xef6, 0xdf8, 0x47f, 0xbe4, 0x263, 0x16d, 0x8ea,
0x686, 0xf01, 0xc0f, 0x588, 0xa13, 0x394, 0x09a, 0x91d, 0x62b, 0xfac, 0xca2, 0x525, 0xabe, 0x339, 0x037, 0x9b0,
0xad0, 0x357, 0x059, 0x9de, 0x645, 0xfc2, 0xccc, 0x54b, 0xa7d, 0x3fa, 0x0f4, 0x973, 0x6e8, 0xf6f, 0xc61, 0x5e6,
0xb8a, 0x20d, 0x103, 0x884, 0x71f, 0xe98, 0xd96, 0x411, 0xb27, 0x2a0, 0x1ae, 0x829, 0x7b2, 0xe35, 0xd3b, 0x4bc,
0x864, 0x1e3, 0x2ed, 0xb6a, 0x4f1, 0xd76, 0xe78, 0x7ff, 0x8c9, 0x14e, 0x240, 0xbc7, 0x45c, 0xddb, 0xed5, 0x752,
0x93e, 0x0b9, 0x3b7, 0xa30, 0x5ab, 0xc2c, 0xf22, 0x6a5, 0x993, 0x014, 0x31a, 0xa9d, 0x506, 0xc81, 0xf8f, 0x608,
0xfb8, 0x63f, 0x531, 0xcb6, 0x32d, 0xaaa, 0x9a4, 0x023, 0xf15, 0x692, 0x59c, 0xc1b, 0x380, 0xa07, 0x909, 0x08e,
0xee2, 0x765, 0x46b, 0xdec, 0x277, 0xbf0, 0x8fe, 0x179, 0xe4f, 0x7c8, 0x4c6, 0xd41, 0x2da, 0xb5d, 0x853, 0x1d4,
0xd0c, 0x48b, 0x785, 0xe02, 0x199, 0x81e, 0xb10, 0x297, 0xda1, 0x426, 0x728, 0xeaf, 0x134, 0x8b3, 0xbbd, 0x23a,
0xc56, 0x5d1, 0x6df, 0xf58, 0x0c3, 0x944, 0xa4a, 0x3cd, 0xcfb, 0x57c, 0x672, 0xff5, 0x06e, 0x9e9, 0xae7, 0x360};
inline void update_crc12(uint32_t &crcv, uint8_t data)
{
uint8_t idx = uint8_t((crcv >> 4) ^ data);
crcv = crc12_table[idx] ^ (crcv << 8);
}
uint32_t calc_crc12(const crypto::secret_key_16 &key, uint8_t extra)
{
uint32_t crcv = 0;
for(size_t i = 0; i < 16; i++)
update_crc12(crcv, tools::unwrap(key).data[i]);
update_crc12(crcv, extra);
return crcv & 0xfff;
}
/*!
* \namespace crypto::ElectrumWords
*
* \brief Mnemonic seed word generation and wallet restoration helper functions.
*/
/*!
* \brief Finds the word list that contains the seed words and puts the indices
* where matches occured in matched_indices.
* \param seed List of words to match.
* \param has_checksum The seed has a checksum word (maybe not checked).
* \param matched_indices The indices where the seed words were found are added to this.
* \param language Language instance pointer to write to after it is found.
* \return true if all the words were present in some language false if not.
*/
bool find_seed_language(const std::vector<std::string> &seed, Language::Base **language)
{
// Yes, I don't like std::pair
struct sort_pair
{
Language::Base *inst;
size_t score;
inline bool operator<(const sort_pair &oth) const { return score < oth.score; }
};
// If there's a new language added, add an instance of it here.
std::vector<sort_pair> language_instances({{Language::Singleton<Language::Chinese_Simplified>::instance(), 0},
{Language::Singleton<Language::English>::instance(), 0},
{Language::Singleton<Language::Dutch>::instance(), 0},
{Language::Singleton<Language::French>::instance(), 0},
{Language::Singleton<Language::Spanish>::instance(), 0},
{Language::Singleton<Language::German>::instance(), 0},
{Language::Singleton<Language::Italian>::instance(), 0},
{Language::Singleton<Language::Portuguese>::instance(), 0},
{Language::Singleton<Language::Japanese>::instance(), 0},
{Language::Singleton<Language::Russian>::instance(), 0},
{Language::Singleton<Language::Esperanto>::instance(), 0},
{Language::Singleton<Language::Lojban>::instance(), 0}});
// Assumption here is that the end user will spell more words correctly than get at random in a foreign lang
for(sort_pair &pair : language_instances)
{
const std::unordered_map<std::string, uint32_t> &word_map = pair.inst->get_word_map();
for(const std::string &word : seed)
{
if(word_map.count(word) > 0)
pair.score++;
}
}
std::sort(language_instances.begin(), language_instances.end());
if(language_instances.back().score > 0)
{
*language = language_instances.back().inst;
return true;
}
return false;
}
bool match_words(const Language::Base &lang, const std::vector<std::string> &seed, std::vector<uint32_t> &matched_indices)
{
size_t trim_size = lang.get_unique_prefix_length();
const std::unordered_map<std::string, uint32_t> &trimmed_word_map = lang.get_trimmed_word_map();
matched_indices.reserve(seed.size());
for(const std::string &word : seed)
{
std::string trimmed_word = Language::utf8prefix(word, trim_size);
if(trimmed_word_map.count(trimmed_word) > 0)
matched_indices.push_back(trimmed_word_map.at(trimmed_word));
else
return false;
}
return true;
}
namespace Electrum
{
/*!
* \brief Gets a list of seed languages that are supported.
* \param languages The vector is set to the list of languages.
*/
const std::vector<const Language::Base *> &get_language_list()
{
static const std::vector<const Language::Base *> language_instances({Language::Singleton<Language::German>::instance(),
Language::Singleton<Language::English>::instance(),
Language::Singleton<Language::Spanish>::instance(),
Language::Singleton<Language::French>::instance(),
Language::Singleton<Language::Italian>::instance(),
Language::Singleton<Language::Dutch>::instance(),
Language::Singleton<Language::Portuguese>::instance(),
Language::Singleton<Language::Russian>::instance(),
Language::Singleton<Language::Japanese>::instance(),
Language::Singleton<Language::Chinese_Simplified>::instance(),
Language::Singleton<Language::Esperanto>::instance(),
Language::Singleton<Language::Lojban>::instance()});
return language_instances;
}
void get_language_list(std::vector<std::string> &languages, bool english)
{
const std::vector<const Language::Base *> language_instances = get_language_list();
for(std::vector<const Language::Base *>::const_iterator it = language_instances.begin();
it != language_instances.end(); it++)
{
languages.push_back(english ? (*it)->get_english_language_name() : (*it)->get_language_name());
}
}
std::string get_english_name_for(const std::string &name)
{
const std::vector<const Language::Base *> language_instances = get_language_list();
for(std::vector<const Language::Base *>::const_iterator it = language_instances.begin();
it != language_instances.end(); it++)
{
if((*it)->get_language_name() == name)
return (*it)->get_english_language_name();
}
return "<language not found>";
}
std::string verify_language_input(std::string input)
{
boost_locale_init();
input = boost::locale::to_title(input);
for(const Language::Base* lng : get_language_list())
{
if(lng->get_language_name() == input)
return lng->get_language_name();
if(lng->get_english_language_name() == input)
return lng->get_language_name();
}
return "";
}
}
namespace Electrum14Words
{
bool words_to_bytes(std::string words, crypto::secret_key_16 &dst, uint8_t &extra, std::string &language_name)
{
std::vector<std::string> seed;
boost::algorithm::trim(words);
boost::split(seed, words, boost::is_any_of(" "), boost::token_compress_on);
if(seed.size() != 14 && seed.size() != 12)
return false;
Language::Base *language;
if(!find_seed_language(seed, &language))
return false;
std::vector<uint32_t> matched_indices;
if(!match_words(*language, seed, matched_indices))
return false;
language_name = language->get_language_name();
uint32_t word_list_length = language->get_word_list().size();
uint32_t *out = (uint32_t *)tools::unwrap(dst).data;
for(unsigned int i = 0; i < seed.size() / 3; i++)
{
uint32_t val;
uint32_t w1, w2, w3;
w1 = matched_indices[i * 3];
w2 = matched_indices[i * 3 + 1];
w3 = matched_indices[i * 3 + 2];
val = w1 + word_list_length * (((word_list_length - w1) + w2) % word_list_length) +
word_list_length * word_list_length * (((word_list_length - w2) + w3) % word_list_length);
if(!(val % word_list_length == w1))
return false;
out[i] = val;
}
if(seed.size() == 14)
{
uint32_t val;
uint32_t w1, w2;
w1 = matched_indices[12];
w2 = matched_indices[13];
val = w1 + word_list_length * (((word_list_length - w1) + w2) % word_list_length);
val &= 0xfffff; // 20 bytes
extra = uint8_t(val & 0xff);
val >>= 8;
if(calc_crc12(dst, extra) != val)
return false;
}
return true;
}
bool bytes_to_words(const crypto::secret_key_16 &src, uint8_t extra, std::string &words, const std::string &language_name)
{
const std::vector<const Language::Base *> &lng_insts = Electrum::get_language_list();
const Language::Base *language = nullptr;
for(const Language::Base *b : lng_insts)
{
if(b->get_language_name() == language_name || b->get_english_language_name() == language_name)
{
language = b;
break;
}
}
if(language == nullptr)
return false;
const std::vector<std::string> &word_list = language->get_word_list();
uint32_t word_list_length = word_list.size();
const uint32_t *psrc = (const uint32_t *)tools::unwrap(src).data;
for(unsigned int i = 0; i < 4; i++, words += ' ')
{
uint32_t w1, w2, w3;
uint32_t val = psrc[i];
w1 = val % word_list_length;
w2 = ((val / word_list_length) + w1) % word_list_length;
w3 = (((val / word_list_length) / word_list_length) + w2) % word_list_length;
words += word_list[w1];
words += ' ';
words += word_list[w2];
words += ' ';
words += word_list[w3];
}
uint32_t w1, w2;
uint32_t checksum = calc_crc12(src, extra);
checksum <<= 8;
checksum |= extra;
w1 = checksum % word_list_length;
w2 = ((checksum / word_list_length) + w1) % word_list_length;
words += word_list[w1];
words += ' ';
words += word_list[w2];
return true;
}
}
namespace Electrum25Words
{
/*!
* \brief Creates a checksum index in the word list array on the list of words.
* \param word_list Vector of words
* \param unique_prefix_length the prefix length of each word to use for checksum
* \return Checksum index
*/
uint32_t create_checksum_index(const std::vector<std::string> &word_list, uint32_t unique_prefix_length)
{
std::string trimmed_words = "";
for(std::vector<std::string>::const_iterator it = word_list.begin(); it != word_list.end(); it++)
{
if(it->length() > unique_prefix_length)
{
trimmed_words += Language::utf8prefix(*it, unique_prefix_length);
}
else
{
trimmed_words += *it;
}
}
boost::crc_32_type result;
result.process_bytes(trimmed_words.data(), trimmed_words.length());
return result.checksum() % seed_length;
}
/*!
* \brief Does the checksum test on the seed passed.
* \param seed Vector of seed words
* \param unique_prefix_length the prefix length of each word to use for checksum
* \return True if the test passed false if not.
*/
bool checksum_test(std::vector<std::string> seed, uint32_t unique_prefix_length)
{
if(seed.empty())
return false;
// The last word is the checksum.
std::string last_word = seed.back();
seed.pop_back();
std::string checksum = seed[create_checksum_index(seed, unique_prefix_length)];
std::string trimmed_checksum = checksum.length() > unique_prefix_length ? Language::utf8prefix(checksum, unique_prefix_length) : checksum;
std::string trimmed_last_word = last_word.length() > unique_prefix_length ? Language::utf8prefix(last_word, unique_prefix_length) : last_word;
return trimmed_checksum == trimmed_last_word;
}
/*!
* \brief Converts seed words to bytes (secret key).
* \param words String containing the words separated by spaces.
* \param dst To put the secret data restored from the words.
* \param len The number of bytes to expect, 0 if unknown
* \param duplicate If true and len is not zero, we accept half the data, and duplicate it
* \param language_name Language of the seed as found gets written here.
* \return false if not a multiple of 3 words, or if word is not in the words list
*/
bool words_to_bytes(std::string words, std::string &dst, size_t len, std::string &language_name)
{
std::vector<std::string> seed;
boost::algorithm::trim(words);
boost::split(seed, words, boost::is_any_of(" "), boost::token_compress_on);
if(len % 4)
return false;
if(seed.size() == 26) //Last word is a funky sumo attempt at a second checksum, ignore it
seed.pop_back();
bool has_checksum = true;
if(len)
{
// error on non-compliant word list
const size_t expected = len * 8 * 3 / 32;
if(seed.size() != expected / 2 && seed.size() != expected && seed.size() != expected + 1)
return false;
// If it is seed with a checksum.
has_checksum = seed.size() == (expected + 1);
}
Language::Base *language;
if(!find_seed_language(seed, &language))
return false;
std::vector<uint32_t> matched_indices;
if(!match_words(*language, seed, matched_indices))
return false;
language_name = language->get_language_name();
uint32_t word_list_length = language->get_word_list().size();
if(has_checksum)
{
if(!checksum_test(seed, language->get_unique_prefix_length()))
{
// Checksum fail
return false;
}
seed.pop_back();
}
for(unsigned int i = 0; i < seed.size() / 3; i++)
{
uint32_t val;
uint32_t w1, w2, w3;
w1 = matched_indices[i * 3];
w2 = matched_indices[i * 3 + 1];
w3 = matched_indices[i * 3 + 2];
val = w1 + word_list_length * (((word_list_length - w1) + w2) % word_list_length) +
word_list_length * word_list_length * (((word_list_length - w2) + w3) % word_list_length);
if(!(val % word_list_length == w1))
return false;
dst.append((const char *)&val, 4); // copy 4 bytes to position
}
return true;
}
/*!
* \brief Converts seed words to bytes (secret key).
* \param words String containing the words separated by spaces.
* \param dst To put the secret key restored from the words.
* \param language_name Language of the seed as found gets written here.
* \return false if not a multiple of 3 words, or if word is not in the words list
*/
bool words_to_bytes(std::string words, crypto::secret_key &dst, std::string &language_name)
{
std::string s;
if(!words_to_bytes(words, s, sizeof(dst), language_name))
return false;
if(s.size() != sizeof(dst))
return false;
dst = *(const crypto::secret_key *)s.data();
return true;
}
/*!
* \brief Converts bytes (secret key) to seed words.
* \param src Secret key
* \param words Space delimited concatenated words get written here.
* \param language_name Seed language name
* \return true if successful false if not. Unsuccessful if wrong key size.
*/
bool bytes_to_words(const char *src, size_t len, std::string &words, const std::string &language_name)
{
if(len % 4 != 0 || len == 0)
return false;
const std::vector<const Language::Base *> &lng_insts = Electrum::get_language_list();
const Language::Base *language = nullptr;
for(const Language::Base *b : lng_insts)
{
if(b->get_language_name() == language_name || b->get_english_language_name() == language_name)
{
language = b;
break;
}
}
if(language == nullptr)
return false;
const std::vector<std::string> &word_list = language->get_word_list();
// To store the words for random access to add the checksum word later.
std::vector<std::string> words_store;
uint32_t word_list_length = word_list.size();
// 4 bytes -> 3 words. 8 digits base 16 -> 3 digits base 1626
for(unsigned int i = 0; i < len / 4; i++, words += ' ')
{
uint32_t w1, w2, w3;
uint32_t val;
memcpy(&val, src + (i * 4), 4);
w1 = val % word_list_length;
w2 = ((val / word_list_length) + w1) % word_list_length;
w3 = (((val / word_list_length) / word_list_length) + w2) % word_list_length;
words += word_list[w1];
words += ' ';
words += word_list[w2];
words += ' ';
words += word_list[w3];
words_store.push_back(word_list[w1]);
words_store.push_back(word_list[w2]);
words_store.push_back(word_list[w3]);
}
words.pop_back();
words += (' ' + words_store[create_checksum_index(words_store, language->get_unique_prefix_length())]);
return true;
}
bool bytes_to_words(const crypto::secret_key &src, std::string &words, const std::string &language_name)
{
return bytes_to_words(src.data, sizeof(src), words, language_name);
}
}
}
| 35.229202 | 143 | 0.686458 | [
"vector"
] |
28afa79536abc467e4f1caf77d6373e22a0f81dc | 3,761 | cc | C++ | prob01/recursion.cc | crimsonGnome/121-Lab-07 | 6c6e7f89c9b399169729559331fc10e5cc0c2b60 | [
"MIT"
] | null | null | null | prob01/recursion.cc | crimsonGnome/121-Lab-07 | 6c6e7f89c9b399169729559331fc10e5cc0c2b60 | [
"MIT"
] | null | null | null | prob01/recursion.cc | crimsonGnome/121-Lab-07 | 6c6e7f89c9b399169729559331fc10e5cc0c2b60 | [
"MIT"
] | null | null | null | // Name: Joseph Eggers
// CWID: 885939488
// Email: joseph.eggers@scu.fullerton.edu
#include "recursion.h"
#include <iostream>
#include <string>
#include <vector>
using std::cout, std::endl, std::map, std::string, std::vector;
// In recursion it's normal to have a helper function call the recursive
// function, passing in the appropriate parameters to start the recursion.
// In this case, the Unscramble function should create a helper function which
// is recursive.
void UnscrambleHelper(vector<string>& permutation, string Head, string tail) {
// base Case is 1
if (tail.size() == 0) {
// If the Tail is 0 bush Back Head
permutation.push_back(Head);
}
// recursive Case
for (size_t j = 0; j < tail.size(); j++) {
string tempHead = Head;
string tempTail = tail;
tempHead.push_back(tail[j]);
tempTail.erase(j, 1);
// Call Function Again
UnscrambleHelper(permutation, tempHead, tempTail);
}
}
void ScrabberSolverHelper(vector<string>& permutation, string Head,
string tail) {
// base Case is 1
if (tail.size() == 0) {
// Do nothing since tail = 0 was already pushed
}
// recursive Case
for (size_t j = 0; j < tail.size(); j++) {
string tempHead = Head;
string tempTail = tail;
tempHead.push_back(tail[j]);
tempTail.erase(j, 1);
// Push head of word2
permutation.push_back(tempHead);
// Call Function Again
ScrabberSolverHelper(permutation, tempHead, tempTail);
}
}
void ScrabbleSolverNoDupesHelper(vector<string>& permutation,
map<std::string, bool>& used_words,
string Head, string tail) {
// base Case is 0
if (tail.size() == 0) {
// Do nothing since tail = 0 was already pushed
}
// recursive Case
for (size_t j = 0; j < tail.size(); j++) {
string tempHead = Head;
string tempTail = tail;
tempHead.push_back(tail[j]);
tempTail.erase(j, 1);
// Push head of word
permutation.push_back(tempHead);
used_words.insert(std::pair<string, bool>(tempHead, false));
// Call Function Again
ScrabbleSolverNoDupesHelper(permutation, used_words, tempHead, tempTail);
}
}
void Unscramble(string letters, std::map<std::string, bool>& words) {
// TODO
// Vector Permutation
vector<string> permutation;
UnscrambleHelper(permutation, "", letters);
for (size_t k = 0; k < permutation.size(); k++) {
if (words[permutation[k]]) {
cout << "The word " << permutation[k] << " is in the dictionary!\n";
}
}
}
// Like Unscramble, ScrabbleSolver should create a helper function which is
// is recursive.
void ScrabbleSolver(std::string letters, std::map<std::string, bool>& words) {
// TODO
vector<string> permutation;
// Recursive Function
ScrabberSolverHelper(permutation, "", letters);
for (size_t k = 0; k < permutation.size(); k++) {
if (words[permutation[k]]) {
cout << "The word " << permutation[k] << " is in the dictionary!\n";
}
}
}
// ScrabbleSolverNoDupes needs to keep track of the previous words which were
// found in order not to print them again. Create a recursive helper function to
// recursively unscramble without duplications.
void ScrabbleSolverNoDupes(std::string letters,
std::map<std::string, bool>& words) {
// TODO
vector<string> permutation;
map<std::string, bool> used_words;
// Recursive Function
ScrabbleSolverNoDupesHelper(permutation, used_words, "", letters);
for (size_t k = 0; k < permutation.size(); k++) {
if (words[permutation[k]] && (used_words[permutation[k]] == false)) {
used_words[permutation[k]] = true;
cout << "The word " << permutation[k] << " is in the dictionary!\n";
}
}
}
| 32.145299 | 80 | 0.648764 | [
"vector"
] |
28afe0ec68e0e5a2209a63be92ff9dbea6ccdf92 | 7,304 | cpp | C++ | src/line.cpp | sathyanarayanrao/gimli | 96eda5a99ba642a75801bd359b6ae746c2955d0b | [
"Apache-2.0"
] | null | null | null | src/line.cpp | sathyanarayanrao/gimli | 96eda5a99ba642a75801bd359b6ae746c2955d0b | [
"Apache-2.0"
] | null | null | null | src/line.cpp | sathyanarayanrao/gimli | 96eda5a99ba642a75801bd359b6ae746c2955d0b | [
"Apache-2.0"
] | null | null | null | /******************************************************************************
* Copyright (C) 2008-2018 by the GIMLi development team *
* Carsten Rücker carsten@resistivity.net *
* *
* 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 "line.h"
namespace GIMLI{
std::ostream & operator << (std::ostream & str, const Line & l){
if (l.valid()){
str << "Line: " << l.p0() << "-- " << l.p1() << " ";
} else {
str << "Line: invalid ";
}
return str;
}
Line::Line()
: valid_(false) {
}
Line::Line(const RVector3 & p)
: p1_(p), valid_(false){
p0_[0] = 0.0; p0_[1] = 0.0; p0_[2] = 0.0;
valid_ = false;
checkValidity();
}
Line::Line(const RVector3 & p0, const RVector3 & p1)
: p0_(p0), p1_(p1), valid_(false){
checkValidity();
}
Line::Line(const Line & line){
copy_(line);
}
Line::~Line(){
}
Line & Line::operator = (const Line & line){
if (this != & line){
copy_(line);
}
return *this;
}
void Line::copy_(const Line & line){
p0_ = line.p0();
p1_ = line.p1();
valid_ = line.valid();
}
bool Line::checkValidity(double tol){
if (p0_.distance(p1_) > tol) valid_ = true; else valid_ = false;
return valid_;
}
bool Line::compare(const Line & line, double epsilon) const {
if (this->touch(line.p0()) && this->touch(line.p1())) return true;
else return false;
}
bool Line::intersectRay(const RVector3 & start, const RVector3 & dir,
RVector3 & pos) const {
RVector3 dirN(dir.norm());
RVector3 v1(start - p0_);
RVector3 v2(p1_ - p0_);
RVector3 v3(-dirN[1], dirN[0]);
double d = v2.dot(v3);
if (abs(d) < TOLERANCE) return false;
// same like below // double t1 = -v1.cross(v2)[2] / d;
double t1 = (v2[0] * v1[1] - v1[0] * v2[1]) / d;
double t2 = v1.dot(v3) / d;
if (t1 >= 0.0 && t2 >= 0.0 && t2 <= 1.0) {
pos = start + t1 * dirN;
return true;
}
return false;
}
RVector3 Line::intersect(const RVector3 & start, const RVector3 & dir) const{
RVector3 p;
if (!this->intersectRay(start, dir, p)){
p.setValid(false);
}
return p;
}
RVector3 Line::intersect(const Line & line) const {
THROW_TO_IMPL
//check parallel and equal
//** in 3D: wenn sie sich ber�hren spannen sie eine Ebene auf.
// x0 + s * x1 = x2 + t * x3;
// x0 - x2 = t * x3 - s * x1;
// RVector3 x0(this->p0_);
// RVector3 x1(this->p1_ - this->p0_);
//
// RVector3 x2(line.p0());
// RVector3 x3(line.p1() - line.p0());
//
// RVector3 b(x0 - x2);
// STLMatrix A(3, 2);
// A.setColumn(0, -1.0 * x1);
// A.setColumn(1, x3);
//RVector3 st(3);
//** simple check if 2D
/* if (x1[2] == 0.0 && x3[2] == 0.0){
MyVec::STLVector b2(2);
b2[0] = b[0];
b2[1] = b[1];
MyVec::STLMatrix A2(2, 2);
A2[0][0] = A[0][0]; A2[1][0] = A[1][0];
A2[0][1] = A[0][1]; A2[1][1] = A[1][1];
solveLU(A2, st, b2);
// cout << A2 << endl;
// cout << b2[0] << " " << b2[1] << endl;
} else {
// L1 = P1 + a V1
// L2 = P2 + b V2
// a (V1 X V2) = (P2 - P1) X V2
RVector3 P1(this->p0());
RVector3 V1(this->p1() - this->p0());
RVector3 P2(line.p0());
RVector3 V2(line.p1() - line.p0());
double a = (P2-P1).cross(V2).abs() / V1.cross(V2).abs();
if (!isnan(a) && !isnan(a)){
return RVector3(P1 + V1 * a);
}
solveLU(A, st, b);*/
// cout << A << endl;
// cout << st[0] << " " << st[1] << endl;
// cout << b[0] << " " << b[1] << " " << b[3] << endl;
// }
// double s = st[0];
// double t = st[1];
//
// if (isnan(s) || isinf(s) || isnan(t) || isinf(t)) {
// // cout << WHERE_AM_I << " s: " << s << " t: " << t << endl;
// return RVector3();
// }
//
//RVector3 iPos(x0 + x1 * s);
//
// if (line.touch(iPos) < 0){
// //cout << WHERE_AM_I << " touch: " << line.touch(iPos) << endl;
return RVector3();
// }
// return iPos;
}
double Line::nearest(const RVector3 & p) const{
/* double t = ((p.x - p0_.x) * (p1_.x - p0_.x)) +
((p.y - p0_.y) * (p1_.y - p0_.y)) +
((p.z - p0_.z) * (p1_.z - p2_.z))*/
return (p-p0_).dot(p1_-p0_)/p1_.distSquared(p0_);
}
double Line::distance(const RVector3 & pos) const {
// cout << p1_ << p0_ << pos << endl;
//cout << p1_ - p0_ << endl;
//cout << (p1_ - p0_).cross(p0_ -pos) << endl;
//cout << "ret " << ((p1_ - p0_).cross(p0_ - pos)).abs() / (p1_ - p0_).abs() << endl;
return ((p1_ - p0_).cross(p0_ - pos)).abs() / (p1_ - p0_).abs();
}
double Line::t(const RVector3 & pos, double tol) const {
RVector3 t(RVector3((pos - p0_).round(tol) / (p1_ - p0_).round(tol)));
// cout << tol << endl;
// cout << (pos - p0_).round(tol) << (p1_ - p0_).round(tol) << endl;
// cout << RVector3((pos - p0_) / (p1_ - p0_)) << endl;
// cout << WHERE_AM_I << t << endl;
if (!isnan(t[0]) && !isinf(t[0])) return t[0];
else if (!isnan(t[1]) && !isinf(t[1])) return t[1];
else if (!isnan(t[2]) && !isinf(t[2])) return t[2];
throwError(1, WHERE_AM_I + " pos is not at this line ");
return 0.0;
}
bool Line::touch(const RVector3 & pos, double tol) const {
if (this->distance(pos) > tol) return false;
return true;
}
bool Line::touch1(const RVector3 & pos, int & pFunIdx, double tol) const{
bool verbose = false;
if (verbose) std::cout << pos << tol << std::endl;
if (verbose) std::cout << "Dist = " << std::fabs(this->distance(pos)) << std::endl;
double length = p0_.distance(p1_);
double dist = std::fabs(this->distance(pos));
if (length > 1) tol*= length;
if (dist > (tol) * 10) {
if (verbose) std::cout << "dist:" << dist << " length: " << length << " > " << "tol: " << (tol) * 10 << std::endl;
pFunIdx = -1;
return false;
}
// cout << "next" <<endl;
if ((dist) < tol) dist = tol;
double tsol = this->t(pos, dist);
if (verbose) std::cout << p0_ << pos << p1_ << "Tsol: " << tsol << std::endl;
if (std::fabs(tsol) < tol) pFunIdx = 2;
if (tsol < 0) pFunIdx = 1;
if (std::fabs(1 - tsol) < tol) pFunIdx = 4;
if (tsol > 1) pFunIdx = 5;
pFunIdx = 3;
return true;
}
} // namespace GIMLI
| 29.216 | 122 | 0.484803 | [
"3d"
] |
28b0e74fe1df2fcb03a75b5a92bf41849fcacb23 | 10,656 | cpp | C++ | src/bitmap.cpp | kanait/MeshToSS | 815a99a4e9e73f8410f32498882f5e2b51d7ce03 | [
"MIT"
] | null | null | null | src/bitmap.cpp | kanait/MeshToSS | 815a99a4e9e73f8410f32498882f5e2b51d7ce03 | [
"MIT"
] | null | null | null | src/bitmap.cpp | kanait/MeshToSS | 815a99a4e9e73f8410f32498882f5e2b51d7ce03 | [
"MIT"
] | 1 | 2021-03-16T12:43:21.000Z | 2021-03-16T12:43:21.000Z | //
// Bitmap.cpp
//
// Copyright (c) 2000 IPA and Keio University SFC Research Institution
//
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
//
#include "StdAfx.h"
//#include "MainFrm.h"
#include "gl\gl.h"
#include "../optmesh/smd.h"
#include "screen.h"
#include "draw.h"
#include "bitmap.h"
BOOL SetupPixelFormat(HDC hDC, CPalette **ppCPalette, DWORD dwFlags, int bpp)
{
PIXELFORMATDESCRIPTOR pfd = {
sizeof(PIXELFORMATDESCRIPTOR), // size of pfd structure
1, // version number
dwFlags,
PFD_TYPE_RGBA, // use RGBA
bpp, // depth of color buffer : 24-bit
0, 0, 0, 0, 0, 0, // specify color bits (ignore)
0, // no alpha plane
0, // specify alpha bits (ignore)
0, // no accumulation buffer
0, 0, 0, 0, // specify accumulation bits (ignore)
16, // z-buffer depth
0, // no stencil buffer
0, // no aux buffer
PFD_MAIN_PLANE, // main plane only
0, // reserved
0, 0, 0 // layer masks ignored
};
int pixelformat;
if ( (pixelformat = ChoosePixelFormat(hDC, &pfd)) == 0 ) {
TRACE("ChoosePixelFormat failed : %d\n", pfd.cColorBits);
return FALSE;
}
DescribePixelFormat(hDC, pixelformat,
sizeof(PIXELFORMATDESCRIPTOR), &pfd);
if (!SetPixelFormat(hDC, pixelformat, &pfd)) {
TRACE("SetPixelFormat failed: %d , %d, %d\n",
pixelformat, pfd.cColorBits, bpp);
return FALSE;
}
if (pfd.dwFlags & PFD_NEED_PALETTE) {
TRACE("Yes, Palette Required\n");
if (!CreateRGBPalette(hDC, ppCPalette)) {
*ppCPalette = NULL;
TRACE("CreateRGBPalette Error\n");
}
} else {
*ppCPalette = NULL;
TRACE("No Palette Required\n");
}
return TRUE;
}
///////////////////////////////////////////////////
// BMP File Utility Function
void setupBmpHeader(BITMAPINFOHEADER *pbmih, int sx, int sy, int bpp)
{
pbmih->biSize = sizeof(BITMAPINFOHEADER);
pbmih->biWidth = sx;
pbmih->biHeight = sy;
pbmih->biPlanes = 1;
pbmih->biBitCount = bpp;
pbmih->biCompression = BI_RGB;
pbmih->biSizeImage = sx * sy * (bpp/8);
pbmih->biXPelsPerMeter = 2925;
pbmih->biYPelsPerMeter = 2925;
pbmih->biClrUsed = 0;
pbmih->biClrImportant = 0;
}
///////////////////////////////////////////////////
// Palette Utility Functions
static unsigned char threeto8[8] = {
0, 0111>>1, 0222>>1, 0333>>1, 0444>>1, 0555>>1, 0666>>1, 0377
};
static unsigned char twoto8[4] = {
0, 0x55, 0xaa, 0xff
};
static unsigned char oneto8[2] = {
0, 255
};
static int defaultOverride[13] = {
0, 3, 24, 27, 64, 67, 88, 173, 181, 236, 247, 164, 91
};
static PALETTEENTRY defaultPalEntry[20] = {
{ 0, 0, 0, 0 },
{ 0x80,0, 0, 0 },
{ 0, 0x80,0, 0 },
{ 0x80,0x80,0, 0 },
{ 0, 0, 0x80, 0 },
{ 0x80,0, 0x80, 0 },
{ 0, 0x80,0x80, 0 },
{ 0xC0,0xC0,0xC0, 0 },
{ 192, 220, 192, 0 },
{ 166, 202, 240, 0 },
{ 255, 251, 240, 0 },
{ 160, 160, 164, 0 },
{ 0x80,0x80,0x80, 0 },
{ 0xFF,0, 0, 0 },
{ 0, 0xFF,0, 0 },
{ 0xFF,0xFF,0, 0 },
{ 0, 0, 0xFF, 0 },
{ 0xFF,0, 0xFF, 0 },
{ 0, 0xFF,0xFF, 0 },
{ 0xFF,0xFF,0xFF, 0 }
};
static unsigned char
ComponentFromIndex(int i, UINT nbits, UINT shift)
{
unsigned char val;
val = (unsigned char) (i >> shift);
switch (nbits) {
case 1:
val &= 0x1;
return oneto8[val];
case 2:
val &= 0x3;
return twoto8[val];
case 3:
val &= 0x7;
return threeto8[val];
default:
return 0;
}
}
BOOL CreateRGBPalette(HDC hDC, CPalette **ppCPalette)
{
// HPALETTE ghPalette;
PIXELFORMATDESCRIPTOR pfd;
LOGPALETTE *pPal;
int n, i;
n = GetPixelFormat(hDC);
DescribePixelFormat(hDC, n, sizeof(PIXELFORMATDESCRIPTOR), &pfd);
if (!(pfd.dwFlags & PFD_NEED_PALETTE)) return FALSE;
n = 1 << pfd.cColorBits;
pPal = (PLOGPALETTE)LocalAlloc(LMEM_FIXED, sizeof(LOGPALETTE) +
n * sizeof(PALETTEENTRY));
pPal->palVersion = 0x300;
pPal->palNumEntries = n;
for (i=0; i<n; i++) {
pPal->palPalEntry[i].peRed =
ComponentFromIndex(i, pfd.cRedBits, pfd.cRedShift);
pPal->palPalEntry[i].peGreen =
ComponentFromIndex(i, pfd.cGreenBits, pfd.cGreenShift);
pPal->palPalEntry[i].peBlue =
ComponentFromIndex(i, pfd.cBlueBits, pfd.cBlueShift);
pPal->palPalEntry[i].peFlags = 0;
}
/* fix up the palette to include the default GDI palette */
if ((pfd.cColorBits == 8) &&
(pfd.cRedBits == 3) && (pfd.cRedShift == 0) &&
(pfd.cGreenBits == 3) && (pfd.cGreenShift == 3) &&
(pfd.cBlueBits == 2) && (pfd.cBlueShift == 6)
) {
for (i = 1 ; i <= 12 ; i++)
pPal->palPalEntry[defaultOverride[i]] = defaultPalEntry[i];
}
if (*ppCPalette) delete *ppCPalette;
*ppCPalette = new CPalette;
BOOL result = (*ppCPalette)->CreatePalette(pPal);
LocalFree(pPal);
return result;
}
void BmpSave(TCHAR *bmpFileName, ScreenAtr *screen)
{
unsigned char *oglImage;
CFile *pbmpFile;
CFileException fileException;
pbmpFile = new CFile;
if (!pbmpFile->Open(bmpFileName ,
CFile::modeCreate | CFile::modeWrite ) ) {
TRACE( "Unable to open file : %s\n, error = %u\n",
bmpFileName ,fileException.m_cause );
}
// TRACE("cx, cy = %d, %d\n", screen->width, screen->height);
int dwSizeImage = screen->width * screen->height * 4;
oglImage = (unsigned char *)malloc(dwSizeImage);
// read RGB data from OpenGL RGB plane
oglGetImage(screen->width, screen->height, oglImage);
// set up BMP header
BITMAPFILEHEADER bmfh;
BITMAPINFOHEADER bmih;
bmfh.bfType = 0x4d42; // 'BM'
int nSize = sizeof(BITMAPINFOHEADER) + dwSizeImage;
bmfh.bfSize = nSize + sizeof(BITMAPFILEHEADER);
::setupBmpHeader(&bmih, screen->width, screen->height, 32);
bmfh.bfReserved1 = bmfh.bfReserved2 = 0;
bmfh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
// Writing the RGBA image
TRY
{
pbmpFile->Write((LPVOID) &bmfh, sizeof(BITMAPFILEHEADER));
pbmpFile->Write((LPVOID) &bmih, sizeof(BITMAPINFOHEADER));
pbmpFile->Write((LPVOID) oglImage, dwSizeImage);
}
CATCH (CException, e)
{
AfxMessageBox( (LPTSTR)"write error");
return;
}
END_CATCH
pbmpFile->Close();
delete pbmpFile;
free(oglImage);
}
void oglGetImage(int sx, int sy, unsigned char *pixels)
{
::glFinish(); /* Finish all OpenGL commands */
::glPixelStorei(GL_PACK_ALIGNMENT, 4); /* Force 4-byte alignment */
::glPixelStorei(GL_PACK_ROW_LENGTH, 0);
::glPixelStorei(GL_PACK_SKIP_ROWS, 0);
::glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
#ifdef GL_VERSION_1_1
::glReadPixels(0, 0, sx, sy, GL_BGRA_EXT, GL_UNSIGNED_BYTE, pixels);
#else
::glReadPixels(0, 0, sx, sy, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
unsigned char *buf = pixels;
unsigned char *bufmax = pixels + sx*sy*4;
unsigned char r;
for (; buf < bufmax; buf += 4) {
r = buf[0];
buf[0] = buf[2];
buf[2] = r;
}
#endif
}
void DibSave(TCHAR *bmpFileName, ScreenAtr *screen)
{
LPVOID lpBits;
CDC *pDC = screen->wnd->GetDC();
ASSERT(pDC->m_hDC);
// Creating Compatible Memory Device Context
CDC *pMemDC = new CDC;
if (!pMemDC->CreateCompatibleDC(pDC)) {
AfxMessageBox( (LPTSTR)"CompatibleDC Error");
return;
}
// Preparing bitmap header for DIB section
BITMAPINFO bi;
int bpp, sx, sy;
ZeroMemory(&bi, sizeof(BITMAPINFO));
// Making a DIB image which is half size of GL window and full color(24 bpp)
// sx = m_size.cx/2;
// sy = m_size.cy/2;
sx = screen->width;
sy = screen->height;
bpp = 24;
int dwSizeImage = sx * sy * bpp / 8; // 8 means 8 bit/byte
setupBmpHeader(&(bi.bmiHeader), sx, sy, bpp);
// Creating a DIB surface
HBITMAP hBm, hBmOld;
hBm = CreateDIBSection(pDC->GetSafeHdc(), &bi, DIB_RGB_COLORS,
(void **)&lpBits, NULL, (DWORD)0);
if (!hBm) {
AfxMessageBox( (LPTSTR)"CreateDIBSection Error");
return;
}
// Selecting the DIB Surface
hBmOld = (HBITMAP)::SelectObject(pMemDC->GetSafeHdc(), hBm);
if (!hBmOld) {
AfxMessageBox( (LPTSTR)"Select Object Error");
return;
}
// Setting up a Pixel format for the DIB surface and Making a palette
CPalette* pMemCPal; //Palette
if (!SetupPixelFormat(pMemDC->m_hDC, &pMemCPal,
PFD_DRAW_TO_BITMAP |
PFD_SUPPORT_OPENGL |
PFD_SUPPORT_GDI,
bpp) ) {
AfxMessageBox( (LPTSTR)"SetPixelFormatError");
}
// Realize the palette, if required
if (pMemCPal) {
CPalette* pOldPal = pMemDC->SelectPalette(pMemCPal, FALSE);
UINT u = pMemDC->RealizePalette();
//if (u != 0) InvalidateRect(NULL, TRUE);
if (u != 0) {
screen->wnd->RedrawWindow();
}
}
// Creating a OpenGL context
HGLRC hmemrc = wglCreateContext(pMemDC->GetSafeHdc());
if (!hmemrc) {
AfxMessageBox( (LPTSTR)"OpenGL Context Error");
}
// Setting up the current OpenGL context
if (!wglMakeCurrent(pMemDC->GetSafeHdc(), hmemrc)) {
AfxMessageBox( (LPTSTR)"Error");
TRACE("wglMakeCurrent Failed %d\r\n", GetLastError());;
return;
}
// OpenGL Rendering
init_gl3d();
clear_gl3d( screen );
::glPushMatrix();
view_init( screen );
//::glPushMatrix();
draws3d( screen );
::glPopMatrix();
::glFinish();
if ( ::SwapBuffers( pDC->GetSafeHdc() ) == FALSE ) {
// SetError(7);
}
// Preparing BMP file header information
BITMAPFILEHEADER bmfh;
bmfh.bfType = 0x4d42; // 'BM'
int nSize = sizeof(BITMAPINFOHEADER) + dwSizeImage;
bmfh.bfSize = nSize + sizeof(BITMAPFILEHEADER);
bmfh.bfReserved1 = bmfh.bfReserved2 = 0;
bmfh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
//char *bmpFileName = "test2.bmp"; // sorry for hard coding
CFile *pbmpFile;
CFileException fileException;
pbmpFile = new CFile;
if (!pbmpFile->Open( bmpFileName,
CFile::modeCreate | CFile::modeWrite ) ) {
TRACE( "Unable to open file: %s\n, error = %u\n",
bmpFileName ,fileException.m_cause);
}
// Wrinting the DIB image
TRY {
pbmpFile->Write( (LPVOID) &bmfh, sizeof(BITMAPFILEHEADER) );
pbmpFile->Write( (LPVOID) &(bi.bmiHeader), sizeof(BITMAPINFOHEADER) );
pbmpFile->Write( (LPVOID) lpBits, dwSizeImage );
}
CATCH (CException, e) {
AfxMessageBox( (LPTSTR)"write error");
return;
}
END_CATCH
// Cleaning
pbmpFile->Close();
delete pbmpFile;
wglMakeCurrent(NULL, NULL);
wglDeleteContext( hmemrc );
hBm = (HBITMAP)::SelectObject(pMemDC->GetSafeHdc(), hBmOld);
DeleteObject(hBm);
if (pMemCPal != 0) delete pMemCPal;
delete pMemDC;
screen->wnd->ReleaseDC( pDC );
}
| 25.492823 | 78 | 0.624906 | [
"object"
] |
28b52692da06bef4daea723bed48ec8300f8c1ce | 17,866 | cpp | C++ | Libraries/LibGUI/GAbstractColumnView.cpp | gla3dr/serenity | 4d6968f95dc15b81e7a2138283c7fc133e00ed71 | [
"BSD-2-Clause"
] | null | null | null | Libraries/LibGUI/GAbstractColumnView.cpp | gla3dr/serenity | 4d6968f95dc15b81e7a2138283c7fc133e00ed71 | [
"BSD-2-Clause"
] | null | null | null | Libraries/LibGUI/GAbstractColumnView.cpp | gla3dr/serenity | 4d6968f95dc15b81e7a2138283c7fc133e00ed71 | [
"BSD-2-Clause"
] | null | null | null | #include <AK/StringBuilder.h>
#include <LibGUI/GAbstractColumnView.h>
#include <LibGUI/GAction.h>
#include <LibGUI/GMenu.h>
#include <LibGUI/GPainter.h>
#include <LibGUI/GScrollBar.h>
static const int minimum_column_width = 2;
GAbstractColumnView::GAbstractColumnView(GWidget* parent)
: GAbstractView(parent)
{
set_frame_shape(FrameShape::Container);
set_frame_shadow(FrameShadow::Sunken);
set_frame_thickness(2);
set_should_hide_unnecessary_scrollbars(true);
}
GAbstractColumnView::~GAbstractColumnView()
{
}
void GAbstractColumnView::update_column_sizes()
{
if (!m_size_columns_to_fit_content)
return;
if (!model())
return;
auto& model = *this->model();
int column_count = model.column_count();
int row_count = model.row_count();
for (int column = 0; column < column_count; ++column) {
if (is_column_hidden(column))
continue;
int header_width = header_font().width(model.column_name(column));
int column_width = header_width;
for (int row = 0; row < row_count; ++row) {
auto cell_data = model.data(model.index(row, column));
int cell_width = 0;
if (cell_data.is_bitmap()) {
cell_width = cell_data.as_bitmap().width();
} else {
cell_width = font().width(cell_data.to_string());
}
column_width = max(column_width, cell_width);
}
auto& column_data = this->column_data(column);
column_data.width = max(column_data.width, column_width);
column_data.has_initialized_width = true;
}
}
void GAbstractColumnView::update_content_size()
{
if (!model())
return set_content_size({});
int content_width = 0;
int column_count = model()->column_count();
for (int i = 0; i < column_count; ++i) {
if (!is_column_hidden(i))
content_width += column_width(i) + horizontal_padding() * 2;
}
int content_height = item_count() * item_height();
set_content_size({ content_width, content_height });
set_size_occupied_by_fixed_elements({ 0, header_height() });
}
Rect GAbstractColumnView::header_rect(int column_index) const
{
if (!model())
return {};
if (is_column_hidden(column_index))
return {};
int x_offset = 0;
for (int i = 0; i < column_index; ++i) {
if (is_column_hidden(i))
continue;
x_offset += column_width(i) + horizontal_padding() * 2;
}
return { x_offset, 0, column_width(column_index) + horizontal_padding() * 2, header_height() };
}
void GAbstractColumnView::set_hovered_header_index(int index)
{
if (m_hovered_column_header_index == index)
return;
m_hovered_column_header_index = index;
update_headers();
}
void GAbstractColumnView::paint_headers(GPainter& painter)
{
if (!headers_visible())
return;
int exposed_width = max(content_size().width(), width());
painter.fill_rect({ 0, 0, exposed_width, header_height() }, Color::WarmGray);
painter.draw_line({ 0, 0 }, { exposed_width - 1, 0 }, Color::White);
painter.draw_line({ 0, header_height() - 1 }, { exposed_width - 1, header_height() - 1 }, Color::MidGray);
int x_offset = 0;
int column_count = model()->column_count();
for (int column_index = 0; column_index < column_count; ++column_index) {
if (is_column_hidden(column_index))
continue;
int column_width = this->column_width(column_index);
bool is_key_column = model()->key_column() == column_index;
Rect cell_rect(x_offset, 0, column_width + horizontal_padding() * 2, header_height());
bool pressed = column_index == m_pressed_column_header_index && m_pressed_column_header_is_pressed;
bool hovered = column_index == m_hovered_column_header_index && model()->column_metadata(column_index).sortable == GModel::ColumnMetadata::Sortable::True;
StylePainter::paint_button(painter, cell_rect, ButtonStyle::Normal, pressed, hovered);
String text;
if (is_key_column) {
StringBuilder builder;
builder.append(model()->column_name(column_index));
auto sort_order = model()->sort_order();
if (sort_order == GSortOrder::Ascending)
builder.append(" \xc3\xb6");
else if (sort_order == GSortOrder::Descending)
builder.append(" \xc3\xb7");
text = builder.to_string();
} else {
text = model()->column_name(column_index);
}
auto text_rect = cell_rect.translated(horizontal_padding(), 0);
if (pressed)
text_rect.move_by(1, 1);
painter.draw_text(text_rect, text, header_font(), TextAlignment::CenterLeft, Color::Black);
x_offset += column_width + horizontal_padding() * 2;
}
}
bool GAbstractColumnView::is_column_hidden(int column) const
{
return !column_data(column).visibility;
}
void GAbstractColumnView::set_column_hidden(int column, bool hidden)
{
auto& column_data = this->column_data(column);
if (column_data.visibility == !hidden)
return;
column_data.visibility = !hidden;
update_content_size();
update();
}
GMenu& GAbstractColumnView::ensure_header_context_menu()
{
// FIXME: This menu needs to be rebuilt if the model is swapped out,
// or if the column count/names change.
if (!m_header_context_menu) {
ASSERT(model());
m_header_context_menu = GMenu::construct();
for (int column = 0; column < model()->column_count(); ++column) {
auto& column_data = this->column_data(column);
auto name = model()->column_name(column);
column_data.visibility_action = GAction::create(name, [this, column](GAction& action) {
action.set_checked(!action.is_checked());
set_column_hidden(column, !action.is_checked());
});
column_data.visibility_action->set_checkable(true);
column_data.visibility_action->set_checked(true);
m_header_context_menu->add_action(*column_data.visibility_action);
}
}
return *m_header_context_menu;
}
const Font& GAbstractColumnView::header_font()
{
return Font::default_bold_font();
}
void GAbstractColumnView::set_cell_painting_delegate(int column, OwnPtr<GTableCellPaintingDelegate>&& delegate)
{
column_data(column).cell_painting_delegate = move(delegate);
}
void GAbstractColumnView::update_headers()
{
Rect rect { 0, 0, frame_inner_rect().width(), header_height() };
rect.move_by(frame_thickness(), frame_thickness());
update(rect);
}
GAbstractColumnView::ColumnData& GAbstractColumnView::column_data(int column) const
{
if (column >= m_column_data.size())
m_column_data.resize(column + 1);
return m_column_data.at(column);
}
Rect GAbstractColumnView::column_resize_grabbable_rect(int column) const
{
if (!model())
return {};
auto header_rect = this->header_rect(column);
return { header_rect.right() - 1, header_rect.top(), 4, header_rect.height() };
}
int GAbstractColumnView::column_width(int column_index) const
{
if (!model())
return 0;
auto& column_data = this->column_data(column_index);
if (!column_data.has_initialized_width) {
ASSERT(!m_size_columns_to_fit_content);
column_data.has_initialized_width = true;
column_data.width = model()->column_metadata(column_index).preferred_width;
}
return column_data.width;
}
void GAbstractColumnView::mousemove_event(GMouseEvent& event)
{
if (!model())
return;
if (m_in_column_resize) {
auto delta = event.position() - m_column_resize_origin;
int new_width = m_column_resize_original_width + delta.x();
if (new_width <= minimum_column_width)
new_width = minimum_column_width;
ASSERT(m_resizing_column >= 0 && m_resizing_column < model()->column_count());
auto& column_data = this->column_data(m_resizing_column);
if (column_data.width != new_width) {
column_data.width = new_width;
dbg() << "New column width: " << new_width;
update_content_size();
update();
}
return;
}
if (m_pressed_column_header_index != -1) {
auto header_rect = this->header_rect(m_pressed_column_header_index);
if (header_rect.contains(event.position())) {
if (!m_pressed_column_header_is_pressed)
update_headers();
m_pressed_column_header_is_pressed = true;
} else {
if (m_pressed_column_header_is_pressed)
update_headers();
m_pressed_column_header_is_pressed = false;
}
return;
}
if (event.buttons() == 0) {
int column_count = model()->column_count();
bool found_hovered_header = false;
for (int i = 0; i < column_count; ++i) {
if (column_resize_grabbable_rect(i).contains(event.position())) {
window()->set_override_cursor(GStandardCursor::ResizeHorizontal);
set_hovered_header_index(-1);
return;
}
if (header_rect(i).contains(event.position())) {
set_hovered_header_index(i);
found_hovered_header = true;
}
}
if (!found_hovered_header)
set_hovered_header_index(-1);
}
window()->set_override_cursor(GStandardCursor::None);
}
void GAbstractColumnView::mouseup_event(GMouseEvent& event)
{
auto adjusted_position = this->adjusted_position(event.position());
if (event.button() == GMouseButton::Left) {
if (m_in_column_resize) {
if (!column_resize_grabbable_rect(m_resizing_column).contains(adjusted_position))
window()->set_override_cursor(GStandardCursor::None);
m_in_column_resize = false;
}
if (m_pressed_column_header_index != -1) {
auto header_rect = this->header_rect(m_pressed_column_header_index);
if (header_rect.contains(event.position())) {
auto new_sort_order = GSortOrder::Ascending;
if (model()->key_column() == m_pressed_column_header_index)
new_sort_order = model()->sort_order() == GSortOrder::Ascending
? GSortOrder::Descending
: GSortOrder::Ascending;
model()->set_key_column_and_sort_order(m_pressed_column_header_index, new_sort_order);
}
m_pressed_column_header_index = -1;
m_pressed_column_header_is_pressed = false;
update_headers();
}
}
}
void GAbstractColumnView::mousedown_event(GMouseEvent& event)
{
if (!model())
return;
if (event.button() != GMouseButton::Left)
return;
if (event.y() < header_height()) {
int column_count = model()->column_count();
for (int i = 0; i < column_count; ++i) {
if (column_resize_grabbable_rect(i).contains(event.position())) {
m_resizing_column = i;
m_in_column_resize = true;
m_column_resize_original_width = column_width(i);
m_column_resize_origin = event.position();
return;
}
auto header_rect = this->header_rect(i);
auto column_metadata = model()->column_metadata(i);
if (header_rect.contains(event.position()) && column_metadata.sortable == GModel::ColumnMetadata::Sortable::True) {
m_pressed_column_header_index = i;
m_pressed_column_header_is_pressed = true;
update_headers();
return;
}
}
return;
}
bool is_toggle;
auto index = index_at_event_position(event.position(), is_toggle);
if (!index.is_valid()) {
selection().clear();
return;
}
if (is_toggle && model()->row_count(index)) {
toggle_index(index);
return;
}
if (event.modifiers() & Mod_Ctrl)
selection().toggle(index);
else
selection().set(index);
}
GModelIndex GAbstractColumnView::index_at_event_position(const Point& position, bool& is_toggle) const
{
is_toggle = false;
if (!model())
return {};
auto adjusted_position = this->adjusted_position(position);
for (int row = 0, row_count = model()->row_count(); row < row_count; ++row) {
if (!row_rect(row).contains(adjusted_position))
continue;
for (int column = 0, column_count = model()->column_count(); column < column_count; ++column) {
if (!content_rect(row, column).contains(adjusted_position))
continue;
return model()->index(row, column);
}
return model()->index(row, 0);
}
return {};
}
int GAbstractColumnView::item_count() const
{
if (!model())
return 0;
return model()->row_count();
}
void GAbstractColumnView::keydown_event(GKeyEvent& event)
{
if (!model())
return;
auto& model = *this->model();
if (event.key() == KeyCode::Key_Return) {
selection().for_each_index([this](auto& index) {
activate(index);
});
return;
}
if (event.key() == KeyCode::Key_Up) {
GModelIndex new_index;
if (!selection().is_empty()) {
auto old_index = selection().first();
new_index = model.index(old_index.row() - 1, old_index.column());
} else {
new_index = model.index(0, 0);
}
if (model.is_valid(new_index)) {
selection().set(new_index);
scroll_into_view(new_index, Orientation::Vertical);
update();
}
return;
}
if (event.key() == KeyCode::Key_Down) {
GModelIndex new_index;
if (!selection().is_empty()) {
auto old_index = selection().first();
new_index = model.index(old_index.row() + 1, old_index.column());
} else {
new_index = model.index(0, 0);
}
if (model.is_valid(new_index)) {
selection().set(new_index);
scroll_into_view(new_index, Orientation::Vertical);
update();
}
return;
}
if (event.key() == KeyCode::Key_PageUp) {
int items_per_page = visible_content_rect().height() / item_height();
auto old_index = selection().first();
auto new_index = model.index(max(0, old_index.row() - items_per_page), old_index.column());
if (model.is_valid(new_index)) {
selection().set(new_index);
scroll_into_view(new_index, Orientation::Vertical);
update();
}
return;
}
if (event.key() == KeyCode::Key_PageDown) {
int items_per_page = visible_content_rect().height() / item_height();
auto old_index = selection().first();
auto new_index = model.index(min(model.row_count() - 1, old_index.row() + items_per_page), old_index.column());
if (model.is_valid(new_index)) {
selection().set(new_index);
scroll_into_view(new_index, Orientation::Vertical);
update();
}
return;
}
return GWidget::keydown_event(event);
}
void GAbstractColumnView::scroll_into_view(const GModelIndex& index, Orientation orientation)
{
auto rect = row_rect(index.row()).translated(0, -header_height());
GScrollableWidget::scroll_into_view(rect, orientation);
}
void GAbstractColumnView::doubleclick_event(GMouseEvent& event)
{
if (!model())
return;
if (event.button() == GMouseButton::Left) {
if (event.y() < header_height())
return;
if (!selection().is_empty()) {
if (is_editable()) {
begin_editing(selection().first());
} else {
selection().for_each_index([this](auto& index) {
activate(index);
});
}
}
}
}
void GAbstractColumnView::context_menu_event(GContextMenuEvent& event)
{
if (!model())
return;
if (event.position().y() < header_height()) {
ensure_header_context_menu().popup(event.screen_position());
return;
}
bool is_toggle;
auto index = index_at_event_position(event.position(), is_toggle);
if (index.is_valid()) {
if (!selection().contains(index))
selection().set(index);
} else {
selection().clear();
}
if (on_context_menu_request)
on_context_menu_request(index, event);
}
void GAbstractColumnView::leave_event(CEvent&)
{
window()->set_override_cursor(GStandardCursor::None);
set_hovered_header_index(-1);
}
Rect GAbstractColumnView::content_rect(int row, int column) const
{
auto row_rect = this->row_rect(row);
int x = 0;
for (int i = 0; i < column; ++i)
x += column_width(i) + horizontal_padding() * 2;
return { row_rect.x() + x, row_rect.y(), column_width(column) + horizontal_padding() * 2, item_height() };
}
Rect GAbstractColumnView::content_rect(const GModelIndex& index) const
{
return content_rect(index.row(), index.column());
}
Rect GAbstractColumnView::row_rect(int item_index) const
{
return { 0, header_height() + (item_index * item_height()), max(content_size().width(), width()), item_height() };
}
Point GAbstractColumnView::adjusted_position(const Point& position) const
{
return position.translated(horizontal_scrollbar().value() - frame_thickness(), vertical_scrollbar().value() - frame_thickness());
}
void GAbstractColumnView::did_update_model()
{
GAbstractView::did_update_model();
update_column_sizes();
update_content_size();
update();
}
| 33.965779 | 162 | 0.623531 | [
"model"
] |
28b676193a2311503061a39c86c0ae52469d6ae9 | 5,043 | hpp | C++ | third_party/knightking/test_node2vec.hpp | madsys-dev/flashmob | 1ac0542ef10e2ee31f2c7d587b8c8d3376e98c80 | [
"MIT"
] | 10 | 2021-09-26T05:14:45.000Z | 2022-02-28T20:32:15.000Z | third_party/knightking/test_node2vec.hpp | flashmobwalk/flashmob | 1ac0542ef10e2ee31f2c7d587b8c8d3376e98c80 | [
"MIT"
] | null | null | null | third_party/knightking/test_node2vec.hpp | flashmobwalk/flashmob | 1ac0542ef10e2ee31f2c7d587b8c8d3376e98c80 | [
"MIT"
] | 2 | 2022-01-19T08:02:14.000Z | 2022-02-18T01:42:28.000Z | /**
* Code in this file are adapted from:
* https://github.com/KnightKingWalk/KnightKing/blob/master/src/tests/test_node2vec.cpp
*
*/
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ke Yang, Tsinghua University
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <utility>
#include <map>
#include <set>
#include <gtest/gtest.h>
#include "type.hpp"
#include "log.hpp"
#include "test_walk.hpp"
void get_node2vec_trans_matrix(vertex_id_t v_num, Edge *edges, edge_id_t e_num, double p, double q, std::vector<std::vector<double> > &trans_mat)
{
std::vector<std::vector<Edge> > graph(v_num);
for (edge_id_t e_i = 0; e_i < e_num; e_i++)
{
graph[edges[e_i].src].push_back(edges[e_i]);
}
for (vertex_id_t v_i = 0; v_i < v_num; v_i++)
{
std::sort(graph[v_i].begin(), graph[v_i].end(), [](const Edge a, const Edge b){return a.dst < b.dst;});
}
for (edge_id_t e_i = 0; e_i < e_num; e_i++)
{
vertex_id_t src = edges[e_i].src;
vertex_id_t dst = edges[e_i].dst;
assert(src != dst);
//must be undirected graph
assert(graph[dst].size() != 0);
for (auto e : graph[dst])
{
if (e.dst == src)
{
trans_mat[e_i][e.dst] += 1 / p; // * get_edge_trans_weight(e);
} else if (std::binary_search(graph[src].begin(), graph[src].end(), e, [](const Edge a, const Edge b){return a.dst < b.dst;}))
{
trans_mat[e_i][e.dst] += 1; // * get_edge_trans_weight(e);
} else
{
trans_mat[e_i][e.dst] += 1 / q; // * get_edge_trans_weight(e);
}
}
}
mat_normalization(trans_mat);
}
void check_node2vec_random_walk(vertex_id_t v_num, Edge *edges, edge_id_t e_num, double p, double q, vertex_id_t *walks, walker_id_t walker_num, int walk_len)
{
std::vector<std::vector<double> > trans_mat(e_num);
for (auto &vec : trans_mat)
{
vec.resize(v_num, 0.0);
}
get_node2vec_trans_matrix(v_num, edges, e_num, p, q, trans_mat);
//check if sequences are legal
std::vector<vertex_id_t> out_degree(v_num, 0);
std::vector<std::vector<bool> > adj_mat(v_num);
for (auto &vec : adj_mat)
{
vec.resize(v_num, false);
}
for (edge_id_t e_i = 0; e_i < e_num; e_i++)
{
adj_mat[edges[e_i].src][edges[e_i].dst] = true;
out_degree[edges[e_i].src]++;
}
for (walker_id_t w_i = 0; w_i < walker_num; w_i++)
{
/*
if (out_degree[s[0]] == 0)
{
for (auto v : s)
{
ASSERT_EQ(v, s[0]);
}
} else
*/
auto *path = walks + w_i * walk_len;
for (int p_i = 0; p_i + 1 < walk_len; p_i++)
{
if (adj_mat[path[p_i]][path[p_i + 1]] == false)
{
printf("fault %u %u\n", path[p_i], path[p_i + 1]);
}
ASSERT_TRUE(adj_mat[path[p_i]][path[p_i + 1]]);
}
}
std::map<std::pair<vertex_id_t, vertex_id_t>, edge_id_t> dict;
for (edge_id_t e_i = 0; e_i < e_num; e_i++)
{
// printf("%u %u\n", edges[e_i].src, edges[e_i].dst);
std::pair<vertex_id_t, vertex_id_t> key = std::pair<vertex_id_t, vertex_id_t>(edges[e_i].src, edges[e_i].dst);
assert(dict.find(key) == dict.end());
dict[key] = e_i;
}
std::vector<std::vector<double> > real_trans_mat(e_num);
for (auto &vec : real_trans_mat)
{
vec.resize(v_num, 0.0);
}
for (walker_id_t w_i = 0; w_i < walker_num; w_i++)
{
auto *path = walks + w_i * walk_len;
for (int p_i = 0; p_i + 2 < walk_len; p_i++)
{
real_trans_mat[dict[std::pair<vertex_id_t, vertex_id_t>(path[p_i], path[p_i + 1])]][path[p_i + 2]] += 1;
}
}
mat_normalization(real_trans_mat);
cmp_trans_matrix(real_trans_mat, trans_mat, 10.0);
} | 33.845638 | 158 | 0.60004 | [
"vector"
] |
28b966117155026e06b8fa4369e5d8e2841b9d12 | 3,334 | cpp | C++ | Json/JsonNode.cpp | DeanoBurrito/Amendieres | fc391087944f54ba62a08af3996f070e3bed5924 | [
"BSL-1.0"
] | 1 | 2021-07-16T12:14:49.000Z | 2021-07-16T12:14:49.000Z | Json/JsonNode.cpp | DeanoBurrito/Amendieres | fc391087944f54ba62a08af3996f070e3bed5924 | [
"BSL-1.0"
] | 4 | 2021-07-08T01:43:19.000Z | 2021-07-21T16:35:42.000Z | Json/JsonNode.cpp | DeanoBurrito/Amendieres | fc391087944f54ba62a08af3996f070e3bed5924 | [
"BSL-1.0"
] | null | null | null | #include "JsonNode.h"
namespace Amendieres
{
int IndexFromPath(const std::string& path)
{
try
{
int index = std::atoi(path.c_str());
return index;
}
catch ( ... )
{
return -1;
}
return -1;
}
bool JsonNode::Exists(const std::string& path) const
{
return Find(path) != nullptr;
}
JsonNode* JsonNode::Find(const std::string& path) const
{
std::string remainder = "";
std::string identifier = path;
auto delimPos = path.find('/');
if (delimPos != std::string::npos)
{
remainder = path.substr(delimPos + 1);
identifier = path.substr(0, delimPos);
}
//if path started with '/', run recursively with remainder of path
if (identifier.size() == 0)
return Find(remainder);
if (type == JsonNodeType::Object)
{
const JsonObject* thisObj = static_cast<const JsonObject*>(this);
for (auto member : thisObj->members)
{
if (member->name.compare(identifier) == 0)
{
//indentity matches
if (remainder.size() > 0)
return member->value->Find(remainder);
else
return member->value;
}
}
}
else if (type == JsonNodeType::Array)
{
const JsonArray* thisArray = static_cast<const JsonArray*>(this);
int index = IndexFromPath(identifier);
//path was either not a number, or is an invalid index, head home.
if (index < 0 || index >= thisArray->elements.size())
return nullptr;
if (remainder.size() > 0)
return thisArray->elements[index]->Find(remainder);
else
return thisArray->elements[index];
}
return nullptr; //path cannot be continued or does not exist
}
JsonObjectMember::JsonObjectMember(std::string nName, JsonNode* nValue)
{
type = JsonNodeType::ObjectMember;
name = nName;
value = nValue;
}
JsonObjectMember::~JsonObjectMember()
{
delete value;
}
JsonObject::JsonObject(std::vector<JsonObjectMember*> nMembers)
{
type = JsonNodeType::Object;
members = nMembers;
}
JsonObject::~JsonObject()
{
for (auto member : members)
delete member;
}
JsonArray::JsonArray(std::vector<JsonNode*> nElements)
{
type = JsonNodeType::Array;
elements = nElements;
}
JsonArray::~JsonArray()
{
for (auto element : elements)
delete element;
}
JsonString::JsonString(std::string nValue)
{
type = JsonNodeType::String;
value = nValue;
}
JsonNumberFloat::JsonNumberFloat(float nValue)
{
type = JsonNodeType::NumberFloat;
value = nValue;
}
JsonNumberInt::JsonNumberInt(int64_t nValue)
{
type = JsonNodeType::NumberInt;
value = nValue;
}
JsonBool::JsonBool(bool nValue)
{
type = JsonNodeType::Bool;
value = nValue;
}
} | 25.257576 | 78 | 0.517097 | [
"object",
"vector"
] |
28bb54d76206ecf8b2f267671561d14fcfe9d01c | 1,111 | cpp | C++ | data/count_min_sketch.cpp | vasiliykarasev/dungeon | 0ea62593ec68ddb0069ef5d79356a1245d4364d5 | [
"MIT"
] | null | null | null | data/count_min_sketch.cpp | vasiliykarasev/dungeon | 0ea62593ec68ddb0069ef5d79356a1245d4364d5 | [
"MIT"
] | null | null | null | data/count_min_sketch.cpp | vasiliykarasev/dungeon | 0ea62593ec68ddb0069ef5d79356a1245d4364d5 | [
"MIT"
] | null | null | null | #include "data/count_min_sketch.h"
#include <glog/logging.h>
namespace dungeon {
CountMinSketch::CountMinSketch(size_t num_hash_functions, size_t table_size)
: num_hash_functions_(num_hash_functions), table_size_(table_size) {
CHECK_GT(num_hash_functions_, 0);
CHECK_GT(table_size_, 0);
counts_ = std::vector<std::vector<size_t>>(
num_hash_functions_, std::vector<size_t>(table_size_, 0));
}
void CountMinSketch::Add(const std::string& key) {
std::hash<std::string> hasher;
for (size_t i = 0; i < num_hash_functions_; ++i) {
size_t digest = hasher(key + std::to_string(i)) % table_size_;
counts_[i][digest]++;
}
}
size_t CountMinSketch::Count(const std::string& key) const {
std::hash<std::string> hasher;
size_t output = std::numeric_limits<size_t>::max();
for (size_t i = 0; i < num_hash_functions_; ++i) {
size_t digest = hasher(key + std::to_string(i)) % table_size_;
output = std::min(output, counts_[i][digest]);
}
return output;
}
const std::vector<std::vector<size_t>>& CountMinSketch::counts() const {
return counts_;
}
} // namespace dungeon
| 28.487179 | 76 | 0.69847 | [
"vector"
] |
28bed57067c8dd072c4521a3dc60ac658bd49754 | 6,787 | hpp | C++ | core/blockchain/impl/block_tree_impl.hpp | iceseer/kagome | a405921659cc19e9fdb851e5f13f1e607fdf8af4 | [
"Apache-2.0"
] | null | null | null | core/blockchain/impl/block_tree_impl.hpp | iceseer/kagome | a405921659cc19e9fdb851e5f13f1e607fdf8af4 | [
"Apache-2.0"
] | null | null | null | core/blockchain/impl/block_tree_impl.hpp | iceseer/kagome | a405921659cc19e9fdb851e5f13f1e607fdf8af4 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef KAGOME_BLOCK_TREE_IMPL_HPP
#define KAGOME_BLOCK_TREE_IMPL_HPP
#include "blockchain/block_tree.hpp"
#include <boost/optional.hpp>
#include <functional>
#include <memory>
#include <queue>
#include <unordered_set>
#include "blockchain/block_header_repository.hpp"
#include "blockchain/block_storage.hpp"
#include "blockchain/impl/common.hpp"
#include "common/logger.hpp"
#include "crypto/hasher.hpp"
#include "network/extrinsic_observer.hpp"
#include "transaction_pool/transaction_pool.hpp"
namespace kagome::blockchain {
/**
* Block tree implementation
*/
class BlockTreeImpl : public BlockTree {
/**
* In-memory light representation of the tree, used for efficiency and usage
* convenience - we would only ask the database for some info, when directly
* requested
*/
struct TreeNode : public std::enable_shared_from_this<TreeNode> {
TreeNode(primitives::BlockHash hash,
primitives::BlockNumber depth,
const std::shared_ptr<TreeNode> &parent,
bool finalized = false);
primitives::BlockHash block_hash;
primitives::BlockNumber depth;
std::weak_ptr<TreeNode> parent;
bool finalized;
std::vector<std::shared_ptr<TreeNode>> children{};
/**
* Get a node of the tree, containing block with the specified hash, if it
* can be found
*/
std::shared_ptr<TreeNode> getByHash(const primitives::BlockHash &hash);
bool operator==(const TreeNode &other) const;
bool operator!=(const TreeNode &other) const;
};
/**
* Useful information about the tree & blocks it contains to make some of
* the operations faster
*/
struct TreeMeta {
explicit TreeMeta(TreeNode &subtree_root_node);
TreeMeta(std::unordered_set<primitives::BlockHash> leaves,
TreeNode &deepest_leaf,
TreeNode &last_finalized);
std::unordered_set<primitives::BlockHash> leaves;
std::reference_wrapper<TreeNode> deepest_leaf;
std::reference_wrapper<TreeNode> last_finalized;
};
public:
enum class Error {
// target block number is past the given maximum number
TARGET_IS_PAST_MAX = 1,
// block resides on a dead fork
BLOCK_ON_DEAD_END,
// block exists in chain but not found when following all
// leaves backwards.
BLOCK_NOT_FOUND
};
/**
* Create an instance of block tree
* @param header_repo - block headers repository
* @param storage - block storage for the tree to be put in
* @param last_finalized_block - last finalized block, from which the tree
* is going to grow
* @param hasher - pointer to the hasher
* @return ptr to the created instance or error
*/
static outcome::result<std::shared_ptr<BlockTreeImpl>> create(
std::shared_ptr<BlockHeaderRepository> header_repo,
std::shared_ptr<BlockStorage> storage,
const primitives::BlockId &last_finalized_block,
std::shared_ptr<network::ExtrinsicObserver> extrinsic_observer,
std::shared_ptr<crypto::Hasher> hasher);
~BlockTreeImpl() override = default;
outcome::result<primitives::BlockHeader> getBlockHeader(
const primitives::BlockId &block) const override;
outcome::result<primitives::BlockBody> getBlockBody(
const primitives::BlockId &block) const override;
outcome::result<primitives::Justification> getBlockJustification(
const primitives::BlockId &block) const override;
outcome::result<void> addBlockHeader(
const primitives::BlockHeader &header) override;
outcome::result<void> addBlock(const primitives::Block &block) override;
outcome::result<void> addBlockBody(
primitives::BlockNumber block_number,
const primitives::BlockHash &block_hash,
const primitives::BlockBody &body) override;
outcome::result<void> finalize(
const primitives::BlockHash &block,
const primitives::Justification &justification) override;
BlockHashVecRes getChainByBlock(
const primitives::BlockHash &block) override;
BlockHashVecRes getChainByBlock(const primitives::BlockHash &block,
bool ascending,
uint64_t maximum) override;
BlockHashVecRes getChainByBlocks(
const primitives::BlockHash &top_block,
const primitives::BlockHash &bottom_block) override;
BlockHashVecRes longestPath() override;
primitives::BlockInfo deepestLeaf() const override;
outcome::result<primitives::BlockInfo> getBestContaining(
const primitives::BlockHash &target_hash,
const boost::optional<primitives::BlockNumber> &max_number)
const override;
std::vector<primitives::BlockHash> getLeaves() const override;
BlockHashVecRes getChildren(const primitives::BlockHash &block) override;
primitives::BlockInfo getLastFinalized() const override;
private:
/**
* Private constructor, so that instances are created only through the
* factory method
*/
BlockTreeImpl(
std::shared_ptr<BlockHeaderRepository> header_repo,
std::shared_ptr<BlockStorage> storage,
std::shared_ptr<TreeNode> tree,
std::shared_ptr<TreeMeta> meta,
std::shared_ptr<network::ExtrinsicObserver> extrinsic_observer,
std::shared_ptr<crypto::Hasher> hasher);
/**
* Walks the chain backwards starting from \param start until the current
* block number is less or equal than \param limit
*/
outcome::result<primitives::BlockHash> walkBackUntilLess(
const primitives::BlockHash &start,
const primitives::BlockNumber &limit) const;
/**
* @returns the tree leaves sorted by their depth
*/
std::vector<primitives::BlockHash> getLeavesSorted() const;
static void collectDescendants(
std::shared_ptr<TreeNode> node,
std::vector<std::pair<primitives::BlockHash, primitives::BlockNumber>>
&container);
outcome::result<void> prune(
const std::shared_ptr<TreeNode> &lastFinalizedNode);
std::shared_ptr<BlockHeaderRepository> header_repo_;
std::shared_ptr<BlockStorage> storage_;
std::shared_ptr<TreeNode> tree_;
std::shared_ptr<TreeMeta> tree_meta_;
std::shared_ptr<network::ExtrinsicObserver> extrinsic_observer_;
std::shared_ptr<crypto::Hasher> hasher_;
common::Logger log_ = common::createLogger("BlockTreeImpl");
};
} // namespace kagome::blockchain
OUTCOME_HPP_DECLARE_ERROR(kagome::blockchain, BlockTreeImpl::Error);
#endif // KAGOME_BLOCK_TREE_IMPL_HPP
| 33.269608 | 80 | 0.692353 | [
"vector"
] |
28c132db3de3a47b3bd52b3cdee4d67bc1f7289b | 2,268 | cpp | C++ | source/Core/Castor3D/Shader/Ubos/HdrConfigUbo.cpp | Mu-L/Castor3D | 7b9c6e7be6f7373ad60c0811d136c0004e50e76b | [
"MIT"
] | null | null | null | source/Core/Castor3D/Shader/Ubos/HdrConfigUbo.cpp | Mu-L/Castor3D | 7b9c6e7be6f7373ad60c0811d136c0004e50e76b | [
"MIT"
] | null | null | null | source/Core/Castor3D/Shader/Ubos/HdrConfigUbo.cpp | Mu-L/Castor3D | 7b9c6e7be6f7373ad60c0811d136c0004e50e76b | [
"MIT"
] | null | null | null | #include "Castor3D/Shader/Ubos/HdrConfigUbo.hpp"
#include "Castor3D/Engine.hpp"
#include "Castor3D/Buffer/UniformBufferPools.hpp"
#include "Castor3D/Render/RenderSystem.hpp"
#include "Castor3D/Render/ToneMapping/HdrConfig.hpp"
#include <ShaderWriter/Source.hpp>
namespace castor3d
{
//*********************************************************************************************
namespace shader
{
HdrConfigData::HdrConfigData( sdw::ShaderWriter & writer
, ast::expr::ExprPtr expr
, bool enabled )
: StructInstance{ writer, std::move( expr ), enabled }
, m_exposure{ getMember< sdw::Float >( "exposure" ) }
, m_gamma{ getMember< sdw::Float >( "gamma" ) }
{
}
ast::type::BaseStructPtr HdrConfigData::makeType( ast::type::TypesCache & cache )
{
auto result = cache.getStruct( ast::type::MemoryLayout::eStd140
, "C3D_HdrConfigData" );
if ( result->empty() )
{
result->declMember( "exposure", ast::type::Kind::eFloat );
result->declMember( "gamma", ast::type::Kind::eFloat );
}
return result;
}
std::unique_ptr< sdw::Struct > HdrConfigData::declare( sdw::ShaderWriter & writer )
{
return std::make_unique< sdw::Struct >( writer
, makeType( writer.getTypesCache() ) );
}
sdw::Vec3 HdrConfigData::removeGamma( sdw::Vec3 const & sRGB )const
{
return pow( max( sRGB, vec3( 0.0_f, 0.0_f, 0.0_f ) ), vec3( m_gamma ) );
}
sdw::Vec3 HdrConfigData::applyGamma( sdw::Vec3 const & hdr )const
{
return pow( max( hdr, vec3( 0.0_f, 0.0_f, 0.0_f ) ), vec3( 1.0_f / m_gamma ) );
}
}
//*********************************************************************************************
castor::String const HdrConfigUbo::BufferHdrConfig = cuT( "HdrConfig" );
castor::String const HdrConfigUbo::HdrConfigData = cuT( "c3d_hdrConfigData" );
HdrConfigUbo::HdrConfigUbo( RenderDevice const & device )
: m_device{ device }
, m_ubo{ m_device.uboPools->getBuffer< Configuration >( VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT ) }
{
}
HdrConfigUbo::~HdrConfigUbo()
{
m_device.uboPools->putBuffer( m_ubo );
}
void HdrConfigUbo::cpuUpdate( HdrConfig const & config )
{
CU_Require( m_ubo );
auto & data = m_ubo.getData();
data.exposure = config.exposure;
data.gamma = config.gamma;
}
}
| 28.35 | 97 | 0.622134 | [
"render"
] |
28c48ab7cfd754a881aa1316e1eeb150fa025820 | 10,577 | hpp | C++ | src/ivorium_graphics/Rendering/FlatShader.hpp | ivorne/ivorium | 1d876b6dcabe29b3110d3058f997e59c40cd6a2b | [
"Apache-2.0"
] | 3 | 2021-02-26T02:59:09.000Z | 2022-02-08T16:44:21.000Z | src/ivorium_graphics/Rendering/FlatShader.hpp | ivorne/ivorium | 1d876b6dcabe29b3110d3058f997e59c40cd6a2b | [
"Apache-2.0"
] | null | null | null | src/ivorium_graphics/Rendering/FlatShader.hpp | ivorne/ivorium | 1d876b6dcabe29b3110d3058f997e59c40cd6a2b | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "Shader.hpp"
#include "Texture.hpp"
#include "CameraState.hpp"
#include "GlSystem.hpp"
#include "../OpenGL/GlMesh.hpp"
#include "../OpenGL/RenderTarget.hpp"
#include <ivorium_systems/ivorium_systems.hpp>
#include <ivorium_core/ivorium_core.hpp>
namespace iv
{
class FlatShader_Subprovider
{
public:
ClientMarker cm;
FlatShader_Subprovider( Instance * inst, VirtualResourceProvider const * );
void each_resource( std::function< void( ResourcePath const & ) > const & ) const;
bool has_resource( ResourcePath const & ) const;
//
Instance * instance() const;
private:
Instance * inst;
};
struct ShaderScissor
{
float4x4 model;
float3 size;
bool enabled;
//ShaderScissor() : model( ( memset( this, 0, sizeof( ShaderScissor ) ), 1 ) ), size( 0, 0, 0 ), enabled( false ){}
ShaderScissor() : model( 1 ), size( 0, 0, 0 ), enabled( false ){}
ShaderScissor( ShaderScissor const & right ) :
//model( ( memset( this, 0, sizeof( ShaderScissor ) ), right.model ) ),
model( right.model ),
size( right.size ),
enabled( right.enabled )
{}
ShaderScissor const & operator*( ShaderScissor const & right ) const
{
return right.enabled ? right : *this;
}
ShaderScissor & operator*=( ShaderScissor const & right )
{
if( right.enabled )
*this = right;
return *this;
}
bool operator==( ShaderScissor const & right ) const
{
if( !this->enabled && !right.enabled )
return true;
return std::tuple( this->enabled, this->model, this->size ) == std::tuple( right.enabled, right.model, right.size );
}
};
class FlatShader : private GlListener
{
public:
enum class FittingStage
{
None
};
enum class PixelizeStage
{
None,
Squares,
Circles
};
enum class ResizeStage
{
Scale,
Fixed,
Repeat,
Frame
};
enum class FilteringStage
{
Plain,
Msdf,
AlphaThreshold,
AlphaThresholdWidth,
AlphaThresholdWidthSmooth ///< Similar to AlphaThresholdWidth, but only center of active alpha range will be fully visible, the farther from center, the lower alpha the fragment will have.
};
struct Params
{
Params( iv::ClientMarker * owner ) :
fittingStage( FittingStage::None ),
pixelizeStage( PixelizeStage::None ), pixelizeSize( owner, float2( 1, 1 ) ), pixelizeOffset( owner, float2( 0, 0 ) ),
resizeStage( ResizeStage::Scale ), resizeAnchor( owner, float2( 0, 0 ) ),
filteringStage( FilteringStage::Plain ), filteringAlphaThreshold( owner, 0 ), filteringAlphaWidth( owner, 0 ),
alpha( owner, 1.0f ),
colorTransform( owner, float4x4( 1.0f ) )
{}
// fitting stage
FittingStage fittingStage;
// pixelize stage
PixelizeStage pixelizeStage;
DirtyAttr< float2 > pixelizeSize; ///< In coordinates after texture resizing (texture_resize parameter in Render method).
DirtyAttr< float2 > pixelizeOffset; ///< In coordinates after texture resizing (texture_resize parameter in Render method).
// resize stage
ResizeStage resizeStage;
DirtyAttr< float2 > resizeAnchor;
// filtering stage
FilteringStage filteringStage;
DirtyAttr< float > filteringAlphaThreshold; ///< If used by filtering_stage, everything with alpha below 0.5 will be always hidden (to not affect smoothing). Pixels between 0.5 and 1.0 will be visible depending on alpha_threshold value, pixels with higher alpha will be visible longer (when transitioning from alpha_threshold 0 to alpha_threshold 1).
DirtyAttr< float > filteringAlphaWidth; ///< Tells use the range of alpha values of texture pixels that will be visible with AlphaThreshold* filtering.
// alpha stage
DirtyAttr< float > alpha;
// color stage
DirtyAttr< float4x4 > colorTransform;
};
public:
ClientMarker cm;
using GlInfo::instance;
FlatShader( Instance * inst, VirtualResourceProvider const *, FlatShader_Subprovider const *, ResourcePath const & path );
/**
Contains 0 if shader is not currently loaded into gpu (gpu is disabled).
*/
GLuint program_id() const;
/**
\param log_target
\param target
\param camera
\param mesh
\param mesh_resize
Resizes input mesh.
Moves all vertices by multiplying their position by this parameter.
This scales the texture if the texture_resize stays the same.
If we scale texture_resize simultaneously with vertex_pos_mul, then the texture render is just resized (not relevant for ResizeStage::Scale, because that one scales either way).
\param mesh_texcoord_density
How many texcoords there are on average per distance of 1 in position units (mesh local units).
Used in pixelize stage and maybe in Msdf for smoothing, not needed in other cases.
NOTE - This should probably be float3 and should be texel density in three dimensions of the mesh. It wouldn't change nothing in 2D meshes, but will make more sense and might be somewhat useful on 3D meshes. But there is no need until we can test it on something that is in fact useful.
\param texture
\param texture_density_rel
texture density / screen density
\param texture_msdf_pixelRange
Used when FilteringStage is msdf.
\param preblend
Alpha is usualy 0 to skip preblending or 255 to apply preblending.
Values in between will apply partial preblending, which can possibly be used as a visual effect (very subtle glow on smoothed renders).
All translucent texels are blended on top given preblend color.
\param translucent
Translucent pixels that were not solidified with preblend will be solidified (alpha set to 1 or discard) according to Params::alpha parameter.
\param model
\param scissor
\param params
*/
void Render(
ClientMarker const & log_target,
// Renderable
CameraState const & camera,
std::optional< float > depth_override,
// Elem
float4x4 const & model,
ShaderScissor const & scissor,
// Translucent
float4 preblend,
bool translucent,
// mesh
GlMesh const * mesh,
float3 mesh_resize,
float2 mesh_texcoord_density,
// texture
GlTexture const * texture,
float texture_density_rel,
float texture_msdf_pixelRange,
// parametrization
Params const & params
) const;
private:
virtual void GlEnable() override;
virtual void GlDisable() override;
virtual void GlDrop() override;
private:
Shader _shader;
// mesh
GLint mesh_resize;
GLint mesh_texcoord_density;
// texture
GLint tex0;
GLint tex0_size;
GLint tex0_density_rel;
GLint tex0_color_space;
// translucent
GLint translucent;
GLint preblend;
// space transform
GLint projection_view_model;
GLint local_to_pixel_space;
GLint pixel_to_local_space;
GLint depth_override_enabled;
GLint depth_override;
// scissor
GLint scissor_enabled;
GLint local_to_scissor_space;
GLint scissor_size;
// shader params - fitting stage
GLint fitting_stage;
// shader params - pixelize stage
GLint pixelize_stage;
GLint pixelize_size;
GLint pixelize_offset;
// shader params - resize stage
GLint resize_stage;
GLint resize_anchor;
// shader params - filtering stage
GLint filtering_stage;
GLint filtering_msdf_pixel_range;
GLint filtering_alpha_threshold;
GLint filtering_alpha_width;
// shader params - color stage
GLint color_transform;
// shader params - alpha stage
GLint alpha;
//
GLint framebuffer_color_space;
};
/**
*/
class FlatShader_Resource : public SingularResource< FlatShader >
{
public:
using SingularResource< FlatShader >::instance;
ClientMarker cm;
FlatShader_Resource( Instance * inst );
};
//=========================================================================================================
//--------------------------- StringIO --------------------------------------------------------------------
template<>
struct StringIO< FlatShader::FittingStage > : public StringIO_Table< FlatShader::FittingStage >
{
static const ValuesType Values;
};
template<>
struct StringIO< FlatShader::PixelizeStage > : public StringIO_Table< FlatShader::PixelizeStage >
{
static const ValuesType Values;
};
template<>
struct StringIO< FlatShader::ResizeStage > : public StringIO_Table< FlatShader::ResizeStage >
{
static const ValuesType Values;
};
template<>
struct StringIO< FlatShader::FilteringStage > : public StringIO_Table< FlatShader::FilteringStage >
{
static const ValuesType Values;
};
}
| 33.577778 | 366 | 0.560178 | [
"mesh",
"render",
"model",
"transform",
"3d"
] |
28c7e0f127aca6f728aa7fe16aae8c338c12558c | 89,824 | cxx | C++ | PWGDQ/dielectron/core/AliAnalysisTaskTagAndProbe.cxx | ilyafokin/AliPhysics | 7a0021a9d7ad4f0a9e52e0a13f9d3ca3b74c63d4 | [
"BSD-3-Clause"
] | null | null | null | PWGDQ/dielectron/core/AliAnalysisTaskTagAndProbe.cxx | ilyafokin/AliPhysics | 7a0021a9d7ad4f0a9e52e0a13f9d3ca3b74c63d4 | [
"BSD-3-Clause"
] | null | null | null | PWGDQ/dielectron/core/AliAnalysisTaskTagAndProbe.cxx | ilyafokin/AliPhysics | 7a0021a9d7ad4f0a9e52e0a13f9d3ca3b74c63d4 | [
"BSD-3-Clause"
] | 1 | 2022-01-24T11:11:09.000Z | 2022-01-24T11:11:09.000Z | #include "TChain.h"
#include "TTree.h"
#include "TObjArray.h"
#include "TClonesArray.h"
#include "TF1.h"
#include "TH1.h"
#include "TH2.h"
#include "TH3.h"
#include "TLorentzVector.h"
#include "TParticle.h"
#include "THnSparse.h"
#include "THashList.h"
#include "TMath.h"
#include "AliAnalysisManager.h"
#include "AliAnalysisTaskSE.h"
#include "AliLog.h"
#include "AliESDtrackCuts.h"
#include "AliESDHeader.h"
#include "AliESDEvent.h"
#include "AliESDVertex.h"
#include "AliESDtrack.h"
#include "AliESDv0KineCuts.h"
#include "AliVEvent.h"
#include "AliVHeader.h"
#include "AliVTrack.h"
#include "AliMultSelection.h"
#include "AliPID.h"
#include "AliPIDResponse.h"
#include "AliAODMCHeader.h"
#include "AliAODHeader.h"
#include "AliAODEvent.h"
#include "AliAODVertex.h"
#include "AliAODTrack.h"
#include "AliAODMCParticle.h"
#include "AliAODInputHandler.h"
#include "AliAODv0KineCuts.h"
#include "AliMCEventHandler.h"
#include "AliMCEvent.h"
#include "AliStack.h"
#include "AliGenEventHeader.h"
#include "AliGenPythiaEventHeader.h"
#include "AliGenHijingEventHeader.h"
#include "AliGenCocktailEventHeader.h"
#include "AliMagF.h"
#include "TGeoGlobalMagField.h"
#include "AliAnalysisFilter.h"
#include "AliDielectronVarManager.h"
#include "AliDielectronTrackCuts.h"
#include "AliDielectronVarCuts.h"
#include "AliDielectronCutGroup.h"
#include "AliDielectronPID.h"
#include "AliAnalysisTaskTagAndProbe.h"
//Author: Daiki Sekihata (Center for Nuclear Study, the University of Tokyo)
//daiki.sekihata@cern.ch
//This analysis task is for data-driven efficiency for a single track with tag-and-probe method.
//Since this task aims to measure the efficiency for a single track,
//electrons from a primary vertex or electrons from gamma conversions do not matter.
//In dielectron analyses, a hit on 1st SPD layer is required for electrons.
//Thus, converted electrons are from the beam pipe.
//They are considered as electrons from the primary vertex which have the similar PID/tracking efficiency.
using namespace std;
ClassImp(AliAnalysisTaskTagAndProbe)
//________________________________________________________________________
AliAnalysisTaskTagAndProbe::AliAnalysisTaskTagAndProbe():
AliAnalysisTaskSE(),
fOutputContainer(0x0),
fTriggerMask(0),
fEvent(0x0),
fESDEvent(0x0),
fAODEvent(0x0),
fEstimator("V0M"),
fMultSelection(0x0),
fCentrality(0),
fCentralityMin(0.),
fCentralityMax(101.),
fNMixed(10),
fZvtxBin(-1),
fPIDResponse(0x0),
fUsedVars(new TBits(AliDielectronVarManager::kNMaxValues)),
fPIDCalibinPU(kTRUE),
fTagTrackArray(0x0),
fProbeTrackArray(0x0),
fPassingProbeTrackArray(0x0),
fEventFilter(0x0),
fTagFilter(0x0),
fProbeFilter(0x0),
fPassingProbeFilter(0x0),
fPIDFilter(0x0),
fMmax(-1),
fPhiVmin(3.2),
fESDtrackCutsGlobalNoDCA(0x0),
fESDv0KineCuts(0x0),
fAODv0KineCuts(0x0),
fPIDCalibMode(kFALSE)
{
// Constructor
for(Int_t i=0;i<3;i++) fVertex[i] = 0;
for(Int_t i=0;i<2;i++){
for(Int_t j=0;j<10;j++){
fEventList[i][j] = 0x0;
}
}
for(Int_t i=0;i<15;i++){
for(Int_t j=0;j<15;j++){
fPostPIDCntrdCorrPU[i][j] = 0x0;
fPostPIDWdthCorrPU[i][j] = 0x0;
}
}
}
//________________________________________________________________________
AliAnalysisTaskTagAndProbe::AliAnalysisTaskTagAndProbe(const char *name):
AliAnalysisTaskSE(name),
fOutputContainer(0x0),
fTriggerMask(0),
fEvent(0x0),
fESDEvent(0x0),
fAODEvent(0x0),
fEstimator("V0M"),
fMultSelection(0x0),
fCentrality(0),
fCentralityMin(0.),
fCentralityMax(101.),
fNMixed(10),
fZvtxBin(-1),
fPIDResponse(0x0),
fUsedVars(new TBits(AliDielectronVarManager::kNMaxValues)),
fPIDCalibinPU(kTRUE),
fTagTrackArray(0x0),
fProbeTrackArray(0x0),
fPassingProbeTrackArray(0x0),
fEventFilter(0x0),
fTagFilter(0x0),
fProbeFilter(0x0),
fPassingProbeFilter(0x0),
fPIDFilter(0x0),
fMmax(-1),
fPhiVmin(3.2),
fESDtrackCutsGlobalNoDCA(0x0),
fESDv0KineCuts(0x0),
fAODv0KineCuts(0x0),
fPIDCalibMode(kFALSE)
{
// Constructor
for(Int_t i=0;i<3;i++) fVertex[i] = 0;
for(Int_t i=0;i<2;i++){
for(Int_t j=0;j<10;j++){
fEventList[i][j] = 0x0;
}
}
for(Int_t i=0;i<15;i++){
for(Int_t j=0;j<15;j++){
fPostPIDCntrdCorrPU[i][j] = 0x0;
fPostPIDWdthCorrPU[i][j] = 0x0;
}
}
fTagTrackArray = new TObjArray(1000);
fTagTrackArray->SetOwner(kFALSE);
fProbeTrackArray = new TObjArray(1000);
fProbeTrackArray->SetOwner(kFALSE);
fPassingProbeTrackArray = new TObjArray(1000);
fPassingProbeTrackArray->SetOwner(kFALSE);
fEventFilter = new AliAnalysisFilter("fEventFilter","fEventFilter");
fTagFilter = new AliAnalysisFilter("fTagFilter" ,"fTagFilter");
fProbeFilter = new AliAnalysisFilter("fProbeFilter","fProbeFilter");
fPassingProbeFilter = new AliAnalysisFilter("fPassingProbeFilter" ,"fPassingProbeFilter");
fPIDFilter = new AliAnalysisFilter("fPIDFilter","fPIDFilter");
fESDtrackCutsGlobalNoDCA = AliESDtrackCuts::GetStandardITSTPCTrackCuts2011(kFALSE,1);
fESDtrackCutsGlobalNoDCA->SetMaxDCAToVertexXY(2.4);
fESDtrackCutsGlobalNoDCA->SetMaxDCAToVertexZ(3.2);
fESDtrackCutsGlobalNoDCA->SetDCAToVertex2D(kTRUE);
fESDv0KineCuts = new AliESDv0KineCuts();
fAODv0KineCuts = new AliAODv0KineCuts();
fESDv0KineCuts->SetMode(AliESDv0KineCuts::kPurity,AliESDv0KineCuts::kPbPb);
fAODv0KineCuts->SetMode(AliAODv0KineCuts::kPurity,AliAODv0KineCuts::kPbPb);
//Float_t Rcut[2] = {0,90};
//fESDv0KineCuts->SetGammaCutVertexR(Rcut);
//fAODv0KineCuts->SetGammaCutVertexR(Rcut);
//fAODv0KineCuts->SetGammaCutInvMass(0.1);//upper limit for mee
// Define input and output slots here
// Input slot #0 works with a TChain
DefineInput(0, TChain::Class());
// Output slot #0 id reserved by the base class for AOD
// Output slot #1 writes into a TH1 container
DefineOutput(1, THashList::Class());
}
//________________________________________________________________________
AliAnalysisTaskTagAndProbe::~AliAnalysisTaskTagAndProbe()
{
delete fEventFilter;
delete fTagFilter;
delete fProbeFilter;
delete fPassingProbeFilter;
delete fPIDFilter;
delete fTagTrackArray;
delete fProbeTrackArray;
delete fPassingProbeTrackArray;
delete fESDtrackCutsGlobalNoDCA;
delete fESDv0KineCuts;
delete fAODv0KineCuts;
delete fUsedVars;
}
//________________________________________________________________________
void AliAnalysisTaskTagAndProbe::UserCreateOutputObjects()
{
// Create histograms
// Called once
fOutputContainer = new THashList();
fOutputContainer->SetOwner(kTRUE);
TH1F *hEventSummary = new TH1F("hEventSummary","Event Summary",10,0.5,10.5);
hEventSummary->GetXaxis()->SetBinLabel(1 ,"all");
hEventSummary->GetXaxis()->SetBinLabel(2 ,"after P.S.");
hEventSummary->GetXaxis()->SetBinLabel(3 ,"selected");
fOutputContainer->Add(hEventSummary);
//event character histogram
fOutputContainer->Add(new TH1F("hVertexZ","VertexZ;Zvtx (cm)",1000,-50.,50.));
fOutputContainer->Add(new TH1F("hVertexZSelectEvent","VertexZ SelectEvent;Zvtx (cm)",1000,-50.,50.));
fOutputContainer->Add(new TH2F(Form("hCentrality%svsNContributor",fEstimator.Data()),Form("Centrality %s vs. Ncontributor;centrality (%%);N_{contributor}",fEstimator.Data()),101,0.,101,500,0,5000));
fOutputContainer->Add(new TH2F("hNTPCclsvsNSDDSSDcls","N_{cls}^{TPC} vs. N_{cls}^{SDD+SSD};N_{cls}^{TPC};N_{cls}^{SDD+SSD}",300,0,6e+6,300,0,6e+4));//for pileup plot
const Int_t NdimPU = 3;
Int_t NbinPU[NdimPU] = { 100, 600, 200};
Double_t xminPU[NdimPU] = { 0, -300, 0};
Double_t xmaxPU[NdimPU] = {6e+4, +300, 2e+4};
const TString sidename[3] = {"A","C",""};
for(Int_t iside=0;iside<3;iside++){
fOutputContainer->Add(new THnSparseF(Form("hsTPCpileup%s",sidename[iside].Data()),Form("TPC pileup %s;N_{cls}^{SDD+SSD};TPC pileup Z (cm);TPC pileup M;",sidename[iside].Data()),NdimPU,NbinPU,xminPU,xmaxPU));
}
//simple track QA
const Int_t Ndim = 3;
Int_t Nbin[Ndim] = {100, 20, 36};
Double_t xmin[Ndim] = { 0, -1, 0};
Double_t xmax[Ndim] = { 10, +1, TMath::TwoPi()};
THnSparseF *hs_PtEtaPhi = new THnSparseF("hs_PtEtaPhi","hs_PtEtaPhi;p_{T} (GeV/c);#eta;#varphi (rad.);",Ndim,Nbin,xmin,xmax);
hs_PtEtaPhi->Sumw2();
fOutputContainer->Add(hs_PtEtaPhi);
fOutputContainer->Add(new TH2F("hTrackDCA","DCA xy vs. z;DCA_{xy} (cm);DCA_{z} (cm)",100,-5,+5,100,-5,+5));
fOutputContainer->Add(new TH1F("hTrackNclsTPC" ,"Number of clusters TPC;N_{cls}^{TPC}" ,161,-0.5,160.5));
fOutputContainer->Add(new TH1F("hTrackNclsPIDTPC","Number of clusters for PID TPC;N_{cls}^{TPC} for PID",161,-0.5,160.5));
fOutputContainer->Add(new TH1F("hTrackNcrTPC" ,"Number of crossed rows TPC;N_{cr}^{TPC}" ,161,-0.5,160.5));
fOutputContainer->Add(new TH1F("hTrackNfTPC" ,"Number of findable clusters TPC;N_{f}^{TPC}" ,161,-0.5,160.5));
fOutputContainer->Add(new TH1F("hTrackRatioNcrtoNfTPC","ratio of N_{cr}^{TPC}/N_{f}^{TPC};N_{cr}^{TPC}/N_{f}^{TPC}",200,0.,2));
fOutputContainer->Add(new TH1F("hTrackChi2TPC","chi2 TPC;#chi^{2}/N_{cls}^{TPC}",100,0,10));
fOutputContainer->Add(new TH1F("hTrackNclsITS","Number of clusters ITS;N_{cls}^{ITS}" ,7,-0.5,6.5));
fOutputContainer->Add(new TH1F("hTrackNscITS" ,"Number of shared clusters ITS;N_{sc}^{ITS}",7,-0.5,6.5));
fOutputContainer->Add(new TH1F("hTrackChi2ITS","chi2 ITS;#chi^{2}/N_{cls}^{ITS}",100,0,10));
fOutputContainer->Add(new TH2F("hTrackTPCdEdx","TPC dE/dx vs. p_{in};p_{in} (GeV/c);TPC dE/dx (a.u.)",200,0.,10,200,0,200));
fOutputContainer->Add(new TH2F("hTrackITSdEdx","ITS dE/dx vs. p_{in};p_{in} (GeV/c);ITS dE/dx (a.u.)",200,0.,10,400,0,400));
fOutputContainer->Add(new TH2F("hTrackTOFbeta","TOF #beta vs. p_{in};p_{in} (GeV/c);TOF #beta" ,200,0.,10,240,0,1.2));
fOutputContainer->Add(new TH2F("hTrackNsigmaElTPCvsPin","n#sigma_{e}^{TPC} vs. p_{in};p_{in} (GeV/c);n#sigma_{e}^{TPC}",200,0.,10,100,-5,+5));
fOutputContainer->Add(new TH2F("hTrackNsigmaElITSvsPin","n#sigma_{e}^{ITS} vs. p_{in};p_{in} (GeV/c);n#sigma_{e}^{ITS}",200,0.,10,100,-5,+5));
fOutputContainer->Add(new TH2F("hTrackNsigmaElTOFvsPin","n#sigma_{e}^{TOF} vs. p_{in};p_{in} (GeV/c);n#sigma_{e}^{TOF}",200,0.,10,100,-5,+5));
fOutputContainer->Add(new TH2F("hTrackNsigmaElTPCvsEta","n#sigma_{e}^{TPC} vs. #eta;#eta;n#sigma_{e}^{TPC}",200,-1,+1,100,-5,+5));
fOutputContainer->Add(new TH2F("hTrackNsigmaElITSvsEta","n#sigma_{e}^{ITS} vs. #eta;#eta;n#sigma_{e}^{ITS}",200,-1,+1,100,-5,+5));
fOutputContainer->Add(new TH2F("hTrackNsigmaElTOFvsEta","n#sigma_{e}^{TOF} vs. #eta;#eta;n#sigma_{e}^{TOF}",200,-1,+1,100,-5,+5));
//pair histograms
fOutputContainer->Add(new TH2F("hPairMvsPhiV","m_{ee} vs.#varphi_{V};#varphi_{V} (rad.);m_{ee} (GeV/c^{2})",100,0,TMath::Pi(),100,0,0.1));
const Int_t Nmee = 150;
Double_t mee[Nmee] = {};
for(Int_t i=0 ;i<110 ;i++) mee[i] = 0.01 * (i- 0) + 0.0;//from 0 to 1.1 GeV/c2, every 0.01 GeV/c2
for(Int_t i=110;i<Nmee;i++) mee[i] = 0.1 * (i-110) + 1.1;//from 1.1 to 5 GeV/c2, evety 0.1 GeV/c2
const Int_t NpTe = 70;
Double_t pTe[NpTe] = {};
for(Int_t i=0 ;i<10 ;i++) pTe[i] = 0.01 * (i- 0) + 0.0;//from 0.0 to 0.1 GeV/c, every 0.01 GeV/c
for(Int_t i=10 ;i<59;i++) pTe[i] = 0.1 * (i-10) + 0.1;//from 0.1 to 5.0 GeV/c,evety 0.1 GeV/c
for(Int_t i=59 ;i<NpTe;i++) pTe[i] = 0.5 * (i-59) + 5.0;//from 5.0 to 10 GeV/c, evety 0.5 GeV/c
const TString probetype[2] = {"Probe","PassingProbe"};
const TString chargetype[3] = {"ULS","LSpp","LSnn"};
const TString eventtype[2] = {"same","mix"};
if(!fPIDCalibMode){
for(Int_t ip=0;ip<2;ip++){
for(Int_t ic=0;ic<3;ic++){
for(Int_t ie=0;ie<2;ie++){
TH2F *h2TAP = new TH2F(Form("h%s_%s_%s",probetype[ip].Data(),chargetype[ic].Data(),eventtype[ie].Data()),Form("h%s_%s_%s",probetype[ip].Data(),chargetype[ic].Data(),eventtype[ie].Data()),Nmee-1,mee,NpTe-1,pTe);
h2TAP->SetXTitle("m_{ee} (GeV/c^{2})");
h2TAP->SetYTitle("p_{T,e} (GeV/c)");
h2TAP->Sumw2();
fOutputContainer->Add(h2TAP);
}
}
}
}
fOutputContainer->Add(new TH1F("hV0CosPointingAngle","V0 cos pointing angle;cos(#theta_{point})",100,0,1));
fOutputContainer->Add(new TH2F("hV0Lxy","V0 L_{xy} vs. m_{ee};V0 L_{xy} (cm);m_{ee} (GeV/c^{2})",600,0,60,50,0,0.05));
fOutputContainer->Add(new TH2F("hV0Lxy_GammaConv","V0 L_{xy} vs. m_{ee};V0 L_{xy} (cm);m_{ee} (GeV/c^{2})",600,0,60,50,0,0.05));
fOutputContainer->Add(new TH2F("hV0AP","AP plot",200,-1,+1,300,0,0.3));
const TString V0name[4] = {"GammaConv","K0S","Lambda","AntiLambda"};
for(Int_t i=0;i<4;i++) fOutputContainer->Add(new TH2F(Form("hV0AP_%s",V0name[i].Data()),Form("V0 AP plot %s",V0name[i].Data()),200,-1,+1,300,0,0.3));
const Int_t Ndim_PID = 8;//NclsSDDSSD, puZ, puM, pin, eta, nsigmaTPC, nsigmaITS, nsigmaTOF
Int_t Nbin_PID[Ndim_PID] = { 4, 6, 4, 28, 20, 100, 100, 100};
Double_t xmin_PID[Ndim_PID] = { 0, -300, 0, 0, -1, -5, -5, -5};
Double_t xmax_PID[Ndim_PID] = {20000, +300,10000, 10, +1, +5, +5, +5};
const TString parname[7] = {"El_online","El_offline","El_bkg_online","El_bkg_offline","Pi","Ka","Pr"};
const Double_t NSDDSSD[5] = {0, 2.5e3, 1e+4, 1.6e+4, 1e+5};//clusters on SDD+SSD layers
const Double_t TPCpileupZ[7] = {-300,-75,-25,0,+25,+75,+300};//in cm (A+C)/2 average
const Double_t TPCpileupMult[5] = {0,400,1200,3000,20000};//pileup contributors A+C sum
const Double_t pinbin[29] = {0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,3,4,5,6,7,8,9,10};//pin for PID calib
for(Int_t i=0;i<7;i++){
THnSparseF *hsPID = new THnSparseF(Form("hsPID_V0%s",parname[i].Data()),Form("hsPID %s;",parname[i].Data()),Ndim_PID,Nbin_PID,xmin_PID,xmax_PID);
hsPID->SetBinEdges(0,NSDDSSD);
hsPID->SetBinEdges(1,TPCpileupZ);
hsPID->SetBinEdges(2,TPCpileupMult);
hsPID->SetBinEdges(3,pinbin);
hsPID->GetAxis(0)->SetTitle("N_{cls}^{SDD+SSD}");
hsPID->GetAxis(1)->SetTitle("Z_{puv} (cm)");
hsPID->GetAxis(2)->SetTitle("M_{puv}");
hsPID->GetAxis(3)->SetTitle("p_{in} (GeV/c)");
hsPID->GetAxis(4)->SetTitle("#eta");
hsPID->GetAxis(5)->SetTitle("n #sigma_{TPC}");
hsPID->GetAxis(6)->SetTitle("n #sigma_{ITS}");
hsPID->GetAxis(7)->SetTitle("n #sigma_{TOF}");
fOutputContainer->Add(hsPID);
}
THnSparseF *hsAll_El_TAP = new THnSparseF("hsAll_El_TAP","hs all e^{#pm} for PID eff.",Ndim,Nbin,xmin,xmax);
//hsAll_El_TAP->SetBinEdges(0,pinbin);
hsAll_El_TAP->GetAxis(0)->SetTitle("p_{T,e} (GeV/c)");
hsAll_El_TAP->GetAxis(1)->SetTitle("#eta_{e}");
hsAll_El_TAP->GetAxis(2)->SetTitle("#varphi_{e}");
fOutputContainer->Add(hsAll_El_TAP);
THnSparseF *hsSel_El_TAP = new THnSparseF("hsSel_El_TAP","hs all e^{#pm} for PID eff.",Ndim,Nbin,xmin,xmax);
//hsSel_El_TAP->SetBinEdges(0,pinbin);
hsSel_El_TAP->GetAxis(0)->SetTitle("p_{T,e} (GeV/c)");
hsSel_El_TAP->GetAxis(1)->SetTitle("#eta_{e}");
hsSel_El_TAP->GetAxis(2)->SetTitle("#varphi_{e}");
fOutputContainer->Add(hsSel_El_TAP);
PostData(1,fOutputContainer);
}
//________________________________________________________________________
void AliAnalysisTaskTagAndProbe::UserExec(Option_t *option)
{
// Main loop
// Called for each event
fEvent = dynamic_cast<AliVEvent*>(InputEvent());
if(!fEvent){
AliError("event is not available.");
return;
}
fESDEvent = dynamic_cast<AliESDEvent*>(fEvent);
fAODEvent = dynamic_cast<AliAODEvent*>(fEvent);
if(!fESDEvent && !fAODEvent){
AliInfo("event class is neither ESD nor AOD. return.");
return;
}
const AliVVertex *vVertex = fEvent->GetPrimaryVertex();
fVertex[0] = vVertex->GetX();
fVertex[1] = vVertex->GetY();
fVertex[2] = vVertex->GetZ();
FillHistogramTH1(fOutputContainer,"hEventSummary",1);//all
FillHistogramTH1(fOutputContainer,"hVertexZ" ,fVertex[2]);
Int_t Ncontributor = vVertex->GetNContributors();
UInt_t fSelectMask = fInputHandler->IsEventSelected();
Bool_t isPhysSelOK = fSelectMask & fTriggerMask;
if(!isPhysSelOK){
AliInfo("event is rejected by physics selection");
return;
}
FillHistogramTH1(fOutputContainer,"hEventSummary",2);//after physics selection
UInt_t selectedMask_ev = (1<<fEventFilter->GetCuts()->GetEntries())-1;
UInt_t cutmask_ev = fEventFilter->IsSelected(InputEvent());
if(cutmask_ev != selectedMask_ev){
AliInfo("event is rejected by event filter. return.");
return;
}
fPIDResponse = fInputHandler->GetPIDResponse();
if(!fPIDResponse){
AliFatal("fPIDResponse does not exist!");
return;
}
AliDielectronVarManager::SetPIDResponse( fInputHandler->GetPIDResponse() );
AliDielectronVarManager::SetFillMap(fUsedVars);
AliDielectronVarManager::SetEvent( InputEvent() );
// if(!fEventFilter->IsSelected(InputEvent())){
// AliInfo("event is rejected by event filter. return.");
// return;
// }
AliDielectronPID::SetPIDCalibinPU(fPIDCalibinPU);
for(Int_t id=0;id<15;id++){//detector loop TPC/ITS/TOF
for(Int_t ip=0;ip<15;ip++){//particle loop e/mu/pi/k/p
if(fPostPIDCntrdCorrPU[id][ip]) AliDielectronPID::SetCentroidCorrFunctionPU(id,ip,fPostPIDCntrdCorrPU[id][ip]);
if(fPostPIDWdthCorrPU[id][ip]) AliDielectronPID::SetWidthCorrFunctionPU( id,ip,fPostPIDWdthCorrPU[id][ip] );
}
}
fTagTrackArray->Clear();
fProbeTrackArray->Clear();
fPassingProbeTrackArray->Clear();
fZvtxBin = (Int_t)((fVertex[2]+10.)/2.);//it should be 0-9.
if(fZvtxBin < 0) fZvtxBin = 0;//protection to avoid fZvtxBin = -1.
if(fZvtxBin > 9) fZvtxBin = 9;//protection to avoid fZvtxBin = 10.
//centrality estimation
//Get Centrality
fMultSelection = (AliMultSelection*)fEvent->FindListObject("MultSelection");
if(!fMultSelection){
//If you get this warning (and fCentralityV0M 300) please check that the AliMultSelectionTask actually ran (before your task)
AliWarning("AliMultSelection object not found! centrality is set to 0.");
fCentrality = 0;
//return;
}
else{
fCentrality = fMultSelection->GetMultiplicityPercentile(fEstimator);
}
//printf("centrality V0M = %f\n",fCentrality);
FillHistogramTH1(fOutputContainer,"hEventSummary",3);//selected
FillHistogramTH1(fOutputContainer,"hVertexZSelectEvent" ,fVertex[2]);
FillHistogramTH2(fOutputContainer,Form("hCentrality%svsNContributor",fEstimator.Data()),fCentrality,Ncontributor);
//Int_t NclsSPD0 = fEvent->GetMultiplicity()->GetNumberOfITSClusters(0);
//Int_t NclsSPD1 = fEvent->GetMultiplicity()->GetNumberOfITSClusters(1);
Int_t NclsSDD0 = fEvent->GetMultiplicity()->GetNumberOfITSClusters(2);
Int_t NclsSDD1 = fEvent->GetMultiplicity()->GetNumberOfITSClusters(3);
Int_t NclsSSD0 = fEvent->GetMultiplicity()->GetNumberOfITSClusters(4);
Int_t NclsSSD1 = fEvent->GetMultiplicity()->GetNumberOfITSClusters(5);
Int_t NSDDSSD = NclsSDD0 + NclsSDD1 + NclsSSD0 + NclsSSD1;
Int_t NclsTPC = 0;
if(fESDEvent) NclsTPC = fESDEvent->GetNumberOfTPCClusters();
else if(fAODEvent) NclsTPC = fAODEvent->GetNumberOfTPCClusters();
FillHistogramTH2(fOutputContainer,"hNTPCclsvsNSDDSSDcls",NclsTPC,NSDDSSD);
Float_t TPCpileupZA = 0;
Float_t TPCpileupZC = 0;
Float_t TPCpileupZ = 0;
Float_t TPCpileupMA = 0;
Float_t TPCpileupMC = 0;
Float_t TPCpileupM = 0;
if(fESDEvent){
TVectorF tpcVertexInfo(10);
AliESDUtils::GetTPCPileupVertexInfo(fESDEvent, tpcVertexInfo);
TPCpileupZA = tpcVertexInfo[0];
TPCpileupZC = tpcVertexInfo[1];
TPCpileupZ = tpcVertexInfo[2];
TPCpileupMA = tpcVertexInfo[3];
TPCpileupMC = tpcVertexInfo[4];
TPCpileupM = tpcVertexInfo[5];
}
else if (fAODEvent){
AliAODHeader *header = dynamic_cast<AliAODHeader*>(fAODEvent->GetHeader());
static TVectorF dummyVertexInfo(10); // to be used with old AODs w/o vertex info
const TVectorF &tpcVertexInfo = header->GetTPCPileUpInfo() ? *header->GetTPCPileUpInfo() : dummyVertexInfo;
TPCpileupZA = tpcVertexInfo[0];
TPCpileupZC = tpcVertexInfo[1];
TPCpileupZ = tpcVertexInfo[2];
TPCpileupMA = tpcVertexInfo[3];
TPCpileupMC = tpcVertexInfo[4];
TPCpileupM = tpcVertexInfo[5];
}
Double_t valuePU[3] = {0,0,0};
valuePU[0] = NSDDSSD;
//for A side
valuePU[1] = TPCpileupZA; valuePU[2] = TPCpileupMA;
FillSparse(fOutputContainer,"hsTPCpileupA",valuePU);
//for C side
valuePU[1] = TPCpileupZC; valuePU[2] = TPCpileupMC;
FillSparse(fOutputContainer,"hsTPCpileupC",valuePU);
//for AC average
valuePU[1] = TPCpileupZ; valuePU[2] = TPCpileupM;
FillSparse(fOutputContainer,"hsTPCpileup",valuePU);
if(!fEventList[0][fZvtxBin]) fEventList[0][fZvtxBin] = new TList();//0 -> probe
if(!fEventList[1][fZvtxBin]) fEventList[1][fZvtxBin] = new TList();//1 -> passing probe
TList *prevEvent_p = fEventList[0][fZvtxBin];
TList *prevEvent_pp = fEventList[1][fZvtxBin];
TrackQA();
if(fESDEvent) FillV0InfoESD();
else if(fAODEvent) FillV0InfoAOD();
if(!fPIDCalibMode) CutEfficiency();
//Now we either add current events to stack or remove
//If no electron in current event - no need to add it to mixed
if(fProbeTrackArray->GetEntriesFast() > 0){
prevEvent_p ->AddFirst(fProbeTrackArray->Clone());
prevEvent_pp->AddFirst(fPassingProbeTrackArray->Clone());
if(prevEvent_p->GetSize() > fNMixed){//Remove redundant events
TObjArray * tmp_p = static_cast<TObjArray*>(prevEvent_p->Last());
prevEvent_p->RemoveLast();
delete tmp_p;
tmp_p = NULL;
TObjArray * tmp_pp = static_cast<TObjArray*>(prevEvent_pp->Last());
prevEvent_pp->RemoveLast();
delete tmp_pp;
tmp_pp = NULL;
}
}
PostData(1, fOutputContainer);
}
//________________________________________________________________________
void AliAnalysisTaskTagAndProbe::Terminate(Option_t *option)
{
//Called once at the end of the query
//In principle, this function is not needed...
AliInfo(Form("%s is done.",GetName()));
}
//________________________________________________________________________
void AliAnalysisTaskTagAndProbe::TrackQA()
{
const Int_t trackMult = fEvent->GetNumberOfTracks();
AliTOFHeader* tofH = 0x0; // from v5-02-Rev10 on subtract the start time
if(fEvent) tofH = (AliTOFHeader*)fEvent->GetTOFHeader();
Double_t vec_3D[3] = {0,0,0};
UInt_t selectedMask_probe = (1<<fProbeFilter->GetCuts()->GetEntries())-1;
UInt_t selectedMask_passingprobe = (1<<fPassingProbeFilter->GetCuts()->GetEntries())-1;
Double_t pT=0, eta=0, phi=0, pin=0;
Double_t TPCsignal=0, ITSsignal = 0, TOFbeta = -1;
Double_t TPCchi2 = 999, ITSchi2 = 999, ratioCRtoF = 0;
Int_t NclsTPC = 0, NclsITS = 0, NcrTPC = 0, NscITS = 0, NfTPC = 0, NclsPIDTPC = 0;
Float_t DCAxy = -999, DCAz = -999;
Double32_t expt[5] = {0};
Double_t l = 0, t = 0 , v = 0;
Float_t nsigma_El_TPC = -999;
Float_t nsigma_El_ITS = -999;
Float_t nsigma_El_TOF = -999;
for(Int_t itrack=0;itrack<trackMult;itrack++){
AliVParticle *particle = (AliVParticle*)fEvent->GetTrack(itrack);
//reduce unnecessary IsSelected()
if(particle->Pt() < 0.15) continue;
if(TMath::Abs(particle->Eta()) > 0.9) continue;
UInt_t cutmask_probe = fProbeFilter->IsSelected(particle);
if(cutmask_probe != selectedMask_probe) continue;
AliVTrack *track = dynamic_cast<AliVTrack*>(particle);
pT = track->Pt();
eta = track->Eta();
phi = track->Phi();
if(phi < 0) phi += TMath::TwoPi();
vec_3D[0] = pT;
vec_3D[1] = eta;
vec_3D[2] = phi;
FillSparse(fOutputContainer,"hs_PtEtaPhi",vec_3D);
pin = track->GetTPCmomentum();
TPCsignal = track->GetTPCsignal();
ITSsignal = track->GetITSsignal();
ULong64_t status = track->GetStatus();
Bool_t isTIME = status & AliVTrack::kTIME;
Bool_t isTOFout = status & AliVTrack::kTOFout;
Bool_t isTOFOK = isTIME & isTOFout;
if(isTOFOK){
for(Int_t i=0;i<5;i++){expt[i] = 0.0;}
track->GetIntegratedTimes(expt,5);// ps
l = TMath::C() * expt[0] * 1e-12; // m
t = track->GetTOFsignal(); // ps start time subtracted (until v5-02-Rev09)
if(tofH) t -= fPIDResponse->GetTOFResponse().GetStartTime(track->P()); // ps
if( (l < 360.e-2 || l > 800.e-2) || (t <= 0.) ) { TOFbeta = -1; }
else {
t *= 1e-12; //ps -> s
v = l / t;
TOFbeta = v / TMath::C();
}
}
else TOFbeta = -1;
FillHistogramTH2(fOutputContainer,"hTrackTPCdEdx",pin,TPCsignal);
FillHistogramTH2(fOutputContainer,"hTrackITSdEdx",pin,ITSsignal);
FillHistogramTH2(fOutputContainer,"hTrackTOFbeta",pin,TOFbeta);
NclsTPC = track->GetNcls(1);
NclsITS = track->GetNcls(0);
NcrTPC = track->GetTPCCrossedRows();
NfTPC = track->GetTPCNclsF();
NclsPIDTPC = track->GetTPCsignalN();
ratioCRtoF = NfTPC > 0 ? (Float_t)NcrTPC / (Float_t)NfTPC : 1;
ITSchi2 = NclsITS > 0 ? track->GetITSchi2() / NclsITS : 999;
TPCchi2 = NclsTPC > 0 ? track->GetTPCchi2() / NclsTPC : 999;
DCAxy = -999, DCAz = -999;
track->GetImpactParameters(DCAxy,DCAz);
NscITS = 0;
for(Int_t il=0;il<6;il++){
if(track->HasSharedPointOnITSLayer(il)) NscITS++;
}
FillHistogramTH2(fOutputContainer,"hTrackDCA" ,DCAxy, DCAz);
FillHistogramTH1(fOutputContainer,"hTrackNclsTPC" ,NclsTPC);
FillHistogramTH1(fOutputContainer,"hTrackNclsPIDTPC" ,NclsPIDTPC);
FillHistogramTH1(fOutputContainer,"hTrackNcrTPC" ,NcrTPC);
FillHistogramTH1(fOutputContainer,"hTrackNfTPC" ,NfTPC);
FillHistogramTH1(fOutputContainer,"hTrackRatioNcrtoNfTPC",ratioCRtoF);
FillHistogramTH1(fOutputContainer,"hTrackChi2TPC" ,TPCchi2);
FillHistogramTH1(fOutputContainer,"hTrackNclsITS" ,NclsITS);
FillHistogramTH1(fOutputContainer,"hTrackNscITS" ,NscITS);
FillHistogramTH1(fOutputContainer,"hTrackChi2ITS" ,ITSchi2);
nsigma_El_TPC = (fPIDResponse->NumberOfSigmasTPC(track,AliPID::kElectron) - AliDielectronPID::GetCorrVal() - AliDielectronPID::GetCntrdCorr(track,AliPID::kElectron)) / AliDielectronPID::GetWdthCorr(track,AliPID::kElectron);
nsigma_El_ITS = (fPIDResponse->NumberOfSigmasITS(track,AliPID::kElectron) - AliDielectronPID::GetCntrdCorrITS(track,AliPID::kElectron)) / AliDielectronPID::GetWdthCorrITS(track,AliPID::kElectron);
nsigma_El_TOF = (fPIDResponse->NumberOfSigmasTOF(track,AliPID::kElectron) - AliDielectronPID::GetCntrdCorrTOF(track,AliPID::kElectron)) / AliDielectronPID::GetWdthCorrTOF(track,AliPID::kElectron);
//printf("For TPC El : cntrd = %f , width = %f\n",AliDielectronPID::GetCntrdCorr(track,AliPID::kElectron),AliDielectronPID::GetWdthCorr(track,AliPID::kElectron));
//printf("For ITS El : cntrd = %f , width = %f\n",AliDielectronPID::GetCntrdCorrITS(track,AliPID::kElectron),AliDielectronPID::GetWdthCorrITS(track,AliPID::kElectron));
//printf("For TOF El : cntrd = %f , width = %f\n",AliDielectronPID::GetCntrdCorrTOF(track,AliPID::kElectron),AliDielectronPID::GetWdthCorrTOF(track,AliPID::kElectron));
//printf("For TPC Pi : cntrd = %f , width = %f\n",AliDielectronPID::GetCntrdCorr(track,AliPID::kPion),AliDielectronPID::GetWdthCorr(track,AliPID::kPion));
//printf("For TPC Ka : cntrd = %f , width = %f\n",AliDielectronPID::GetCntrdCorr(track,AliPID::kKaon),AliDielectronPID::GetWdthCorr(track,AliPID::kKaon));
//printf("For TPC Pr : cntrd = %f , width = %f\n",AliDielectronPID::GetCntrdCorr(track,AliPID::kProton),AliDielectronPID::GetWdthCorr(track,AliPID::kProton));
//printf("nsigma_El_TPC = %f\n",nsigma_El_TPC);
//printf("nsigma_El_ITS = %f\n",nsigma_El_ITS);
//printf("nsigma_El_TOF = %f\n",nsigma_El_TOF);
FillHistogramTH2(fOutputContainer,"hTrackNsigmaElTPCvsPin",pin,nsigma_El_TPC);
FillHistogramTH2(fOutputContainer,"hTrackNsigmaElITSvsPin",pin,nsigma_El_ITS);
FillHistogramTH2(fOutputContainer,"hTrackNsigmaElTOFvsPin",pin,nsigma_El_TOF);
FillHistogramTH2(fOutputContainer,"hTrackNsigmaElTPCvsEta",eta,nsigma_El_TPC);
FillHistogramTH2(fOutputContainer,"hTrackNsigmaElITSvsEta",eta,nsigma_El_ITS);
FillHistogramTH2(fOutputContainer,"hTrackNsigmaElTOFvsEta",eta,nsigma_El_TOF);
fProbeTrackArray->Add(particle);//array of probe electrons for mixed event, // copy constructor?
UInt_t cutmask_passingprobe = fPassingProbeFilter->IsSelected(particle);
if(cutmask_passingprobe == selectedMask_passingprobe){
fPassingProbeTrackArray->Add(particle);//array of passing probe electrons for mixed event
}
}//end of track loop
//create tag track array
UInt_t selectedMask_tag = (1<<fTagFilter->GetCuts()->GetEntries())-1;
for(Int_t itrack=0;itrack<trackMult;itrack++){
AliVParticle *particle = (AliVParticle*)fEvent->GetTrack(itrack);
//reduce unnecessary IsSelected()
if(particle->Pt() < 0.15) continue;
if(TMath::Abs(particle->Eta()) > 0.9) continue;
UInt_t cutmask_tag= fTagFilter->IsSelected(particle);
if(cutmask_tag == selectedMask_tag) fTagTrackArray->Add(particle);
}//end of track loop
//only for Kaon PID calibration
//As statistics of K is too large and merge will fail due to too large output size.
//Thus, Kaon is randomly rejected.
Float_t nsigma_Ka_TPC = -999;
Float_t nsigma_Ka_ITS = -999;
Float_t nsigma_Ka_TOF = -999;
Double_t value8[8] = {0.};
Int_t NclsSDD0 = fEvent->GetMultiplicity()->GetNumberOfITSClusters(2);
Int_t NclsSDD1 = fEvent->GetMultiplicity()->GetNumberOfITSClusters(3);
Int_t NclsSSD0 = fEvent->GetMultiplicity()->GetNumberOfITSClusters(4);
Int_t NclsSSD1 = fEvent->GetMultiplicity()->GetNumberOfITSClusters(5);
Int_t NSDDSSD = NclsSDD0 + NclsSDD1 + NclsSSD0 + NclsSSD1;
Float_t TPCpileupZA = 0;
Float_t TPCpileupZC = 0;
Float_t TPCpileupZ = 0;
Float_t TPCpileupMA = 0;
Float_t TPCpileupMC = 0;
Float_t TPCpileupM = 0;
if(fESDEvent){
TVectorF tpcVertexInfo(10);
AliESDUtils::GetTPCPileupVertexInfo(fESDEvent, tpcVertexInfo);
TPCpileupZA = tpcVertexInfo[0];
TPCpileupZC = tpcVertexInfo[1];
TPCpileupZ = tpcVertexInfo[2];
TPCpileupMA = tpcVertexInfo[3];
TPCpileupMC = tpcVertexInfo[4];
TPCpileupM = tpcVertexInfo[5];
}
else if (fAODEvent){
AliAODHeader *header = dynamic_cast<AliAODHeader*>(fAODEvent->GetHeader());
static TVectorF dummyVertexInfo(10); // to be used with old AODs w/o vertex info
const TVectorF &tpcVertexInfo = header->GetTPCPileUpInfo() ? *header->GetTPCPileUpInfo() : dummyVertexInfo;
TPCpileupZA = tpcVertexInfo[0];
TPCpileupZC = tpcVertexInfo[1];
TPCpileupZ = tpcVertexInfo[2];
TPCpileupMA = tpcVertexInfo[3];
TPCpileupMC = tpcVertexInfo[4];
TPCpileupM = tpcVertexInfo[5];
}
value8[0] = NSDDSSD;
value8[1] = TPCpileupZ;
value8[2] = TPCpileupM;
TRandom3 *r3 = new TRandom3(1);
for(Int_t itrack=0;itrack<trackMult;itrack++){
AliVTrack *track = (AliVTrack*)fEvent->GetTrack(itrack);
if(track->Pt() < 0.15) continue;
if(TMath::Abs(track->Eta()) > 0.9) continue;
if(fESDEvent){
AliESDtrack *esdtrack = dynamic_cast<AliESDtrack*>(track);
if(!fESDtrackCutsGlobalNoDCA->AcceptTrack(esdtrack)) continue;//standard cuts with very loose DCA cut //bit4
}
else if(fAODEvent){
AliAODTrack *aodtrack = dynamic_cast<AliAODTrack*>(track);
if(!aodtrack->TestFilterBit(AliAODTrack::kTrkGlobalNoDCA)) continue;//standard cuts with very loose DCA cut //bit4
}
nsigma_Ka_TPC = (fPIDResponse->NumberOfSigmasTPC(track,AliPID::kKaon) - AliDielectronPID::GetCorrVal() - AliDielectronPID::GetCntrdCorr(track,AliPID::kKaon)) / AliDielectronPID::GetWdthCorr(track,AliPID::kKaon);
nsigma_Ka_ITS = (fPIDResponse->NumberOfSigmasITS(track,AliPID::kKaon) - AliDielectronPID::GetCntrdCorrITS(track,AliPID::kKaon)) / AliDielectronPID::GetWdthCorrITS(track,AliPID::kKaon);
nsigma_Ka_TOF = (fPIDResponse->NumberOfSigmasTOF(track,AliPID::kKaon) - AliDielectronPID::GetCntrdCorrTOF(track,AliPID::kKaon)) / AliDielectronPID::GetWdthCorrTOF(track,AliPID::kKaon);
if(nsigma_Ka_ITS < -2 || +2 < nsigma_Ka_ITS) continue;
if(track->GetTPCmomentum() > 0.4 && (nsigma_Ka_TOF < -2 || +2 < nsigma_Ka_TOF)) continue;
if(r3->Rndm() > 0.001) continue;//accept only 0.1% of Kaons.
value8[3] = track->GetTPCmomentum();
value8[4] = track->Eta();
value8[5] = nsigma_Ka_TPC;
value8[6] = nsigma_Ka_ITS;
value8[7] = nsigma_Ka_TOF;
FillSparse(fOutputContainer,"hsPID_V0Ka",value8);
}//end of track loop
delete r3;
r3 = 0x0;
}
//________________________________________________________________________
void AliAnalysisTaskTagAndProbe::FillV0InfoESD()
{
Int_t NclsSDD0 = fEvent->GetMultiplicity()->GetNumberOfITSClusters(2);
Int_t NclsSDD1 = fEvent->GetMultiplicity()->GetNumberOfITSClusters(3);
Int_t NclsSSD0 = fEvent->GetMultiplicity()->GetNumberOfITSClusters(4);
Int_t NclsSSD1 = fEvent->GetMultiplicity()->GetNumberOfITSClusters(5);
Int_t NSDDSSD = NclsSDD0 + NclsSDD1 + NclsSSD0 + NclsSSD1;
const AliVVertex *vVertex = fEvent->GetPrimaryVertex();
AliKFVertex primaryVertexKF(*vVertex);
Double_t secVtx[3] = {primaryVertexKF.GetX(), primaryVertexKF.GetY(), primaryVertexKF.GetZ()};
fESDv0KineCuts->SetEvent(InputEvent());
fESDv0KineCuts->SetPrimaryVertex(&primaryVertexKF);
const Double_t Me = TDatabasePDG::Instance()->GetParticle(11)->Mass();
const Double_t Mpi = TDatabasePDG::Instance()->GetParticle(211)->Mass();
const Double_t Mp = TDatabasePDG::Instance()->GetParticle(2212)->Mass();
TVectorF tpcVertexInfo(10);
AliESDUtils::GetTPCPileupVertexInfo(fESDEvent, tpcVertexInfo);
Float_t TPCpileupZ = tpcVertexInfo[2];
Float_t TPCpileupM = tpcVertexInfo[5];
UInt_t selectedMask_pid = (1<<fPIDFilter->GetCuts()->GetEntries())-1;
Double_t M1 = 0;
Double_t M2 = 0;
Double_t M12 = 0;
Int_t pdgV0 = 0, pdgP = 0, pdgN = 0;
Float_t qT = 0, alpha = 0;
Float_t Lxy = 0;
Float_t nsigma_El_TPC = -999 , nsigma_Pi_TPC = -999 , nsigma_Pr_TPC = -999;
Float_t nsigma_El_ITS = -999 , nsigma_Pi_ITS = -999 , nsigma_Pr_ITS = -999;
Float_t nsigma_El_TOF = -999 , nsigma_Pi_TOF = -999 , nsigma_Pr_TOF = -999;
Double_t value3D[3] = {0,0,0};
Double_t value[8] = {};
for(Int_t i=0;i<8;i++) value[i] = 0.0;
value[0] = NSDDSSD;
value[1] = TPCpileupZ;
value[2] = TPCpileupM;
const Int_t Nv0 = fEvent->GetNumberOfV0s();
for(Int_t iv0=0;iv0<Nv0;iv0++){
AliESDv0 *v0 = (AliESDv0*)fESDEvent->GetV0(iv0);
if(v0->GetRr() > 60.) continue;
if(v0->GetDcaV0Daughters() > 0.25) continue;
if(v0->GetV0CosineOfPointingAngle(secVtx[0],secVtx[1],secVtx[2]) < 0.98) continue;
AliESDtrack* legPos = fESDEvent->GetTrack(v0->GetPindex());
AliESDtrack* legNeg = fESDEvent->GetTrack(v0->GetNindex());
if(legPos->Charge() * legNeg->Charge() > 0) continue;//reject same sign pair
if(legPos->Pt() < 0.15) continue;
if(legNeg->Pt() < 0.15) continue;
if(TMath::Abs(legPos->Eta()) > 0.9) continue;
if(TMath::Abs(legNeg->Eta()) > 0.9) continue;
Float_t DCAxy_leg = -999, DCAz_leg = -999;
legPos->GetImpactParameters(DCAxy_leg,DCAz_leg);
if(TMath::Abs(DCAxy_leg) > 1.) continue;
if(TMath::Abs(DCAz_leg) > 3.) continue;
DCAxy_leg = -999; DCAz_leg = -999;
legNeg->GetImpactParameters(DCAxy_leg,DCAz_leg);
if(TMath::Abs(DCAxy_leg) > 1.) continue;
if(TMath::Abs(DCAz_leg) > 3.) continue;
if(legPos->GetKinkIndex(0) != 0) continue;
if(legNeg->GetKinkIndex(0) != 0) continue;
if(!(legPos->GetStatus() & AliVTrack::kITSrefit)) continue;
if(!(legNeg->GetStatus() & AliVTrack::kITSrefit)) continue;
if(legPos->GetNcls(0) < 2.5) continue;//minimum number of ITS cluster 3
if(legNeg->GetNcls(0) < 2.5) continue;//minimum number of ITS cluster 3
if(legPos->GetITSchi2() / legPos->GetNcls(0) > 36.) continue;//maximum chi2 per cluster ITS
if(legNeg->GetITSchi2() / legNeg->GetNcls(0) > 36.) continue;//maximum chi2 per cluster ITS
if(!(legPos->GetStatus() & AliVTrack::kTPCrefit)) continue;
if(!(legNeg->GetStatus() & AliVTrack::kTPCrefit)) continue;
if(legPos->GetTPCCrossedRows() < 70) continue;//minimum number of TPC crossed rows 70
if(legNeg->GetTPCCrossedRows() < 70) continue;//minimum number of TPC crossed rows 70
if(legPos->GetTPCchi2() / legPos->GetNcls(1) > 2.5) continue;//maximum chi2 per cluster TPC
if(legNeg->GetTPCchi2() / legNeg->GetNcls(1) > 2.5) continue;//maximum chi2 per cluster TPC
Float_t ratio_pos = legPos->GetTPCNclsF() > 0 ? (Float_t)legPos->GetTPCCrossedRows() / (Float_t)legPos->GetTPCNclsF() : 1.0;
Float_t ratio_neg = legNeg->GetTPCNclsF() > 0 ? (Float_t)legNeg->GetTPCCrossedRows() / (Float_t)legNeg->GetTPCNclsF() : 1.0;
if(ratio_pos < 0.8) continue;
if(ratio_neg < 0.8) continue;
if(!legPos->HasPointOnITSLayer(0) && !legPos->HasPointOnITSLayer(1)) continue;//accept SPDany
if(!legNeg->HasPointOnITSLayer(0) && !legNeg->HasPointOnITSLayer(1)) continue;//accept SPDany
Lxy = v0->GetRr();
alpha = v0->AlphaV0();
qT = v0->PtArmV0();
FillHistogramTH2(fOutputContainer,"hV0AP",alpha,qT);
pdgV0 = 0; pdgP = 0; pdgN = 0;
if(!fESDv0KineCuts->ProcessV0(v0,pdgV0,pdgP,pdgN)) continue;
for(Int_t i=3;i<8;i++) value[i] = 0.0;
if(pdgV0 == 22 && TMath::Abs(pdgP) == 11 && TMath::Abs(pdgN) == 11){//GammaConv
M1 = Me;
M2 = Me;
M12 = v0->GetEffMassExplicit(M1,M2);
FillHistogramTH2(fOutputContainer,"hV0Lxy",Lxy,M12);
nsigma_El_TPC = (fPIDResponse->NumberOfSigmasTPC(legPos,AliPID::kElectron) - AliDielectronPID::GetCorrVal() - AliDielectronPID::GetCntrdCorr(legPos,AliPID::kElectron)) / AliDielectronPID::GetWdthCorr(legPos,AliPID::kElectron);
nsigma_El_ITS = (fPIDResponse->NumberOfSigmasITS(legPos,AliPID::kElectron) - AliDielectronPID::GetCntrdCorrITS(legPos,AliPID::kElectron)) / AliDielectronPID::GetWdthCorrITS(legPos,AliPID::kElectron);
nsigma_El_TOF = (fPIDResponse->NumberOfSigmasTOF(legPos,AliPID::kElectron) - AliDielectronPID::GetCntrdCorrTOF(legPos,AliPID::kElectron)) / AliDielectronPID::GetWdthCorrTOF(legPos,AliPID::kElectron);
value[3] = legPos->GetTPCmomentum();
value[4] = legPos->Eta();
value[5] = nsigma_El_TPC;
value[6] = nsigma_El_ITS;
value[7] = nsigma_El_TOF;
if(HasConversionPointOnSPD(v0,legPos,legNeg)){
FillHistogramTH2(fOutputContainer,"hV0Lxy_GammaConv",Lxy,M12);
FillHistogramTH2(fOutputContainer,"hV0AP_GammaConv",alpha,qT);
if(v0->GetOnFlyStatus()) FillSparse(fOutputContainer,"hsPID_V0El_online" ,value);
else FillSparse(fOutputContainer,"hsPID_V0El_offline",value);
}
else if(TMath::Abs(Lxy - 20.0) < 2.0){ //18-22cm in radius
if(v0->GetOnFlyStatus()) FillSparse(fOutputContainer,"hsPID_V0El_bkg_online" ,value);
else FillSparse(fOutputContainer,"hsPID_V0El_bkg_offline",value);
}
nsigma_El_TPC = (fPIDResponse->NumberOfSigmasTPC(legNeg,AliPID::kElectron) - AliDielectronPID::GetCorrVal() - AliDielectronPID::GetCntrdCorr(legNeg,AliPID::kElectron)) / AliDielectronPID::GetWdthCorr(legNeg,AliPID::kElectron);
nsigma_El_ITS = (fPIDResponse->NumberOfSigmasITS(legNeg,AliPID::kElectron) - AliDielectronPID::GetCntrdCorrITS(legNeg,AliPID::kElectron)) / AliDielectronPID::GetWdthCorrITS(legNeg,AliPID::kElectron);
nsigma_El_TOF = (fPIDResponse->NumberOfSigmasTOF(legNeg,AliPID::kElectron) - AliDielectronPID::GetCntrdCorrTOF(legNeg,AliPID::kElectron)) / AliDielectronPID::GetWdthCorrTOF(legNeg,AliPID::kElectron);
value[3] = legNeg->GetTPCmomentum();
value[4] = legNeg->Eta();
value[5] = nsigma_El_TPC;
value[6] = nsigma_El_ITS;
value[7] = nsigma_El_TOF;
if(HasConversionPointOnSPD(v0,legPos,legNeg)){
if(v0->GetOnFlyStatus()) FillSparse(fOutputContainer,"hsPID_V0El_online" ,value);
else FillSparse(fOutputContainer,"hsPID_V0El_offline",value);
}
else if(TMath::Abs(Lxy - 20.0) < 2.0){ //18-22cm in radius
if(v0->GetOnFlyStatus()) FillSparse(fOutputContainer,"hsPID_V0El_bkg_online" ,value);
else FillSparse(fOutputContainer,"hsPID_V0El_bkg_offline",value);
}
if(TMath::Abs(nsigma_El_TPC) < 3.){//electron is pre-selected by loose 3 sigma.
//for PID efficiency by DDA
//fill denominator
value3D[0] = legPos->Pt();
value3D[1] = legPos->Eta();
value3D[2] = legPos->Phi();
FillSparse(fOutputContainer,"hsAll_El_TAP",value3D);
value3D[0] = legNeg->Pt();
value3D[1] = legNeg->Eta();
value3D[2] = legNeg->Phi();
FillSparse(fOutputContainer,"hsAll_El_TAP",value3D);
//fill nominator
UInt_t cutmask_pid = fPIDFilter->IsSelected(legPos);
if(cutmask_pid == selectedMask_pid){
value3D[0] = legPos->Pt();
value3D[1] = legPos->Eta();
value3D[2] = legPos->Phi();
FillSparse(fOutputContainer,"hsSel_El_TAP",value3D);
}
cutmask_pid = 0;
cutmask_pid = fPIDFilter->IsSelected(legNeg);
if(cutmask_pid == selectedMask_pid){
value3D[0] = legNeg->Pt();
value3D[1] = legNeg->Eta();
value3D[2] = legNeg->Phi();
FillSparse(fOutputContainer,"hsSel_El_TAP",value3D);
}
}
}
else if(pdgV0 == 310 && TMath::Abs(pdgP) == 211 && TMath::Abs(pdgN) == 211){//K0S
M1 = Mpi;
M2 = Mpi;
if(!v0->GetOnFlyStatus()){
FillHistogramTH2(fOutputContainer,"hV0AP_K0S",alpha,qT);
nsigma_Pi_TPC = (fPIDResponse->NumberOfSigmasTPC(legPos,AliPID::kPion) - AliDielectronPID::GetCorrVal() - AliDielectronPID::GetCntrdCorr(legPos,AliPID::kPion)) / AliDielectronPID::GetWdthCorr(legPos,AliPID::kPion);
nsigma_Pi_ITS = (fPIDResponse->NumberOfSigmasITS(legPos,AliPID::kPion) - AliDielectronPID::GetCntrdCorrITS(legPos,AliPID::kPion)) / AliDielectronPID::GetWdthCorrITS(legPos,AliPID::kPion);
nsigma_Pi_TOF = (fPIDResponse->NumberOfSigmasTOF(legPos,AliPID::kPion) - AliDielectronPID::GetCntrdCorrTOF(legPos,AliPID::kPion)) / AliDielectronPID::GetWdthCorrTOF(legPos,AliPID::kPion);
value[3] = legPos->GetTPCmomentum();
value[4] = legPos->Eta();
value[5] = fPIDResponse->NumberOfSigmasTPC(legPos,AliPID::kPion);
value[6] = fPIDResponse->NumberOfSigmasITS(legPos,AliPID::kPion);
value[7] = fPIDResponse->NumberOfSigmasTOF(legPos,AliPID::kPion);
FillSparse(fOutputContainer,"hsPID_V0Pi",value);
nsigma_Pi_TPC = (fPIDResponse->NumberOfSigmasTPC(legNeg,AliPID::kPion) - AliDielectronPID::GetCorrVal() - AliDielectronPID::GetCntrdCorr(legNeg,AliPID::kPion)) / AliDielectronPID::GetWdthCorr(legNeg,AliPID::kPion);
nsigma_Pi_ITS = (fPIDResponse->NumberOfSigmasITS(legNeg,AliPID::kPion) - AliDielectronPID::GetCntrdCorrITS(legNeg,AliPID::kPion)) / AliDielectronPID::GetWdthCorrITS(legNeg,AliPID::kPion);
nsigma_Pi_TOF = (fPIDResponse->NumberOfSigmasTOF(legNeg,AliPID::kPion) - AliDielectronPID::GetCntrdCorrTOF(legNeg,AliPID::kPion)) / AliDielectronPID::GetWdthCorrTOF(legNeg,AliPID::kPion);
value[3] = legNeg->GetTPCmomentum();
value[4] = legNeg->Eta();
value[5] = fPIDResponse->NumberOfSigmasTPC(legNeg,AliPID::kPion);
value[6] = fPIDResponse->NumberOfSigmasITS(legNeg,AliPID::kPion);
value[7] = fPIDResponse->NumberOfSigmasTOF(legNeg,AliPID::kPion);
FillSparse(fOutputContainer,"hsPID_V0Pi",value);
}
}
else if(pdgV0 == 3122 && (TMath::Abs(pdgP) == 2212 || TMath::Abs(pdgP) == 211) && (TMath::Abs(pdgN) == 211 || TMath::Abs(pdgN) == 2212)){//Lambda
M1 = Mp;
M2 = Mpi;
if(!v0->GetOnFlyStatus()){
FillHistogramTH2(fOutputContainer,"hV0AP_Lambda",alpha,qT);
if(pdgP == -211 && pdgN == 2212){//swapped (this does NOT mean AntiLambda)
M1 = Mpi;
M2 = Mp;
legPos = fESDEvent->GetTrack(v0->GetNindex());//proton
legNeg = fESDEvent->GetTrack(v0->GetPindex());//pi-
}
nsigma_Pr_TPC = (fPIDResponse->NumberOfSigmasTPC(legPos,AliPID::kProton) - AliDielectronPID::GetCorrVal() - AliDielectronPID::GetCntrdCorr(legPos,AliPID::kProton)) / AliDielectronPID::GetWdthCorr(legPos,AliPID::kProton);
nsigma_Pr_ITS = (fPIDResponse->NumberOfSigmasITS(legPos,AliPID::kProton) - AliDielectronPID::GetCntrdCorrITS(legPos,AliPID::kProton)) / AliDielectronPID::GetWdthCorrITS(legPos,AliPID::kProton);
nsigma_Pr_TOF = (fPIDResponse->NumberOfSigmasTOF(legPos,AliPID::kProton) - AliDielectronPID::GetCntrdCorrTOF(legPos,AliPID::kProton)) / AliDielectronPID::GetWdthCorrTOF(legPos,AliPID::kProton);
value[3] = legPos->GetTPCmomentum();
value[4] = legPos->Eta();
value[5] = nsigma_Pr_TPC;
value[6] = nsigma_Pr_ITS;
value[7] = nsigma_Pr_TOF;
FillSparse(fOutputContainer,"hsPID_V0Pr",value);
nsigma_Pi_TPC = (fPIDResponse->NumberOfSigmasTPC(legNeg,AliPID::kPion) - AliDielectronPID::GetCorrVal() - AliDielectronPID::GetCntrdCorr(legNeg,AliPID::kPion)) / AliDielectronPID::GetWdthCorr(legNeg,AliPID::kPion);
nsigma_Pi_ITS = (fPIDResponse->NumberOfSigmasITS(legNeg,AliPID::kPion) - AliDielectronPID::GetCntrdCorrITS(legNeg,AliPID::kPion)) / AliDielectronPID::GetWdthCorrITS(legNeg,AliPID::kPion);
nsigma_Pi_TOF = (fPIDResponse->NumberOfSigmasTOF(legNeg,AliPID::kPion) - AliDielectronPID::GetCntrdCorrTOF(legNeg,AliPID::kPion)) / AliDielectronPID::GetWdthCorrTOF(legNeg,AliPID::kPion);
value[3] = legNeg->GetTPCmomentum();
value[4] = legNeg->Eta();
value[5] = nsigma_Pi_TPC;
value[6] = nsigma_Pi_ITS;
value[7] = nsigma_Pi_TOF;
FillSparse(fOutputContainer,"hsPID_V0Pi",value);
}
}
else if(pdgV0 == -3122 && (TMath::Abs(pdgP) == 2212 || TMath::Abs(pdgP) == 211) && (TMath::Abs(pdgN) == 211 || TMath::Abs(pdgN) == 2212)){//Anti-Lambda
M1 = Mpi;
M2 = Mp;
if(!v0->GetOnFlyStatus()){
FillHistogramTH2(fOutputContainer,"hV0AP_AntiLambda",alpha,qT);
if(pdgP == -2212 && pdgN == 211){//swapped (this does NOT mean Lambda)
M1 = Mp;
M2 = Mpi;
legPos = fESDEvent->GetTrack(v0->GetNindex());//pi+
legNeg = fESDEvent->GetTrack(v0->GetPindex());//anti-proton
}
nsigma_Pi_TPC = (fPIDResponse->NumberOfSigmasTPC(legPos,AliPID::kPion) - AliDielectronPID::GetCorrVal() - AliDielectronPID::GetCntrdCorr(legPos,AliPID::kPion)) / AliDielectronPID::GetWdthCorr(legPos,AliPID::kPion);
nsigma_Pi_ITS = (fPIDResponse->NumberOfSigmasITS(legPos,AliPID::kPion) - AliDielectronPID::GetCntrdCorrITS(legPos,AliPID::kPion)) / AliDielectronPID::GetWdthCorrITS(legPos,AliPID::kPion);
nsigma_Pi_TOF = (fPIDResponse->NumberOfSigmasTOF(legPos,AliPID::kPion) - AliDielectronPID::GetCntrdCorrTOF(legPos,AliPID::kPion)) / AliDielectronPID::GetWdthCorrTOF(legPos,AliPID::kPion);
value[3] = legPos->GetTPCmomentum();
value[4] = legPos->Eta();
value[5] = nsigma_Pi_TPC;
value[6] = nsigma_Pi_ITS;
value[7] = nsigma_Pi_TOF;
FillSparse(fOutputContainer,"hsPID_V0Pi",value);
nsigma_Pr_TPC = (fPIDResponse->NumberOfSigmasTPC(legNeg,AliPID::kProton) - AliDielectronPID::GetCorrVal() - AliDielectronPID::GetCntrdCorr(legNeg,AliPID::kProton)) / AliDielectronPID::GetWdthCorr(legNeg,AliPID::kProton);
nsigma_Pr_ITS = (fPIDResponse->NumberOfSigmasITS(legNeg,AliPID::kProton) - AliDielectronPID::GetCntrdCorrITS(legNeg,AliPID::kProton)) / AliDielectronPID::GetWdthCorrITS(legNeg,AliPID::kProton);
nsigma_Pr_TOF = (fPIDResponse->NumberOfSigmasTOF(legNeg,AliPID::kProton) - AliDielectronPID::GetCntrdCorrTOF(legNeg,AliPID::kProton)) / AliDielectronPID::GetWdthCorrTOF(legNeg,AliPID::kProton);
value[3] = legNeg->GetTPCmomentum();
value[4] = legNeg->Eta();
value[5] = nsigma_Pr_TPC;
value[6] = nsigma_Pr_ITS;
value[7] = nsigma_Pr_TOF;
FillSparse(fOutputContainer,"hsPID_V0Pr",value);
}
}
}
}
//________________________________________________________________________
void AliAnalysisTaskTagAndProbe::FillV0InfoAOD()
{
Int_t NclsSDD0 = fEvent->GetMultiplicity()->GetNumberOfITSClusters(2);
Int_t NclsSDD1 = fEvent->GetMultiplicity()->GetNumberOfITSClusters(3);
Int_t NclsSSD0 = fEvent->GetMultiplicity()->GetNumberOfITSClusters(4);
Int_t NclsSSD1 = fEvent->GetMultiplicity()->GetNumberOfITSClusters(5);
Int_t NSDDSSD = NclsSDD0 + NclsSDD1 + NclsSSD0 + NclsSSD1;
AliAODHeader *header = dynamic_cast<AliAODHeader*>(fAODEvent->GetHeader());
static TVectorF dummyVertexInfo(10); // to be used with old AODs w/o vertex info
const TVectorF &tpcVertexInfo = header->GetTPCPileUpInfo() ? *header->GetTPCPileUpInfo() : dummyVertexInfo;
Float_t TPCpileupZ = tpcVertexInfo[2];
Float_t TPCpileupM = tpcVertexInfo[5];
const AliVVertex *vVertex = fEvent->GetPrimaryVertex();
AliKFVertex primaryVertexKF(*vVertex);
fAODv0KineCuts->SetEvent(InputEvent());
fAODv0KineCuts->SetPrimaryVertex(&primaryVertexKF);
UInt_t selectedMask_pid = (1<<fPIDFilter->GetCuts()->GetEntries())-1;
Double_t M12 = 0;
Int_t pdgV0 = 0, pdgP = 0, pdgN = 0;
Float_t qT = 0, alpha = 0;
Float_t Lxy = 0;
Float_t nsigma_El_TPC = -999 , nsigma_Pi_TPC = -999 , nsigma_Pr_TPC = -999;
Float_t nsigma_El_ITS = -999 , nsigma_Pi_ITS = -999 , nsigma_Pr_ITS = -999;
Float_t nsigma_El_TOF = -999 , nsigma_Pi_TOF = -999 , nsigma_Pr_TOF = -999;
Double_t value3D[3] = {0,0,0};
const Int_t Nv0 = fEvent->GetNumberOfV0s();
Double_t value[8] = {};
for(Int_t i=0;i<8;i++) value[i] = 0.0;
value[0] = NSDDSSD;
value[1] = TPCpileupZ;
value[2] = TPCpileupM;
for(Int_t iv0=0;iv0<Nv0;iv0++){
AliAODv0 *v0 = (AliAODv0*)fAODEvent->GetV0(iv0);
if(v0->RadiusV0() > 60.) continue;
if(v0->CosPointingAngle(dynamic_cast<AliAODVertex *>(fAODEvent->GetPrimaryVertex())) < 0.98) continue;
AliAODTrack *legPos = dynamic_cast<AliAODTrack*>(v0->GetSecondaryVtx()->GetDaughter(0));
AliAODTrack *legNeg = dynamic_cast<AliAODTrack*>(v0->GetSecondaryVtx()->GetDaughter(1));
if(legPos->Charge() * legNeg->Charge() > 0) continue;//reject same sign pair
if(legPos->Pt() < 0.15) continue;
if(legNeg->Pt() < 0.15) continue;
if(TMath::Abs(legPos->Eta()) > 0.9) continue;
if(TMath::Abs(legNeg->Eta()) > 0.9) continue;
if(!legPos->TestFilterBit(AliAODTrack::kTrkGlobalNoDCA)) continue;//standard cuts with very loose DCA cut //bit4
if(!legNeg->TestFilterBit(AliAODTrack::kTrkGlobalNoDCA)) continue;//standard cuts with very loose DCA cut //bit4
Float_t DCAxy_leg = -999, DCAz_leg = -999;
legPos->GetImpactParameters(DCAxy_leg,DCAz_leg);
if(TMath::Abs(DCAxy_leg) > 1.) continue;
if(TMath::Abs(DCAz_leg) > 3.) continue;
DCAxy_leg = -999; DCAz_leg = -999;
legNeg->GetImpactParameters(DCAxy_leg,DCAz_leg);
if(TMath::Abs(DCAxy_leg) > 1.) continue;
if(TMath::Abs(DCAz_leg) > 3.) continue;
AliAODVertex *avp = (AliAODVertex*)legPos->GetProdVertex();
AliAODVertex *avn = (AliAODVertex*)legNeg->GetProdVertex();
if(avp->GetType() == AliAODVertex::kKink) continue;//reject kink
if(avn->GetType() == AliAODVertex::kKink) continue;//reject kink
if(!(legPos->GetStatus() & AliVTrack::kITSrefit)) continue;
if(!(legNeg->GetStatus() & AliVTrack::kITSrefit)) continue;
if(legPos->GetNcls(0) < 2.5) continue;//minimum number of ITS cluster 3
if(legNeg->GetNcls(0) < 2.5) continue;//minimum number of ITS cluster 3
if(legPos->GetITSchi2() / legPos->GetNcls(0) > 36.) continue;//maximum chi2 per cluster ITS
if(legNeg->GetITSchi2() / legNeg->GetNcls(0) > 36.) continue;//maximum chi2 per cluster ITS
if(!(legPos->GetStatus() & AliVTrack::kTPCrefit)) continue;
if(!(legNeg->GetStatus() & AliVTrack::kTPCrefit)) continue;
if(legPos->GetTPCCrossedRows() < 70) continue;//minimum number of TPC crossed rows 70
if(legNeg->GetTPCCrossedRows() < 70) continue;//minimum number of TPC crossed rows 70
if(legPos->GetTPCchi2() / legPos->GetNcls(1) > 2.5) continue;//maximum chi2 per cluster TPC
if(legNeg->GetTPCchi2() / legNeg->GetNcls(1) > 2.5) continue;//maximum chi2 per cluster TPC
Float_t ratio_pos = legPos->GetTPCNclsF() > 0 ? (Float_t)legPos->GetTPCCrossedRows() / (Float_t)legPos->GetTPCNclsF() : 1.0;
Float_t ratio_neg = legNeg->GetTPCNclsF() > 0 ? (Float_t)legNeg->GetTPCCrossedRows() / (Float_t)legNeg->GetTPCNclsF() : 1.0;
if(ratio_pos < 0.8) continue;
if(ratio_neg < 0.8) continue;
if(!legPos->HasPointOnITSLayer(0) && !legPos->HasPointOnITSLayer(1)) continue;//accept SPDany
if(!legNeg->HasPointOnITSLayer(0) && !legNeg->HasPointOnITSLayer(1)) continue;//accept SPDany
Lxy = v0->RadiusV0();//in cm
alpha = v0->AlphaV0();
qT = v0->PtArmV0();
FillHistogramTH2(fOutputContainer,"hV0AP",alpha,qT);
FillHistogramTH1(fOutputContainer,"hV0CosPointingAngle",v0->CosPointingAngle(dynamic_cast<AliAODVertex *>(fAODEvent->GetPrimaryVertex())) );
//ULong64_t status1 = legPos->GetStatus();
//ULong64_t status2 = legNeg->GetStatus();
//Bool_t isTIME1 = status1 & AliVTrack::kTIME;
//Bool_t isTIME2 = status2 & AliVTrack::kTIME;
//Bool_t isTOFout1 = status1 & AliVTrack::kTOFout;
//Bool_t isTOFout2 = status2 & AliVTrack::kTOFout;
//Bool_t isTOFOK1 = isTIME1 & isTOFout1;
//Bool_t isTOFOK2 = isTIME2 & isTOFout2;
pdgV0 = 0; pdgP = 0; pdgN = 0;
if(!fAODv0KineCuts->ProcessV0(v0,pdgV0,pdgP,pdgN)) continue;
//fV0Mass.push_back(v0->InvMass2Prongs(0,1,TMath::Abs(pdgP),TMath::Abs(pdgN)));
for(Int_t i=3;i<8;i++) value[i] = 0.0;
if(pdgV0 == 22 && TMath::Abs(pdgP) == 11 && TMath::Abs(pdgN) == 11){//GammaConv
M12 = v0->InvMass2Prongs(0,1,TMath::Abs(pdgP),TMath::Abs(pdgN));
FillHistogramTH2(fOutputContainer,"hV0Lxy",Lxy,M12);
nsigma_El_TPC = (fPIDResponse->NumberOfSigmasTPC(legPos,AliPID::kElectron) - AliDielectronPID::GetCorrVal() - AliDielectronPID::GetCntrdCorr(legPos,AliPID::kElectron)) / AliDielectronPID::GetWdthCorr(legPos,AliPID::kElectron);
nsigma_El_ITS = (fPIDResponse->NumberOfSigmasITS(legPos,AliPID::kElectron) - AliDielectronPID::GetCntrdCorrITS(legPos,AliPID::kElectron)) / AliDielectronPID::GetWdthCorrITS(legPos,AliPID::kElectron);
nsigma_El_TOF = (fPIDResponse->NumberOfSigmasTOF(legPos,AliPID::kElectron) - AliDielectronPID::GetCntrdCorrTOF(legPos,AliPID::kElectron)) / AliDielectronPID::GetWdthCorrTOF(legPos,AliPID::kElectron);
value[3] = legPos->GetTPCmomentum();
value[4] = legPos->Eta();
value[5] = nsigma_El_TPC;
value[6] = nsigma_El_ITS;
value[7] = nsigma_El_TOF;
if(HasConversionPointOnSPD(v0,legPos,legNeg)){
FillHistogramTH2(fOutputContainer,"hV0Lxy_GammaConv",Lxy,M12);
FillHistogramTH2(fOutputContainer,"hV0AP_GammaConv",alpha,qT);
if(v0->GetOnFlyStatus()) FillSparse(fOutputContainer,"hsPID_V0El_online" ,value);
else FillSparse(fOutputContainer,"hsPID_V0El_offline",value);
}
else if(TMath::Abs(Lxy - 20.0) < 2.0){ //18-22cm in radius
if(v0->GetOnFlyStatus()) FillSparse(fOutputContainer,"hsPID_V0El_bkg_online" ,value);
else FillSparse(fOutputContainer,"hsPID_V0El_bkg_offline",value);
}
nsigma_El_TPC = (fPIDResponse->NumberOfSigmasTPC(legNeg,AliPID::kElectron) - AliDielectronPID::GetCorrVal() - AliDielectronPID::GetCntrdCorr(legNeg,AliPID::kElectron)) / AliDielectronPID::GetWdthCorr(legNeg,AliPID::kElectron);
nsigma_El_ITS = (fPIDResponse->NumberOfSigmasITS(legNeg,AliPID::kElectron) - AliDielectronPID::GetCntrdCorrITS(legNeg,AliPID::kElectron)) / AliDielectronPID::GetWdthCorrITS(legNeg,AliPID::kElectron);
nsigma_El_TOF = (fPIDResponse->NumberOfSigmasTOF(legNeg,AliPID::kElectron) - AliDielectronPID::GetCntrdCorrTOF(legNeg,AliPID::kElectron)) / AliDielectronPID::GetWdthCorrTOF(legNeg,AliPID::kElectron);
value[3] = legNeg->GetTPCmomentum();
value[4] = legNeg->Eta();
value[5] = nsigma_El_TPC;
value[6] = nsigma_El_ITS;
value[7] = nsigma_El_TOF;
if(HasConversionPointOnSPD(v0,legPos,legNeg)){
if(v0->GetOnFlyStatus()) FillSparse(fOutputContainer,"hsPID_V0El_online" ,value);
else FillSparse(fOutputContainer,"hsPID_V0El_offline",value);
}
else if(TMath::Abs(Lxy - 20.0) < 2.0){ //18-22cm in radius
if(v0->GetOnFlyStatus()) FillSparse(fOutputContainer,"hsPID_V0El_bkg_online" ,value);
else FillSparse(fOutputContainer,"hsPID_V0El_bkg_offline",value);
}
if(TMath::Abs(nsigma_El_TPC) < 3.){//electron is pre-selected by loose 3 sigma.
//for PID efficiency by DDA
//fill denominator
value3D[0] = legPos->Pt();
value3D[1] = legPos->Eta();
value3D[2] = legPos->Phi();
FillSparse(fOutputContainer,"hsAll_El_TAP",value3D);
value3D[0] = legNeg->Pt();
value3D[1] = legNeg->Eta();
value3D[2] = legNeg->Phi();
FillSparse(fOutputContainer,"hsAll_El_TAP",value3D);
//fill nominator
UInt_t cutmask_pid = fPIDFilter->IsSelected(legPos);
if(cutmask_pid == selectedMask_pid){
value3D[0] = legPos->Pt();
value3D[1] = legPos->Eta();
value3D[2] = legPos->Phi();
FillSparse(fOutputContainer,"hsSel_El_TAP",value3D);
}
cutmask_pid = 0;
cutmask_pid = fPIDFilter->IsSelected(legNeg);
if(cutmask_pid == selectedMask_pid){
value3D[0] = legNeg->Pt();
value3D[1] = legNeg->Eta();
value3D[2] = legNeg->Phi();
FillSparse(fOutputContainer,"hsSel_El_TAP",value3D);
}
}
}
else if(pdgV0 == 310 && TMath::Abs(pdgP) == 211 && TMath::Abs(pdgN) == 211){//K0S
if(!v0->GetOnFlyStatus()){
FillHistogramTH2(fOutputContainer,"hV0AP_K0S",alpha,qT);
nsigma_Pi_TPC = (fPIDResponse->NumberOfSigmasTPC(legPos,AliPID::kPion) - AliDielectronPID::GetCorrVal() - AliDielectronPID::GetCntrdCorr(legPos,AliPID::kPion)) / AliDielectronPID::GetWdthCorr(legPos,AliPID::kPion);
nsigma_Pi_ITS = (fPIDResponse->NumberOfSigmasITS(legPos,AliPID::kPion) - AliDielectronPID::GetCntrdCorrITS(legPos,AliPID::kPion)) / AliDielectronPID::GetWdthCorrITS(legPos,AliPID::kPion);
nsigma_Pi_TOF = (fPIDResponse->NumberOfSigmasTOF(legPos,AliPID::kPion) - AliDielectronPID::GetCntrdCorrTOF(legPos,AliPID::kPion)) / AliDielectronPID::GetWdthCorrTOF(legPos,AliPID::kPion);
value[3] = legPos->GetTPCmomentum();
value[4] = legPos->Eta();
value[5] = fPIDResponse->NumberOfSigmasTPC(legPos,AliPID::kPion);
value[6] = fPIDResponse->NumberOfSigmasITS(legPos,AliPID::kPion);
value[7] = fPIDResponse->NumberOfSigmasTOF(legPos,AliPID::kPion);
FillSparse(fOutputContainer,"hsPID_V0Pi",value);
nsigma_Pi_TPC = (fPIDResponse->NumberOfSigmasTPC(legNeg,AliPID::kPion) - AliDielectronPID::GetCorrVal() - AliDielectronPID::GetCntrdCorr(legNeg,AliPID::kPion)) / AliDielectronPID::GetWdthCorr(legNeg,AliPID::kPion);
nsigma_Pi_ITS = (fPIDResponse->NumberOfSigmasITS(legNeg,AliPID::kPion) - AliDielectronPID::GetCntrdCorrITS(legNeg,AliPID::kPion)) / AliDielectronPID::GetWdthCorrITS(legNeg,AliPID::kPion);
nsigma_Pi_TOF = (fPIDResponse->NumberOfSigmasTOF(legNeg,AliPID::kPion) - AliDielectronPID::GetCntrdCorrTOF(legNeg,AliPID::kPion)) / AliDielectronPID::GetWdthCorrTOF(legNeg,AliPID::kPion);
value[3] = legNeg->GetTPCmomentum();
value[4] = legNeg->Eta();
value[5] = fPIDResponse->NumberOfSigmasTPC(legNeg,AliPID::kPion);
value[6] = fPIDResponse->NumberOfSigmasITS(legNeg,AliPID::kPion);
value[7] = fPIDResponse->NumberOfSigmasTOF(legNeg,AliPID::kPion);
FillSparse(fOutputContainer,"hsPID_V0Pi",value);
}
}
else if(pdgV0 == 3122 && (TMath::Abs(pdgP) == 2212 || TMath::Abs(pdgP) == 211) && (TMath::Abs(pdgN) == 211 || TMath::Abs(pdgN) == 2212)){//Lambda
if(!v0->GetOnFlyStatus()){
FillHistogramTH2(fOutputContainer,"hV0AP_Lambda",alpha,qT);
if(pdgP == -211 && pdgN == 2212){//swapped (this does NOT mean AntiLambda)
legPos = dynamic_cast<AliAODTrack*>(v0->GetSecondaryVtx()->GetDaughter(1));//proton
legNeg = dynamic_cast<AliAODTrack*>(v0->GetSecondaryVtx()->GetDaughter(0));//pi-
}
nsigma_Pr_TPC = (fPIDResponse->NumberOfSigmasTPC(legPos,AliPID::kProton) - AliDielectronPID::GetCorrVal() - AliDielectronPID::GetCntrdCorr(legPos,AliPID::kProton)) / AliDielectronPID::GetWdthCorr(legPos,AliPID::kProton);
nsigma_Pr_ITS = (fPIDResponse->NumberOfSigmasITS(legPos,AliPID::kProton) - AliDielectronPID::GetCntrdCorrITS(legPos,AliPID::kProton)) / AliDielectronPID::GetWdthCorrITS(legPos,AliPID::kProton);
nsigma_Pr_TOF = (fPIDResponse->NumberOfSigmasTOF(legPos,AliPID::kProton) - AliDielectronPID::GetCntrdCorrTOF(legPos,AliPID::kProton)) / AliDielectronPID::GetWdthCorrTOF(legPos,AliPID::kProton);
value[3] = legPos->GetTPCmomentum();
value[4] = legPos->Eta();
value[5] = nsigma_Pr_TPC;
value[6] = nsigma_Pr_ITS;
value[7] = nsigma_Pr_TOF;
FillSparse(fOutputContainer,"hsPID_V0Pr",value);
nsigma_Pi_TPC = (fPIDResponse->NumberOfSigmasTPC(legNeg,AliPID::kPion) - AliDielectronPID::GetCorrVal() - AliDielectronPID::GetCntrdCorr(legNeg,AliPID::kPion)) / AliDielectronPID::GetWdthCorr(legNeg,AliPID::kPion);
nsigma_Pi_ITS = (fPIDResponse->NumberOfSigmasITS(legNeg,AliPID::kPion) - AliDielectronPID::GetCntrdCorrITS(legNeg,AliPID::kPion)) / AliDielectronPID::GetWdthCorrITS(legNeg,AliPID::kPion);
nsigma_Pi_TOF = (fPIDResponse->NumberOfSigmasTOF(legNeg,AliPID::kPion) - AliDielectronPID::GetCntrdCorrTOF(legNeg,AliPID::kPion)) / AliDielectronPID::GetWdthCorrTOF(legNeg,AliPID::kPion);
value[3] = legNeg->GetTPCmomentum();
value[4] = legNeg->Eta();
value[5] = nsigma_Pi_TPC;
value[6] = nsigma_Pi_ITS;
value[7] = nsigma_Pi_TOF;
FillSparse(fOutputContainer,"hsPID_V0Pi",value);
}
}
else if(pdgV0 == -3122 && (TMath::Abs(pdgP) == 2212 || TMath::Abs(pdgP) == 211) && (TMath::Abs(pdgN) == 211 || TMath::Abs(pdgN) == 2212)){//Anti-Lambda
if(!v0->GetOnFlyStatus()){
FillHistogramTH2(fOutputContainer,"hV0AP_AntiLambda",alpha,qT);
if(pdgP == -2212 && pdgN == 211){//swapped (this does NOT mean Lambda)
legPos = dynamic_cast<AliAODTrack*>(v0->GetSecondaryVtx()->GetDaughter(1));//pi+
legNeg = dynamic_cast<AliAODTrack*>(v0->GetSecondaryVtx()->GetDaughter(0));//anti-proton
}
nsigma_Pi_TPC = (fPIDResponse->NumberOfSigmasTPC(legPos,AliPID::kPion) - AliDielectronPID::GetCorrVal() - AliDielectronPID::GetCntrdCorr(legPos,AliPID::kPion)) / AliDielectronPID::GetWdthCorr(legPos,AliPID::kPion);
nsigma_Pi_ITS = (fPIDResponse->NumberOfSigmasITS(legPos,AliPID::kPion) - AliDielectronPID::GetCntrdCorrITS(legPos,AliPID::kPion)) / AliDielectronPID::GetWdthCorrITS(legPos,AliPID::kPion);
nsigma_Pi_TOF = (fPIDResponse->NumberOfSigmasTOF(legPos,AliPID::kPion) - AliDielectronPID::GetCntrdCorrTOF(legPos,AliPID::kPion)) / AliDielectronPID::GetWdthCorrTOF(legPos,AliPID::kPion);
value[3] = legPos->GetTPCmomentum();
value[4] = legPos->Eta();
value[5] = nsigma_Pi_TPC;
value[6] = nsigma_Pi_ITS;
value[7] = nsigma_Pi_TOF;
FillSparse(fOutputContainer,"hsPID_V0Pi",value);
nsigma_Pr_TPC = (fPIDResponse->NumberOfSigmasTPC(legNeg,AliPID::kProton) - AliDielectronPID::GetCorrVal() - AliDielectronPID::GetCntrdCorr(legNeg,AliPID::kProton)) / AliDielectronPID::GetWdthCorr(legNeg,AliPID::kProton);
nsigma_Pr_ITS = (fPIDResponse->NumberOfSigmasITS(legNeg,AliPID::kProton) - AliDielectronPID::GetCntrdCorrITS(legNeg,AliPID::kProton)) / AliDielectronPID::GetWdthCorrITS(legNeg,AliPID::kProton);
nsigma_Pr_TOF = (fPIDResponse->NumberOfSigmasTOF(legNeg,AliPID::kProton) - AliDielectronPID::GetCntrdCorrTOF(legNeg,AliPID::kProton)) / AliDielectronPID::GetWdthCorrTOF(legNeg,AliPID::kProton);
value[3] = legNeg->GetTPCmomentum();
value[4] = legNeg->Eta();
value[5] = nsigma_Pr_TPC;
value[6] = nsigma_Pr_ITS;
value[7] = nsigma_Pr_TOF;
FillSparse(fOutputContainer,"hsPID_V0Pr",value);
}
}
}//end of v0 loop
}
//________________________________________________________________________
void AliAnalysisTaskTagAndProbe::CutEfficiency()
{
//tag and probe method.
const Double_t Me = TDatabasePDG::Instance()->GetParticle(11)->Mass();
//const Int_t trackMult = fEvent->GetNumberOfTracks();
//UInt_t selectedMask_tag = (1<<fTagFilter->GetCuts()->GetEntries())-1;
//UInt_t selectedMask_probe = (1<<fProbeFilter->GetCuts()->GetEntries())-1;
//UInt_t selectedMask_passingprobe = (1<<fPassingProbeFilter->GetCuts()->GetEntries())-1;
Double_t value[4] = {0,0,0,0};
const Int_t trackMult_tag = fTagTrackArray->GetEntries();
const Int_t trackMult_p = fProbeTrackArray->GetEntries();
const Int_t trackMult_pp = fPassingProbeTrackArray->GetEntries();
//same particle combination is rejected by pointer.
//fill ULS -+ same
for(Int_t i1=0;i1<trackMult_tag;i1++){
AliVParticle *par1 = (AliVParticle*)fTagTrackArray->At(i1);
if(par1->Charge() > 0) continue;
//apply tight cut to particle1
TLorentzVector pv1 = TLorentzVector();
pv1.SetPtEtaPhiM(par1->Pt(),par1->Eta(),par1->Phi(),Me);
for(Int_t i2=0;i2<trackMult_p;i2++){
AliVParticle *par2 = (AliVParticle*)fProbeTrackArray->At(i2);
if(par2 == par1) continue;
if(par2->Charge() < 0) continue;
TLorentzVector pv2 = TLorentzVector();
pv2.SetPtEtaPhiM(par2->Pt(),par2->Eta(),par2->Phi(),Me);
TLorentzVector p12 = pv1 + pv2;
value[0] = p12.M();
value[1] = pv2.Pt();
value[2] = pv2.Eta();
value[3] = pv2.Phi();
if(value[3] < 0) value[3] += TMath::TwoPi();
Float_t phiv = PhivPair(fEvent->GetMagneticField(),par1->Charge(),par2->Charge(),pv1.Vect(),pv2.Vect());
FillHistogramTH2(fOutputContainer,"hPairMvsPhiV",phiv,p12.M());
if(
(0 < p12.M() && p12.M() < fMmax)
&& (fPhiVmin < phiv && phiv < TMath::Pi())
) continue;
FillHistogramTH2(fOutputContainer,"hProbe_ULS_same",p12.M(),pv2.Pt());
}//end of par2
for(Int_t i2=0;i2<trackMult_pp;i2++){
AliVParticle *par2 = (AliVParticle*)fPassingProbeTrackArray->At(i2);
if(par2 == par1) continue;
if(par2->Charge() < 0) continue;
TLorentzVector pv2 = TLorentzVector();
pv2.SetPtEtaPhiM(par2->Pt(),par2->Eta(),par2->Phi(),Me);
TLorentzVector p12 = pv1 + pv2;
value[0] = p12.M();
value[1] = pv2.Pt();
value[2] = pv2.Eta();
value[3] = pv2.Phi();
if(value[3] < 0) value[3] += TMath::TwoPi();
Float_t phiv = PhivPair(fEvent->GetMagneticField(),par1->Charge(),par2->Charge(),pv1.Vect(),pv2.Vect());
if(
(0 < p12.M() && p12.M() < fMmax)
&& (fPhiVmin < phiv && phiv < TMath::Pi())
) continue;
FillHistogramTH2(fOutputContainer,"hPassingProbe_ULS_same",p12.M(),pv2.Pt());
}//end of par2
}//end of par1
//fill ULS +- same
for(Int_t i1=0;i1<trackMult_tag;i1++){
//AliVParticle *par1 = (AliVParticle*)fEvent->GetTrack(i1);
AliVParticle *par1 = (AliVParticle*)fTagTrackArray->At(i1);
if(par1->Charge() < 0) continue;
//apply tight cut to particle1
TLorentzVector pv1 = TLorentzVector();
pv1.SetPtEtaPhiM(par1->Pt(),par1->Eta(),par1->Phi(),Me);
for(Int_t i2=0;i2<trackMult_p;i2++){
//if(i2==i1) continue;//reject same track combination
//AliVParticle *par2 = (AliVParticle*)fEvent->GetTrack(i2);
AliVParticle *par2 = (AliVParticle*)fProbeTrackArray->At(i2);
if(par2 == par1) continue;
if(par2->Charge() > 0) continue;
TLorentzVector pv2 = TLorentzVector();
pv2.SetPtEtaPhiM(par2->Pt(),par2->Eta(),par2->Phi(),Me);
TLorentzVector p12 = pv1 + pv2;
value[0] = p12.M();
value[1] = pv2.Pt();
value[2] = pv2.Eta();
value[3] = pv2.Phi();
if(value[3] < 0) value[3] += TMath::TwoPi();
Float_t phiv = PhivPair(fEvent->GetMagneticField(),par1->Charge(),par2->Charge(),pv1.Vect(),pv2.Vect());
FillHistogramTH2(fOutputContainer,"hPairMvsPhiV",phiv,p12.M());
if(
(0 < p12.M() && p12.M() < fMmax)
&& (fPhiVmin < phiv && phiv < TMath::Pi())
) continue;
FillHistogramTH2(fOutputContainer,"hProbe_ULS_same",p12.M(),pv2.Pt());
}//end of par2
for(Int_t i2=0;i2<trackMult_pp;i2++){
//if(i2==i1) continue;//reject same track combination
//AliVParticle *par2 = (AliVParticle*)fEvent->GetTrack(i2);
AliVParticle *par2 = (AliVParticle*)fPassingProbeTrackArray->At(i2);
if(par2 == par1) continue;
if(par2->Charge() > 0) continue;
TLorentzVector pv2 = TLorentzVector();
pv2.SetPtEtaPhiM(par2->Pt(),par2->Eta(),par2->Phi(),Me);
TLorentzVector p12 = pv1 + pv2;
value[0] = p12.M();
value[1] = pv2.Pt();
value[2] = pv2.Eta();
value[3] = pv2.Phi();
if(value[3] < 0) value[3] += TMath::TwoPi();
Float_t phiv = PhivPair(fEvent->GetMagneticField(),par1->Charge(),par2->Charge(),pv1.Vect(),pv2.Vect());
if(
(0 < p12.M() && p12.M() < fMmax)
&& (fPhiVmin < phiv && phiv < TMath::Pi())
) continue;
FillHistogramTH2(fOutputContainer,"hPassingProbe_ULS_same",p12.M(),pv2.Pt());
}//end of par2
}//end of par1
//fill LS ++ same
for(Int_t i1=0;i1<trackMult_tag;i1++){
//AliVParticle *par1 = (AliVParticle*)fEvent->GetTrack(i1);
AliVParticle *par1 = (AliVParticle*)fTagTrackArray->At(i1);
if(par1->Charge() < 0) continue;
//apply tight cut to particle1
TLorentzVector pv1 = TLorentzVector();
pv1.SetPtEtaPhiM(par1->Pt(),par1->Eta(),par1->Phi(),Me);
for(Int_t i2=0;i2<trackMult_p;i2++){
//if(i2==i1) continue;//reject same track combination
//AliVParticle *par2 = (AliVParticle*)fEvent->GetTrack(i2);
AliVParticle *par2 = (AliVParticle*)fProbeTrackArray->At(i2);
if(par2 == par1) continue;
if(par2->Charge() < 0) continue;
TLorentzVector pv2 = TLorentzVector();
pv2.SetPtEtaPhiM(par2->Pt(),par2->Eta(),par2->Phi(),Me);
TLorentzVector p12 = pv1 + pv2;
value[0] = p12.M();
value[1] = pv2.Pt();
value[2] = pv2.Eta();
value[3] = pv2.Phi();
if(value[3] < 0) value[3] += TMath::TwoPi();
Float_t phiv = PhivPair(fEvent->GetMagneticField(),par1->Charge(),par2->Charge(),pv1.Vect(),pv2.Vect());
if(
(0 < p12.M() && p12.M() < fMmax)
&& (fPhiVmin < phiv && phiv < TMath::Pi())
) continue;
FillHistogramTH2(fOutputContainer,"hProbe_LSpp_same",p12.M(),pv2.Pt());
}//end of par2
for(Int_t i2=0;i2<trackMult_pp;i2++){
//if(i2==i1) continue;//reject same track combination
//AliVParticle *par2 = (AliVParticle*)fEvent->GetTrack(i2);
AliVParticle *par2 = (AliVParticle*)fPassingProbeTrackArray->At(i2);
if(par2 == par1) continue;
if(par2->Charge() < 0) continue;
TLorentzVector pv2 = TLorentzVector();
pv2.SetPtEtaPhiM(par2->Pt(),par2->Eta(),par2->Phi(),Me);
TLorentzVector p12 = pv1 + pv2;
value[0] = p12.M();
value[1] = pv2.Pt();
value[2] = pv2.Eta();
value[3] = pv2.Phi();
if(value[3] < 0) value[3] += TMath::TwoPi();
Float_t phiv = PhivPair(fEvent->GetMagneticField(),par1->Charge(),par2->Charge(),pv1.Vect(),pv2.Vect());
if(
(0 < p12.M() && p12.M() < fMmax)
&& (fPhiVmin < phiv && phiv < TMath::Pi())
) continue;
FillHistogramTH2(fOutputContainer,"hPassingProbe_LSpp_same",p12.M(),pv2.Pt());
}//end of par2
}//end of par1
//fill LS -- same
for(Int_t i1=0;i1<trackMult_tag;i1++){
AliVParticle *par1 = (AliVParticle*)fTagTrackArray->At(i1);
if(par1->Charge() > 0) continue;
//apply tight cut to particle1
TLorentzVector pv1 = TLorentzVector();
pv1.SetPtEtaPhiM(par1->Pt(),par1->Eta(),par1->Phi(),Me);
for(Int_t i2=0;i2<trackMult_p;i2++){
AliVParticle *par2 = (AliVParticle*)fProbeTrackArray->At(i2);
if(par2 == par1) continue;
if(par2->Charge() > 0) continue;
TLorentzVector pv2 = TLorentzVector();
pv2.SetPtEtaPhiM(par2->Pt(),par2->Eta(),par2->Phi(),Me);
TLorentzVector p12 = pv1 + pv2;
value[0] = p12.M();
value[1] = pv2.Pt();
value[2] = pv2.Eta();
value[3] = pv2.Phi();
if(value[3] < 0) value[3] += TMath::TwoPi();
Float_t phiv = PhivPair(fEvent->GetMagneticField(),par1->Charge(),par2->Charge(),pv1.Vect(),pv2.Vect());
if(
(0 < p12.M() && p12.M() < fMmax)
&& (fPhiVmin < phiv && phiv < TMath::Pi())
) continue;
FillHistogramTH2(fOutputContainer,"hProbe_LSnn_same",p12.M(),pv2.Pt());
}//end of par2
for(Int_t i2=0;i2<trackMult_pp;i2++){
AliVParticle *par2 = (AliVParticle*)fPassingProbeTrackArray->At(i2);
if(par2 == par1) continue;
if(par2->Charge() > 0) continue;
TLorentzVector pv2 = TLorentzVector();
pv2.SetPtEtaPhiM(par2->Pt(),par2->Eta(),par2->Phi(),Me);
TLorentzVector p12 = pv1 + pv2;
value[0] = p12.M();
value[1] = pv2.Pt();
value[2] = pv2.Eta();
value[3] = pv2.Phi();
if(value[3] < 0) value[3] += TMath::TwoPi();
Float_t phiv = PhivPair(fEvent->GetMagneticField(),par1->Charge(),par2->Charge(),pv1.Vect(),pv2.Vect());
if(
(0 < p12.M() && p12.M() < fMmax)
&& (fPhiVmin < phiv && phiv < TMath::Pi())
) continue;
FillHistogramTH2(fOutputContainer,"hPassingProbe_LSnn_same",p12.M(),pv2.Pt());
}//end of par2
}//end of par1
//next mixed event
TList *prevEvent_p = fEventList[0][fZvtxBin];
TList *prevEvent_pp = fEventList[1][fZvtxBin];
//fill ULS -+ mix
for(Int_t i1=0;i1<trackMult_tag;i1++){
AliVParticle *par1 = (AliVParticle*)fTagTrackArray->At(i1);
if(par1->Charge() > 0) continue;
//apply tight cut to particle1
TLorentzVector pv1 = TLorentzVector();
pv1.SetPtEtaPhiM(par1->Pt(),par1->Eta(),par1->Phi(),Me);
for(Int_t iev=0;iev<prevEvent_p->GetEntries();iev++){
TObjArray *arrmix = static_cast<TObjArray*>(prevEvent_p->At(iev));
for(Int_t i2=0;i2<arrmix->GetEntriesFast();i2++){
AliVParticle *par2 = (AliVParticle*)arrmix->At(i2);
if(par2->Charge() < 0) continue;
//UInt_t cutmask_probe = fProbeFilter->IsSelected(par2);
//if(cutmask_probe != selectedMask_probe) continue;
TLorentzVector pv2 = TLorentzVector();
pv2.SetPtEtaPhiM(par2->Pt(),par2->Eta(),par2->Phi(),Me);
TLorentzVector p12 = pv1 + pv2;
value[0] = p12.M();
value[1] = pv2.Pt();
value[2] = pv2.Eta();
value[3] = pv2.Phi();
if(value[3] < 0) value[3] += TMath::TwoPi();
Float_t phiv = PhivPair(fEvent->GetMagneticField(),par1->Charge(),par2->Charge(),pv1.Vect(),pv2.Vect());
if(
(0 < p12.M() && p12.M() < fMmax)
&& (fPhiVmin < phiv && phiv < TMath::Pi())
) continue;
FillHistogramTH2(fOutputContainer,"hProbe_ULS_mix",p12.M(),pv2.Pt());
}//end of par2
}//end of mix event loop
for(Int_t iev=0;iev<prevEvent_pp->GetEntries();iev++){
TObjArray *arrmix = (TObjArray*)prevEvent_pp->At(iev);
for(Int_t i2=0;i2<arrmix->GetEntries();i2++){
AliVParticle *par2 = (AliVParticle*)arrmix->At(i2);
if(par2->Charge() < 0) continue;
//UInt_t cutmask_probe = fProbeFilter->IsSelected(par2);
//if(cutmask_probe != selectedMask_probe) continue;
TLorentzVector pv2 = TLorentzVector();
pv2.SetPtEtaPhiM(par2->Pt(),par2->Eta(),par2->Phi(),Me);
TLorentzVector p12 = pv1 + pv2;
value[0] = p12.M();
value[1] = pv2.Pt();
value[2] = pv2.Eta();
value[3] = pv2.Phi();
if(value[3] < 0) value[3] += TMath::TwoPi();
Float_t phiv = PhivPair(fEvent->GetMagneticField(),par1->Charge(),par2->Charge(),pv1.Vect(),pv2.Vect());
if(
(0 < p12.M() && p12.M() < fMmax)
&& (fPhiVmin < phiv && phiv < TMath::Pi())
) continue;
FillHistogramTH2(fOutputContainer,"hPassingProbe_ULS_mix",p12.M(),pv2.Pt());
}//end of par2
}//end of mix event loop
}//end of par1
//fill ULS +- mix
for(Int_t i1=0;i1<trackMult_tag;i1++){
AliVParticle *par1 = (AliVParticle*)fTagTrackArray->At(i1);
if(par1->Charge() < 0) continue;
//apply tight cut to particle1
TLorentzVector pv1 = TLorentzVector();
pv1.SetPtEtaPhiM(par1->Pt(),par1->Eta(),par1->Phi(),Me);
for(Int_t iev=0;iev<prevEvent_p->GetEntries();iev++){
TObjArray *arrmix = (TObjArray*)prevEvent_p->At(iev);
for(Int_t i2=0;i2<arrmix->GetEntries();i2++){
AliVParticle *par2 = (AliVParticle*)arrmix->At(i2);
if(par2->Charge() > 0) continue;
TLorentzVector pv2 = TLorentzVector();
pv2.SetPtEtaPhiM(par2->Pt(),par2->Eta(),par2->Phi(),Me);
TLorentzVector p12 = pv1 + pv2;
value[0] = p12.M();
value[1] = pv2.Pt();
value[2] = pv2.Eta();
value[3] = pv2.Phi();
if(value[3] < 0) value[3] += TMath::TwoPi();
Float_t phiv = PhivPair(fEvent->GetMagneticField(),par1->Charge(),par2->Charge(),pv1.Vect(),pv2.Vect());
if(
(0 < p12.M() && p12.M() < fMmax)
&& (fPhiVmin < phiv && phiv < TMath::Pi())
) continue;
FillHistogramTH2(fOutputContainer,"hProbe_ULS_mix",p12.M(),pv2.Pt());
}//end of par2
}//end of mix event loop
for(Int_t iev=0;iev<prevEvent_pp->GetEntries();iev++){
TObjArray *arrmix = (TObjArray*)prevEvent_pp->At(iev);
for(Int_t i2=0;i2<arrmix->GetEntries();i2++){
AliVParticle *par2 = (AliVParticle*)arrmix->At(i2);
if(par2->Charge() > 0) continue;
TLorentzVector pv2 = TLorentzVector();
pv2.SetPtEtaPhiM(par2->Pt(),par2->Eta(),par2->Phi(),Me);
TLorentzVector p12 = pv1 + pv2;
value[0] = p12.M();
value[1] = pv2.Pt();
value[2] = pv2.Eta();
value[3] = pv2.Phi();
if(value[3] < 0) value[3] += TMath::TwoPi();
Float_t phiv = PhivPair(fEvent->GetMagneticField(),par1->Charge(),par2->Charge(),pv1.Vect(),pv2.Vect());
if(
(0 < p12.M() && p12.M() < fMmax)
&& (fPhiVmin < phiv && phiv < TMath::Pi())
) continue;
FillHistogramTH2(fOutputContainer,"hPassingProbe_ULS_mix",p12.M(),pv2.Pt());
}//end of par2
}//end of mix event loop
}//end of par1
//fill ULS ++ mix
for(Int_t i1=0;i1<trackMult_tag;i1++){
AliVParticle *par1 = (AliVParticle*)fTagTrackArray->At(i1);
if(par1->Charge() < 0) continue;
//apply tight cut to particle1
TLorentzVector pv1 = TLorentzVector();
pv1.SetPtEtaPhiM(par1->Pt(),par1->Eta(),par1->Phi(),Me);
for(Int_t iev=0;iev<prevEvent_p->GetEntries();iev++){
TObjArray *arrmix = (TObjArray*)prevEvent_p->At(iev);
for(Int_t i2=0;i2<arrmix->GetEntries();i2++){
AliVParticle *par2 = (AliVParticle*)arrmix->At(i2);
if(par2->Charge() < 0) continue;
TLorentzVector pv2 = TLorentzVector();
pv2.SetPtEtaPhiM(par2->Pt(),par2->Eta(),par2->Phi(),Me);
TLorentzVector p12 = pv1 + pv2;
value[0] = p12.M();
value[1] = pv2.Pt();
value[2] = pv2.Eta();
value[3] = pv2.Phi();
if(value[3] < 0) value[3] += TMath::TwoPi();
Float_t phiv = PhivPair(fEvent->GetMagneticField(),par1->Charge(),par2->Charge(),pv1.Vect(),pv2.Vect());
if(
(0 < p12.M() && p12.M() < fMmax)
&& (fPhiVmin < phiv && phiv < TMath::Pi())
) continue;
FillHistogramTH2(fOutputContainer,"hProbe_LSpp_mix",p12.M(),pv2.Pt());
}//end of par2
}//end of mix event loop
for(Int_t iev=0;iev<prevEvent_pp->GetEntries();iev++){
TObjArray *arrmix = (TObjArray*)prevEvent_pp->At(iev);
for(Int_t i2=0;i2<arrmix->GetEntries();i2++){
AliVParticle *par2 = (AliVParticle*)arrmix->At(i2);
if(par2->Charge() < 0) continue;
TLorentzVector pv2 = TLorentzVector();
pv2.SetPtEtaPhiM(par2->Pt(),par2->Eta(),par2->Phi(),Me);
TLorentzVector p12 = pv1 + pv2;
value[0] = p12.M();
value[1] = pv2.Pt();
value[2] = pv2.Eta();
value[3] = pv2.Phi();
if(value[3] < 0) value[3] += TMath::TwoPi();
Float_t phiv = PhivPair(fEvent->GetMagneticField(),par1->Charge(),par2->Charge(),pv1.Vect(),pv2.Vect());
if(
(0 < p12.M() && p12.M() < fMmax)
&& (fPhiVmin < phiv && phiv < TMath::Pi())
) continue;
FillHistogramTH2(fOutputContainer,"hPassingProbe_LSpp_mix",p12.M(),pv2.Pt());
}//end of par2
}//end of mix event loop
}//end of par1
//fill ULS -- mix
for(Int_t i1=0;i1<trackMult_tag;i1++){
AliVParticle *par1 = (AliVParticle*)fTagTrackArray->At(i1);
if(par1->Charge() > 0) continue;
//apply tight cut to particle1
TLorentzVector pv1 = TLorentzVector();
pv1.SetPtEtaPhiM(par1->Pt(),par1->Eta(),par1->Phi(),Me);
for(Int_t iev=0;iev<prevEvent_p->GetEntries();iev++){
TObjArray *arrmix = (TObjArray*)prevEvent_p->At(iev);
for(Int_t i2=0;i2<arrmix->GetEntries();i2++){
AliVParticle *par2 = (AliVParticle*)arrmix->At(i2);
if(par2->Charge() > 0) continue;
TLorentzVector pv2 = TLorentzVector();
pv2.SetPtEtaPhiM(par2->Pt(),par2->Eta(),par2->Phi(),Me);
TLorentzVector p12 = pv1 + pv2;
value[0] = p12.M();
value[1] = pv2.Pt();
value[2] = pv2.Eta();
value[3] = pv2.Phi();
if(value[3] < 0) value[3] += TMath::TwoPi();
Float_t phiv = PhivPair(fEvent->GetMagneticField(),par1->Charge(),par2->Charge(),pv1.Vect(),pv2.Vect());
if(
(0 < p12.M() && p12.M() < fMmax)
&& (fPhiVmin < phiv && phiv < TMath::Pi())
) continue;
FillHistogramTH2(fOutputContainer,"hProbe_LSnn_mix",p12.M(),pv2.Pt());
}//end of par2
}//end of mix event loop
for(Int_t iev=0;iev<prevEvent_pp->GetEntries();iev++){
TObjArray *arrmix = (TObjArray*)prevEvent_pp->At(iev);
for(Int_t i2=0;i2<arrmix->GetEntries();i2++){
AliVParticle *par2 = (AliVParticle*)arrmix->At(i2);
if(par2->Charge() > 0) continue;
TLorentzVector pv2 = TLorentzVector();
pv2.SetPtEtaPhiM(par2->Pt(),par2->Eta(),par2->Phi(),Me);
TLorentzVector p12 = pv1 + pv2;
value[0] = p12.M();
value[1] = pv2.Pt();
value[2] = pv2.Eta();
value[3] = pv2.Phi();
if(value[3] < 0) value[3] += TMath::TwoPi();
Float_t phiv = PhivPair(fEvent->GetMagneticField(),par1->Charge(),par2->Charge(),pv1.Vect(),pv2.Vect());
if(
(0 < p12.M() && p12.M() < fMmax)
&& (fPhiVmin < phiv && phiv < TMath::Pi())
) continue;
FillHistogramTH2(fOutputContainer,"hPassingProbe_LSnn_mix",p12.M(),pv2.Pt());
}//end of par2
}//end of mix event loop
}//end of par1
}
//________________________________________________________________________
void AliAnalysisTaskTagAndProbe::FillHistogramTH1(TList *list, const Char_t *hname, Double_t x, Double_t w, Option_t *opt) const
{
//FillHistogram
TH1 * hist = dynamic_cast<TH1*>(list->FindObject(hname));
if(!hist){
AliError(Form("can not find histogram (of instance TH1) <%s> ",hname));
return;
}
else{
TString optstring(opt);
Double_t myweight = optstring.Contains("w") ? 1. : w;
if(optstring.Contains("wx")){
// use bin width as weight
Int_t bin = hist->GetXaxis()->FindBin(x);
// check if not overflow or underflow bin
if(bin != 0 && bin != hist->GetXaxis()->GetNbins()){
Double_t binwidth = hist->GetXaxis()->GetBinWidth(bin);
myweight = w/binwidth;
}
}
hist->Fill(x, myweight);
return;
}
}
//_____________________________________________________________________________
void AliAnalysisTaskTagAndProbe::FillHistogramTH2(TList *list, const Char_t *name, Double_t x, Double_t y, Double_t w, Option_t *opt) const
{
TH2 * hist = dynamic_cast<TH2*>(list->FindObject(name));
if(!hist){
AliError(Form("can not find histogram (of instance TH2) <%s> ",name));
return;
}
else{
TString optstring(opt);
Double_t myweight = optstring.Contains("w") ? 1. : w;
if(optstring.Contains("wx")){
Int_t binx = hist->GetXaxis()->FindBin(x);
if(binx != 0 && binx != hist->GetXaxis()->GetNbins()) myweight *= 1./hist->GetXaxis()->GetBinWidth(binx);
}
if(optstring.Contains("wy")){
Int_t biny = hist->GetYaxis()->FindBin(y);
if(biny != 0 && biny != hist->GetYaxis()->GetNbins()) myweight *= 1./hist->GetYaxis()->GetBinWidth(biny);
}
hist->Fill(x, y, myweight);
return;
}
}
//_____________________________________________________________________________
void AliAnalysisTaskTagAndProbe::FillHistogramTH3(TList *list, const Char_t *name, Double_t x, Double_t y, Double_t z, Double_t w, Option_t *opt) const
{
TH3 * hist = dynamic_cast<TH3*>(list->FindObject(name));
if(!hist){
AliError(Form("can not find histogram (of instance TH3) <%s> ",name));
return;
}
else{
TString optstring(opt);
Double_t myweight = optstring.Contains("w") ? 1. : w;
if(optstring.Contains("wx")){
Int_t binx = hist->GetXaxis()->FindBin(x);
if(binx != 0 && binx != hist->GetXaxis()->GetNbins()) myweight *= 1./hist->GetXaxis()->GetBinWidth(binx);
}
if(optstring.Contains("wy")){
Int_t biny = hist->GetYaxis()->FindBin(y);
if(biny != 0 && biny != hist->GetYaxis()->GetNbins()) myweight *= 1./hist->GetYaxis()->GetBinWidth(biny);
}
if(optstring.Contains("wz")){
Int_t binz = hist->GetZaxis()->FindBin(z);
if(binz != 0 && binz != hist->GetZaxis()->GetNbins()) myweight *= 1./hist->GetZaxis()->GetBinWidth(binz);
}
hist->Fill(x, y, z, myweight);
return;
}
}
//_____________________________________________________________________________
void AliAnalysisTaskTagAndProbe::FillSparse(TList *list, const Char_t *name, Double_t *x, Double_t w) const
{
THnSparse * hist = dynamic_cast<THnSparse*>(list->FindObject(name));
if(!hist){
AliError(Form("can not find histogram (of instance THnSparse) <%s> ",name));
return;
}
else{
hist->Fill(x,w);
return;
}
}
//_______________________________________________________________________________
Double_t AliAnalysisTaskTagAndProbe::PhivPair(Double_t MagField, Int_t charge1, Int_t charge2, TVector3 dau1, TVector3 dau2) //const
{
/// Following the idea to use opening of collinear pairs in magnetic field from e.g. PHENIX
/// to identify conversions. Angle between ee plane and magnetic field is calculated (0 to pi).
/// Due to tracking to the primary vertex, conversions with no intrinsic opening angle
/// always end up as pair in "cowboy" configuration. The function as defined here then
/// returns values close to pi.
/// Correlated Like Sign pairs (from double conversion / dalitz + conversion) may show up
/// at pi or at 0 depending on which leg has the higher momentum. (not checked yet)
/// This expected ambiguity is not seen due to sorting of track arrays in this framework.
/// To reach the same result as for ULS (~pi), the legs are flipped for LS.
/// from PWGDQ/dielectron/core/AliDielectronPair.cxx
//Define local buffer variables for leg properties
Double_t px1=-9999.,py1=-9999.,pz1=-9999.;
Double_t px2=-9999.,py2=-9999.,pz2=-9999.;
TVector3 fD1=dau1;
TVector3 fD2=dau2;
Int_t d1Q=charge1;
//Int_t d2Q=charge2;
if (charge1*charge2 > 0.) { // Like Sign
if(MagField<0){ // inverted behaviour
if(d1Q>0){
px1 = fD1.Px(); py1 = fD1.Py(); pz1 = fD1.Pz();
px2 = fD2.Px(); py2 = fD2.Py(); pz2 = fD2.Pz();
}else{
px1 = fD2.Px(); py1 = fD2.Py(); pz1 = fD2.Pz();
px2 = fD1.Px(); py2 = fD1.Py(); pz2 = fD1.Pz();
}
}else{
if(d1Q>0){
px1 = fD2.Px(); py1 = fD2.Py(); pz1 = fD2.Pz();
px2 = fD1.Px(); py2 = fD1.Py(); pz2 = fD1.Pz();
}else{
px1 = fD1.Px(); py1 = fD1.Py(); pz1 = fD1.Pz();
px2 = fD2.Px(); py2 = fD2.Py(); pz2 = fD2.Pz();
}
}
}
else { // Unlike Sign
if(MagField>0){ // regular behaviour
if(d1Q>0){
px1 = fD1.Px();
py1 = fD1.Py();
pz1 = fD1.Pz();
px2 = fD2.Px();
py2 = fD2.Py();
pz2 = fD2.Pz();
}else{
px1 = fD2.Px();
py1 = fD2.Py();
pz1 = fD2.Pz();
px2 = fD1.Px();
py2 = fD1.Py();
pz2 = fD1.Pz();
}
}else{
if(d1Q>0){
px1 = fD2.Px();
py1 = fD2.Py();
pz1 = fD2.Pz();
px2 = fD1.Px();
py2 = fD1.Py();
pz2 = fD1.Pz();
}else{
px1 = fD1.Px();
py1 = fD1.Py();
pz1 = fD1.Pz();
px2 = fD2.Px();
py2 = fD2.Py();
pz2 = fD2.Pz();
}
}
}
Double_t px = px1+px2;
Double_t py = py1+py2;
Double_t pz = pz1+pz2;
Double_t dppair = TMath::Sqrt(px*px+py*py+pz*pz);
//unit vector of (pep+pem)
Double_t pl = dppair;
Double_t ux = px/pl;
Double_t uy = py/pl;
Double_t uz = pz/pl;
Double_t ax = uy/TMath::Sqrt(ux*ux+uy*uy);
Double_t ay = -ux/TMath::Sqrt(ux*ux+uy*uy);
//momentum of e+ and e- in (ax,ay,az) axis. Note that az=0 by definition.
//Double_t ptep = iep->Px()*ax + iep->Py()*ay;
//Double_t ptem = iem->Px()*ax + iem->Py()*ay;
Double_t pxep = px1;
Double_t pyep = py1;
Double_t pzep = pz1;
Double_t pxem = px2;
Double_t pyem = py2;
Double_t pzem = pz2;
//vector product of pep X pem
Double_t vpx = pyep*pzem - pzep*pyem;
Double_t vpy = pzep*pxem - pxep*pzem;
Double_t vpz = pxep*pyem - pyep*pxem;
Double_t vp = sqrt(vpx*vpx+vpy*vpy+vpz*vpz);
//Double_t thev = acos(vpz/vp);
//unit vector of pep X pem
Double_t vx = vpx/vp;
Double_t vy = vpy/vp;
Double_t vz = vpz/vp;
//The third axis defined by vector product (ux,uy,uz)X(vx,vy,vz)
Double_t wx = uy*vz - uz*vy;
Double_t wy = uz*vx - ux*vz;
//Double_t wz = ux*vy - uy*vx;
//Double_t wl = sqrt(wx*wx+wy*wy+wz*wz);
// by construction, (wx,wy,wz) must be a unit vector.
// measure angle between (wx,wy,wz) and (ax,ay,0). The angle between them
// should be small if the pair is conversion.
// this function then returns values close to pi!
Double_t cosPhiV = wx*ax + wy*ay;
Double_t phiv = TMath::ACos(cosPhiV);
return phiv;
}
//________________________________________________________________________
| 42.329877 | 232 | 0.676245 | [
"object",
"vector"
] |
28c9791b05fd00acd8f35b46fe40002825ba2bc1 | 6,580 | cc | C++ | third_party/webrtc/src/chromium/src/gin/object_template_builder.cc | bopopescu/webrtc-streaming-node | 727a441204344ff596401b0253caac372b714d91 | [
"MIT"
] | 8 | 2016-02-08T11:59:31.000Z | 2020-05-31T15:19:54.000Z | third_party/webrtc/src/chromium/src/gin/object_template_builder.cc | bopopescu/webrtc-streaming-node | 727a441204344ff596401b0253caac372b714d91 | [
"MIT"
] | 1 | 2021-05-05T11:11:31.000Z | 2021-05-05T11:11:31.000Z | third_party/webrtc/src/chromium/src/gin/object_template_builder.cc | bopopescu/webrtc-streaming-node | 727a441204344ff596401b0253caac372b714d91 | [
"MIT"
] | 7 | 2016-02-09T09:28:14.000Z | 2020-07-25T19:03:36.000Z | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "gin/object_template_builder.h"
#include "gin/interceptor.h"
#include "gin/per_isolate_data.h"
#include "gin/public/wrapper_info.h"
namespace gin {
namespace {
WrappableBase* WrappableFromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val) {
if (!val->IsObject())
return NULL;
v8::Local<v8::Object> obj = v8::Local<v8::Object>::Cast(val);
WrapperInfo* info = WrapperInfo::From(obj);
// If this fails, the object is not managed by Gin.
if (!info)
return NULL;
// We don't further validate the type of the object, but assume it's derived
// from WrappableBase. We look up the pointer in a global registry, to make
// sure it's actually pointed to a valid life object.
return static_cast<WrappableBase*>(
obj->GetAlignedPointerFromInternalField(kEncodedValueIndex));
}
NamedPropertyInterceptor* NamedInterceptorFromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val) {
WrappableBase* base = WrappableFromV8(isolate, val);
if (!base)
return NULL;
return PerIsolateData::From(isolate)->GetNamedPropertyInterceptor(base);
}
IndexedPropertyInterceptor* IndexedInterceptorFromV8(
v8::Isolate* isolate,
v8::Local<v8::Value> val) {
WrappableBase* base = WrappableFromV8(isolate, val);
if (!base)
return NULL;
return PerIsolateData::From(isolate)->GetIndexedPropertyInterceptor(base);
}
void NamedPropertyGetter(v8::Local<v8::String> property,
const v8::PropertyCallbackInfo<v8::Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
NamedPropertyInterceptor* interceptor =
NamedInterceptorFromV8(isolate, info.Holder());
if (!interceptor)
return;
std::string name;
ConvertFromV8(isolate, property, &name);
info.GetReturnValue().Set(interceptor->GetNamedProperty(isolate, name));
}
void NamedPropertySetter(v8::Local<v8::String> property,
v8::Local<v8::Value> value,
const v8::PropertyCallbackInfo<v8::Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
NamedPropertyInterceptor* interceptor =
NamedInterceptorFromV8(isolate, info.Holder());
if (!interceptor)
return;
std::string name;
ConvertFromV8(isolate, property, &name);
if (interceptor->SetNamedProperty(isolate, name, value))
info.GetReturnValue().Set(value);
}
void NamedPropertyQuery(v8::Local<v8::String> property,
const v8::PropertyCallbackInfo<v8::Integer>& info) {
v8::Isolate* isolate = info.GetIsolate();
NamedPropertyInterceptor* interceptor =
NamedInterceptorFromV8(isolate, info.Holder());
if (!interceptor)
return;
std::string name;
ConvertFromV8(isolate, property, &name);
if (interceptor->GetNamedProperty(isolate, name).IsEmpty())
return;
info.GetReturnValue().Set(0);
}
void NamedPropertyEnumerator(const v8::PropertyCallbackInfo<v8::Array>& info) {
v8::Isolate* isolate = info.GetIsolate();
NamedPropertyInterceptor* interceptor =
NamedInterceptorFromV8(isolate, info.Holder());
if (!interceptor)
return;
v8::Local<v8::Value> properties;
if (!TryConvertToV8(isolate, interceptor->EnumerateNamedProperties(isolate),
&properties))
return;
info.GetReturnValue().Set(v8::Local<v8::Array>::Cast(properties));
}
void IndexedPropertyGetter(uint32_t index,
const v8::PropertyCallbackInfo<v8::Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
IndexedPropertyInterceptor* interceptor =
IndexedInterceptorFromV8(isolate, info.Holder());
if (!interceptor)
return;
info.GetReturnValue().Set(interceptor->GetIndexedProperty(isolate, index));
}
void IndexedPropertySetter(uint32_t index,
v8::Local<v8::Value> value,
const v8::PropertyCallbackInfo<v8::Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
IndexedPropertyInterceptor* interceptor =
IndexedInterceptorFromV8(isolate, info.Holder());
if (!interceptor)
return;
if (interceptor->SetIndexedProperty(isolate, index, value))
info.GetReturnValue().Set(value);
}
void IndexedPropertyEnumerator(
const v8::PropertyCallbackInfo<v8::Array>& info) {
v8::Isolate* isolate = info.GetIsolate();
IndexedPropertyInterceptor* interceptor =
IndexedInterceptorFromV8(isolate, info.Holder());
if (!interceptor)
return;
v8::Local<v8::Value> properties;
if (!TryConvertToV8(isolate, interceptor->EnumerateIndexedProperties(isolate),
&properties))
return;
info.GetReturnValue().Set(v8::Local<v8::Array>::Cast(properties));
}
} // namespace
ObjectTemplateBuilder::ObjectTemplateBuilder(v8::Isolate* isolate)
: isolate_(isolate), template_(v8::ObjectTemplate::New(isolate)) {
template_->SetInternalFieldCount(kNumberOfInternalFields);
}
ObjectTemplateBuilder::~ObjectTemplateBuilder() {
}
ObjectTemplateBuilder& ObjectTemplateBuilder::AddNamedPropertyInterceptor() {
template_->SetNamedPropertyHandler(&NamedPropertyGetter,
&NamedPropertySetter,
&NamedPropertyQuery,
NULL,
&NamedPropertyEnumerator);
return *this;
}
ObjectTemplateBuilder& ObjectTemplateBuilder::AddIndexedPropertyInterceptor() {
template_->SetIndexedPropertyHandler(&IndexedPropertyGetter,
&IndexedPropertySetter,
NULL,
NULL,
&IndexedPropertyEnumerator);
return *this;
}
ObjectTemplateBuilder& ObjectTemplateBuilder::SetImpl(
const base::StringPiece& name, v8::Local<v8::Data> val) {
template_->Set(StringToSymbol(isolate_, name), val);
return *this;
}
ObjectTemplateBuilder& ObjectTemplateBuilder::SetPropertyImpl(
const base::StringPiece& name, v8::Local<v8::FunctionTemplate> getter,
v8::Local<v8::FunctionTemplate> setter) {
template_->SetAccessorProperty(StringToSymbol(isolate_, name), getter,
setter);
return *this;
}
v8::Local<v8::ObjectTemplate> ObjectTemplateBuilder::Build() {
v8::Local<v8::ObjectTemplate> result = template_;
template_.Clear();
return result;
}
} // namespace gin
| 35 | 80 | 0.672796 | [
"object"
] |
28ce6b72692560d3e2f075d6a744786f4403fb82 | 1,179 | cpp | C++ | LeetCodeCPP/_1140. Stone Game II/main.cpp | 18600130137/leetcode | fd2dc72c0b85da50269732f0fcf91326c4787d3a | [
"Apache-2.0"
] | 1 | 2019-03-29T03:33:56.000Z | 2019-03-29T03:33:56.000Z | LeetCodeCPP/_1140. Stone Game II/main.cpp | 18600130137/leetcode | fd2dc72c0b85da50269732f0fcf91326c4787d3a | [
"Apache-2.0"
] | null | null | null | LeetCodeCPP/_1140. Stone Game II/main.cpp | 18600130137/leetcode | fd2dc72c0b85da50269732f0fcf91326c4787d3a | [
"Apache-2.0"
] | null | null | null | //
// main.cpp
// _1140. Stone Game II
//
// Created by admin on 2019/7/29.
// Copyright © 2019年 liu. All rights reserved.
//
#include <iostream>
#include <vector>
using namespace std;
class Solution {
private:
int helper(vector<int>& sum,int index,int M,vector<vector<int>> &rem,int m){
if(index>=m) return 0;
if(index+2*M>=m){
return sum[index];
}
if(rem[index][M]) return rem[index][M];
int nextMin=INT_MAX;
for(int i=1;i<=2*M;i++){
nextMin=min(nextMin,helper(sum,index+i,max(i,M),rem,m));
}
rem[index][M]=sum[index]-nextMin;
return rem[index][M];
}
public:
int stoneGameII(vector<int>& piles) {
int m=piles.size();
if(m==0){
return 0;
}
vector<vector<int>> rem(m,vector<int>(m,0));
for(int i=m-2;i>=0;i--){
piles[i]+=piles[i+1];
}
return helper(piles,0,1,rem,m);
}
};
int main(int argc, const char * argv[]) {
vector<int> input={2,7,9,4,4};
Solution so=Solution();
int ret=so.stoneGameII(input);
cout<<"The ret is:"<<ret<<endl;
return 0;
}
| 23.117647 | 81 | 0.529262 | [
"vector"
] |
28d0c5b8996ea40f6f8932e7df9df017e37317d3 | 11,020 | cpp | C++ | src/plugins/intel_cpu/src/nodes/mkldnn_broadcast_node.cpp | pfinashx/openvino | 1d417e888b508415510fb0a92e4a9264cf8bdef7 | [
"Apache-2.0"
] | 1 | 2022-02-26T17:33:44.000Z | 2022-02-26T17:33:44.000Z | src/plugins/intel_cpu/src/nodes/mkldnn_broadcast_node.cpp | pfinashx/openvino | 1d417e888b508415510fb0a92e4a9264cf8bdef7 | [
"Apache-2.0"
] | 18 | 2022-01-21T08:42:58.000Z | 2022-03-28T13:21:31.000Z | src/plugins/intel_cpu/src/nodes/mkldnn_broadcast_node.cpp | AlexRogalskiy/openvino | ac2e639ff8f9a607c3c682a4c4e165c238eb817f | [
"Apache-2.0"
] | 1 | 2020-12-13T22:16:54.000Z | 2020-12-13T22:16:54.000Z | // Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <cmath>
#include <vector>
#include <string>
#include <mkldnn_types.h>
#include "ie_parallel.hpp"
#include "utils/bfloat16.hpp"
#include <mkldnn_selective_build.h>
#include "mkldnn_broadcast_node.h"
#include <nodes/common/blocked_desc_creator.h>
#include <ngraph/opsets/opset1.hpp>
#include "common/cpu_memcpy.h"
using namespace MKLDNNPlugin;
using namespace InferenceEngine;
bool MKLDNNBroadcastNode::isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std::string& errorMessage) noexcept {
try {
if (!ov::is_type<ov::op::v1::Broadcast>(op)) {
errorMessage = "Only Broadcast operations from opset1 are supported.";
return false;
}
if (!one_of(ov::as_type_ptr<const ov::op::v1::Broadcast>(op)->get_broadcast_spec().m_type,
ov::op::AutoBroadcastType::NUMPY, ov::op::AutoBroadcastType::EXPLICIT)) {
errorMessage = "Only NUMPY and EXPLICIT broadcast types are supported.";
return false;
}
if (op->get_input_partial_shape(TARGET_SHAPE_IDX).is_dynamic() ||
(op->get_input_size() > AXES_MAPPING_IDX && op->get_input_partial_shape(AXES_MAPPING_IDX).is_dynamic())) {
errorMessage = "Only static shapes are supported for target shape and axes mapping inputs.";
return false;
}
if (!isDynamicNgraphNode(op) &&
(!ov::is_type<ov::op::v0::Constant>(op->get_input_node_ptr(TARGET_SHAPE_IDX)) ||
(op->get_input_size() > AXES_MAPPING_IDX &&
!ov::is_type<ov::op::v0::Constant>(op->get_input_node_ptr(AXES_MAPPING_IDX))))) {
errorMessage = "Only constant target shapes and axis mapping inputs are supported for static shapes.";
return false;
}
} catch (...) {
return false;
}
return true;
}
MKLDNNBroadcastNode::MKLDNNBroadcastNode(const std::shared_ptr<ov::Node>& op, const mkldnn::engine& eng,
MKLDNNWeightsSharing::Ptr &cache) : MKLDNNNode(op, eng, cache) {
std::string errorMessage;
if (!isSupportedOperation(op, errorMessage)) {
IE_THROW(NotImplemented) << errorMessage;
}
errorPrefix = "Broadcast node with name '" + op->get_friendly_name() + "' ";
if (op->get_input_size() != 2 && op->get_input_size() != 3)
IE_THROW() << errorPrefix << "has incorrect number of input edges: " << getParentEdges().size();
if (op->get_output_size() == 0)
IE_THROW() << errorPrefix << "has no output edges.";
auto broadcastOp = ov::as_type_ptr<const ov::op::v1::Broadcast>(op);
if (broadcastOp->get_broadcast_spec().m_type == ov::op::AutoBroadcastType::NUMPY) {
broadcastType = NUMPY;
} else if (broadcastOp->get_broadcast_spec().m_type == ov::op::AutoBroadcastType::EXPLICIT) {
if (op->get_input_size() <= AXES_MAPPING_IDX)
IE_THROW() << errorPrefix << " and EXPLICIT mode must have tree input edges: " << getParentEdges().size();
broadcastType = EXPLICIT;
} else {
IE_THROW() << errorPrefix << "has unexpected broadcast type: " << broadcastOp->get_broadcast_spec().m_type;
}
if (ov::is_type<ov::op::v0::Constant>(op->get_input_node_ptr(TARGET_SHAPE_IDX))) {
constMap[TARGET_SHAPE_IDX] = true;
targetShape = (ov::as_type<ov::op::v0::Constant>(op->get_input_node_ptr(TARGET_SHAPE_IDX)))->get_vector<int32_t>();
}
if (broadcastType == EXPLICIT &&
ov::is_type<ov::op::v0::Constant>(op->get_input_node_ptr(AXES_MAPPING_IDX))) {
constMap[AXES_MAPPING_IDX] = true;
axesMapping = ov::as_type<ov::op::v0::Constant>(op->get_input_node_ptr(AXES_MAPPING_IDX))->get_vector<int32_t>();
}
}
void MKLDNNBroadcastNode::getSupportedDescriptors() {
if (!isDynamicNode()) {
const auto& srcDims = getInputShapeAtPort(INPUT_DATA_IDX).getDims();
repeats.assign(targetShape.begin(), targetShape.end());
const auto ndims = repeats.size();
if (broadcastType == NUMPY) {
for (size_t i = 0lu; i < srcDims.size(); i++) {
repeats[ndims - 1lu - i] /= srcDims[srcDims.size() - 1lu - i];
}
} else if (broadcastType == EXPLICIT) {
for (size_t i = 0lu; i < axesMapping.size(); i++) {
repeats[axesMapping[i]] /= srcDims[i];
}
}
needPrepareParamsVar = true;
}
}
void MKLDNNBroadcastNode::initSupportedPrimitiveDescriptors() {
if (!supportedPrimitiveDescriptors.empty())
return;
supportedPrimitiveDescriptors = getSupportedConfigs(this);
}
bool MKLDNNBroadcastNode::needPrepareParams() const {
return needPrepareParamsVar;
}
void MKLDNNBroadcastNode::prepareParams() {
if (!constMap[TARGET_SHAPE_IDX]) {
const auto& targetShapeMem = getParentEdgesAtPort(TARGET_SHAPE_IDX)[0]->getMemory();
const int32_t* targetShapeData = reinterpret_cast<const int32_t *>(targetShapeMem.GetPtr());
targetShape.assign(targetShapeData, targetShapeData + targetShapeMem.getStaticDims()[0]);
}
if (broadcastType == EXPLICIT && !constMap[AXES_MAPPING_IDX]) {
const auto& axesMapMem = getParentEdgesAtPort(AXES_MAPPING_IDX)[0]->getMemory();
const int32_t* axesMapData = reinterpret_cast<const int32_t *>(axesMapMem.GetPtr());
axesMapping.assign(axesMapData, axesMapData + axesMapMem.getStaticDims()[0]);
}
const auto& srcDims = getParentEdgesAtPort(INPUT_DATA_IDX)[0]->getMemory().GetShape().getStaticDims();
repeats.assign(targetShape.begin(), targetShape.end());
const auto ndims = repeats.size();
auto srcBlockedDims = getParentEdgeAt(INPUT_DATA_IDX)->getMemory().GetDescWithType<BlockedMemoryDesc>()->getBlockDims();
auto dstBlockedDims = getChildEdgeAt(0)->getMemory().GetDescWithType<BlockedMemoryDesc>()->getBlockDims();
if (broadcastType == NUMPY) {
for (size_t i = 0lu; i < srcDims.size(); i++) {
repeats[ndims - 1lu - i] /= srcDims[srcDims.size() - 1lu - i];
}
} else if (broadcastType == EXPLICIT) {
for (size_t i = 0; i < getInputShapeAtPort(AXES_MAPPING_IDX).getDims()[0]; i++) {
repeats[axesMapping[i]] /= srcDims[i];
}
SizeVector newSrcBlockedDims = SizeVector(dstBlockedDims.size(), 1);
for (size_t i = 0; i < getInputShapeAtPort(AXES_MAPPING_IDX).getDims()[0]; i++) {
newSrcBlockedDims[axesMapping[i]] = srcBlockedDims[i];
}
srcBlockedDims = newSrcBlockedDims;
}
optimizedCase = prepareOptimizedParams(this, srcBlockedDims, dstBlockedDims);
}
bool MKLDNNBroadcastNode::needShapeInfer() const {
needPrepareParamsVar = true;
if (inputShapesModified()) {
return true;
}
if (!constMap[TARGET_SHAPE_IDX]) {
if (targetShape.empty()) {
return true;
}
const int32_t* targetShapeData = reinterpret_cast<const int32_t *>(getParentEdgesAtPort(TARGET_SHAPE_IDX)[0]->getMemory().GetPtr());
for (size_t i = 0lu; i < targetShape.size(); i++) {
if (targetShape[i] != targetShapeData[i]) {
return true;
}
}
}
if (broadcastType == EXPLICIT && !constMap[AXES_MAPPING_IDX]) {
if (axesMapping.empty()) {
return true;
}
const int32_t* axesMappingData = reinterpret_cast<const int32_t *>(getParentEdgesAtPort(AXES_MAPPING_IDX)[0]->getMemory().GetPtr());
for (size_t i = 0lu; i < axesMapping.size(); i++) {
if (axesMapping[i] != axesMappingData[i]) {
return true;
}
}
}
needPrepareParamsVar = false;
return false;
}
std::vector<VectorDims> MKLDNNBroadcastNode::shapeInfer() const {
return MKLDNNNode::shapeInferGeneric(PortMask(TARGET_SHAPE_IDX, AXES_MAPPING_IDX));
}
bool MKLDNNBroadcastNode::isExecutable() const {
return !isInputTensorAtPortEmpty(0);
}
void MKLDNNBroadcastNode::executeDynamicImpl(mkldnn::stream strm) {
execute(strm);
}
void MKLDNNBroadcastNode::execute(mkldnn::stream strm) {
if (optimizedCase) {
optimizedExecute(getParentEdgeAt(INPUT_DATA_IDX)->getMemoryPtr(), getChildEdgeAt(0)->getMemoryPtr());
} else {
plainExecute(strm);
}
}
void MKLDNNBroadcastNode::plainExecute(mkldnn::stream strm) {
VectorDims srcDims = getParentEdgeAt(INPUT_DATA_IDX)->getMemory().getStaticDims();
const auto& dstDims = getChildEdgeAt(0)->getMemory().getStaticDims();
const auto& dataSrcRank = getParentEdgeAt(INPUT_DATA_IDX)->getMemory().GetShape().getRank();
const auto& dataDstRank = getChildEdgeAt(0)->getMemory().GetShape().getRank();
auto srcDesc = getParentEdgeAt(INPUT_DATA_IDX)->getMemory().GetDescWithType<BlockedMemoryDesc>();
VectorDims srcStrides = srcDesc->getStrides();
const size_t dataSize = srcDesc->getPrecision().size();
if (!dataSrcRank)
srcDims = VectorDims(1, 1);
if (!srcStrides.size())
srcStrides = VectorDims(1, 1);
auto dstDesc = getChildEdgeAt(0)->getMemory().GetDescWithType<BlockedMemoryDesc>();
VectorDims dstStrides = dstDesc->getStrides();
VectorDims srcAligned(dataDstRank);
VectorDims srcStridesAligned(dataDstRank);
const size_t prefixSize = dataDstRank - dataSrcRank;
for (size_t i = 0lu; i < dataDstRank; i++) {
if (i < prefixSize) {
srcAligned[i] = 1;
srcStridesAligned[i] = srcStrides[0];
} else {
srcAligned[i] = srcDims[i - prefixSize];
srcStridesAligned[i] = srcStrides[i - prefixSize];
}
}
const size_t workAmountDst = dstStrides[0] * dstDims[0];
const auto *srcData = reinterpret_cast<const uint8_t *>(getParentEdgeAt(INPUT_DATA_IDX)->getMemoryPtr()->GetPtr());
auto *dstData = reinterpret_cast<uint8_t *>(getChildEdgeAt(0)->getMemoryPtr()->GetPtr());
parallel_nt(0, [&](const int ithr, const int nthr) {
size_t i = 0lu, srcIdx = 0lu, start = 0lu, end = 0lu;
VectorDims counters(dataDstRank, 0);
splitter(workAmountDst, nthr, ithr, start, end);
for (int j = dataDstRank - 1, i = start; j >= 0; j--) {
counters[j] = i % dstDims[j];
i /= dstDims[j];
}
for (size_t iwork = start * dataSize; iwork < end * dataSize; iwork += dataSize) {
for (i = 0lu, srcIdx = 0lu; i < dataDstRank; ++i)
srcIdx += counters[i] ? ((counters[i] % srcAligned[i]) * srcStridesAligned[i]) : 0;
cpu_memcpy(&dstData[iwork], &srcData[srcIdx * dataSize], dataSize);
for (int j = dataDstRank - 1; j >= 0; j--) {
counters[j] = (counters[j] + 1) % dstDims[j];
if (counters[j] != 0) break;
}
}
});
}
bool MKLDNNBroadcastNode::created() const {
return getType() == Broadcast;
}
REG_MKLDNN_PRIM_FOR(MKLDNNBroadcastNode, Broadcast)
| 41.584906 | 140 | 0.644283 | [
"shape",
"vector"
] |
28d4e62a1fa6535a0d41769e2172438ab4863b11 | 748 | hpp | C++ | source/backend/hiai/execution/NPUInt8ToFloat.hpp | JujuDel/MNN | 8a82f5c5a7ae37192784c2dbd6dfc8ca8833565a | [
"Apache-2.0"
] | 6,958 | 2019-05-06T02:38:02.000Z | 2022-03-31T18:08:48.000Z | source/backend/hiai/execution/NPUInt8ToFloat.hpp | JujuDel/MNN | 8a82f5c5a7ae37192784c2dbd6dfc8ca8833565a | [
"Apache-2.0"
] | 1,775 | 2019-05-06T04:40:19.000Z | 2022-03-30T15:39:24.000Z | source/backend/hiai/execution/NPUInt8ToFloat.hpp | JujuDel/MNN | 8a82f5c5a7ae37192784c2dbd6dfc8ca8833565a | [
"Apache-2.0"
] | 1,511 | 2019-05-06T02:38:05.000Z | 2022-03-31T16:59:39.000Z | //
// NPUInt8ToFloat.hpp
// MNN
//
// Created by MNN on 2019/09/11.
// Copyright © 2018, Alibaba Group Holding Limited
//
#ifndef MNN_NPUINT8TOFLOAT_HPP
#define MNN_NPUINT8TOFLOAT_HPP
#include "NPUCommonExecution.hpp"
#include "NPUBackend.hpp"
namespace MNN {
class NPUInt8ToFloat : public NPUCommonExecution {
public:
NPUInt8ToFloat(Backend *b, const Op *op, const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs);
ErrorCode onResize(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs);
virtual ~NPUInt8ToFloat() = default;
private:
ge::op::Const mConst_fliter;
ge::op::Const mConstMax;
ge::op::Const mConstMin;
};
} // namespace MNN
#endif // MNN_NPUINT8TOFLOAT_HPP
| 24.129032 | 120 | 0.71123 | [
"vector"
] |
28d6e2bc083189f7086909cb0035c5662ce1ceee | 63,048 | cpp | C++ | Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityHelpers.cpp | CStudios15/o3de | 9dc85000a3ec1a6c6633d718f5c455ab11a46818 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-11-11T18:02:46.000Z | 2021-11-11T18:02:46.000Z | Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityHelpers.cpp | CStudios15/o3de | 9dc85000a3ec1a6c6633d718f5c455ab11a46818 | [
"Apache-2.0",
"MIT"
] | null | null | null | Code/Framework/AzToolsFramework/AzToolsFramework/Entity/EditorEntityHelpers.cpp | CStudios15/o3de | 9dc85000a3ec1a6c6633d718f5c455ab11a46818 | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* 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 "EditorEntityHelpers.h"
#include <AzCore/Component/ComponentApplicationBus.h>
#include <AzCore/Component/TransformBus.h>
#include <AzCore/Debug/Profiler.h>
#include <AzCore/std/algorithm.h>
#include <AzCore/std/sort.h>
#include <AzCore/RTTI/AttributeReader.h>
#include <AzCore/Serialization/SerializeContext.h>
#include <AzToolsFramework/Commands/EntityStateCommand.h>
#include <AzToolsFramework/ContainerEntity/ContainerEntityInterface.h>
#include <AzToolsFramework/Entity/EditorEntityInfoBus.h>
#include <AzToolsFramework/Entity/EditorEntityContextBus.h>
#include <AzToolsFramework/Entity/SliceEditorEntityOwnershipServiceBus.h>
#include <AzToolsFramework/FocusMode/FocusModeInterface.h>
#include <AzToolsFramework/Slice/SliceMetadataEntityContextBus.h>
#include <AzToolsFramework/Slice/SliceUtilities.h>
#include <AzToolsFramework/ToolsComponents/EditorLockComponentBus.h>
#include <AzToolsFramework/ToolsComponents/EditorVisibilityBus.h>
#include <AzToolsFramework/ToolsComponents/GenericComponentWrapper.h>
#include <AzToolsFramework/ToolsComponents/EditorInspectorComponentBus.h>
namespace AzToolsFramework
{
namespace Internal
{
/// Internal helper function for CloneInstantiatedEntities. Performs the initial cloning of the given set of entities if they
/// are slice or sub-slice entities, recursively. Populates a list of loose entities to clone as it traverses the duplication set.
/// @param duplicationSet The set of entities to clone.
/// @param out_allEntityClones Output parameter populated with all cloned entities.
/// @param out_sourceToCloneEntityIdMap Output parameter populated with a map from all source entities to cloned entities.
/// @param out_looseEntitiesToClone Output parameter populated with all not yet cloned entities that are not associated with a slice.
/// This will be used after slices are cloned to clone these entities.
void CloneSliceEntitiesAndChildren(
const EntityIdSet& duplicationSet,
EntityList& out_allEntityClones,
AZ::SliceComponent::EntityIdToEntityIdMap& out_sourceToCloneEntityIdMap,
EntityIdList& out_looseEntitiesToClone);
/// Internal helper function for CloneInstantiatedEntities. Updates entity ID references in all cloned entities based on
/// the given entity ID map. This handles cases like entity transform parents, entity attachments, and entity ID references
/// in scripting components. This will update all references in the pool of cloned entities to reference other cloned
/// entities, if they were previously referencing any of the source entities.
/// @param inout_allEntityClones The collection of entities that have been cloned and should have entity references updated
/// based on the given map.
/// @param sourceToCloneEntityIdMap A map of entity IDs to update in the given clone list, any references to key will be
/// changed to a reference to value instead.
void UpdateClonedEntityReferences(
AZ::SliceComponent::InstantiatedContainer& inout_allEntityClones,
const AZ::SliceComponent::EntityIdToEntityIdMap& sourceToCloneEntityIdMap);
/// Internal helper function for CloneInstantiatedEntities. Selects all cloned entities, and updates the undo stack with
/// information on all cloned entities.
/// @param allEntityClones The collection of all entities that were cloned.
/// @param undoBatch The undo batch used for tracking the cloning operation.
void UpdateUndoStackAndSelectClonedEntities(
const EntityList& allEntityClones,
ScopedUndoBatch& undoBatch);
/// Internal helper function for CloneInstantiatedEntities. If the given entity identified by the ancestor list is a slice root, clone it.
/// @param ancestors The entity to clone if it is a slice root entity, tracked through its ancestry.
/// @param out_allEntityClones Output parameter populated with all cloned entities.
/// @param out_sourceToCloneEntityIdMap Output parameter populated with a map from all source entities to cloned entities.
/// @return True if the passed in entity was cloned, false if not.
bool CloneIfSliceRoot(
const AZ::SliceComponent::EntityAncestorList& ancestors,
EntityList& out_allEntityClones,
AZ::SliceComponent::EntityIdToEntityIdMap& out_sourceToCloneEntityIdMap);
/// Internal helper function for CloneInstantiatedEntities. If the given entity identified by the slice address and
/// ancestor list is a subslice root, clone it.
/// @param owningSliceAddress The slice address that owns this entity. This is necessary to clone the subslice.
/// @param ancestors The entity to clone if it is a subslice root entity, tracked through its ancestry.
/// @param out_allEntityClones Output parameter populated with all cloned entities.
/// @param out_sourceToCloneEntityIdMap Output parameter populated with a map from all source entities to cloned entities.
/// @return True if the passed in entity was cloned, false if not.
bool CloneIfSubsliceRoot(
const AZ::SliceComponent::SliceInstanceAddress& owningSliceAddress,
const AZ::SliceComponent::EntityAncestorList& ancestors,
EntityList& out_allEntityClones,
AZ::SliceComponent::EntityIdToEntityIdMap& out_sourceToCloneEntityIdMap);
/// Internal helper function for CloneInstantiatedEntities. Clones the given entity collection as loose entities.
/// @param duplicationList The collection of entities to clone.
/// @param out_allEntityClones Output parameter populated with all cloned entities.
/// @param out_sourceToCloneEntityIdMap Output parameter populated with a map from all source entities to cloned entities.
/// @param out_clonedLooseEntities Output parameter populated with all cloned loose entities.
void CloneLooseEntities(
const EntityIdList& duplicationList,
EntityList& out_allEntityClones,
AZ::SliceComponent::EntityIdToEntityIdMap& out_sourceToCloneEntityIdMap,
EntityList& out_clonedLooseEntities);
} // namespace Internal
AZ::Entity* GetEntityById(const AZ::EntityId& entityId)
{
AZ_Assert(entityId.IsValid(), "Invalid EntityId provided.");
if (!entityId.IsValid())
{
return nullptr;
}
AZ::Entity* entity = nullptr;
AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationRequests::FindEntity, entityId);
return entity;
}
AZStd::string GetEntityName(const AZ::EntityId& entityId, const AZStd::string_view& nameOverride)
{
if (!entityId.IsValid())
{
return AZStd::string();
}
if (!nameOverride.empty())
{
return nameOverride;
}
const AZ::Entity* entity = GetEntityById(entityId);
if (!entity)
{
return AZStd::string();
}
return entity->GetName();
}
EntityList EntityIdListToEntityList(const EntityIdList& inputEntityIds)
{
EntityList entities;
entities.reserve(inputEntityIds.size());
for (AZ::EntityId entityId : inputEntityIds)
{
if (!entityId.IsValid())
{
continue;
}
if (auto entity = GetEntityById(entityId))
{
entities.emplace_back(entity);
}
}
return entities;
}
EntityList EntityIdSetToEntityList(const EntityIdSet& inputEntityIds)
{
EntityList entities;
entities.reserve(inputEntityIds.size());
for (AZ::EntityId entityId : inputEntityIds)
{
if (!entityId.IsValid())
{
continue;
}
if (auto entity = GetEntityById(entityId))
{
entities.emplace_back(entity);
}
}
return entities;
}
void GetAllComponentsForEntity(const AZ::Entity* entity, AZ::Entity::ComponentArrayType& componentsOnEntity)
{
if (entity)
{
//build a set of all active and pending components associated with the entity
componentsOnEntity.insert(componentsOnEntity.end(), entity->GetComponents().begin(), entity->GetComponents().end());
EditorPendingCompositionRequestBus::Event(entity->GetId(), &EditorPendingCompositionRequests::GetPendingComponents, componentsOnEntity);
EditorDisabledCompositionRequestBus::Event(entity->GetId(), &EditorDisabledCompositionRequests::GetDisabledComponents, componentsOnEntity);
}
}
void GetAllComponentsForEntity(const AZ::EntityId& entityId, AZ::Entity::ComponentArrayType& componentsOnEntity)
{
GetAllComponentsForEntity(GetEntity(entityId), componentsOnEntity);
}
AZ::Uuid GetComponentTypeId(const AZ::Component* component)
{
return GetUnderlyingComponentType(*component);
}
const AZ::SerializeContext::ClassData* GetComponentClassData(const AZ::Component* component)
{
return GetComponentClassDataForType(GetComponentTypeId(component));
}
const AZ::SerializeContext::ClassData* GetComponentClassDataForType(const AZ::Uuid& componentTypeId)
{
AZ::SerializeContext* serializeContext = nullptr;
AZ::ComponentApplicationBus::BroadcastResult(serializeContext, &AZ::ComponentApplicationRequests::GetSerializeContext);
const AZ::SerializeContext::ClassData* componentClassData = serializeContext->FindClassData(componentTypeId);
return componentClassData;
}
AZStd::string GetFriendlyComponentName(const AZ::Component* component)
{
auto className = component->RTTI_GetTypeName();
auto classData = GetComponentClassData(component);
if (!classData)
{
return className;
}
if (!classData->m_editData)
{
return classData->m_name;
}
if (auto editorData = classData->m_editData->FindElementData(AZ::Edit::ClassElements::EditorData))
{
if (auto nameAttribute = editorData->FindAttribute(AZ::Edit::Attributes::NameLabelOverride))
{
AZStd::string name;
AZ::AttributeReader nameReader(const_cast<AZ::Component*>(component), nameAttribute);
nameReader.Read<AZStd::string>(name);
return name;
}
}
return classData->m_editData->m_name;
}
const char* GetFriendlyComponentDescription(const AZ::Component* component)
{
auto classData = GetComponentClassData(component);
if (!classData || !classData->m_editData)
{
return "";
}
return classData->m_editData->m_description;
}
AZ::ComponentDescriptor* GetComponentDescriptor(const AZ::Component* component)
{
AZ::ComponentDescriptor* componentDescriptor = nullptr;
AZ::ComponentDescriptorBus::EventResult(componentDescriptor, GetComponentTypeId(component), &AZ::ComponentDescriptor::GetDescriptor);
return componentDescriptor;
}
Components::EditorComponentDescriptor* GetEditorComponentDescriptor(const AZ::Component* component)
{
Components::EditorComponentDescriptor* editorComponentDescriptor = nullptr;
Components::EditorComponentDescriptorBus::EventResult(editorComponentDescriptor, component->RTTI_GetType(), &Components::EditorComponentDescriptor::GetEditorDescriptor);
return editorComponentDescriptor;
}
Components::EditorComponentBase* GetEditorComponent(AZ::Component* component)
{
auto editorComponentBaseComponent = azrtti_cast<Components::EditorComponentBase*>(component);
AZ_Assert(editorComponentBaseComponent, "Editor component does not derive from EditorComponentBase");
return editorComponentBaseComponent;
}
bool OffersRequiredServices(
const AZ::SerializeContext::ClassData* componentClass,
const AZStd::vector<AZ::ComponentServiceType>& serviceFilter,
const AZStd::vector<AZ::ComponentServiceType>& incompatibleServiceFilter
)
{
AZ_Assert(componentClass, "Component class must not be null");
if (!componentClass)
{
return false;
}
AZ::ComponentDescriptor* componentDescriptor = nullptr;
AZ::ComponentDescriptorBus::EventResult(
componentDescriptor, componentClass->m_typeId, &AZ::ComponentDescriptor::GetDescriptor);
if (!componentDescriptor)
{
return false;
}
// If no services are provided, this function returns true
if (serviceFilter.empty())
{
return true;
}
AZ::ComponentDescriptor::DependencyArrayType providedServices;
componentDescriptor->GetProvidedServices(providedServices, nullptr);
//reject this component if it does not offer any of the required services
if (AZStd::find_first_of(
providedServices.begin(),
providedServices.end(),
serviceFilter.begin(),
serviceFilter.end()) == providedServices.end())
{
return false;
}
//reject this component if it does offer any of the incompatible services
if (AZStd::find_first_of(
providedServices.begin(),
providedServices.end(),
incompatibleServiceFilter.begin(),
incompatibleServiceFilter.end()) != providedServices.end())
{
return false;
}
return true;
}
bool OffersRequiredServices(
const AZ::SerializeContext::ClassData* componentClass,
const AZStd::vector<AZ::ComponentServiceType>& serviceFilter
)
{
const AZStd::vector<AZ::ComponentServiceType> incompatibleServices;
return OffersRequiredServices(componentClass, serviceFilter, incompatibleServices);
}
bool ShouldInspectorShowComponent(const AZ::Component* component)
{
if (!component)
{
return false;
}
const AZ::SerializeContext::ClassData* classData = GetComponentClassData(component);
// Don't show components without edit data
if (!classData || !classData->m_editData)
{
return false;
}
// Don't show components that are set to invisible.
if (const AZ::Edit::ElementData* editorDataElement = classData->m_editData->FindElementData(AZ::Edit::ClassElements::EditorData))
{
if (AZ::Edit::Attribute* visibilityAttribute = editorDataElement->FindAttribute(AZ::Edit::Attributes::Visibility))
{
PropertyAttributeReader reader(const_cast<AZ::Component*>(component), visibilityAttribute);
AZ::u32 visibilityValue;
if (reader.Read<AZ::u32>(visibilityValue))
{
if (visibilityValue == AZ::Edit::PropertyVisibility::Hide)
{
return false;
}
}
}
}
return true;
}
AZ::EntityId GetEntityIdForSortInfo(const AZ::EntityId parentId)
{
AZ::EntityId sortEntityId = parentId;
if (!sortEntityId.IsValid())
{
AzFramework::EntityContextId editorEntityContextId = AzFramework::EntityContextId::CreateNull();
EditorEntityContextRequestBus::BroadcastResult(editorEntityContextId, &EditorEntityContextRequestBus::Events::GetEditorEntityContextId);
AZ::SliceComponent* rootSliceComponent = nullptr;
AzFramework::SliceEntityOwnershipServiceRequestBus::EventResult(rootSliceComponent, editorEntityContextId,
&AzFramework::SliceEntityOwnershipServiceRequestBus::Events::GetRootSlice);
if (rootSliceComponent)
{
return rootSliceComponent->GetMetadataEntity()->GetId();
}
}
return sortEntityId;
}
void AddEntityIdToSortInfo(const AZ::EntityId parentId, const AZ::EntityId childId, bool forceAddToBack)
{
AZ_PROFILE_FUNCTION(AzToolsFramework);
AZ::EntityId sortEntityId = GetEntityIdForSortInfo(parentId);
bool success = false;
EditorEntitySortRequestBus::EventResult(success, sortEntityId, &EditorEntitySortRequestBus::Events::AddChildEntity, childId, forceAddToBack);
if (success && parentId != sortEntityId)
{
EditorEntitySortNotificationBus::Event(parentId, &EditorEntitySortNotificationBus::Events::ChildEntityOrderArrayUpdated);
}
}
void AddEntityIdToSortInfo(const AZ::EntityId parentId, const AZ::EntityId childId, const AZ::EntityId beforeEntity)
{
AZ_PROFILE_FUNCTION(AzToolsFramework);
AZ::EntityId sortEntityId = GetEntityIdForSortInfo(parentId);
bool success = false;
EditorEntitySortRequestBus::EventResult(success, sortEntityId, &EditorEntitySortRequestBus::Events::AddChildEntityAtPosition, childId, beforeEntity);
if (success && parentId != sortEntityId)
{
EditorEntitySortNotificationBus::Event(parentId, &EditorEntitySortNotificationBus::Events::ChildEntityOrderArrayUpdated);
}
}
bool RecoverEntitySortInfo(const AZ::EntityId parentId, const AZ::EntityId childId, AZ::u64 sortIndex)
{
AZ_PROFILE_FUNCTION(AzToolsFramework);
EntityOrderArray entityOrderArray;
EditorEntitySortRequestBus::EventResult(entityOrderArray, GetEntityIdForSortInfo(parentId), &EditorEntitySortRequestBus::Events::GetChildEntityOrderArray);
// Make sure the child entity isn't already in order array.
auto sortIter = AZStd::find(entityOrderArray.begin(), entityOrderArray.end(), childId);
if (sortIter != entityOrderArray.end())
{
entityOrderArray.erase(sortIter);
}
// Make sure we don't overwrite the bounds of our vector.
if (sortIndex > entityOrderArray.size())
{
sortIndex = entityOrderArray.size();
}
entityOrderArray.insert(entityOrderArray.begin() + sortIndex, childId);
// Push the final array back to the sort component
return SetEntityChildOrder(parentId, entityOrderArray);
}
void RemoveEntityIdFromSortInfo(const AZ::EntityId parentId, const AZ::EntityId childId)
{
AZ_PROFILE_FUNCTION(AzToolsFramework);
AZ::EntityId sortEntityId = GetEntityIdForSortInfo(parentId);
bool success = false;
EditorEntitySortRequestBus::EventResult(success, sortEntityId, &EditorEntitySortRequestBus::Events::RemoveChildEntity, childId);
if (success && parentId != sortEntityId)
{
EditorEntitySortNotificationBus::Event(parentId, &EditorEntitySortNotificationBus::Events::ChildEntityOrderArrayUpdated);
}
}
bool SetEntityChildOrder(const AZ::EntityId parentId, const EntityIdList& children)
{
AZ_PROFILE_FUNCTION(AzToolsFramework);
auto sortEntityId = GetEntityIdForSortInfo(parentId);
bool success = false;
EditorEntitySortRequestBus::EventResult(success, sortEntityId, &EditorEntitySortRequestBus::Events::SetChildEntityOrderArray, children);
if (success && parentId != sortEntityId)
{
EditorEntitySortNotificationBus::Event(parentId, &EditorEntitySortNotificationBus::Events::ChildEntityOrderArrayUpdated);
}
return success;
}
EntityIdList GetEntityChildOrder(const AZ::EntityId parentId)
{
AZ_PROFILE_FUNCTION(AzToolsFramework);
EntityIdList children;
EditorEntityInfoRequestBus::EventResult(children, parentId, &EditorEntityInfoRequestBus::Events::GetChildren);
EntityIdList entityChildOrder;
AZ::EntityId sortEntityId = GetEntityIdForSortInfo(parentId);
EditorEntitySortRequestBus::EventResult(entityChildOrder, sortEntityId, &EditorEntitySortRequestBus::Events::GetChildEntityOrderArray);
// Prune out any entries in the child order array that aren't currently known to be children
entityChildOrder.erase(
AZStd::remove_if(
entityChildOrder.begin(),
entityChildOrder.end(),
[&children](const AZ::EntityId& entityId)
{
// Return true to remove if entity id was not in the child array
return AZStd::find(children.begin(), children.end(), entityId) == children.end();
}
),
entityChildOrder.end()
);
return entityChildOrder;
}
//build an address based on depth and order of entities
void GetEntityLocationInHierarchy(const AZ::EntityId& entityId, AZStd::list<AZ::u64>& location)
{
if(entityId.IsValid())
{
AZ::EntityId parentId;
EditorEntityInfoRequestBus::EventResult(parentId, entityId, &EditorEntityInfoRequestBus::Events::GetParent);
AZ::u64 entityOrder = 0;
EditorEntitySortRequestBus::EventResult(entityOrder, GetEntityIdForSortInfo(parentId), &EditorEntitySortRequestBus::Events::GetChildEntityIndex, entityId);
location.push_front(entityOrder);
GetEntityLocationInHierarchy(parentId, location);
}
}
//sort vector of entities by how they're arranged
void SortEntitiesByLocationInHierarchy(EntityIdList& entityIds)
{
AZ_PROFILE_FUNCTION(AzToolsFramework);
//cache locations for faster sort
AZStd::unordered_map<AZ::EntityId, AZStd::list<AZ::u64>> locations;
for (auto entityId : entityIds)
{
GetEntityLocationInHierarchy(entityId, locations[entityId]);
}
AZStd::sort(entityIds.begin(), entityIds.end(), [&locations](const AZ::EntityId& e1, const AZ::EntityId& e2) {
//sort by container contents
const auto& locationsE1 = locations[e1];
const auto& locationsE2 = locations[e2];
return AZStd::lexicographical_compare(locationsE1.begin(), locationsE1.end(), locationsE2.begin(), locationsE2.end());
});
}
AZ::SliceComponent* GetEntityRootSlice(AZ::EntityId entityId)
{
if (entityId.IsValid())
{
AzFramework::EntityContextId contextId = AzFramework::EntityContextId::CreateNull();
AzFramework::EntityIdContextQueryBus::EventResult(contextId, entityId, &AzFramework::EntityIdContextQueryBus::Events::GetOwningContextId);
if (!contextId.IsNull())
{
AZ::SliceComponent* rootSlice = nullptr;
AzFramework::SliceEntityOwnershipServiceRequestBus::EventResult(rootSlice, contextId,
&AzFramework::SliceEntityOwnershipServiceRequestBus::Events::GetRootSlice);
return rootSlice;
}
}
return nullptr;
}
bool ComponentArrayHasComponentOfType(const AZ::Entity::ComponentArrayType& components, AZ::Uuid componentType)
{
for (const AZ::Component* component : components)
{
if (component)
{
if (GetUnderlyingComponentType(*component) == componentType)
{
return true;
}
}
}
return false;
}
bool EntityHasComponentOfType(const AZ::EntityId& entityId, AZ::Uuid componentType, bool checkPendingComponents, bool checkDisabledComponents)
{
AZ::Entity* entity = nullptr;
AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationRequests::FindEntity, entityId);
if (entity)
{
const AZ::Entity::ComponentArrayType components = entity->GetComponents();
if (ComponentArrayHasComponentOfType(components, componentType))
{
return true;
}
if (checkPendingComponents)
{
AZ::Entity::ComponentArrayType pendingComponents;
AzToolsFramework::EditorPendingCompositionRequestBus::Event(entity->GetId(), &AzToolsFramework::EditorPendingCompositionRequests::GetPendingComponents, pendingComponents);
if (ComponentArrayHasComponentOfType(pendingComponents, componentType))
{
return true;
}
}
if (checkDisabledComponents)
{
// Check for disabled component
AZ::Entity::ComponentArrayType disabledComponents;
AzToolsFramework::EditorDisabledCompositionRequestBus::Event(entity->GetId(), &AzToolsFramework::EditorDisabledCompositionRequests::GetDisabledComponents, disabledComponents);
if (ComponentArrayHasComponentOfType(disabledComponents, componentType))
{
return true;
}
}
}
return false;
}
bool IsComponentWithServiceRegistered(const AZ::Crc32& serviceId)
{
bool result = false;
AZ::SerializeContext* serializeContext = nullptr;
AZ::ComponentApplicationBus::BroadcastResult(serializeContext, &AZ::ComponentApplicationRequests::GetSerializeContext);
if (serializeContext)
{
serializeContext->EnumerateDerived<AZ::Component>(
[&](const AZ::SerializeContext::ClassData* componentClass, const AZ::Uuid& knownType) -> bool
{
(void)knownType;
AZ::ComponentDescriptor* componentDescriptor = nullptr;
EBUS_EVENT_ID_RESULT(componentDescriptor, componentClass->m_typeId, AZ::ComponentDescriptorBus, GetDescriptor);
if (componentDescriptor)
{
AZ::ComponentDescriptor::DependencyArrayType providedServices;
componentDescriptor->GetProvidedServices(providedServices, nullptr);
if (AZStd::find(providedServices.begin(), providedServices.end(), serviceId) != providedServices.end())
{
result = true;
return false;
}
}
return true;
}
);
}
return result;
}
void RemoveHiddenComponents(AZ::Entity::ComponentArrayType& componentsOnEntity)
{
componentsOnEntity.erase(
AZStd::remove_if(
componentsOnEntity.begin(), componentsOnEntity.end(),
[](const AZ::Component* component)
{
return !ShouldInspectorShowComponent(component);
}),
componentsOnEntity.end());
}
bool IsSelected(const AZ::EntityId entityId)
{
AZ_PROFILE_FUNCTION(AzToolsFramework);
bool selected = false;
EditorEntityInfoRequestBus::EventResult(
selected, entityId, &EditorEntityInfoRequestBus::Events::IsSelected);
return selected;
}
bool IsSelectableInViewport(const AZ::EntityId entityId)
{
AZ_PROFILE_FUNCTION(AzToolsFramework);
// Detect if the Entity is Visible
bool visible = false;
EditorEntityInfoRequestBus::EventResult(
visible, entityId, &EditorEntityInfoRequestBus::Events::IsVisible);
if (!visible)
{
return false;
}
// Detect if the Entity is Locked
bool locked = false;
EditorEntityInfoRequestBus::EventResult(locked, entityId, &EditorEntityInfoRequestBus::Events::IsLocked);
if (locked)
{
return false;
}
// Detect if the Entity is part of the Editor Focus
if (auto focusModeInterface = AZ::Interface<FocusModeInterface>::Get();
!focusModeInterface->IsInFocusSubTree(entityId))
{
return false;
}
// Detect if the Entity is a descendant of a closed container
if (auto containerEntityInterface = AZ::Interface<ContainerEntityInterface>::Get();
containerEntityInterface->IsUnderClosedContainerEntity(entityId))
{
return false;
}
return true;
}
static void SetEntityLockStateRecursively(
const AZ::EntityId entityId, const bool locked,
const AZ::EntityId toggledEntityId, const bool toggledEntityWasLayer)
{
AZ_PROFILE_FUNCTION(AzToolsFramework);
if (!entityId.IsValid())
{
return;
}
// first set lock state of the entity in the outliner we clicked on to lock
bool notifyChildrenOfLayer = true;
if (!toggledEntityWasLayer || toggledEntityId == entityId)
{
EditorLockComponentRequestBus::Event(
entityId, &EditorLockComponentRequests::SetLocked, locked);
}
else
{
bool layerEntity = false;
Layers::EditorLayerComponentRequestBus::EventResult(
layerEntity, entityId, &Layers::EditorLayerComponentRequestBus::Events::HasLayer);
bool prevLockState = false;
EditorEntityInfoRequestBus::EventResult(
prevLockState, entityId, &EditorEntityInfoRequestBus::Events::IsLocked);
// if we're unlocking a layer, we do not want to notify/modify child entities
// as this is a non-destructive change (their individual lock state is preserved)
if (prevLockState && layerEntity && !locked)
{
notifyChildrenOfLayer = false;
}
// for all other entities, if we're unlocking and they were individually already locked,
// keep their lock state, otherwise if we're locking, set all entities to be locked.
// note: this notification will update the lock state in ComponentEntityObject and EditorLockComponent
bool newLockState = locked ? true : prevLockState;
EditorLockComponentNotificationBus::Event(
entityId, &EditorLockComponentNotificationBus::Events::OnEntityLockChanged,
newLockState);
}
if (notifyChildrenOfLayer)
{
EntityIdList children;
EditorEntityInfoRequestBus::EventResult(
children, entityId, &EditorEntityInfoRequestBus::Events::GetChildren);
for (auto childId : children)
{
SetEntityLockStateRecursively(childId, locked, toggledEntityId, toggledEntityWasLayer);
}
}
}
// if a child of a layer has its lock state changed to false, change that layer to no longer be locked
// do this for all layers in the hierarchy (this is because not all entities under these layers
// will be locked so the layer cannot be represented as 'fully' locked)
// note: must be called on layer entity
static void UnlockLayer(const AZ::EntityId entityId)
{
AZ_PROFILE_FUNCTION(AzToolsFramework);
EditorLockComponentRequestBus::Event(
entityId, &EditorLockComponentRequestBus::Events::SetLocked, false);
// recursive lambda - notify all children of the layer if the lock has changed
const auto notifyChildrenOfLockChange = [](const AZ::EntityId entityId)
{
const auto notifyChildrenOfLockChangeImpl =
[](const AZ::EntityId entityId, const auto& notifyChildrenRef) -> void
{
EntityIdList children;
EditorEntityInfoRequestBus::EventResult(
children, entityId, &EditorEntityInfoRequestBus::Events::GetChildren);
for (auto childId : children)
{
notifyChildrenRef(childId, notifyChildrenRef);
}
bool locked = false;
EditorLockComponentRequestBus::EventResult(
locked, entityId, &EditorLockComponentRequests::GetLocked);
EditorEntityLockComponentNotificationBus::Event(
entityId, &EditorEntityLockComponentNotificationBus::Events::OnEntityLockChanged,
locked);
};
notifyChildrenOfLockChangeImpl(entityId, notifyChildrenOfLockChangeImpl);
};
notifyChildrenOfLockChange(entityId);
}
void SetEntityLockState(const AZ::EntityId entityId, const bool locked)
{
AZ_PROFILE_FUNCTION(AzToolsFramework);
// when an entity is unlocked, if it was in a locked layer(s), unlock those layers
if (!locked)
{
AZ::EntityId currentEntityId = entityId;
while (currentEntityId.IsValid())
{
AZ::EntityId parentId;
EditorEntityInfoRequestBus::EventResult(
parentId, currentEntityId, &EditorEntityInfoRequestBus::Events::GetParent);
bool parentLayer = false;
Layers::EditorLayerComponentRequestBus::EventResult(
parentLayer, parentId, &Layers::EditorLayerComponentRequestBus::Events::HasLayer);
if (parentLayer && IsEntitySetToBeLocked(parentId))
{
// if a child of a layer has its lock state changed to false, unlock
// that layer, do this for all layers in the hierarchy
UnlockLayer(parentId);
// even though layer lock state is saved to each layer individually, parents still
// need to be checked recursively so that the entity that was toggled can be unlocked
}
currentEntityId = parentId;
}
}
bool isLayer = false;
Layers::EditorLayerComponentRequestBus::EventResult(
isLayer, entityId, &Layers::EditorLayerComponentRequestBus::Events::HasLayer);
SetEntityLockStateRecursively(entityId, locked, entityId, isLayer);
}
void ToggleEntityLockState(const AZ::EntityId entityId)
{
AZ_PROFILE_FUNCTION(AzToolsFramework);
if (entityId.IsValid())
{
bool locked = false;
EditorLockComponentRequestBus::EventResult(
locked, entityId, &EditorLockComponentRequests::GetLocked);
AzToolsFramework::ScopedUndoBatch undo("Toggle Entity Lock State");
if (IsSelected(entityId))
{
// handles the case where we have multiple entities selected but
// must click one entity specifically in the outliner, this will
// apply the lock state to all entities in the selection
// (note: shift must be held)
EntityIdList selectedEntityIds;
ToolsApplicationRequestBus::BroadcastResult(
selectedEntityIds, &ToolsApplicationRequests::GetSelectedEntities);
for (auto selectedId : selectedEntityIds)
{
SetEntityLockState(selectedId, !locked);
}
}
else
{
// just change the single clicked entity in the outliner
// without affecting the current selection (should one exist)
SetEntityLockState(entityId, !locked);
}
}
}
static void SetEntityVisibilityInternal(const AZ::EntityId entityId, const bool visibility)
{
AZ_PROFILE_FUNCTION(AzToolsFramework);
bool layerEntity = false;
Layers::EditorLayerComponentRequestBus::EventResult(
layerEntity, entityId, &Layers::EditorLayerComponentRequestBus::Events::HasLayer);
if (layerEntity)
{
// update the EditorLayerComponent state to stay in sync with Entity visibility
Layers::EditorLayerComponentRequestBus::Event(
entityId, &Layers::EditorLayerComponentRequestBus::Events::SetLayerChildrenVisibility,
visibility);
}
else
{
EditorVisibilityRequestBus::Event(
entityId, &EditorVisibilityRequestBus::Events::SetVisibilityFlag, visibility);
}
}
// note: must be called on layer entity
static void ShowLayer(const AZ::EntityId entityId)
{
AZ_PROFILE_FUNCTION(AzToolsFramework);
SetEntityVisibilityInternal(entityId, true);
// recursive lambda - notify all children of the layer if visibility has changed
const auto notifyChildrenOfVisibilityChange =
[](const AZ::EntityId entityId)
{
const auto notifyChildrenOfVisibilityChangeImpl =
[](const AZ::EntityId entityId, const auto& notifyChildrenRef) -> void
{
EntityIdList children;
EditorEntityInfoRequestBus::EventResult(
children, entityId, &EditorEntityInfoRequestBus::Events::GetChildren);
for (auto childId : children)
{
notifyChildrenRef(childId, notifyChildrenRef);
}
EditorVisibilityNotificationBus::Event(
entityId, &EditorVisibilityNotificationBus::Events::OnEntityVisibilityChanged,
IsEntitySetToBeVisible(entityId));
};
notifyChildrenOfVisibilityChangeImpl(entityId, notifyChildrenOfVisibilityChangeImpl);
};
notifyChildrenOfVisibilityChange(entityId);
}
static void SetEntityVisibilityStateRecursively(
const AZ::EntityId entityId, const bool visible,
const AZ::EntityId toggledEntityId, const bool toggledEntityWasLayer)
{
AZ_PROFILE_FUNCTION(AzToolsFramework);
if (!entityId.IsValid())
{
return;
}
// should we notify children of this entity or layer of a visibility change
bool notifyChildrenOfLayer = true;
if (!toggledEntityWasLayer || toggledEntityId == entityId)
{
SetEntityVisibilityInternal(entityId, visible);
}
else
{
bool layerEntity = false;
Layers::EditorLayerComponentRequestBus::EventResult(
layerEntity, entityId, &Layers::EditorLayerComponentRequestBus::Events::HasLayer);
// if the layer in question was not visible and we're trying to make
// entities visible, do not override the state of the layer and notify
// child entities of a change in visibility
bool oldVisibilityState = IsEntitySetToBeVisible(entityId);
if (!oldVisibilityState && layerEntity && visible)
{
notifyChildrenOfLayer = false;
}
bool newVisibilityState = visible ? oldVisibilityState : false;
EditorVisibilityNotificationBus::Event(
entityId, &EditorVisibilityNotificationBus::Events::OnEntityVisibilityChanged,
newVisibilityState);
}
if (notifyChildrenOfLayer)
{
EntityIdList children;
EditorEntityInfoRequestBus::EventResult(
children, entityId, &EditorEntityInfoRequestBus::Events::GetChildren);
for (auto childId : children)
{
SetEntityVisibilityStateRecursively(childId, visible, toggledEntityId, toggledEntityWasLayer);
}
}
}
void SetEntityVisibility(const AZ::EntityId entityId, const bool visible)
{
AZ_PROFILE_FUNCTION(AzToolsFramework);
// when an entity is set to visible, if it was in an invisible layer(s), make that layer visible
if (visible)
{
AZ::EntityId currentEntityId = entityId;
while (currentEntityId.IsValid())
{
AZ::EntityId parentId;
EditorEntityInfoRequestBus::EventResult(
parentId, currentEntityId, &EditorEntityInfoRequestBus::Events::GetParent);
bool parentLayer = false;
Layers::EditorLayerComponentRequestBus::EventResult(
parentLayer, parentId, &Layers::EditorLayerComponentRequestBus::Events::HasLayer);
if (parentLayer && !IsEntitySetToBeVisible(parentId))
{
// if a child of a layer has its visibility state changed to true, change
// that layer to be visible, do this for all layers in the hierarchy
ShowLayer(parentId);
// even though layer visibility is saved to each layer individually, parents still
// need to be checked recursively so that the entity that was toggled can become visible
}
currentEntityId = parentId;
}
}
bool isLayer = false;
Layers::EditorLayerComponentRequestBus::EventResult(
isLayer, entityId, &Layers::EditorLayerComponentRequestBus::Events::HasLayer);
SetEntityVisibilityStateRecursively(entityId, visible, entityId, isLayer);
}
void ToggleEntityVisibility(const AZ::EntityId entityId)
{
AZ_PROFILE_FUNCTION(AzToolsFramework);
if (entityId.IsValid())
{
bool visible = IsEntitySetToBeVisible(entityId);
AzToolsFramework::ScopedUndoBatch undo("Toggle Entity Visibility");
if (IsSelected(entityId))
{
// handles the case where we have multiple entities selected but
// must click one entity specifically in the outliner, this will
// apply the visibility change to all entities in the selection
// (note: shift must be held)
EntityIdList selectedEntityIds;
ToolsApplicationRequestBus::BroadcastResult(
selectedEntityIds, &ToolsApplicationRequests::GetSelectedEntities);
for (AZ::EntityId selectedId : selectedEntityIds)
{
SetEntityVisibility(selectedId, !visible);
}
}
else
{
// just change the single clicked entity in the outliner
// without affecting the current selection (should one exist)
SetEntityVisibility(entityId, !visible);
}
}
}
bool IsEntitySetToBeLocked(const AZ::EntityId entityId)
{
bool locked = false;
EditorLockComponentRequestBus::EventResult(
locked, entityId, &EditorLockComponentRequestBus::Events::GetLocked);
return locked;
}
bool IsEntityLocked(const AZ::EntityId entityId)
{
bool locked = false;
EditorEntityInfoRequestBus::EventResult(
locked, entityId, &EditorEntityInfoRequestBus::Events::IsLocked);
return locked;
}
bool IsEntitySetToBeVisible(const AZ::EntityId entityId)
{
AZ_PROFILE_FUNCTION(AzToolsFramework);
// Visibility state is tracked in 5 places, see OutlinerListModel::dataForLock for info on 3 of these ways.
// Visibility's fourth state over lock is the EditorVisibilityRequestBus has two sets of
// setting and getting functions for visibility. Get/SetVisibilityFlag is what should be used in most cases.
// The fifth state is tracked on layers. Layers are always invisible to other systems, so the visibility flag
// is set false there. However, layers need to be able to toggle visibility to hide/show their children, so
// layers have a unique flag.
bool layerEntity = false;
Layers::EditorLayerComponentRequestBus::EventResult(
layerEntity, entityId, &Layers::EditorLayerComponentRequestBus::Events::HasLayer);
bool visible = true;
if (layerEntity)
{
Layers::EditorLayerComponentRequestBus::EventResult(
visible, entityId, &Layers::EditorLayerComponentRequestBus::Events::AreLayerChildrenVisible);
}
else
{
EditorVisibilityRequestBus::EventResult(
visible, entityId, &EditorVisibilityRequestBus::Events::GetVisibilityFlag);
}
return visible;
}
bool IsEntityVisible(const AZ::EntityId entityId)
{
bool visible = false;
EditorEntityInfoRequestBus::EventResult(
visible, entityId, &EditorEntityInfoRequestBus::Events::IsVisible);
return visible;
}
AZ::Vector3 GetWorldTranslation(const AZ::EntityId entityId)
{
AZ_PROFILE_FUNCTION(AzToolsFramework);
AZ::Vector3 worldTranslation = AZ::Vector3::CreateZero();
AZ::TransformBus::EventResult(
worldTranslation, entityId, &AZ::TransformBus::Events::GetWorldTranslation);
return worldTranslation;
}
AZ::Vector3 GetLocalTranslation(const AZ::EntityId entityId)
{
AZ_PROFILE_FUNCTION(AzToolsFramework);
AZ::Vector3 localTranslation = AZ::Vector3::CreateZero();
AZ::TransformBus::EventResult(
localTranslation, entityId, &AZ::TransformBus::Events::GetLocalTranslation);
return localTranslation;
}
AZ::Transform GetWorldTransform(const AZ::EntityId entityId)
{
AZ::Transform transform = AZ::Transform::CreateIdentity();
AZ::TransformBus::EventResult(transform, entityId, &AZ::TransformBus::Events::GetWorldTM);
return transform;
}
void SetWorldTransform(const AZ::EntityId entityId, const AZ::Transform& transform)
{
AZ::TransformBus::Event(entityId, &AZ::TransformBus::Events::SetWorldTM, transform);
}
void SelectEntity(const AZ::EntityId entity)
{
AzToolsFramework::ToolsApplicationRequestBus::Broadcast(
&AzToolsFramework::ToolsApplicationRequestBus::Events::SetSelectedEntities,
AzToolsFramework::EntityIdList{entity});
}
void SelectEntities(const AzToolsFramework::EntityIdList& entities)
{
AzToolsFramework::ToolsApplicationRequestBus::Broadcast(
&AzToolsFramework::ToolsApplicationRequestBus::Events::SetSelectedEntities, entities);
}
bool CloneInstantiatedEntities(const EntityIdSet& entitiesToClone, EntityIdSet& clonedEntities)
{
EditorEntityContextNotificationBus::Broadcast(&EditorEntityContextNotification::OnEntitiesAboutToBeCloned);
ScopedUndoBatch undoBatch("Clone Selection");
// Track the mapping of source to cloned entity. This both helps make sure that an entity is not accidentally
// cloned twice, as well as provides the information needed to remap entity references.
AZ::SliceComponent::EntityIdToEntityIdMap sourceToCloneEntityIdMap;
// Track every entity that has been cloned in the container type that AZ::EntityUtils::ReplaceEntityRefs uses.
AZ::SliceComponent::InstantiatedContainer allEntityClonesContainer(false);
// Loose entities can all be cloned at once, so track each one found while looking for slice instances to clone.
EntityIdList looseEntitiesToClone;
// Clone the entities.
Internal::CloneSliceEntitiesAndChildren(
entitiesToClone,
allEntityClonesContainer.m_entities,
sourceToCloneEntityIdMap,
looseEntitiesToClone);
// All entities cloned so far are slice entities, so store those in a container to use for adding to the editor.
EntityList clonedSliceEntities(allEntityClonesContainer.m_entities.begin(), allEntityClonesContainer.m_entities.end());
// Capture all cloned loose entities, so they can be added to the editor.
EntityList clonedLooseEntities;
Internal::CloneLooseEntities(
looseEntitiesToClone,
allEntityClonesContainer.m_entities,
sourceToCloneEntityIdMap,
clonedLooseEntities);
// Update any references cloned entities have to each other.
Internal::UpdateClonedEntityReferences(allEntityClonesContainer, sourceToCloneEntityIdMap);
// Add the cloned entities to the editor, which will also activate them.
EditorEntityContextRequestBus::Broadcast(
&EditorEntityContextRequests::AddEditorEntities,
clonedLooseEntities);
EditorEntityContextRequestBus::Broadcast(
&EditorEntityContextRequests::HandleEntitiesAdded, clonedSliceEntities);
// Make sure an undo operation will delete all of these cloned entities.
// Also replace the selection with the entities that have been cloned.
Internal::UpdateUndoStackAndSelectClonedEntities(allEntityClonesContainer.m_entities, undoBatch);
EditorEntityContextNotificationBus::Broadcast(&EditorEntityContextNotification::OnEntitiesCloned);
for (const AZ::Entity* entity : allEntityClonesContainer.m_entities)
{
clonedEntities.insert(entity->GetId());
}
return !allEntityClonesContainer.m_entities.empty();
}
EntityIdSet GetCulledEntityHierarchy(const EntityIdList& entities)
{
EntityIdSet culledEntities;
for (const AZ::EntityId& entityId : entities)
{
bool selectionIncludesTransformHeritage = false;
AZ::EntityId parentEntityId = entityId;
do
{
AZ::EntityId nextParentId;
AZ::TransformBus::EventResult(
/*result*/ nextParentId,
/*address*/ parentEntityId,
&AZ::TransformBus::Events::GetParentId);
parentEntityId = nextParentId;
if (!parentEntityId.IsValid())
{
break;
}
for (const AZ::EntityId& parentCheck : entities)
{
if (parentCheck == parentEntityId)
{
selectionIncludesTransformHeritage = true;
break;
}
}
} while (parentEntityId.IsValid() && !selectionIncludesTransformHeritage);
if (!selectionIncludesTransformHeritage)
{
culledEntities.insert(entityId);
}
}
return culledEntities;
}
namespace Internal
{
void CloneSliceEntitiesAndChildren(
const EntityIdSet& duplicationSet,
EntityList& out_allEntityClones,
AZ::SliceComponent::EntityIdToEntityIdMap& out_sourceToCloneEntityIdMap,
EntityIdList& out_looseEntitiesToClone)
{
for (const AZ::EntityId& entityId : duplicationSet)
{
AZ::SliceComponent::SliceInstanceAddress owningSliceAddress;
AzFramework::SliceEntityRequestBus::EventResult(owningSliceAddress, entityId,
&AzFramework::SliceEntityRequestBus::Events::GetOwningSlice);
AZ::SliceComponent::EntityAncestorList ancestors;
bool hasInstanceEntityAncestors = false;
if (owningSliceAddress.IsValid())
{
hasInstanceEntityAncestors = owningSliceAddress.GetReference()->GetInstanceEntityAncestry(entityId, ancestors);
}
AZ::SliceComponent::SliceInstanceAddress sourceSliceInstance;
// Don't clone if this entity has already been cloned.
if (out_sourceToCloneEntityIdMap.find(entityId) != out_sourceToCloneEntityIdMap.end())
{
}
// Slice roots take first priority when cloning.
else if (hasInstanceEntityAncestors &&
CloneIfSliceRoot(
ancestors,
out_allEntityClones,
out_sourceToCloneEntityIdMap))
{
}
// Subslice roots take second priority.
else if (hasInstanceEntityAncestors &&
CloneIfSubsliceRoot(
owningSliceAddress,
ancestors,
out_allEntityClones,
out_sourceToCloneEntityIdMap))
{
}
else
{
// If this wasn't a slice root or subslice root, clone it as a loose entity.
out_looseEntitiesToClone.push_back(entityId);
}
// Search through all the children of this entity for anything that needs to be cloned.
// Slice instance entities that are not subslice roots will have been cloned already
// when the slice root was cloned or the subslice root was cloned. Entities may exist
// in the hierarchy that weren't cloned if they are entities that have a slice instance entity
// as a parent, but the entity itself is not part of that slice instance.
EntityIdList children;
AZ::TransformBus::EventResult(
/*result*/ children,
/*address*/ entityId,
&AZ::TransformBus::Events::GetChildren);
EntityIdSet childrenSet;
for (const AZ::EntityId& child : children)
{
childrenSet.insert(child);
}
CloneSliceEntitiesAndChildren(
childrenSet,
out_allEntityClones,
out_sourceToCloneEntityIdMap,
out_looseEntitiesToClone);
}
}
void UpdateClonedEntityReferences(
AZ::SliceComponent::InstantiatedContainer& inout_allEntityClones,
const AZ::SliceComponent::EntityIdToEntityIdMap& sourceToCloneEntityIdMap)
{
// Update all cloned entities to reference other cloned entities, if any references were to entities that were cloned.
// This includes parenting. If Parent and Child are two cloned entities, and Child is a transform child of Parent,
// this will update that reference, so that Child (Clone) is now a child of Parent (Clone).
// It will also include other entity references. If Entity A has an entity reference in Script Canvas to Entity B,
// and both are cloned, then Entity A (Clone)'s Script Canvas entity reference will now be to Unrelated Entity B (Clone).
// If only Entity A was cloned, then Entity B will not be in the mapping, and Entity A (Clone) will continue to reference Entity B.
AZ::EntityUtils::ReplaceEntityRefs(&inout_allEntityClones,
[&sourceToCloneEntityIdMap](const AZ::EntityId& originalId, bool /*isEntityId*/) -> AZ::EntityId
{
auto findIt = sourceToCloneEntityIdMap.find(originalId);
if (findIt == sourceToCloneEntityIdMap.end())
{
return originalId; // entityId is not being remapped
}
else
{
return findIt->second; // return the remapped id
}
});
}
void UpdateUndoStackAndSelectClonedEntities(
const EntityList& allEntityClones,
ScopedUndoBatch &undoBatch)
{
EntityIdList selectEntities;
selectEntities.reserve(allEntityClones.size());
for (AZ::Entity* newEntity : allEntityClones)
{
AZ::EntityId entityId = newEntity->GetId();
selectEntities.push_back(entityId);
// Make sure all cloned entities are contained within the currently active undo batch command.
EntityCreateCommand* command = aznew EntityCreateCommand(
static_cast<UndoSystem::URCommandID>(entityId));
command->Capture(newEntity);
command->SetParent(undoBatch.GetUndoBatch());
}
// Clear selection and select everything we cloned.
ToolsApplicationRequestBus::Broadcast(&ToolsApplicationRequests::SetSelectedEntities, selectEntities);
}
bool CloneIfSliceRoot(
const AZ::SliceComponent::EntityAncestorList& ancestors,
EntityList& out_allEntityClones,
AZ::SliceComponent::EntityIdToEntityIdMap& out_sourceToCloneEntityIdMap)
{
// This entity can't be a slice root if it has no ancestors.
if (ancestors.size() <= 0)
{
return false;
}
// This entity is a slice root if it is the root entity of the first ancestor.
if (!ancestors[0].m_entity || !SliceUtilities::IsRootEntity(*ancestors[0].m_entity))
{
return false;
}
AZ::SliceComponent::EntityIdToEntityIdMap sourceToCloneSliceEntityIdMap;
AZ::SliceComponent::SliceInstanceAddress newInstance;
SliceEditorEntityOwnershipServiceRequestBus::BroadcastResult(newInstance,
&SliceEditorEntityOwnershipServiceRequests::CloneEditorSliceInstance,
ancestors[0].m_sliceAddress, sourceToCloneSliceEntityIdMap);
if (!newInstance.IsValid())
{
AZ_Warning(
"Cloning",
false,
"Unable to clone slice instance, check your duplicated entity selection and verify it contains the entities you expect to see.");
return false;
}
for (AZ::Entity* clone : newInstance.GetInstance()->GetInstantiated()->m_entities)
{
out_allEntityClones.push_back(clone);
}
for (const AZStd::pair<AZ::EntityId, AZ::EntityId>& sourceIdToCloneId : sourceToCloneSliceEntityIdMap)
{
out_sourceToCloneEntityIdMap.insert(sourceIdToCloneId);
}
return true;
}
bool CloneIfSubsliceRoot(
const AZ::SliceComponent::SliceInstanceAddress& owningSliceAddress,
const AZ::SliceComponent::EntityAncestorList& ancestors,
EntityList& out_allEntityClones,
AZ::SliceComponent::EntityIdToEntityIdMap& out_sourceToCloneEntityIdMap)
{
bool result = false;
// This entity can't be a subslice root if there was only one ancestor.
if (ancestors.size() <= 1)
{
return result;
}
AZStd::vector<AZ::SliceComponent::SliceInstanceAddress> sourceSubSliceAncestry;
AZ::SliceComponent::EntityAncestorList::const_iterator ancestorIter = ancestors.begin();
// Skip the first, that would be a regular slice root and not a subslice root, which was already checked.
++ancestorIter;
for (; ancestorIter != ancestors.end(); ++ancestorIter)
{
const AZ::SliceComponent::Ancestor& ancestor = *ancestorIter;
if (!ancestor.m_entity || !SliceUtilities::IsRootEntity(*ancestor.m_entity))
{
// This entity was not the root entity of this slice, so add the slice to the ancestor
// list and move on to the next ancestor.
sourceSubSliceAncestry.push_back(ancestor.m_sliceAddress);
continue;
}
// This entity has been verified to be a subslice root at this point, so clone the entity's subslice instance.
AZ::SliceComponent::SliceInstanceAddress clonedAddress;
AZ::SliceComponent::EntityIdToEntityIdMap sourceToCloneSliceEntityIdMap;
SliceEditorEntityOwnershipServiceRequestBus::BroadcastResult(clonedAddress,
&SliceEditorEntityOwnershipServiceRequests::CloneSubSliceInstance, owningSliceAddress, sourceSubSliceAncestry,
ancestor.m_sliceAddress, &sourceToCloneSliceEntityIdMap);
for (AZ::Entity* instanceEntity : clonedAddress.GetInstance()->GetInstantiated()->m_entities)
{
out_allEntityClones.push_back(instanceEntity);
}
for (const AZStd::pair<AZ::EntityId, AZ::EntityId>& sourceIdToCloneId : sourceToCloneSliceEntityIdMap)
{
out_sourceToCloneEntityIdMap.insert(sourceIdToCloneId);
}
// Only perform one clone, and prioritize the first found ancestor, which will track against
// the rest of the ancestors automatically.
result = true;
break;
}
return result;
}
void CloneLooseEntities(
const EntityIdList& duplicationList,
EntityList& out_allEntityClones,
AZ::SliceComponent::EntityIdToEntityIdMap& out_sourceToCloneEntityIdMap,
EntityList& out_clonedLooseEntities)
{
AZ::SliceComponent::EntityIdToEntityIdMap looseSourceToCloneEntityIdMap;
EntityList looseEntityClones;
EditorEntityContextRequestBus::Broadcast(
&EditorEntityContextRequests::CloneEditorEntities,
duplicationList,
looseEntityClones,
looseSourceToCloneEntityIdMap);
AZ_Error("Clone", looseEntityClones.size() == duplicationList.size(), "Cloned entity set is a different size from the source entity set.");
out_allEntityClones.insert(out_allEntityClones.end(), looseEntityClones.begin(), looseEntityClones.end());
out_clonedLooseEntities.insert(out_clonedLooseEntities.end(), looseEntityClones.begin(), looseEntityClones.end());
for (int entityIndex = 0; entityIndex < looseEntityClones.size(); ++entityIndex)
{
EditorEntityContextNotificationBus::Broadcast(&EditorEntityContextNotification::OnEditorEntityDuplicated, duplicationList[entityIndex], looseEntityClones[entityIndex]->GetId());
out_sourceToCloneEntityIdMap[duplicationList[entityIndex]] = looseEntityClones[entityIndex]->GetId();
}
}
} // namespace Internal
} // namespace AzToolsFramework
| 42.628803 | 193 | 0.639338 | [
"vector",
"transform",
"3d"
] |
28dfd62b82b9c4794eca6225ea54a93a962c96c7 | 4,805 | cpp | C++ | MiniJVM/vm/vm_heap.cpp | lanrobin/minijvm | d6056012494656669a6665c981e6b23d8d121df8 | [
"MIT"
] | null | null | null | MiniJVM/vm/vm_heap.cpp | lanrobin/minijvm | d6056012494656669a6665c981e6b23d8d121df8 | [
"MIT"
] | null | null | null | MiniJVM/vm/vm_heap.cpp | lanrobin/minijvm | d6056012494656669a6665c981e6b23d8d121df8 | [
"MIT"
] | null | null | null | #include "base_type.h"
#include "vm_heap.h"
#include "vm_class.h"
#include "string_utils.h"
#include "vm.h"
ArrayVMHeapObject::ArrayVMHeapObject(weak_ptr<VMClass> typeClz, size_t size) :ReferenceVMHeapObject(typeClz), maxsize(size) {
elements.reserve(size);
auto thisClzName = typeClz.lock()->getClassSignature();
assert(thisClzName.length() > 0 && thisClzName[0] == L'[');
componentType = VMHelper::loadClass(thisClzName.substr(1, thisClzName.length() - 1));
}
weak_ptr<IntegerVMHeapObject> VMHeapPool::createIntegerVMHeapObject(int defaultValue) {
shared_ptr<IntegerVMHeapObject> obj = nullptr;
auto clz = VMPrimitiveClass::getPrimitiveVMClass(L"I");
assert(!clz.expired());
obj = make_shared<IntegerVMHeapObject>(defaultValue, clz);
storeObject(obj);
return obj;
}
weak_ptr<FloatVMHeapObject> VMHeapPool::createFloatVMHeapObject(float defaultValue) {
shared_ptr<FloatVMHeapObject> obj = make_shared<FloatVMHeapObject>(defaultValue);
storeObject(obj);
return obj;
}
weak_ptr<LongVMHeapObject> VMHeapPool::createLongVMHeapObject(long long defaultValue) {
shared_ptr<LongVMHeapObject> obj = make_shared<LongVMHeapObject>(defaultValue);
storeObject(obj);
return obj;
}
weak_ptr<DoubleVMHeapObject> VMHeapPool::createDoubleVMHeapObject(double defaultValue) {
shared_ptr<DoubleVMHeapObject> obj = make_shared<DoubleVMHeapObject>(defaultValue);
storeObject(obj);
return obj;
}
weak_ptr<VMHeapObject> VMHeapPool::createStringVMHeapObject(const wstring& defaultValue) {
auto clz = VMHelper::loadClass(L"java/lang/String");
shared_ptr<VMHeapObject> obj = make_shared<InstanceVMHeapObject>(clz);
storeObject(obj);
return obj;
}
weak_ptr<VMHeapObject> VMHeapPool::createVMHeapObject(const wstring& s) {
shared_ptr<VMHeapObject> obj = nullptr;
if (s[0] == L'L' && s[s.length() - 1] == L';') {
// 普通的类
auto clz = VMHelper::loadClass(s);
obj = make_shared<InstanceVMHeapObject>(clz);
storeObject(obj);
}
else {
throw runtime_error("Incorrect object. signature:" + w2s(s));
}
return obj;
}
weak_ptr<ArrayVMHeapObject> VMHeapPool::createArrayVMHeapObject(const wstring& s, size_t demension) {
shared_ptr<ArrayVMHeapObject> obj = nullptr;
auto thizClassName = L"[" + s;
auto clz = VMHelper::loadArrayClass(thizClassName);
obj = make_shared<ArrayVMHeapObject>(clz, demension);
storeObject(obj);
return obj;
}
weak_ptr<ClassRefVMHeapObject> VMHeapPool::createClassRefVMHeapObject(weak_ptr<VMClass> clz) {
assert(!clz.expired());
auto obj = make_shared<ClassRefVMHeapObject>(clz);
storeObject(obj);
return obj;
}
weak_ptr<NullVMHeapObject> FixSizeVMHeapPool::getNullVMHeapObject() const {
// 第一个元素就是null.
return std::dynamic_pointer_cast<NullVMHeapObject>(objects[0]);
}
weak_ptr<VoidVMHeapObject> FixSizeVMHeapPool::getVoidVMHeapObject() const {
// 第二个元素就是null.
return std::dynamic_pointer_cast<VoidVMHeapObject>(objects[0]);
}
void FixSizeVMHeapPool::storeObject(shared_ptr< VMHeapObject> obj) {
if (obj == nullptr) {
spdlog::warn("Try to store nullptr into heap area.");
return;
}
objects.push_back(obj);
}
weak_ptr< VMHeapObject> InstanceVMHeapObject::getField(const wstring& signature, const wstring& name) const {
if (isInterface) {
throw runtime_error("No field operation for Java interface.");
}
// 直接找自己的,如果没有就返回空,数据验证在put那里验证。
auto key = makeLookupKey(signature, name);
auto f = fields.find(key);
if (f != fields.end()) {
return f->second;
}
return std::weak_ptr<VMHeapObject>();
}
weak_ptr< VMHeapObject> InstanceVMHeapObject::getStaticField(const wstring& signature, const wstring& name) const {
auto clz = typeClass.lock();
return clz->findStaticField(signature, name);
}
void InstanceVMHeapObject::putField(const wstring& signature, const wstring& name, weak_ptr<VMHeapObject> value)
{
// 如果field已经存在,直接写。
/*
其实如果不存在,要去验证一下是不是有这个字段,如果没有不让写,这里就先简单处理,其实Java编译器已经帮我们处理过了。
*/
auto key = makeLookupKey(signature, name);
fields[key] = value;
}
void InstanceVMHeapObject::putStaticField(const wstring& signature, const wstring& name, weak_ptr<VMHeapObject> value)
{
typeClass.lock()->putStaticField(signature, name, value);
}
void ArrayVMHeapObject::putArray(size_t index, weak_ptr<VMHeapObject> value) {
if (index < 0 || index >= maxsize) {
throw runtime_error("Should throw IndexOutOfBoundException.");
}
elements[index] = value;
}
weak_ptr<VMHeapObject> ArrayVMHeapObject::getArray(size_t index) const {
if (index < 0 || index >= maxsize) {
throw runtime_error("Should throw IndexOutOfBoundException.");
}
return elements[index];
}
shared_ptr<VMHeapPool> VMHeapPoolFactory::createVMHeapPool(weak_ptr<Configurations> conf) {
auto cf = conf.lock();
if (cf->useFixHeap()) {
return make_shared< FixSizeVMHeapPool>(cf->maxHeapSize());
}
else {
throw runtime_error("Exensible heap not impemented yet.");
}
} | 33.368056 | 125 | 0.76129 | [
"object"
] |
28e30e7df7d381e1c7f32e2abbe8e8ec77f05082 | 5,868 | cc | C++ | src/ops/broadcast_to_op.cc | llehtahw/jittor | d83389117fd026a0881dd713e658ce5ae2a75bcb | [
"Apache-2.0"
] | 5 | 2020-08-09T02:27:58.000Z | 2021-01-13T16:04:32.000Z | src/ops/broadcast_to_op.cc | llehtahw/jittor | d83389117fd026a0881dd713e658ce5ae2a75bcb | [
"Apache-2.0"
] | null | null | null | src/ops/broadcast_to_op.cc | llehtahw/jittor | d83389117fd026a0881dd713e658ce5ae2a75bcb | [
"Apache-2.0"
] | 1 | 2020-06-23T16:25:42.000Z | 2020-06-23T16:25:42.000Z | // ***************************************************************
// Copyright (c) 2020 Jittor. Authors: Dun Liang <randonlang@gmail.com>. All Rights Reserved.
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
// ***************************************************************
#include <cmath>
#include <algorithm>
#include "var.h"
#include "ops/broadcast_to_op.h"
#include "ops/op_register.h"
namespace jittor {
#ifndef JIT
static auto make_reduce = get_op_info("reduce")
.get_constructor<VarPtr, Var*, NanoString, uint, bool>();
BroadcastToOp::BroadcastToOp(Var* x, Var* y, NanoVector dims) : x(x), y(y) {
// forward x if don't need broadcast
if (y->num>=0 && !need_broadcast(x, y->shape)) {
forward(x);
return;
}
flags.set(NodeFlags::_cpu);
flags.set(NodeFlags::_cuda);
set_type(OpType::broadcast);
z = create_output(NanoVector(), x->dtype());
bcast_mask = 0;
keepdims = 0;
if (dims.size()) {
for (auto a : dims) bcast_mask |= 1 << a;
} else
keepdims = 1;
}
BroadcastToOp::BroadcastToOp(Var* x, Var* y, uint dims_mask) : x(x), y(y) {
// forward x if don't need broadcast
if (y->num>=0 && !need_broadcast(x, y->shape)) {
forward(x);
return;
}
flags.set(NodeFlags::_cpu);
flags.set(NodeFlags::_cuda);
set_type(OpType::broadcast);
z = create_output(NanoVector(), x->dtype());
bcast_mask = dims_mask;
keepdims = 0;
}
BroadcastToOp::BroadcastToOp(Var* x, NanoVector shape, NanoVector dims) : x(x), y(nullptr), shape(shape) {
// forward x if don't need broadcast
if (!need_broadcast(x, shape)) {
forward(x);
return;
}
flags.set(NodeFlags::_cpu);
flags.set(NodeFlags::_cuda);
set_type(OpType::broadcast);
CHECKop(shape.size(),>,0u) << "Number of shape should greater than 0.";
for (auto v : shape)
CHECKop(v,>,0u) << "Shape should greater than 0.";
z = create_output(nullptr, x->dtype());
bcast_mask = 0;
keepdims = 0;
if (dims.size()) {
for (auto a : dims) bcast_mask |= 1 << a;
} else
keepdims = 1;
}
bool BroadcastToOp::need_broadcast(const Var* x, const NanoVector& shape) {
if (x->shape.size() < shape.size()) return true;
for (uint i=shape.size()-1, j=x->shape.size()-1; i<shape.size(); i--,j--)
if (x->shape[j]< 0 || x->shape[j] < shape[i]) return true;
return false;
}
VarPtr BroadcastToOp::grad(Var* out, Var* dout, Var* v, int v_index) {
if (v_index==1) return nullptr;
if (bcast_mask==0) return dout;
VarPtr dv = make_reduce(dout, ns_add, bcast_mask, keepdims);
if (dv->shape.size() != v->shape.size())
dv->shape = v->shape;
return dv;
}
void BroadcastToOp::infer_shape() {
if (y && y->num>=0) {
// shape of y is already solved, we can remove deps
LOGvvvv << "Remove broadcast y deps" << y;
shape = y->shape;
set_inputs({x});
y = nullptr;
}
auto yshapes = y ? y->shape : shape;
auto xdim = x->shape.size();
auto ydim = yshapes.size();
auto zdim = std::max(xdim, ydim);
NanoVector zshape;
if (bcast_mask) {
uint j=0;
for (uint i=0; i<yshapes.size(); i++) {
if (bcast_mask>>i&1) {
zshape.push_back_check_overflow(yshapes[i]);
continue;
}
CHECK(j<xdim) << "Number of shape not match.";
// yshape[i] == 1 will be broadcast to xshape[j]
// use case, xshape = [-3], yshape = [1, 3], dims=[1]
// zshape -> [-3, 3]
auto zs = (yshapes[i]<=1) ? x->shape[j] : yshapes[i];
zshape.push_back_check_overflow(zs);
CHECKop(x->shape[j],==,zs) << "Shape not match.";
j++;
}
j += j==0;
CHECKop(j,==,xdim) << "Number of shape not match.";
z->set_shape(zshape);
LOGvvv << "Broadcast x(" >> x >> ") dims" << std::hex >>
bcast_mask << "-> z(" >> z >> ")";
return;
}
for (size_t i=0; i<zdim; i++) {
bool bx = i-zdim+xdim<xdim;
bool by = i-zdim+ydim<ydim;
auto xshape = bx ? x->shape[i-zdim+xdim] : 1;
auto yshape = by ? yshapes[i-zdim+ydim] : 1;
bcast_mask |= ((xshape==1 && (yshape!=1 || !bx) )&1) << i;
int64 zs;
if ((xshape == 1 || yshape == 1) && (xshape != yshape)) {
zs = xshape * yshape;
} else if (xshape < 0 || yshape < 0) {
zs = std::min(xshape, yshape);
} else {
CHECKop(xshape,==,yshape) << "Shape not match" << x->shape << yshapes;
zs = xshape;
}
zshape.push_back_check_overflow(zs);
}
z->set_shape(zshape);
LOGvvv << "Broadcast x(" >> x >> ") shape" << yshapes << "-> z(" >> z >> ")";
}
void BroadcastToOp::jit_prepare() {
add_jit_define("Tx", x->dtype());
add_jit_define("DIM", JK::hex1(z->shape.size()));
add_jit_define("BCAST", JK::hex(bcast_mask));
}
#else // JIT
void BroadcastToOp::jit_run() {
auto* __restrict__ xp = x->ptr<Tx>();
auto* __restrict__ zp = z->ptr<Tx>();
// define z shape
@for(i, 0, DIM, index_t zshape@i = z->shape[@i];)
// define z stride
index_t zstride@{DIM-1} = 1;
@for(i, DIM-2, -1, -1, auto zstride@i = zstride@{i+1} * zshape@{i+1};)
// define x stride
index_t xstride@{DIM-1} = 1;
@for(i, DIM-2, -1, -1, auto xstride@i = xstride@{i+1} * @if(BCAST>>(i+1)&1,1,zshape@{i+1});)
// generate d-for loop
@for(d, 0, DIM, for (index_t i@d=0; i@d < zshape@d; i@d++)) {
auto zid = @for(d, 0, DIM, + i@d * zstride@d);
auto xid = @for(d, 0, DIM, + @if(BCAST>>d&1,0,i@d) * xstride@d);
zp[zid] = xp[xid];
}
}
#endif // JIT
} // jittor | 33.919075 | 106 | 0.53698 | [
"shape"
] |
28eccc62e1392ee0e36407d542450003baa8a99b | 815 | cpp | C++ | OJ/acm.hdu.edu.cn/2018Multi-UniversityTrainingContest7/J.cpp | webturing/CPlusPlus | 6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f | [
"AFL-2.0"
] | 14 | 2018-06-21T14:41:26.000Z | 2021-12-19T14:43:51.000Z | OJ/acm.hdu.edu.cn/2018Multi-UniversityTrainingContest7/J.cpp | webturing/CPlusPlus | 6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f | [
"AFL-2.0"
] | null | null | null | OJ/acm.hdu.edu.cn/2018Multi-UniversityTrainingContest7/J.cpp | webturing/CPlusPlus | 6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f | [
"AFL-2.0"
] | 2 | 2020-04-20T11:16:53.000Z | 2021-01-02T15:58:35.000Z | #include <bits/stdc++.h>
using namespace std;
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define per(i, a, b) for (int i = (a); i >= (b); i--)
typedef long long LL;
const int MOD = 1e9 + 7;
#define LOCAL
int main() {
#ifdef LOCAL
ifstream cin("J.in");
assert(cin);
ofstream cout("J.out");
LL start = clock();
#endif
ios::sync_with_stdio(false);
int T;
cin >> T;
while (T--) {
int A, B, C, D, P, n;
cin >> A >> B >> C >> D >> P >> n;
vector<int> F(n + 1);
F[1] = A;
F[2] = B;
for (int i = 3; i <= n; i++)
F[i] = (F[i - 2] * C + F[i - 1] * D + (P + i - 1) / i) % MOD;
cout << F[n] << endl;
}
#ifdef LOCAL
LL end = clock();
cerr << fixed << setprecision(2) << 1.0 * (end - start) / CLOCKS_PER_SEC
<< " second(s)." << endl;
#endif
return 0;
}
| 23.285714 | 74 | 0.484663 | [
"vector"
] |
28edef586067c8646f5fc3e7b297984def0dce4b | 13,152 | cpp | C++ | examples/Demos/MultiBody/TestJointTorqueSetup.cpp | ousttrue/bullet3 | 8ad206dd144b94767718cd71cf21f0d37ea89268 | [
"Zlib"
] | null | null | null | examples/Demos/MultiBody/TestJointTorqueSetup.cpp | ousttrue/bullet3 | 8ad206dd144b94767718cd71cf21f0d37ea89268 | [
"Zlib"
] | null | null | null | examples/Demos/MultiBody/TestJointTorqueSetup.cpp | ousttrue/bullet3 | 8ad206dd144b94767718cd71cf21f0d37ea89268 | [
"Zlib"
] | null | null | null | //test addJointTorque
#include "TestJointTorqueSetup.h"
#include "BulletDynamics/Featherstone/btMultiBodyLinkCollider.h"
#include "BulletDynamics/Featherstone/btMultiBodyJointFeedback.h"
#include <CommonMultiBodyBase.h>
#include "../Utils/b3ResourcePath.h"
#include "CommonCameraInterface.h"
static btScalar radius(0.2);
struct TestJointTorqueSetup : public CommonMultiBodyBase
{
btMultiBody* m_multiBody;
btAlignedObjectArray<btMultiBodyJointFeedback*> m_jointFeedbacks;
bool m_once = true;
public:
TestJointTorqueSetup(struct GUIHelperInterface* helper) : CommonMultiBodyBase(helper) {}
~TestJointTorqueSetup() override {}
void initPhysics(CommonCameraInterface* camera, struct GUIHelperInterface* m_guiHelper) override;
virtual void stepSimulation(float deltaTime);
CameraResetInfo cameraResetInfo() const override
{
CameraResetInfo info;
info.camDist = 5;
info.pitch = -21;
info.yaw = 270;
info.camPosX = -1.34;
info.camPosY = 3.4;
info.camPosZ = -0.44;
info.upAxis = 1;
return info;
}
};
void TestJointTorqueSetup::initPhysics(CommonCameraInterface* camera, struct GUIHelperInterface* m_guiHelper)
{
btVector4 colors[4] =
{
btVector4(1, 0, 0, 1),
btVector4(0, 1, 0, 1),
btVector4(0, 1, 1, 1),
btVector4(1, 1, 0, 1),
};
int curColor = 0;
this->createEmptyDynamicsWorld();
m_guiHelper->createPhysicsDebugDrawer(m_dynamicsWorld);
m_dynamicsWorld->getDebugDrawer()->setDebugMode(
//btIDebugDraw::DBG_DrawConstraints
+btIDebugDraw::DBG_DrawWireframe + btIDebugDraw::DBG_DrawContactPoints + btIDebugDraw::DBG_DrawAabb); //+btIDebugDraw::DBG_DrawConstraintLimits);
m_dynamicsWorld->getSolverInfo().m_jointFeedbackInWorldSpace = true;
m_dynamicsWorld->getSolverInfo().m_jointFeedbackInJointFrame = true;
//create a static ground object
if (1)
{
auto upAxis = cameraResetInfo().upAxis;
btVector3 groundHalfExtents(1, 1, 0.2);
groundHalfExtents[upAxis] = 1.f;
btBoxShape* box = new btBoxShape(groundHalfExtents);
box->initializePolyhedralFeatures();
m_guiHelper->createCollisionShapeGraphicsObject(box);
btTransform start;
start.setIdentity();
btVector3 groundOrigin(-0.4f, 3.f, 0.f);
groundOrigin[upAxis] -= .5;
groundOrigin[2] -= 0.6;
start.setOrigin(groundOrigin);
btQuaternion groundOrn(btVector3(0, 1, 0), 0.25 * SIMD_PI);
// start.setRotation(groundOrn);
btRigidBody* body = createRigidBody(0, start, box);
body->setFriction(0);
btVector4 color = colors[curColor];
curColor++;
curColor &= 3;
m_guiHelper->createRigidBodyGraphicsObject(body, color);
}
{
bool floating = false;
bool damping = false;
bool gyro = false;
int numLinks = 2;
bool spherical = false; //set it ot false -to use 1DoF hinges instead of 3DoF sphericals
bool canSleep = false;
bool selfCollide = false;
btVector3 linkHalfExtents(0.05, 0.37, 0.1);
btVector3 baseHalfExtents(0.05, 0.37, 0.1);
btVector3 basePosition = btVector3(-0.4f, 3.f, 0.f);
//mbC->forceMultiDof(); //if !spherical, you can comment this line to check the 1DoF algorithm
//init the base
btVector3 baseInertiaDiag(0.f, 0.f, 0.f);
float baseMass = 1.f;
if (baseMass)
{
//btCollisionShape *shape = new btSphereShape(baseHalfExtents[0]);// btBoxShape(btVector3(baseHalfExtents[0], baseHalfExtents[1], baseHalfExtents[2]));
btCollisionShape* shape = new btBoxShape(btVector3(baseHalfExtents[0], baseHalfExtents[1], baseHalfExtents[2]));
shape->calculateLocalInertia(baseMass, baseInertiaDiag);
delete shape;
}
btMultiBody* pMultiBody = new btMultiBody(numLinks, baseMass, baseInertiaDiag, !floating, canSleep);
m_multiBody = pMultiBody;
btQuaternion baseOriQuat(0.f, 0.f, 0.f, 1.f);
// baseOriQuat.setEulerZYX(-.25*SIMD_PI,0,-1.75*SIMD_PI);
pMultiBody->setBasePos(basePosition);
pMultiBody->setWorldToBaseRot(baseOriQuat);
btVector3 vel(0, 0, 0);
// pMultiBody->setBaseVel(vel);
//init the links
btVector3 hingeJointAxis(1, 0, 0);
//y-axis assumed up
btVector3 parentComToCurrentCom(0, -linkHalfExtents[1] * 2.f, 0); //par body's COM to cur body's COM offset
btVector3 currentPivotToCurrentCom(0, -linkHalfExtents[1], 0); //cur body's COM to cur body's PIV offset
btVector3 parentComToCurrentPivot = parentComToCurrentCom - currentPivotToCurrentCom; //par body's COM to cur body's PIV offset
//////
btScalar q0 = 0.f * SIMD_PI / 180.f;
btQuaternion quat0(btVector3(0, 1, 0).normalized(), q0);
quat0.normalize();
/////
for (int i = 0; i < numLinks; ++i)
{
float linkMass = 1.f;
//if (i==3 || i==2)
// linkMass= 1000;
btVector3 linkInertiaDiag(0.f, 0.f, 0.f);
btCollisionShape* shape = 0;
if (i == 0)
{
shape = new btBoxShape(btVector3(linkHalfExtents[0], linkHalfExtents[1], linkHalfExtents[2])); //
}
else
{
shape = new btSphereShape(radius);
}
shape->calculateLocalInertia(linkMass, linkInertiaDiag);
delete shape;
if (!spherical)
{
//pMultiBody->setupRevolute(i, linkMass, linkInertiaDiag, i - 1, btQuaternion(0.f, 0.f, 0.f, 1.f), hingeJointAxis, parentComToCurrentPivot, currentPivotToCurrentCom, false);
if (i == 0)
{
pMultiBody->setupRevolute(i, linkMass, linkInertiaDiag, i - 1,
btQuaternion(0.f, 0.f, 0.f, 1.f),
hingeJointAxis,
parentComToCurrentPivot,
currentPivotToCurrentCom, false);
}
else
{
btVector3 parentComToCurrentCom(0, -radius * 2.f, 0); //par body's COM to cur body's COM offset
btVector3 currentPivotToCurrentCom(0, -radius, 0); //cur body's COM to cur body's PIV offset
btVector3 parentComToCurrentPivot = parentComToCurrentCom - currentPivotToCurrentCom; //par body's COM to cur body's PIV offset
pMultiBody->setupFixed(i, linkMass, linkInertiaDiag, i - 1,
btQuaternion(0.f, 0.f, 0.f, 1.f),
parentComToCurrentPivot,
currentPivotToCurrentCom);
}
//pMultiBody->setupFixed(i,linkMass,linkInertiaDiag,i-1,btQuaternion(0,0,0,1),parentComToCurrentPivot,currentPivotToCurrentCom,false);
}
else
{
//pMultiBody->setupPlanar(i, linkMass, linkInertiaDiag, i - 1, btQuaternion(0.f, 0.f, 0.f, 1.f)/*quat0*/, btVector3(1, 0, 0), parentComToCurrentPivot*2, false);
pMultiBody->setupSpherical(i, linkMass, linkInertiaDiag, i - 1, btQuaternion(0.f, 0.f, 0.f, 1.f), parentComToCurrentPivot, currentPivotToCurrentCom, false);
}
}
pMultiBody->finalizeMultiDof();
//for (int i=pMultiBody->getNumLinks()-1;i>=0;i--)//
for (int i = 0; i < pMultiBody->getNumLinks(); i++)
{
btMultiBodyJointFeedback* fb = new btMultiBodyJointFeedback();
pMultiBody->getLink(i).m_jointFeedback = fb;
m_jointFeedbacks.push_back(fb);
//break;
}
btMultiBodyDynamicsWorld* world = m_dynamicsWorld;
///
world->addMultiBody(pMultiBody);
btMultiBody* mbC = pMultiBody;
mbC->setCanSleep(canSleep);
mbC->setHasSelfCollision(selfCollide);
mbC->setUseGyroTerm(gyro);
//
if (!damping)
{
mbC->setLinearDamping(0.f);
mbC->setAngularDamping(0.f);
}
else
{
mbC->setLinearDamping(0.1f);
mbC->setAngularDamping(0.9f);
}
//
m_dynamicsWorld->setGravity(btVector3(0, 0, -10));
//////////////////////////////////////////////
if (/* DISABLES CODE */ (0)) //numLinks > 0)
{
btScalar q0 = 45.f * SIMD_PI / 180.f;
if (!spherical)
{
mbC->setJointPosMultiDof(0, &q0);
}
else
{
btQuaternion quat0(btVector3(1, 1, 0).normalized(), q0);
quat0.normalize();
mbC->setJointPosMultiDof(0, quat0);
}
}
///
btAlignedObjectArray<btQuaternion> world_to_local;
world_to_local.resize(pMultiBody->getNumLinks() + 1);
btAlignedObjectArray<btVector3> local_origin;
local_origin.resize(pMultiBody->getNumLinks() + 1);
world_to_local[0] = pMultiBody->getWorldToBaseRot();
local_origin[0] = pMultiBody->getBasePos();
// double friction = 1;
{
// float pos[4]={local_origin[0].x(),local_origin[0].y(),local_origin[0].z(),1};
// btScalar quat[4]={-world_to_local[0].x(),-world_to_local[0].y(),-world_to_local[0].z(),world_to_local[0].w()};
if (1)
{
btCollisionShape* shape = new btBoxShape(btVector3(baseHalfExtents[0], baseHalfExtents[1], baseHalfExtents[2])); //new btSphereShape(baseHalfExtents[0]);
m_guiHelper->createCollisionShapeGraphicsObject(shape);
btMultiBodyLinkCollider* col = new btMultiBodyLinkCollider(pMultiBody, -1);
col->setCollisionShape(shape);
btTransform tr;
tr.setIdentity();
//if we don't set the initial pose of the btCollisionObject, the simulator will do this
//when syncing the btMultiBody link transforms to the btMultiBodyLinkCollider
tr.setOrigin(local_origin[0]);
btQuaternion orn(btVector3(0, 0, 1), 0.25 * 3.1415926538);
tr.setRotation(orn);
col->setWorldTransform(tr);
bool isDynamic = (baseMass > 0 && floating);
int collisionFilterGroup = isDynamic ? int(btBroadphaseProxy::DefaultFilter) : int(btBroadphaseProxy::StaticFilter);
int collisionFilterMask = isDynamic ? int(btBroadphaseProxy::AllFilter) : int(btBroadphaseProxy::AllFilter ^ btBroadphaseProxy::StaticFilter);
world->addCollisionObject(col, collisionFilterGroup, collisionFilterMask); //, 2,1+2);
btVector3 color(0.0, 0.0, 0.5);
m_guiHelper->createCollisionObjectGraphicsObject(col, color);
// col->setFriction(friction);
pMultiBody->setBaseCollider(col);
}
}
for (int i = 0; i < pMultiBody->getNumLinks(); ++i)
{
const int parent = pMultiBody->getParent(i);
world_to_local[i + 1] = pMultiBody->getParentToLocalRot(i) * world_to_local[parent + 1];
local_origin[i + 1] = local_origin[parent + 1] + (quatRotate(world_to_local[i + 1].inverse(), pMultiBody->getRVector(i)));
}
for (int i = 0; i < pMultiBody->getNumLinks(); ++i)
{
btVector3 posr = local_origin[i + 1];
// float pos[4]={posr.x(),posr.y(),posr.z(),1};
btScalar quat[4] = {-world_to_local[i + 1].x(), -world_to_local[i + 1].y(), -world_to_local[i + 1].z(), world_to_local[i + 1].w()};
btCollisionShape* shape = 0;
if (i == 0)
{
shape = new btBoxShape(btVector3(linkHalfExtents[0], linkHalfExtents[1], linkHalfExtents[2])); //btSphereShape(linkHalfExtents[0]);
}
else
{
shape = new btSphereShape(radius);
}
m_guiHelper->createCollisionShapeGraphicsObject(shape);
btMultiBodyLinkCollider* col = new btMultiBodyLinkCollider(pMultiBody, i);
col->setCollisionShape(shape);
btTransform tr;
tr.setIdentity();
tr.setOrigin(posr);
tr.setRotation(btQuaternion(quat[0], quat[1], quat[2], quat[3]));
col->setWorldTransform(tr);
// col->setFriction(friction);
bool isDynamic = 1; //(linkMass > 0);
int collisionFilterGroup = isDynamic ? int(btBroadphaseProxy::DefaultFilter) : int(btBroadphaseProxy::StaticFilter);
int collisionFilterMask = isDynamic ? int(btBroadphaseProxy::AllFilter) : int(btBroadphaseProxy::AllFilter ^ btBroadphaseProxy::StaticFilter);
//if (i==0||i>numLinks-2)
{
world->addCollisionObject(col, collisionFilterGroup, collisionFilterMask); //,2,1+2);
btVector4 color = colors[curColor];
curColor++;
curColor &= 3;
m_guiHelper->createCollisionObjectGraphicsObject(col, color);
pMultiBody->getLink(i).m_collider = col;
}
}
}
btSerializer* s = new btDefaultSerializer;
m_dynamicsWorld->serialize(s);
char resourcePath[1024];
if (b3ResourcePath::findResourcePath("multibody.bullet", resourcePath, 1024, 0))
{
FILE* f = fopen(resourcePath, "wb");
fwrite(s->getBufferPointer(), s->getCurrentBufferSize(), 1, f);
fclose(f);
}
}
void TestJointTorqueSetup::stepSimulation(float deltaTime)
{
//m_multiBody->addLinkForce(0,btVector3(100,100,100));
if (/* DISABLES CODE */ (0)) //m_once)
{
m_once = false;
m_multiBody->addJointTorque(0, 10.0);
btScalar torque = m_multiBody->getJointTorque(0);
b3Printf("t = %f,%f,%f\n", torque, torque, torque); //[0],torque[1],torque[2]);
}
m_dynamicsWorld->stepSimulation(1. / 240, 0);
static int count = 0;
if ((count & 0x0f) == 0)
{
for (int i = 0; i < m_jointFeedbacks.size(); i++)
{
b3Printf("F_reaction[%i] linear:%f,%f,%f, angular:%f,%f,%f",
i,
m_jointFeedbacks[i]->m_reactionForces.m_topVec[0],
m_jointFeedbacks[i]->m_reactionForces.m_topVec[1],
m_jointFeedbacks[i]->m_reactionForces.m_topVec[2],
m_jointFeedbacks[i]->m_reactionForces.m_bottomVec[0],
m_jointFeedbacks[i]->m_reactionForces.m_bottomVec[1],
m_jointFeedbacks[i]->m_reactionForces.m_bottomVec[2]
);
}
}
count++;
/*
b3Printf("base angvel = %f,%f,%f",m_multiBody->getBaseOmega()[0],
m_multiBody->getBaseOmega()[1],
m_multiBody->getBaseOmega()[2]
);
*/
// btScalar jointVel =m_multiBody->getJointVel(0);
// b3Printf("child angvel = %f",jointVel);
}
class CommonExampleInterface* TestJointTorqueCreateFunc(struct CommonExampleOptions& options)
{
return new TestJointTorqueSetup(options.m_guiHelper);
}
| 33.636829 | 177 | 0.686512 | [
"object",
"shape"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.