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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
36b87ecbeffaff30fca46bbfde8ae277844e178e | 2,998 | hh | C++ | vm/vm/main/datatype-decl.hh | Ahzed11/mozart2 | 4806504b103e11be723e7813be8f69e4d85875cf | [
"BSD-2-Clause"
] | 379 | 2015-01-02T20:27:33.000Z | 2022-03-26T23:18:17.000Z | vm/vm/main/datatype-decl.hh | Ahzed11/mozart2 | 4806504b103e11be723e7813be8f69e4d85875cf | [
"BSD-2-Clause"
] | 81 | 2015-01-08T13:18:52.000Z | 2021-12-21T14:02:21.000Z | vm/vm/main/datatype-decl.hh | Ahzed11/mozart2 | 4806504b103e11be723e7813be8f69e4d85875cf | [
"BSD-2-Clause"
] | 75 | 2015-01-06T09:08:20.000Z | 2021-12-17T09:40:18.000Z | // Copyright © 2012, Université catholique de Louvain
// 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.
//
// 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.
#ifndef MOZART_DATATYPE_DECL_H
#define MOZART_DATATYPE_DECL_H
#include "core-forward-decl.hh"
#include "store-decl.hh"
#include "uuid-decl.hh"
#include "typeinfo-decl.hh"
namespace mozart {
//////////////
// DataType //
//////////////
/**
* Base class for all data types of the VM Object Model
*
* It uses CRTP, so subclasses should be declared as:
* class SomeDataType: public DataType<SomeDataType> { ... };
*/
template <class T>
class DataType: public DataTypeStorageHelper<T, typename Storage<T>::Type> {
public:
static Type type() {
return TypeInfoOf<T>::type();
}
template <class... Args>
static UnstableNode build(VM vm, Args&&... args) {
return UnstableNode::build<T>(vm, std::forward<Args>(args)...);
}
};
//////////////
// WithHome //
//////////////
class WithHome {
public:
WithHome(SpaceRef home): _home(home) {}
inline
WithHome(VM vm);
inline
WithHome(VM vm, GR gr, WithHome& from);
Space* home() {
return _home;
}
protected:
inline
bool isHomedInCurrentSpace(VM vm);
private:
SpaceRef _home;
};
/////////////////////
// Trivial markers //
/////////////////////
template<class T>
struct Interface{};
template<class...>
struct ImplementedBy{};
struct NoAutoWait{};
struct NoAutoReflectiveCalls{};
struct Transient{};
template<class>
struct StoredAs{};
template<class>
struct StoredWithArrayOf{};
struct WithValueBehavior{};
struct WithStructuralBehavior{};
template<unsigned char>
struct WithVariableBehavior{};
template<class>
struct BasedOn{};
struct NoAutoGCollect{};
struct NoAutoSClone{};
}
#endif // MOZART_DATATYPE_DECL_H
| 24.77686 | 79 | 0.714143 | [
"object",
"model"
] |
36b9246ee5f3f4718ee7ad1066dd58f9ff0ee402 | 2,019 | hpp | C++ | include/armnnTfLiteParser/ITfLiteParser.hpp | VinayKarnam/armnn | 98525965c7cfecd9bf48297b433b2122cd1b4a1d | [
"MIT"
] | 1 | 2019-06-26T23:00:46.000Z | 2019-06-26T23:00:46.000Z | include/armnnTfLiteParser/ITfLiteParser.hpp | VinayKarnam/armnn | 98525965c7cfecd9bf48297b433b2122cd1b4a1d | [
"MIT"
] | null | null | null | include/armnnTfLiteParser/ITfLiteParser.hpp | VinayKarnam/armnn | 98525965c7cfecd9bf48297b433b2122cd1b4a1d | [
"MIT"
] | 1 | 2021-09-15T04:31:21.000Z | 2021-09-15T04:31:21.000Z | //
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#pragma once
#include "armnn/Types.hpp"
#include "armnn/NetworkFwd.hpp"
#include "armnn/Tensor.hpp"
#include "armnn/INetwork.hpp"
#include <memory>
#include <map>
#include <vector>
namespace armnnTfLiteParser
{
using BindingPointInfo = armnn::BindingPointInfo;
class ITfLiteParser;
using ITfLiteParserPtr = std::unique_ptr<ITfLiteParser, void(*)(ITfLiteParser* parser)>;
class ITfLiteParser
{
public:
static ITfLiteParser* CreateRaw();
static ITfLiteParserPtr Create();
static void Destroy(ITfLiteParser* parser);
/// Create the network from a flatbuffers binary file on disk
virtual armnn::INetworkPtr CreateNetworkFromBinaryFile(const char* graphFile) = 0;
/// Create the network from a flatbuffers binary
virtual armnn::INetworkPtr CreateNetworkFromBinary(const std::vector<uint8_t> & binaryContent) = 0;
/// Retrieve binding info (layer id and tensor info) for the network input identified by
/// the given layer name and subgraph id
virtual BindingPointInfo GetNetworkInputBindingInfo(size_t subgraphId,
const std::string& name) const = 0;
/// Retrieve binding info (layer id and tensor info) for the network output identified by
/// the given layer name and subgraph id
virtual BindingPointInfo GetNetworkOutputBindingInfo(size_t subgraphId,
const std::string& name) const = 0;
/// Return the number of subgraphs in the parsed model
virtual size_t GetSubgraphCount() const = 0;
/// Return the input tensor names for a given subgraph
virtual std::vector<std::string> GetSubgraphInputTensorNames(size_t subgraphId) const = 0;
/// Return the output tensor names for a given subgraph
virtual std::vector<std::string> GetSubgraphOutputTensorNames(size_t subgraphId) const = 0;
protected:
virtual ~ITfLiteParser() {};
};
}
| 33.098361 | 103 | 0.703814 | [
"vector",
"model"
] |
36bb686b3ce135d2e7d1c4dd8d1f26298c940cde | 3,708 | cpp | C++ | packages/QUIReflection/dev/source/common/XMLSerializer.cpp | phaser/quintessence | 6fdd46c9b0ef397827717e9095c218aeeb89b6d3 | [
"MIT"
] | 1 | 2015-05-21T09:23:16.000Z | 2015-05-21T09:23:16.000Z | packages/QUIReflection/dev/source/common/XMLSerializer.cpp | phaser/quintessence | 6fdd46c9b0ef397827717e9095c218aeeb89b6d3 | [
"MIT"
] | null | null | null | packages/QUIReflection/dev/source/common/XMLSerializer.cpp | phaser/quintessence | 6fdd46c9b0ef397827717e9095c218aeeb89b6d3 | [
"MIT"
] | null | null | null | // Copyright (C) 2012 Cristian Bidea
// This file is part of QUIReflection.
//
// QUIReflection is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// QUIReflection 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 QUIReflection. If not, see <http://www.gnu.org/licenses/>.
#include <qui/XMLSerializer.h>
#include <qui/ReflectableObject.h>
#include <qui/ReflectionManager.h>
#include <qui/VirtualFS.h>
#include <tinyxml.h>
#include <string>
#include <vector>
namespace qui
{
XMLSerializer::XMLSerializer(const std::string& fileName)
: fileName(fileName)
{
}
XMLSerializer::~XMLSerializer()
{
}
qui::ReflectableObject* XMLSerializer::deserialize(const std::string& className)
{
qui::VirtualFS fs;
qui::ReflectionManager rm;
cpp0x::shared_ptr<char> contents = fs.getFileContentsAsText(this->fileName);
if (!contents.get())
{
LOG(LERROR) << "Error occured while reading file -> " << this->fileName << "!";
return NULL;
}
TiXmlDocument document;
document.Parse(contents.get(), 0, TIXML_ENCODING_UTF8);
const TiXmlElement* root = document.FirstChildElement("object");
if (!root)
{
LOG(LERROR) << "Bad serialization format: couldn't find object tag!";
return NULL;
}
const char* xmlClassName = root->Attribute("class");
if (!xmlClassName)
{
LOG(LERROR) << "Bad serialization format: object doesn't have a class attribute!";
return NULL;
}
// TODO(cbidea): Verify if xmlClassName == className
return processObject(root, xmlClassName);
}
void XMLSerializer::processMember(const TiXmlElement *child, qui::ReflectableObject *object)
{
qui::ReflectionManager rm;
std::string memberId = child->Attribute("id");
std::string memberType = child->Attribute("type");
if (memberType.find("array") == std::string::npos)
{
std::string value = child->GetText();
object->setValue(memberId, value);
}
else
{
std::vector<ReflectableObject*>* array = new std::vector<ReflectableObject*>();
child = child->FirstChildElement("object");
while (child)
{
std::string xmlClassName = child->Attribute("class");
ReflectableObject *object = processObject(child, xmlClassName);
if (object)
{
array->push_back(object);
}
else
{
LOG(LERROR) << "Couldn't parse object!";
}
child = child->NextSiblingElement();
}
object->setPointer(memberId, array);
}
}
ReflectableObject* XMLSerializer::processObject(const TiXmlElement* root, const std::string& xmlClassName)
{
qui::ReflectionManager rm;
qui::ReflectableObject *object = rm.getInstanceForClassName(xmlClassName);
if (!object)
{
LOG(LERROR) << "Deserialization error! Class is not reflectable!";
return NULL;
}
const TiXmlElement* child = root->FirstChildElement("member");
if (!child)
{
return object;
}
while (child)
{
processMember(child, object);
child = child->NextSiblingElement();
}
return object;
}
} // namespace qui
| 30.9 | 106 | 0.64698 | [
"object",
"vector"
] |
36c0f5d2379d67bc00a7eb849b5935120b759288 | 2,102 | cpp | C++ | C-PhotoDeal_framework/CannyPhoto.cpp | numberwolf/iOSDealFace | 5a109690d143ac125a4b679a8ea6ef28a9f147e3 | [
"Apache-2.0"
] | 8 | 2016-03-12T08:39:56.000Z | 2021-07-12T01:48:20.000Z | C-PhotoDeal_framework/CannyPhoto.cpp | numberwolf/iOSDealFace | 5a109690d143ac125a4b679a8ea6ef28a9f147e3 | [
"Apache-2.0"
] | null | null | null | C-PhotoDeal_framework/CannyPhoto.cpp | numberwolf/iOSDealFace | 5a109690d143ac125a4b679a8ea6ef28a9f147e3 | [
"Apache-2.0"
] | 2 | 2016-03-15T09:48:38.000Z | 2017-02-04T23:53:32.000Z | //
// CannyPhoto.cpp
// cameraDeal
//
// Created by numberwolf on 16/9/10.
// Copyright © 2016年 numberwolf. All rights reserved.
//
#include "CannyPhoto.hpp"
void CannyPhoto::sobelCanny(int width, int height){
// 定义sobel数组常量长度
const int sobel_len = 9;
int sobel_y[sobel_len] = {
1,2,1,
0,0,0,
-1,-2,-1
}; //sobel算子
int sobel_x[sobel_len] = {
1,0,-1,
2,0,-2,
1,0,-1
};
// int sobel_l[sobel_len] = {
// 2,1,0,
// 1,0,-1,
// 0,-1,-2
// };
// int sobel_r[sobel_len] = {
// 0,1,2,
// -1,0,1,
// -2,-1,0
// };
int a[9],k;
int **temp_data = new int*[height];
for (int j = 0; j < height; j++) {
temp_data[j] = new int[width];
for (int i = 0; i < width; i++) {
temp_data[j][i] = this->CannyPixels->getGray(i, j);
}
}
for (int y = 1; y < height-1; y++) {
for (int x = 1; x < width-1; x++) {
/****/
int grayx = 0;
int grayy = 0;
// int grayl = 0;
// int grayr = 0;
a[0] = temp_data[y-1][x-1];
a[1] = temp_data[y][x-1];
a[2] = temp_data[y+1][x-1];
a[3] = temp_data[y-1][x];
a[4] = temp_data[y][x];
a[5] = temp_data[y+1][x];
a[6] = temp_data[y-1][x+1];
a[7] = temp_data[y][x+1];
a[8] = temp_data[y+1][x+1];
for(k = 0;k < 9;k++)
grayy+=a[k]*sobel_y[k];
for(k = 0;k < 9;k++)
grayx+=a[k]*sobel_x[k];
// for(k = 0;k < 9;k++)
// grayl+=a[k]*sobel_l[k];
// for(k = 0;k < 9;k++)
// grayr+=a[k]*sobel_r[k];
int px = grayx + grayy ;//+ grayl + grayr
// printf("%3d\r\n",px);
px = (px<0?0:px);
this->CannyPixels->rgbMake(x, y, px, px, px);
/****/
}
}
}
| 22.847826 | 63 | 0.372502 | [
"3d"
] |
36c661e04dd2fdedb2df58b953a70dae48716c57 | 927 | cpp | C++ | docs/ds/code/binary-heap/binary-heap_1.cpp | xiaocairush/xiaocairush.github.io | 4f1d864b9b3fba1e2100f6a50932756c0373971c | [
"MIT"
] | null | null | null | docs/ds/code/binary-heap/binary-heap_1.cpp | xiaocairush/xiaocairush.github.io | 4f1d864b9b3fba1e2100f6a50932756c0373971c | [
"MIT"
] | null | null | null | docs/ds/code/binary-heap/binary-heap_1.cpp | xiaocairush/xiaocairush.github.io | 4f1d864b9b3fba1e2100f6a50932756c0373971c | [
"MIT"
] | null | null | null | #include <cstdio>
#include <iostream>
#include <queue>
using namespace std;
int t, x;
int main() {
scanf("%d", &t);
while (t--) {
// 大根堆,维护前一半元素(存小值)
priority_queue<int, vector<int>, less<int> > a;
// 小根堆,维护后一半元素(存大值)
priority_queue<int, vector<int>, greater<int> > b;
while (scanf("%d", &x) && x) {
// 若为查询并删除操作,输出并删除大根堆堆顶元素
// 因为这题要求输出中位数中较小者(偶数个数字会存在两个中位数候选)
// 这个和上面的第k大讲解有稍许出入,但如果理解了上面的,这个稍微变通下便可理清
if (x == -1) {
printf("%d\n", a.top());
a.pop();
}
// 若为插入操作,根据大根堆堆顶的元素值,选择合适的堆进行插入
else {
if (a.empty() || x <= a.top())
a.push(x);
else
b.push(x);
}
// 对堆顶堆进行调整
if (a.size() > (a.size() + b.size() + 1) / 2) {
b.push(a.top());
a.pop();
} else if (a.size() < (a.size() + b.size() + 1) / 2) {
a.push(b.top());
b.pop();
}
}
}
return 0;
} | 23.769231 | 60 | 0.476807 | [
"vector"
] |
36c8cfa40cef9bdb8cd1eff3fc4d442427289324 | 2,555 | cc | C++ | chrome/browser/about_internets_status_view.cc | bluebellzhy/chromium | 008c4fef2676506869a0404239da31e83fd6ccc7 | [
"BSD-3-Clause"
] | 1 | 2016-05-08T15:35:17.000Z | 2016-05-08T15:35:17.000Z | chrome/browser/about_internets_status_view.cc | bluebellzhy/chromium | 008c4fef2676506869a0404239da31e83fd6ccc7 | [
"BSD-3-Clause"
] | null | null | null | chrome/browser/about_internets_status_view.cc | bluebellzhy/chromium | 008c4fef2676506869a0404239da31e83fd6ccc7 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2006-2008 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 "base/file_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "chrome/browser/about_internets_status_view.h"
#include "chrome/browser/tab_contents_delegate.h"
AboutInternetsStatusView::AboutInternetsStatusView()
: StatusView(TAB_CONTENTS_ABOUT_INTERNETS_STATUS_VIEW) {}
AboutInternetsStatusView::~AboutInternetsStatusView() {
if (process_handle_.IsValid())
TerminateProcess(process_handle_.Get(), 0);
}
const std::wstring AboutInternetsStatusView::GetDefaultTitle() const {
return L"Don't Clog the Tubes!";
}
const std::wstring& AboutInternetsStatusView::GetTitle() const {
return title_;
}
void AboutInternetsStatusView::OnCreate(const CRect& rect) {
HWND contents_hwnd = GetContainerHWND();
STARTUPINFO startup_info;
memset(&startup_info, 0, sizeof(startup_info));
startup_info.cb = sizeof(startup_info);
PROCESS_INFORMATION process_info = {0};
std::wstring path;
PathService::Get(base::DIR_SYSTEM, &path);
file_util::AppendToPath(&path, L"sspipes.scr");
std::wstring parameters;
parameters.append(path.c_str());
// Append the handle of the HWND that we want to render the pipes into.
parameters.append(L" /p ");
parameters.append(
Int64ToWString(reinterpret_cast<int64>(contents_hwnd)).c_str());
BOOL result =
CreateProcess(NULL,
const_cast<LPWSTR>(parameters.c_str()),
NULL, // LPSECURITY_ATTRIBUTES lpProcessAttributes
NULL, // LPSECURITY_ATTRIBUTES lpThreadAttributes
FALSE, // BOOL bInheritHandles
CREATE_DEFAULT_ERROR_MODE, // DWORD dwCreationFlags
NULL, // LPVOID lpEnvironment
NULL, // LPCTSTR lpCurrentDirectory
&startup_info, // LPstartup_info lpstartup_info
&process_info); // LPPROCESS_INFORMATION
// lpProcessInformation
if (result) {
title_ = GetDefaultTitle();
CloseHandle(process_info.hThread);
process_handle_.Set(process_info.hProcess);
} else {
title_ = L"The Tubes are Clogged!";
}
}
void AboutInternetsStatusView::OnSize(const CRect& rect) {
// We're required to implement this because it is abstract, but we don't
// actually have anything to do right here.
}
| 36.5 | 80 | 0.679061 | [
"render"
] |
36d228c7c5916c3477d1c2b69280d3bc9e0745fa | 4,185 | cpp | C++ | Plugins/PLFrontendQt/src/DataModels/TreeSortAndFilterProxyModel.cpp | ktotheoz/pixellight | 43a661e762034054b47766d7e38d94baf22d2038 | [
"MIT"
] | 83 | 2015-01-08T15:06:14.000Z | 2021-07-20T17:07:00.000Z | Plugins/PLFrontendQt/src/DataModels/TreeSortAndFilterProxyModel.cpp | PixelLightFoundation/pixellight | 43a661e762034054b47766d7e38d94baf22d2038 | [
"MIT"
] | 27 | 2019-06-18T06:46:07.000Z | 2020-02-02T11:11:28.000Z | Plugins/PLFrontendQt/src/DataModels/TreeSortAndFilterProxyModel.cpp | naetherm/PixelLight | d7666f5b49020334cbb5debbee11030f34cced56 | [
"MIT"
] | 40 | 2015-02-25T18:24:34.000Z | 2021-03-06T09:01:48.000Z | /*********************************************************\
* File: TreeSortAndFilterProxyModel.cpp *
*
* Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/)
*
* This file is part of PixelLight.
*
* 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.
\*********************************************************/
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include <QtCore/QStringList>
#include <PLCore/Container/List.h>
#include <PLCore/Base/Class.h>
#include <PLCore/Base/Module.h>
#include <PLCore/Base/ClassManager.h>
#include "PLFrontendQt/QtStringAdapter.h"
#include "PLFrontendQt/DataModels/TreeSortAndFilterProxyModel.h"
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace PLFrontendQt {
namespace DataModels {
//[-------------------------------------------------------]
//[ Public functions ]
//[-------------------------------------------------------]
TreeSortAndFilterProxyModel::TreeSortAndFilterProxyModel(QObject *parent) : QSortFilterProxyModel(parent)
{
}
void TreeSortAndFilterProxyModel::setFilterString(const QString &filters)
{
setFilterWildcard(filters);
}
//[-------------------------------------------------------]
//[ Protected functions ]
//[-------------------------------------------------------]
bool TreeSortAndFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
{
if (filterAcceptsRowItself(source_row, source_parent))
return true;
// //accept if any of the parents is accepted on it's own merits
// QModelIndex parent = source_parent;
// while (parent.isValid()) {
// if (filterAcceptsRowItself(parent.row(), parent.parent()))
// return true;
// parent = parent.parent();
// }
//accept if any of the children is accepted on it's own merits
if (hasAcceptedChildren(source_row, source_parent)) {
return true;
}
return false;
}
bool TreeSortAndFilterProxyModel::filterAcceptsRowItself(int source_row, const QModelIndex &source_parent) const
{
return QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent);
}
bool TreeSortAndFilterProxyModel::hasAcceptedChildren(int source_row, const QModelIndex &source_parent) const
{
QModelIndex item = sourceModel()->index(source_row,0,source_parent);
if (!item.isValid()) {
return false;
}
//check if there are children
int childCount = item.model()->rowCount(item);
if (childCount == 0)
return false;
for (int i = 0; i < childCount; ++i) {
if (filterAcceptsRowItself(i, item))
return true;
//recursive call
if (hasAcceptedChildren(i, item))
return true;
}
return false;
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // DataModels
} // PLFrontendQt
| 37.366071 | 112 | 0.582796 | [
"model"
] |
36dfdf42f5aba6bb0a8ecdd34ebce685642113cb | 5,176 | cpp | C++ | src/luaexport/Tilemap.cpp | Oberon00/jd | 0724e059cfa56615afb0a50c27ce9885faa54ed6 | [
"BSD-2-Clause"
] | 1 | 2015-10-10T14:05:56.000Z | 2015-10-10T14:05:56.000Z | src/luaexport/Tilemap.cpp | Oberon00/jd | 0724e059cfa56615afb0a50c27ce9885faa54ed6 | [
"BSD-2-Clause"
] | null | null | null | src/luaexport/Tilemap.cpp | Oberon00/jd | 0724e059cfa56615afb0a50c27ce9885faa54ed6 | [
"BSD-2-Clause"
] | null | null | null | // Part of the Jade Engine -- Copyright (c) Christian Neumüller 2012--2013
// This file is subject to the terms of the BSD 2-Clause License.
// See LICENSE.txt or http://opensource.org/licenses/BSD-2-Clause
#include "container.hpp"
#include "MapInfo.hpp"
#include "SfBaseTypes.hpp"
#include "sharedPtrConverter.hpp"
#include "Tilemap.hpp"
#include "TransformGroup.hpp" // GroupedDrawable
static char const libname[] = "Tilemap";
#include "ExportThis.hpp"
static unsigned Tilemap_get(jd::Tilemap const& map, sf::Vector3i p)
{
if (!map.isValidPosition(p))
throw "invalid tile position (@get)";
return map[static_cast<jd::Vector3u>(p)];
}
static void Tilemap_set(jd::Tilemap& map, sf::Vector3i p, unsigned tid)
{
if (!map.isValidPosition(p))
throw "invalid tile position (@set)";
map.set(static_cast<jd::Vector3u>(p), tid);
}
static void init(LuaVm& vm)
{
vm.initLib("SfGraphics");
using namespace luabind;
class_<PropertyMap> cPropertyMap("StringTable");
exportAssocContainer<false>(cPropertyMap);
class_<MapObjectGroup::Map> cObjectGroupMap("ObjectGroupTable");
exportAssocContainer<true>(cObjectGroupMap);
class_<std::vector<PropertyMap>> cPropertyMapVec("StringTableList");
exportRandomAccessContainer<true>(cPropertyMapVec);
class_<std::vector<sf::Vector2f>> cPointVec("PointList");
exportRandomAccessContainer<false>(cPointVec);
class_<std::vector<MapObject>> cMapObjectVec("ObjectList");
exportRandomAccessContainer<true>(cMapObjectVec);
LHMODULE [
namespace_("mapInfo") [
cPropertyMap,
cObjectGroupMap,
cPropertyMapVec,
cMapObjectVec,
cPointVec,
# define LHCURCLASS MapInfo
class_<LHCURCLASS>("Map")
.def(constructor<LHCURCLASS const&>())
.LHPROPRW(tileProperties)
.LHPROPRW(layerProperties)
.LHPROPRW(objectGroups),
# undef LHCURCLASS
# define LHCURCLASS MapObject
class_<LHCURCLASS>("Object")
.def(constructor<LHCURCLASS const&>())
.LHPROPRW(name)
.LHPROPRW(type)
.LHPROPRW(position)
.LHPROPRW(size)
.LHPROPRW(tileId)
.LHPROPRW(objectType)
.LHPROPRW(relativePoints)
.LHPROPG(absolutePoints)
.enum_("t")[
value("RECT", MapObject::T::rect),
value("TILE", MapObject::T::tile),
value("LINE", MapObject::T::line),
value("POLY", MapObject::T::poly)
]
.LHPROPRW(properties),
# undef LHCURCLASS
# define LHCURCLASS MapObjectGroup
class_<LHCURCLASS>("ObjectGroup")
.def(constructor<LHCURCLASS const&>())
.LHPROPRW(name)
.LHPROPRW(objects)
.LHPROPRW(properties)
# undef LHCURCLASS
],
# define LHCURCLASS jd::Tileset
class_<LHCURCLASS>("Tileset")
.def(constructor<
sf::Vector2u,
// HACK: For some reason, ConstPtr is not recognized by luabind:
ResourceTraits<sf::Texture>::Ptr>())
.def("texturePosition", &LHCURCLASS::position)
.LHPROPG(size)
.LHPROPG(texture),
# undef LHCURCLASS
class_<jd::Tilemap, bases<sf::Drawable, sf::Transformable>>("@Tilemap@"),
# define LHCURCLASS GroupedDrawable<jd::Tilemap>
class_<LHCURCLASS, bases<TransformGroup::AutoEntry, jd::Tilemap>>("Tilemap")
.def(constructor<>())
.def(constructor<TransformGroup&>())
.def(constructor<LHCURCLASS const&>())
.property("group", &LHCURCLASS::group, &LHCURCLASS::setGroup)
.LHMEMFN(isValidPosition)
.def("get", &Tilemap_get)
.def("set", &Tilemap_set)
.property("bounds", &LHCURCLASS::getGlobalBounds)
.property("localBounds", &LHCURCLASS::getLocalBounds)
.property("tileset", &LHCURCLASS::tileset, &LHCURCLASS::setTileset)
.property("size", &LHCURCLASS::size, &LHCURCLASS::setSize)
.LHMEMFN(localTilePos)
.def("addAnimation",
(void(LHCURCLASS::*)(std::size_t, std::size_t, float))
&LHCURCLASS::addAnimation)
.def("addAnimation",
(void(LHCURCLASS::*)(jd::Vector3u, std::size_t, float))
&LHCURCLASS::addAnimation)
.def("removeAnimation",
(void(LHCURCLASS::*)(std::size_t))&LHCURCLASS::removeAnimation)
.def("removeAnimation",
(void(LHCURCLASS::*)(jd::Vector3u))&LHCURCLASS::removeAnimation)
.LHMEMFN(animate)
.def("tilePos", &LHCURCLASS::globalTilePos)
.LHMEMFN(tilePosFromLocal)
.LHMEMFN(tilePosFromGlobal)
.def("tileRect", &LHCURCLASS::globalTileRect)
.LHMEMFN(localTileRect)
.def("loadFromFile", &loadTilemap)
# undef LHCURCLASS
];
}
| 36.70922 | 84 | 0.590031 | [
"object",
"vector"
] |
36e46d50123154c1ed0375f8894dba8d2f07fd7d | 4,921 | cpp | C++ | src/armed/ActionBar.cpp | retrowork/wme | 54cf8905091736aef0a35fe6d3e05b818441f3c8 | [
"MIT"
] | null | null | null | src/armed/ActionBar.cpp | retrowork/wme | 54cf8905091736aef0a35fe6d3e05b818441f3c8 | [
"MIT"
] | null | null | null | src/armed/ActionBar.cpp | retrowork/wme | 54cf8905091736aef0a35fe6d3e05b818441f3c8 | [
"MIT"
] | null | null | null | // This file is part of Wintermute Engine
// For conditions of distribution and use, see copyright notice in license.txt
#include "StdAfx.h"
#include "ActionBar.h"
#include "ActionManager.h"
#include "ActionBarItem.h"
namespace Armed
{
//////////////////////////////////////////////////////////////////////////
ActionBar::ActionBar(QObject* parent, QMenuBar* menuBar, ActionBarItem* items) : QObject(parent)
{
m_Type = ACTION_BAR_MENUBAR;
m_MenuBar = menuBar;
m_Items = items;
m_Menu = NULL;
m_ToolBar = NULL;
}
//////////////////////////////////////////////////////////////////////////
ActionBar::ActionBar(QObject* parent, QMenu* menu, ActionBarItem* items) : QObject(parent)
{
m_Type = ACTION_BAR_MENU;
m_Menu = menu;
m_Items = items;
m_MenuBar = NULL;
m_ToolBar = NULL;
}
//////////////////////////////////////////////////////////////////////////
ActionBar::ActionBar(QObject* parent, QToolBar* toolBar, ActionBarItem* items) : QObject(parent)
{
m_Type = ACTION_BAR_TOOBAR;
m_ToolBar = toolBar;
m_Items = items;
m_MenuBar = NULL;
m_Menu = NULL;
}
//////////////////////////////////////////////////////////////////////////
ActionBar::~ActionBar()
{
}
//////////////////////////////////////////////////////////////////////////
void ActionBar::Rebuild()
{
switch (m_Type)
{
case ACTION_BAR_MENUBAR:
RebuildMenuBar();
break;
case ACTION_BAR_MENU:
RebuildMenu();
break;
case ACTION_BAR_TOOBAR:
RebuildToolBar();
break;
}
}
//////////////////////////////////////////////////////////////////////////
void ActionBar::Clear()
{
switch (m_Type)
{
case ACTION_BAR_MENUBAR:
m_MenuBar->clear();
break;
case ACTION_BAR_MENU:
m_Menu->clear();
break;
case ACTION_BAR_TOOBAR:
m_ToolBar->clear();
break;
}
}
//////////////////////////////////////////////////////////////////////////
void ActionBar::RebuildMenuBar()
{
m_MenuBar->clear();
ActionManager* am = ActionManager::GetInstance();
qforeach (ActionBarItem* subMenu, m_Items->GetChildren())
{
QMenu* menu = m_MenuBar->addMenu(subMenu->GetCaption());
bool hasAction = false;
qforeach (ActionBarItem* item, subMenu->GetChildren())
{
if (item->GetName().isEmpty()) menu->addSeparator();
else
{
QAction* action = am->GetAction(item->GetName());
if (action && action->isVisible())
{
hasAction = true;
menu->addAction(action);
}
}
}
menu->menuAction()->setVisible(hasAction);
}
}
//////////////////////////////////////////////////////////////////////////
void ActionBar::RebuildMenu()
{
}
//////////////////////////////////////////////////////////////////////////
void ActionBar::RebuildToolBar()
{
m_ToolBar->setVisible(false);
m_ToolBar->clear();
ActionManager* am = ActionManager::GetInstance();
bool prevSeparator = false;
bool hasAction = false;
qforeach (ActionBarItem* item, m_Items->GetChildren())
{
if (item->GetName().isEmpty())
{
prevSeparator = true;
continue;
}
QAction* action = am->GetAction(item->GetName());
if (action && action->isVisible())
{
if (prevSeparator && hasAction) m_ToolBar->addSeparator();
prevSeparator = false;
hasAction = true;
m_ToolBar->addAction(action);
}
}
m_ToolBar->setVisible(hasAction);
}
//////////////////////////////////////////////////////////////////////////
ActionBarItem* ActionBar::DefineStandardMenu(QObject* parent)
{
ActionBarItem* root = new ActionBarItem(parent);
ActionBarItem* fileMenu = root->AddSub("FileMenu", tr("File"));
fileMenu->AddItem("File.New");
fileMenu->AddItem("File.Open");
fileMenu->AddItem();
fileMenu->AddItem("File.Save");
fileMenu->AddItem("File.SaveAs");
fileMenu->AddItem();
fileMenu->AddItem("File.Exit");
ActionBarItem* editMenu = root->AddSub("EditMenu", tr("Edit"));
editMenu->AddItem("Edit.Find");
editMenu->AddItem("Edit.FindNext");
editMenu->AddItem("Edit.FindPrev");
ActionBarItem* sceneMenu = root->AddSub("SceneMenu", tr("Scene"));
sceneMenu->AddItem("Scene.Transform.Select");
sceneMenu->AddItem("Scene.Transform.Move");
sceneMenu->AddItem("Scene.Transform.Rotate");
sceneMenu->AddItem("Scene.Transform.Scale");
sceneMenu->AddItem();
sceneMenu->AddItem("Scene.GizmoMode.Local");
sceneMenu->AddItem("Scene.GizmoMode.World");
return root;
}
//////////////////////////////////////////////////////////////////////////
ActionBarItem* ActionBar::DefineStandardToolBar(QObject* parent)
{
ActionBarItem* root = new ActionBarItem(parent);
root->AddItem("File.New");
root->AddItem("File.Open");
root->AddItem();
root->AddItem("File.Save");
root->AddItem();
root->AddItem("Edit.Find");
root->AddItem();
root->AddItem("File.Exit");
root->AddItem();
return root;
}
} // namespace Armed
| 23.88835 | 97 | 0.552327 | [
"transform"
] |
36ed7211f5a4085f90a3761beb3a40813fd12a7d | 13,648 | hpp | C++ | include/Org/BouncyCastle/Crypto/BufferedCipherBase.hpp | marksteward/BeatSaber-Quest-Codegen | a76f063f71cef207a9f048ad7613835f554911a7 | [
"Unlicense"
] | null | null | null | include/Org/BouncyCastle/Crypto/BufferedCipherBase.hpp | marksteward/BeatSaber-Quest-Codegen | a76f063f71cef207a9f048ad7613835f554911a7 | [
"Unlicense"
] | null | null | null | include/Org/BouncyCastle/Crypto/BufferedCipherBase.hpp | marksteward/BeatSaber-Quest-Codegen | a76f063f71cef207a9f048ad7613835f554911a7 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: Org.BouncyCastle.Crypto.IBufferedCipher
#include "Org/BouncyCastle/Crypto/IBufferedCipher.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: Org::BouncyCastle::Crypto
namespace Org::BouncyCastle::Crypto {
// Forward declaring type: ICipherParameters
class ICipherParameters;
}
// Completed forward declares
// Type namespace: Org.BouncyCastle.Crypto
namespace Org::BouncyCastle::Crypto {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: Org.BouncyCastle.Crypto.BufferedCipherBase
// [TokenAttribute] Offset: FFFFFFFF
class BufferedCipherBase : public ::Il2CppObject/*, public Org::BouncyCastle::Crypto::IBufferedCipher*/ {
public:
// Creating value type constructor for type: BufferedCipherBase
BufferedCipherBase() noexcept {}
// Creating interface conversion operator: operator Org::BouncyCastle::Crypto::IBufferedCipher
operator Org::BouncyCastle::Crypto::IBufferedCipher() noexcept {
return *reinterpret_cast<Org::BouncyCastle::Crypto::IBufferedCipher*>(this);
}
// Get static field: static protected readonly System.Byte[] EmptyBuffer
static ::Array<uint8_t>* _get_EmptyBuffer();
// Set static field: static protected readonly System.Byte[] EmptyBuffer
static void _set_EmptyBuffer(::Array<uint8_t>* value);
// static private System.Void .cctor()
// Offset: 0x1887428
static void _cctor();
// public System.Void Init(System.Boolean forEncryption, Org.BouncyCastle.Crypto.ICipherParameters parameters)
// Offset: 0xFFFFFFFF
void Init(bool forEncryption, Org::BouncyCastle::Crypto::ICipherParameters* parameters);
// public System.Int32 GetBlockSize()
// Offset: 0xFFFFFFFF
int GetBlockSize();
// public System.Int32 GetOutputSize(System.Int32 inputLen)
// Offset: 0xFFFFFFFF
int GetOutputSize(int inputLen);
// public System.Int32 GetUpdateOutputSize(System.Int32 inputLen)
// Offset: 0xFFFFFFFF
int GetUpdateOutputSize(int inputLen);
// public System.Byte[] ProcessBytes(System.Byte[] input, System.Int32 inOff, System.Int32 length)
// Offset: 0xFFFFFFFF
::Array<uint8_t>* ProcessBytes(::Array<uint8_t>* input, int inOff, int length);
// public System.Int32 ProcessBytes(System.Byte[] input, System.Int32 inOff, System.Int32 length, System.Byte[] output, System.Int32 outOff)
// Offset: 0x188722C
int ProcessBytes(::Array<uint8_t>* input, int inOff, int length, ::Array<uint8_t>* output, int outOff);
// public System.Byte[] DoFinal()
// Offset: 0xFFFFFFFF
::Array<uint8_t>* DoFinal();
// public System.Byte[] DoFinal(System.Byte[] input)
// Offset: 0x188732C
::Array<uint8_t>* DoFinal(::Array<uint8_t>* input);
// public System.Byte[] DoFinal(System.Byte[] input, System.Int32 inOff, System.Int32 length)
// Offset: 0xFFFFFFFF
::Array<uint8_t>* DoFinal(::Array<uint8_t>* input, int inOff, int length);
// public System.Int32 DoFinal(System.Byte[] output, System.Int32 outOff)
// Offset: 0x1887354
int DoFinal(::Array<uint8_t>* output, int outOff);
// public System.Void Reset()
// Offset: 0xFFFFFFFF
void Reset();
// protected System.Void .ctor()
// Offset: 0x188748C
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static BufferedCipherBase* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("Org::BouncyCastle::Crypto::BufferedCipherBase::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<BufferedCipherBase*, creationType>()));
}
}; // Org.BouncyCastle.Crypto.BufferedCipherBase
#pragma pack(pop)
}
DEFINE_IL2CPP_ARG_TYPE(Org::BouncyCastle::Crypto::BufferedCipherBase*, "Org.BouncyCastle.Crypto", "BufferedCipherBase");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::BufferedCipherBase::_cctor
// Il2CppName: .cctor
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&Org::BouncyCastle::Crypto::BufferedCipherBase::_cctor)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::BufferedCipherBase*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::BufferedCipherBase::Init
// Il2CppName: Init
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Org::BouncyCastle::Crypto::BufferedCipherBase::*)(bool, Org::BouncyCastle::Crypto::ICipherParameters*)>(&Org::BouncyCastle::Crypto::BufferedCipherBase::Init)> {
static const MethodInfo* get() {
static auto* forEncryption = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* parameters = &::il2cpp_utils::GetClassFromName("Org.BouncyCastle.Crypto", "ICipherParameters")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::BufferedCipherBase*), "Init", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{forEncryption, parameters});
}
};
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::BufferedCipherBase::GetBlockSize
// Il2CppName: GetBlockSize
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (Org::BouncyCastle::Crypto::BufferedCipherBase::*)()>(&Org::BouncyCastle::Crypto::BufferedCipherBase::GetBlockSize)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::BufferedCipherBase*), "GetBlockSize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::BufferedCipherBase::GetOutputSize
// Il2CppName: GetOutputSize
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (Org::BouncyCastle::Crypto::BufferedCipherBase::*)(int)>(&Org::BouncyCastle::Crypto::BufferedCipherBase::GetOutputSize)> {
static const MethodInfo* get() {
static auto* inputLen = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::BufferedCipherBase*), "GetOutputSize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{inputLen});
}
};
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::BufferedCipherBase::GetUpdateOutputSize
// Il2CppName: GetUpdateOutputSize
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (Org::BouncyCastle::Crypto::BufferedCipherBase::*)(int)>(&Org::BouncyCastle::Crypto::BufferedCipherBase::GetUpdateOutputSize)> {
static const MethodInfo* get() {
static auto* inputLen = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::BufferedCipherBase*), "GetUpdateOutputSize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{inputLen});
}
};
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::BufferedCipherBase::ProcessBytes
// Il2CppName: ProcessBytes
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Array<uint8_t>* (Org::BouncyCastle::Crypto::BufferedCipherBase::*)(::Array<uint8_t>*, int, int)>(&Org::BouncyCastle::Crypto::BufferedCipherBase::ProcessBytes)> {
static const MethodInfo* get() {
static auto* input = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
static auto* inOff = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* length = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::BufferedCipherBase*), "ProcessBytes", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{input, inOff, length});
}
};
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::BufferedCipherBase::ProcessBytes
// Il2CppName: ProcessBytes
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (Org::BouncyCastle::Crypto::BufferedCipherBase::*)(::Array<uint8_t>*, int, int, ::Array<uint8_t>*, int)>(&Org::BouncyCastle::Crypto::BufferedCipherBase::ProcessBytes)> {
static const MethodInfo* get() {
static auto* input = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
static auto* inOff = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* length = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* output = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
static auto* outOff = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::BufferedCipherBase*), "ProcessBytes", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{input, inOff, length, output, outOff});
}
};
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::BufferedCipherBase::DoFinal
// Il2CppName: DoFinal
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Array<uint8_t>* (Org::BouncyCastle::Crypto::BufferedCipherBase::*)()>(&Org::BouncyCastle::Crypto::BufferedCipherBase::DoFinal)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::BufferedCipherBase*), "DoFinal", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::BufferedCipherBase::DoFinal
// Il2CppName: DoFinal
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Array<uint8_t>* (Org::BouncyCastle::Crypto::BufferedCipherBase::*)(::Array<uint8_t>*)>(&Org::BouncyCastle::Crypto::BufferedCipherBase::DoFinal)> {
static const MethodInfo* get() {
static auto* input = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::BufferedCipherBase*), "DoFinal", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{input});
}
};
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::BufferedCipherBase::DoFinal
// Il2CppName: DoFinal
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Array<uint8_t>* (Org::BouncyCastle::Crypto::BufferedCipherBase::*)(::Array<uint8_t>*, int, int)>(&Org::BouncyCastle::Crypto::BufferedCipherBase::DoFinal)> {
static const MethodInfo* get() {
static auto* input = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
static auto* inOff = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* length = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::BufferedCipherBase*), "DoFinal", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{input, inOff, length});
}
};
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::BufferedCipherBase::DoFinal
// Il2CppName: DoFinal
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (Org::BouncyCastle::Crypto::BufferedCipherBase::*)(::Array<uint8_t>*, int)>(&Org::BouncyCastle::Crypto::BufferedCipherBase::DoFinal)> {
static const MethodInfo* get() {
static auto* output = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
static auto* outOff = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::BufferedCipherBase*), "DoFinal", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{output, outOff});
}
};
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::BufferedCipherBase::Reset
// Il2CppName: Reset
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Org::BouncyCastle::Crypto::BufferedCipherBase::*)()>(&Org::BouncyCastle::Crypto::BufferedCipherBase::Reset)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::BufferedCipherBase*), "Reset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::BufferedCipherBase::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 65.615385 | 243 | 0.729997 | [
"object",
"vector"
] |
36f4ac0e94e737c0c58d9db1f2af6781e9e5da6d | 4,833 | cpp | C++ | src/Graphics/OpenGL/TileMapShaderProgram.cpp | jonkuhn/jkengine | 8c8d8d90eab47ca22cece6b31ae602c8d288a19c | [
"MIT"
] | null | null | null | src/Graphics/OpenGL/TileMapShaderProgram.cpp | jonkuhn/jkengine | 8c8d8d90eab47ca22cece6b31ae602c8d288a19c | [
"MIT"
] | null | null | null | src/Graphics/OpenGL/TileMapShaderProgram.cpp | jonkuhn/jkengine | 8c8d8d90eab47ca22cece6b31ae602c8d288a19c | [
"MIT"
] | null | null | null | #include "TileMapShaderProgram.h"
#include "Shader.h"
#include "ShaderProgram.h"
#include "TileAtlas.h"
#include "TileMap.h"
using namespace Graphics::OpenGL;
namespace
{
const char *vertexShaderSource = R"GLSL(
#version 330 core
layout (location = 0) in vec3 vertex;
out vec2 tileMapLocation;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
uniform vec2 tileMapSizeInTiles;
void main()
{
// tileMapLocation must be multiplied up in the vertex shader and then
// divided back down in the fragment shader in order for interpolation
// and rounding to work right to pick the right indices from the tile
// map. It cannot be calculated from tileMapLocationInWorld because
// that is in world coordinates and we want the world coordinate
// position of it to not affect the content of the tile mapped object.
tileMapLocation.x = vertex.x * tileMapSizeInTiles.x;
// Invert Y so that top left of the tile in the tile atlas image is
// in the top left of the displayed tile. This is because the
// conventional y axis in an image goes from top to bottom, but
// the y axis of our unit quad runs from bottom to top (as does our
// world coordinate system) OpenGL's texture y axis also runs from
// bottom to top, but since the engine represents images in memory
// in the conventional way such that the first pixel in the buffer
// corresponds to the upper left of the image at coordinates (0, 0),
// this effectively means that OpenGL texture coordinates match actual
// image coordinates. Since the lower left of our unit quad is (0, 0)
// and the upper right is (1, 1), it means that to display tiles from
// an image right-side-up we need to make y=0 of our unit quad correspond
// to the bottom of a tile in the image and y=1 of our unit quad correspond
// to the top of the tile in the image. And in the image (and texture)
// "top" has lower y values than "bottom"
tileMapLocation.y = (1.0 - vertex.y) * tileMapSizeInTiles.y;
vec4 tileMapLocationInWorld = (model * vec4(vertex.xy, 1.0, 1.0));
gl_Position = projection * view * tileMapLocationInWorld;
}
)GLSL";
const char *fragmentShaderSource = R"GLSL(
#version 330 core
uniform vec2 tileMapSizeInTiles;
uniform sampler2D tileMap;
uniform sampler2D tileAtlas;
uniform vec2 tileAtlasSizeInTiles;
in vec2 tileMapLocation;
out vec4 FragColor;
void main()
{
// Note that the y axis of the atlas location does not need inverted
// because it is intended to represent the tile's x and y offset from
// the upper left of the tile atlas image.
vec2 tileAtlasLocation = texture(tileMap, tileMapLocation / tileMapSizeInTiles).xy * 255;
FragColor = texture(tileAtlas, (tileAtlasLocation + fract(tileMapLocation)) / tileAtlasSizeInTiles);
}
)GLSL";
ShaderProgram createTileMapShaderProgram(IOpenGLWrapper& gl)
{
Shader vertexShader(gl, Shader::Type::Vertex, vertexShaderSource);
Shader fragmentShader(gl, Shader::Type::Fragment, fragmentShaderSource);
// Note that the vertex and fragment shader instances can be destroyed
// after the shader program has been constructed.
ShaderProgram shaderProgram(gl, vertexShader, fragmentShader);
return shaderProgram;
}
}
TileMapShaderProgram::TileMapShaderProgram(IOpenGLWrapper& gl)
: _shaderProgram(createTileMapShaderProgram(gl))
{
}
void TileMapShaderProgram::Use()
{
_shaderProgram.Use();
}
void TileMapShaderProgram::ModelMatrix(const glm::mat4& model)
{
_shaderProgram.SetUniform("model", model);
}
void TileMapShaderProgram::ViewMatrix(const glm::mat4& view)
{
_shaderProgram.SetUniform("view", view);
}
void TileMapShaderProgram::ProjectionMatrix(const glm::mat4& projection)
{
_shaderProgram.SetUniform("projection", projection);
}
void TileMapShaderProgram::Map(const TileMap& map)
{
const int mapTextureIndex = 0;
map.MapTexture().Bind(mapTextureIndex);
_shaderProgram.SetUniform("tileMap", mapTextureIndex);
_shaderProgram.SetUniform("tileMapSizeInTiles", map.SizeInTiles());
}
void TileMapShaderProgram::Atlas(const TileAtlas& atlas)
{
const int atlasTextureIndex = 1;
atlas.AtlasTexture().Bind(atlasTextureIndex);
_shaderProgram.SetUniform("tileAtlas", atlasTextureIndex);
_shaderProgram.SetUniform("tileAtlasSizeInTiles", atlas.SizeInTiles());
}
| 37.176923 | 112 | 0.672046 | [
"object",
"model"
] |
3c02e2e2b3c5357f4cf365e2a24dd4f756dffcee | 55,288 | cpp | C++ | Cryptbot.cpp | Cryptyc/CryptBot | 9d6bf8fe16b9659d15d8aab72c585f1f6fd2b307 | [
"MIT"
] | 14 | 2017-10-05T07:11:30.000Z | 2020-01-24T07:17:19.000Z | Cryptbot.cpp | Cryptyc/CryptBot | 9d6bf8fe16b9659d15d8aab72c585f1f6fd2b307 | [
"MIT"
] | 1 | 2018-03-30T11:56:17.000Z | 2019-03-09T22:20:55.000Z | Cryptbot.cpp | Cryptyc/CryptBot | 9d6bf8fe16b9659d15d8aab72c585f1f6fd2b307 | [
"MIT"
] | 5 | 2017-10-15T22:50:22.000Z | 2019-10-05T20:05:27.000Z | #include <iostream>
#include "Cryptbot.h"
#include "sc2api/sc2_api.h"
#include "Strategys.h"
struct IsAttackable {
bool operator()(const Unit& unit) {
switch (unit.unit_type.ToType()) {
case UNIT_TYPEID::ZERG_OVERLORD: return false;
case UNIT_TYPEID::ZERG_OVERSEER: return false;
case UNIT_TYPEID::PROTOSS_OBSERVER: return false;
default: return true;
}
}
};
struct IsBuilding {
bool operator()(const sc2::Unit & unit)
{
switch (unit.unit_type.ToType())
{
case sc2::UNIT_TYPEID::TERRAN_ARMORY: return true;
case sc2::UNIT_TYPEID::PROTOSS_ASSIMILATOR: return true;
case sc2::UNIT_TYPEID::ZERG_BANELINGNEST: return true;
case sc2::UNIT_TYPEID::TERRAN_BARRACKS: return true;
case sc2::UNIT_TYPEID::TERRAN_BARRACKSREACTOR: return true;
case sc2::UNIT_TYPEID::TERRAN_BARRACKSTECHLAB: return true;
case sc2::UNIT_TYPEID::TERRAN_BUNKER: return true;
case sc2::UNIT_TYPEID::TERRAN_COMMANDCENTER: return true;
case sc2::UNIT_TYPEID::PROTOSS_CYBERNETICSCORE: return true;
case sc2::UNIT_TYPEID::PROTOSS_DARKSHRINE: return true;
case sc2::UNIT_TYPEID::TERRAN_ENGINEERINGBAY: return true;
case sc2::UNIT_TYPEID::ZERG_EVOLUTIONCHAMBER: return true;
case sc2::UNIT_TYPEID::ZERG_EXTRACTOR: return true;
case sc2::UNIT_TYPEID::TERRAN_FACTORY: return true;
case sc2::UNIT_TYPEID::TERRAN_FACTORYREACTOR: return true;
case sc2::UNIT_TYPEID::TERRAN_FACTORYTECHLAB: return true;
case sc2::UNIT_TYPEID::PROTOSS_FLEETBEACON: return true;
case sc2::UNIT_TYPEID::PROTOSS_FORGE: return true;
case sc2::UNIT_TYPEID::TERRAN_FUSIONCORE: return true;
case sc2::UNIT_TYPEID::PROTOSS_GATEWAY: return true;
case sc2::UNIT_TYPEID::PROTOSS_WARPGATE: return true;
case sc2::UNIT_TYPEID::TERRAN_GHOSTACADEMY: return true;
case sc2::UNIT_TYPEID::ZERG_HATCHERY: return true;
case sc2::UNIT_TYPEID::ZERG_HYDRALISKDEN: return true;
case sc2::UNIT_TYPEID::ZERG_INFESTATIONPIT: return true;
case sc2::UNIT_TYPEID::TERRAN_MISSILETURRET: return true;
case sc2::UNIT_TYPEID::PROTOSS_NEXUS: return true;
case sc2::UNIT_TYPEID::ZERG_NYDUSCANAL: return true;
case sc2::UNIT_TYPEID::ZERG_NYDUSNETWORK: return true;
case sc2::UNIT_TYPEID::PROTOSS_PHOTONCANNON: return true;
case sc2::UNIT_TYPEID::PROTOSS_PYLON: return true;
case sc2::UNIT_TYPEID::TERRAN_REFINERY: return true;
case sc2::UNIT_TYPEID::ZERG_ROACHWARREN: return true;
case sc2::UNIT_TYPEID::PROTOSS_ROBOTICSBAY: return true;
case sc2::UNIT_TYPEID::PROTOSS_ROBOTICSFACILITY: return true;
case sc2::UNIT_TYPEID::TERRAN_SENSORTOWER: return true;
case sc2::UNIT_TYPEID::ZERG_SPAWNINGPOOL: return true;
case sc2::UNIT_TYPEID::ZERG_SPINECRAWLER: return true;
case sc2::UNIT_TYPEID::ZERG_SPIRE: return true;
case sc2::UNIT_TYPEID::ZERG_SPORECRAWLER: return true;
case sc2::UNIT_TYPEID::PROTOSS_STARGATE: return true;
case sc2::UNIT_TYPEID::TERRAN_STARPORT: return true;
case sc2::UNIT_TYPEID::TERRAN_STARPORTREACTOR: return true;
case sc2::UNIT_TYPEID::TERRAN_STARPORTTECHLAB: return true;
case sc2::UNIT_TYPEID::TERRAN_SUPPLYDEPOT: return true;
case sc2::UNIT_TYPEID::PROTOSS_TEMPLARARCHIVE: return true;
case sc2::UNIT_TYPEID::PROTOSS_TWILIGHTCOUNCIL: return true;
case sc2::UNIT_TYPEID::ZERG_ULTRALISKCAVERN: return true;
case sc2::UNIT_TYPEID::ZERG_HIVE: return true;
case sc2::UNIT_TYPEID::ZERG_LAIR: return true;
case sc2::UNIT_TYPEID::ZERG_GREATERSPIRE: return true;
case sc2::UNIT_TYPEID::TERRAN_ORBITALCOMMAND: return true;
case sc2::UNIT_TYPEID::TERRAN_PLANETARYFORTRESS: return true;
case sc2::UNIT_TYPEID::TERRAN_SUPPLYDEPOTLOWERED: return true;
case sc2::UNIT_TYPEID::TERRAN_FACTORYFLYING: return true;
case sc2::UNIT_TYPEID::TERRAN_BARRACKSFLYING: return true;
case sc2::UNIT_TYPEID::TERRAN_COMMANDCENTERFLYING: return true;
case sc2::UNIT_TYPEID::TERRAN_ORBITALCOMMANDFLYING: return true;
case sc2::UNIT_TYPEID::TERRAN_STARPORTFLYING: return true;
case sc2::UNIT_TYPEID::TERRAN_TECHLAB: return true;
default: return false;
}
}
};
struct IsArmy {
bool operator()(const sc2::Unit & unit)
{
switch (unit.unit_type.ToType())
{
case UNIT_TYPEID::TERRAN_BANSHEE: return true;
case UNIT_TYPEID::TERRAN_BATTLECRUISER: return true;
case UNIT_TYPEID::TERRAN_CYCLONE: return true;
case UNIT_TYPEID::TERRAN_GHOST: return true;
case UNIT_TYPEID::TERRAN_HELLION: return true;
case UNIT_TYPEID::TERRAN_HELLIONTANK: return true;
case UNIT_TYPEID::TERRAN_LIBERATOR: return true;
case UNIT_TYPEID::TERRAN_LIBERATORAG: return true;
case UNIT_TYPEID::TERRAN_MARAUDER: return true;
case UNIT_TYPEID::TERRAN_MARINE: return true;
case UNIT_TYPEID::TERRAN_MEDIVAC: return true;
case UNIT_TYPEID::TERRAN_MULE: return true;
case UNIT_TYPEID::TERRAN_RAVEN: return true;
case UNIT_TYPEID::TERRAN_REAPER: return true;
case UNIT_TYPEID::TERRAN_SCV: return true;
case UNIT_TYPEID::TERRAN_SIEGETANK: return true;
case UNIT_TYPEID::TERRAN_SIEGETANKSIEGED: return true;
case UNIT_TYPEID::TERRAN_THOR: return true;
case UNIT_TYPEID::TERRAN_THORAP: return true;
case UNIT_TYPEID::TERRAN_VIKINGASSAULT: return true;
case UNIT_TYPEID::TERRAN_VIKINGFIGHTER: return true;
case UNIT_TYPEID::ZERG_BANELING: return true;
case UNIT_TYPEID::ZERG_BROODLING: return true;
case UNIT_TYPEID::ZERG_BROODLORD: return true;
case UNIT_TYPEID::ZERG_BROODLORDCOCOON: return true;
case UNIT_TYPEID::ZERG_CHANGELING: return true;
case UNIT_TYPEID::ZERG_CHANGELINGMARINE: return true;
case UNIT_TYPEID::ZERG_CHANGELINGMARINESHIELD: return true;
case UNIT_TYPEID::ZERG_CHANGELINGZEALOT: return true;
case UNIT_TYPEID::ZERG_CHANGELINGZERGLING: return true;
case UNIT_TYPEID::ZERG_CHANGELINGZERGLINGWINGS: return true;
case UNIT_TYPEID::ZERG_CORRUPTOR: return true;
case UNIT_TYPEID::ZERG_DRONE: return true;
case UNIT_TYPEID::ZERG_HYDRALISK: return true;
case UNIT_TYPEID::ZERG_INFESTEDTERRANSEGG: return true;
case UNIT_TYPEID::ZERG_INFESTOR: return true;
case UNIT_TYPEID::ZERG_INFESTORTERRAN: return true;
case UNIT_TYPEID::ZERG_LOCUSTMP: return true;
case UNIT_TYPEID::ZERG_LOCUSTMPFLYING: return true;
case UNIT_TYPEID::ZERG_LURKERMP: return true;
case UNIT_TYPEID::ZERG_MUTALISK: return true;
case UNIT_TYPEID::ZERG_OVERLORD: return true;
case UNIT_TYPEID::ZERG_OVERLORDTRANSPORT: return true;
case UNIT_TYPEID::ZERG_OVERSEER: return true;
case UNIT_TYPEID::ZERG_QUEEN: return true;
case UNIT_TYPEID::ZERG_RAVAGER: return true;
case UNIT_TYPEID::ZERG_ROACH: return true;
case UNIT_TYPEID::ZERG_SPINECRAWLERUPROOTED: return true;
case UNIT_TYPEID::ZERG_SPORECRAWLERUPROOTED: return true;
case UNIT_TYPEID::ZERG_SWARMHOSTBURROWEDMP: return true;
case UNIT_TYPEID::ZERG_SWARMHOSTMP: return true;
case UNIT_TYPEID::ZERG_TRANSPORTOVERLORDCOCOON: return true;
case UNIT_TYPEID::ZERG_ULTRALISK: return true;
case UNIT_TYPEID::ZERG_VIPER: return true;
case UNIT_TYPEID::ZERG_ZERGLING: return true;
case UNIT_TYPEID::PROTOSS_ADEPT: return true;
case UNIT_TYPEID::PROTOSS_ARCHON: return true;
case UNIT_TYPEID::PROTOSS_CARRIER: return true;
case UNIT_TYPEID::PROTOSS_COLOSSUS: return true;
case UNIT_TYPEID::PROTOSS_DARKTEMPLAR: return true;
case UNIT_TYPEID::PROTOSS_DISRUPTOR: return true;
case UNIT_TYPEID::PROTOSS_HIGHTEMPLAR: return true;
case UNIT_TYPEID::PROTOSS_IMMORTAL: return true;
case UNIT_TYPEID::PROTOSS_INTERCEPTOR: return true;
case UNIT_TYPEID::PROTOSS_MOTHERSHIP: return true;
case UNIT_TYPEID::PROTOSS_MOTHERSHIPCORE: return true;
case UNIT_TYPEID::PROTOSS_OBSERVER: return true;
case UNIT_TYPEID::PROTOSS_ORACLE: return true;
case UNIT_TYPEID::PROTOSS_PHOENIX: return true;
case UNIT_TYPEID::PROTOSS_PROBE: return true;
case UNIT_TYPEID::PROTOSS_SENTRY: return true;
case UNIT_TYPEID::PROTOSS_STALKER: return true;
case UNIT_TYPEID::PROTOSS_TEMPEST: return true;
case UNIT_TYPEID::PROTOSS_VOIDRAY: return true;
case UNIT_TYPEID::PROTOSS_WARPPRISM: return true;
case UNIT_TYPEID::PROTOSS_ZEALOT: return true;
default: return false;
}
}
};
struct IsGroundArmy {
bool operator()(const sc2::Unit & unit)
{
switch (unit.unit_type.ToType())
{
case UNIT_TYPEID::TERRAN_BANSHEE: return true;
case UNIT_TYPEID::TERRAN_BATTLECRUISER: return true;
case UNIT_TYPEID::TERRAN_CYCLONE: return true;
case UNIT_TYPEID::TERRAN_GHOST: return true;
case UNIT_TYPEID::TERRAN_HELLION: return true;
case UNIT_TYPEID::TERRAN_HELLIONTANK: return true;
case UNIT_TYPEID::TERRAN_MARAUDER: return true;
case UNIT_TYPEID::TERRAN_MARINE: return true;
case UNIT_TYPEID::TERRAN_MULE: return true;
case UNIT_TYPEID::TERRAN_REAPER: return true;
case UNIT_TYPEID::TERRAN_SCV: return true;
case UNIT_TYPEID::TERRAN_SIEGETANK: return true;
case UNIT_TYPEID::TERRAN_SIEGETANKSIEGED: return true;
case UNIT_TYPEID::TERRAN_THOR: return true;
case UNIT_TYPEID::TERRAN_THORAP: return true;
case UNIT_TYPEID::TERRAN_VIKINGASSAULT: return true;
case UNIT_TYPEID::ZERG_BANELING: return true;
case UNIT_TYPEID::ZERG_BROODLING: return true;
case UNIT_TYPEID::ZERG_BROODLORDCOCOON: return true;
case UNIT_TYPEID::ZERG_CHANGELING: return true;
case UNIT_TYPEID::ZERG_CHANGELINGMARINE: return true;
case UNIT_TYPEID::ZERG_CHANGELINGMARINESHIELD: return true;
case UNIT_TYPEID::ZERG_CHANGELINGZEALOT: return true;
case UNIT_TYPEID::ZERG_CHANGELINGZERGLING: return true;
case UNIT_TYPEID::ZERG_CHANGELINGZERGLINGWINGS: return true;
case UNIT_TYPEID::ZERG_CORRUPTOR: return true;
case UNIT_TYPEID::ZERG_DRONE: return true;
case UNIT_TYPEID::ZERG_HYDRALISK: return true;
case UNIT_TYPEID::ZERG_INFESTEDTERRANSEGG: return true;
case UNIT_TYPEID::ZERG_INFESTOR: return true;
case UNIT_TYPEID::ZERG_INFESTORTERRAN: return true;
case UNIT_TYPEID::ZERG_LURKERMP: return true;
case UNIT_TYPEID::ZERG_OVERLORD: return true;
case UNIT_TYPEID::ZERG_OVERLORDTRANSPORT: return true;
case UNIT_TYPEID::ZERG_OVERSEER: return true;
case UNIT_TYPEID::ZERG_QUEEN: return true;
case UNIT_TYPEID::ZERG_RAVAGER: return true;
case UNIT_TYPEID::ZERG_ROACH: return true;
case UNIT_TYPEID::ZERG_SPINECRAWLERUPROOTED: return true;
case UNIT_TYPEID::ZERG_SPORECRAWLERUPROOTED: return true;
case UNIT_TYPEID::ZERG_SWARMHOSTBURROWEDMP: return true;
case UNIT_TYPEID::ZERG_SWARMHOSTMP: return true;
case UNIT_TYPEID::ZERG_TRANSPORTOVERLORDCOCOON: return true;
case UNIT_TYPEID::ZERG_ULTRALISK: return true;
case UNIT_TYPEID::ZERG_ZERGLING: return true;
case UNIT_TYPEID::PROTOSS_ADEPT: return true;
case UNIT_TYPEID::PROTOSS_ARCHON: return true;
case UNIT_TYPEID::PROTOSS_COLOSSUS: return true;
case UNIT_TYPEID::PROTOSS_DARKTEMPLAR: return true;
case UNIT_TYPEID::PROTOSS_DISRUPTOR: return true;
case UNIT_TYPEID::PROTOSS_HIGHTEMPLAR: return true;
case UNIT_TYPEID::PROTOSS_IMMORTAL: return true;
case UNIT_TYPEID::PROTOSS_PROBE: return true;
case UNIT_TYPEID::PROTOSS_SENTRY: return true;
case UNIT_TYPEID::PROTOSS_STALKER: return true;
case UNIT_TYPEID::PROTOSS_ZEALOT: return true;
default: return false;
}
}
};
struct IsTownHall {
bool operator()(const Unit& unit) {
switch (unit.unit_type.ToType()) {
case UNIT_TYPEID::ZERG_HATCHERY: return true;
case UNIT_TYPEID::ZERG_LAIR: return true;
case UNIT_TYPEID::ZERG_HIVE: return true;
case UNIT_TYPEID::TERRAN_COMMANDCENTER: return true;
case UNIT_TYPEID::TERRAN_ORBITALCOMMAND: return true;
case UNIT_TYPEID::TERRAN_ORBITALCOMMANDFLYING: return true;
case UNIT_TYPEID::TERRAN_PLANETARYFORTRESS: return true;
case UNIT_TYPEID::PROTOSS_NEXUS: return true;
default: return false;
}
}
};
struct IsVespeneGeyser {
bool operator()(const Unit& unit) {
switch (unit.unit_type.ToType()) {
case UNIT_TYPEID::NEUTRAL_VESPENEGEYSER: return true;
case UNIT_TYPEID::NEUTRAL_SPACEPLATFORMGEYSER: return true;
case UNIT_TYPEID::NEUTRAL_PROTOSSVESPENEGEYSER: return true;
default: return false;
}
}
};
struct IsWorker {
bool operator()(const Unit& unit) {
switch (unit.unit_type.ToType()) {
case UNIT_TYPEID::PROTOSS_PROBE: return true;
case UNIT_TYPEID::ZERG_DRONE: return true;
case UNIT_TYPEID::TERRAN_SCV: return true;
default: return false;
}
}
};
size_t CalculateQueries(float radius, float step_size, const Point2D& center, sc2::ABILITY_ID Structure, QueryType QType, std::vector<QueryInterface::PlacementQuery>& queries) {
Point2D current_grid, previous_grid(std::numeric_limits<float>::max(), std::numeric_limits<float>::max());
size_t valid_queries = 0;
// Find a buildable location on the circumference of the sphere
float loc = 0.0f;
while (loc < 360.0f) {
Point2D point = Point2D(
(radius * std::cos((loc * PI) / 180.0f)) + center.x,
(radius * std::sin((loc * PI) / 180.0f)) + center.y);
switch (QType)
{
case MaxXMinY:
if (point.x > center.x || point.y < center.y)
{
loc += step_size;
continue;
}
break;
case MaxXMaxY:
if (point.x > center.x || point.y > center.y)
{
loc += step_size;
continue;
}
break;
case MinXMinY:
if (point.x > center.x || point.y > center.y)
{
loc += step_size;
continue;
}
break;
case MinXMaxY:
if (point.x < center.x || point.y > center.y)
{
loc += step_size;
continue;
}
break;
}
QueryInterface::PlacementQuery query(Structure, point);
current_grid = Point2D(floor(point.x), floor(point.y));
if (previous_grid != current_grid) {
queries.push_back(query);
++valid_queries;
}
previous_grid = current_grid;
loc += step_size;
}
return valid_queries;
}
Point2D CryptBot::GetRandomBuildableLocationFor(sc2::ABILITY_ID Structure, sc2::Point2D Location, QueryType QType, sc2::search::ExpansionParameters parameters)
{
// Get the required queries for this cluster.
std::vector<QueryInterface::PlacementQuery> queries;
size_t query_count = 0;
for (auto r : parameters.radiuses_) {
query_count += CalculateQueries(r, parameters.circle_step_size_, Location, Structure, QType, queries);
}
float distance = std::numeric_limits<float>::max();
std::vector<bool> results = Query()->Placement(queries);
std::vector<QueryInterface::PlacementQuery> validqueries;
for (size_t j = 0; j < results.size(); ++j)
{
if (!results[j]) {
continue;
}
validqueries.push_back(queries[j]);
}
Point2D place;
srand(time(0));
if (validqueries.size() < 1)
{
std::cout << "No valid placement locations \n";
}
const QueryInterface::PlacementQuery& random_location = GetRandomEntry(validqueries);
place = random_location.target_pos;
return place;
}
Point2D CryptBot::GetNearestBuildableLocationFor(sc2::ABILITY_ID Structure, sc2::Point2D Location, QueryType QType, sc2::search::ExpansionParameters parameters)
{
// Get the required queries for this cluster.
std::vector<QueryInterface::PlacementQuery> queries;
size_t query_count = 0;
for (auto r : parameters.radiuses_) {
query_count += CalculateQueries(r, parameters.circle_step_size_, Location, Structure, QType, queries);
}
float distance = std::numeric_limits<float>::max();
Point2D closest;
std::vector<bool> results = Query()->Placement(queries);
for (size_t j = 0; j < results.size(); ++j)
{
if (!results[j]) {
continue;
}
Point2D& p = queries[j].target_pos;
float d = Distance2D(p, Location);
if (d < distance)
{
distance = d;
closest = p;
}
}
return closest;
}
CryptBot::CryptBot()
: Scouting(false)
, ScoutingUnitTag(0)
, RushUnitTag(0)
, Expanding(false)
, FirstPylon(true)
, RushPylon(true)
, CurrentDefenseCannons(0)
, MaxDefenseCannons(3)
, CurrentOffenseno(0)
, HasTrainedCarrierLaunch(false)
, RushPylonDestroyed(false)
, UseAltStrategy(false)
{
PylonSearchParams.radiuses_ = { 1.0f, 1.5f, 2.0f, 2.5f, 3.0f, 3.5f, 4.0f, 4.5f, 5.0f, 5.5f, 6.0f };
PylonSearchParams.circle_step_size_ = 0.5f;
PylonSearchParams.cluster_distance_ = 15.0f;
}
void CryptBot::SetupRushLocation(const ObservationInterface *observation)
{
if (StartPosition == nullptr || (StartPosition->x == 0 && StartPosition->y == 0 && StartPosition->z == 0))
{
return;
}
Point2D Point1;
Point2D Point2;
if (game_info_->map_name.compare("Ascension to Aiur LE") == 0)
{
Point1 = Point2D(33.397f, 119.001f);//, 10.0061f);
Point2 = Point2D(142.58f, 32.9744f);//, 10.0032f);
}
else if (game_info_->map_name.compare("Proxima Station LE") == 0)
{
Point1 = Point2D(55.5349f, 45.8899f);//, 12.0083f);
Point2 = Point2D(144.946f, 119.996f);//, 12.0068f);
}
else if (game_info_->map_name.compare("Mech Depot LE") == 0)
{
Point1 = Point2D(144.891f, 126.548f);//, 9.99219f);
Point2 = Point2D(38.4912f, 36.8269f);//, 10.0034f);
}
else if (game_info_->map_name.compare("Odyssey LE") == 0)
{
Point1 = Point2D(140.301f, 46.1042f);//, 10.0193f);
Point2 = Point2D(29.7517f, 123.95f);//, 9.99219f);
}
else if (game_info_->map_name.compare("Abyssal Reef LE") == 0)
{
Point1 = Point2D(51.3499f, 119.31f);//, 9.98828f);
Point2 = Point2D(148.648f, 24.686f);//, 9.98828f);
}
else if (game_info_->map_name.compare("Interloper LE") == 0)
{
Point1 = Point2D(113.626f, 43.3684f);
Point2 = Point2D(40.6443f, 130.659f);
}
else if (game_info_->map_name.compare("Blackpink LE") == 0)
{
Point1 = Point2D(144.061f, 122.754f);
Point2 = Point2D(24.4409f, 37.0681f);
}
else if (game_info_->map_name.compare("Acolyte LE") == 0)
{
Point1 = Point2D(123.395f, 160.331f);
Point2 = Point2D(48.7954f, 23.0759f);
}
else
{
return;
}
if (Distance2D(*StartPosition, Point1) > Distance2D(*StartPosition, Point2))
{
RushLocation = Point1;
}
else
{
RushLocation = Point2;
}
/*
MapLocations.clear();
MapLocations.push_back(PylonLocations("ProximaStationLE.SC2Map", Point3D(144.352, 122.625, 11.9883), Point3D(55.6426, 45.3745, 11.9883)));
MapLocations.push_back(PylonLocations("AscensiontoAiurLE.SC2Map", Point3D(27.9182, 111.522, 10.0061), Point3D(148.082, 40.4775, 10.0032)));
MapLocations.push_back(PylonLocations("InterloperLE.SC2Map", Point3D(32.7385, 126.32, 12.0083), Point3D(119.261, 41.6794, 12.0068)));
MapLocations.push_back(PylonLocations("MechDepotLE.SC2Map", Point3D(145.541, 115.666, 9.99219), Point3D(37.6521, 48.0205, 10.0034)));
MapLocations.push_back(PylonLocations("OdysseyLE.SC2Map", Point3D(140.301, 46.1042, 10.0193), Point3D(29.7517, 123.95, 9.99219)));
MapLocations.push_back(PylonLocations("AbyssalReefLE.SC2Map", Point3D(61.4775, 112.321, 9.98828), Point3D(139.389, 30.9661, 9.98828)));
*/
}
int32_t CryptBot::GetCurrentMaxSupply()
{
int32_t MaxSupply = 0;
const Units NewUnits = Observation()->GetUnits();
for (auto &u : NewUnits)
{
if (u->unit_type == UNIT_TYPEID::PROTOSS_NEXUS && u->build_progress == 1.0f)
{
MaxSupply += 15;
}
else if (u->unit_type == UNIT_TYPEID::PROTOSS_PYLON && u->build_progress == 1.0f)
{
MaxSupply += 8;
}
}
return MaxSupply;
}
void CryptBot::OnGameStart()
{
const Units NewUnits = Observation()->GetUnits();
for (auto &u : NewUnits)
{
if (u->unit_type == UNIT_TYPEID::PROTOSS_NEXUS)
{
StartPosition = new sc2::Point3D(u->pos);
Actions()->UnitCommand(u, ABILITY_ID::TRAIN_PROBE);
break;
}
}
expansions_ = search::CalculateExpansionLocations(Observation(), Query());
game_info_ = new sc2::GameInfo(Observation()->GetGameInfo());
bool OwnRaceFound = false;
for (const auto &info : game_info_->player_info)
{
if (info.race_actual == sc2::Race::Protoss && OwnRaceFound == false)
{
OwnRaceFound = true;
continue;
}
OpponentRace = info.race_actual;
}
SetupRushLocation(Observation());
}
void CryptBot::OnUnitDestroyed(const Unit *unit) {
switch (unit->unit_type.ToType()) {
case UNIT_TYPEID::PROTOSS_PROBE: {
if (unit->tag == ScoutingUnitTag)
{
Scouting = false;
ScoutingUnitTag = GetAvailableWorker();
}
break;
}
case UNIT_TYPEID::PROTOSS_PYLON:
if (unit->alliance == sc2::Unit::Alliance::Self && Distance2D(unit->pos, *StartPosition) > Distance2D(unit->pos, RushLocation))
{
RushPylonDestroyed = true;
UseAltStrategy = true;
}
break;
case UNIT_TYPEID::PROTOSS_PHOTONCANNON:
{
if (unit->alliance == sc2::Unit::Alliance::Self && Distance2D(unit->pos, *StartPosition) < Distance2D(unit->pos, RushLocation))
{
CurrentDefenseCannons -= 1;
MaxDefenseCannons += 2;
}
break;
}
case UNIT_TYPEID::PROTOSS_VOIDRAY: {
/*
for (auto& ThisBG : BattleGroups)
{
int thisMember = 0;
for (const uint64_t ThisUnit : ThisBG.Members)
{
if (ThisUnit == unit.tag)
{
ThisBG.Members.erase(ThisBG.Members.begin() + thisMember);
}
thisMember++;
}
}
*/
}
}
}
bool CryptBot::CheckShouldBuildProbe(const sc2::Unit Nexus)
{
const ObservationInterface* observation = Observation();
if (CurrentMaxSupply >= observation->GetFoodUsed())
{
return false;
}
uint64_t mineral_target;
if (Nexus.assigned_harvesters < Nexus.ideal_harvesters)
{
Actions()->UnitCommand(&Nexus, ABILITY_ID::TRAIN_PROBE);
return true;
}
else if (FindNearestGeaser(Nexus.pos, mineral_target, MAX_GEASER_DISTANCE))
{
Actions()->UnitCommand(&Nexus, ABILITY_ID::TRAIN_PROBE);
return true;
}
return false;
}
void CryptBot::OnUnitEnterVision(const Unit *unit)
{
if (unit->unit_type == sc2::UNIT_TYPEID::TERRAN_SCV
|| unit->unit_type == sc2::UNIT_TYPEID::PROTOSS_PROBE
|| unit->unit_type == sc2::UNIT_TYPEID::ZERG_DRONE)
{
const Units NewUnits = Observation()->GetUnits(sc2::Unit::Alliance::Self, IsUnit(UNIT_TYPEID::PROTOSS_PROBE));
for (const Unit *Nextunit : NewUnits)
{
if (Nextunit->tag != ScoutingUnitTag && sc2::Distance3D(Nextunit->pos, unit->pos) < 100)
{
Actions()->UnitCommand(Nextunit, ABILITY_ID::ATTACK, unit);
return;
}
}
}
else if (unit->unit_type == sc2::UNIT_TYPEID::PROTOSS_NEXUS
|| unit->unit_type == sc2::UNIT_TYPEID::ZERG_HATCHERY
|| unit->unit_type == sc2::UNIT_TYPEID::ZERG_LAIR
|| unit->unit_type == sc2::UNIT_TYPEID::ZERG_HIVE
|| unit->unit_type == sc2::UNIT_TYPEID::TERRAN_COMMANDCENTER
|| unit->unit_type == sc2::UNIT_TYPEID::TERRAN_ORBITALCOMMAND
|| unit->unit_type == sc2::UNIT_TYPEID::TERRAN_PLANETARYFORTRESS
|| unit->unit_type == sc2::UNIT_TYPEID::TERRAN_COMMANDCENTERFLYING)
{
// Begin cannon rush
}
}
void CryptBot::OnBuildingConstructionComplete(const Unit* unit)
{
if (unit->unit_type == sc2::UNIT_TYPEID::PROTOSS_PYLON)
{
if (Distance2D(RushLocation, unit->pos) < 20)
{
std::cout << "Rush Pylon Built";
}
}
}
void CryptBot::OnUnitCreated(const Unit *unit)
{
if (unit->alliance != sc2::Unit::Alliance::Self)
{
return;
}
const ObservationInterface* observation = Observation();
switch (unit->unit_type.ToType()) {
case UNIT_TYPEID::PROTOSS_NEXUS: {
Expanding = false;
ExpandingFrame = 0;
break;
}
case UNIT_TYPEID::PROTOSS_PYLON:
{
if (Distance2D(unit->pos, *StartPosition) > Distance2D(unit->pos, RushLocation))
{
CurrentOffenseno = 0;
}
}
break;
case UNIT_TYPEID::PROTOSS_PHOTONCANNON:
{
if (Distance2D(unit->pos, *StartPosition) > Distance2D(unit->pos, RushLocation))
{
CurrentOffenseno++;
}
else
{
CurrentDefenseCannons++;
}
}
break;
case UNIT_TYPEID::PROTOSS_ADEPT:
case UNIT_TYPEID::PROTOSS_ARCHON:
case UNIT_TYPEID::PROTOSS_CARRIER:
case UNIT_TYPEID::PROTOSS_COLOSSUS:
case UNIT_TYPEID::PROTOSS_DARKTEMPLAR:
case UNIT_TYPEID::PROTOSS_DISRUPTOR:
case UNIT_TYPEID::PROTOSS_HIGHTEMPLAR:
case UNIT_TYPEID::PROTOSS_IMMORTAL:
case UNIT_TYPEID::PROTOSS_INTERCEPTOR:
case UNIT_TYPEID::PROTOSS_MOTHERSHIP:
case UNIT_TYPEID::PROTOSS_MOTHERSHIPCORE:
case UNIT_TYPEID::PROTOSS_OBSERVER:
case UNIT_TYPEID::PROTOSS_ORACLE:
case UNIT_TYPEID::PROTOSS_PHOENIX:
case UNIT_TYPEID::PROTOSS_SENTRY:
case UNIT_TYPEID::PROTOSS_STALKER:
case UNIT_TYPEID::PROTOSS_TEMPEST:
case UNIT_TYPEID::PROTOSS_VOIDRAY:
case UNIT_TYPEID::PROTOSS_WARPPRISM:
case UNIT_TYPEID::PROTOSS_ZEALOT:
{
for (auto& ThisBG : BattleGroups)
{
if (ThisBG.UnitType == unit->unit_type.ToType() && ThisBG.Members.size() < BATTLEGROUP_SIZE && !ThisBG.Attacking)
{
ThisBG.Members.push_back(unit->tag);
if (ThisBG.Members.size() >= BATTLEGROUP_SIZE)
{
ThisBG.Attacking = true;
}
break;
}
else if (unit->unit_type.ToType() == UNIT_TYPEID::PROTOSS_MOTHERSHIP)
{
ThisBG.Members.push_back(unit->tag);
break;
}
}
BattleGroup BG;
BG.Attacking = false;
BG.engaged_tag = 0;
BG.UnitType = unit->unit_type.ToType();
BG.Members.push_back(unit->tag);
BattleGroups.push_back(BG);
break;
Units enemy_units = observation->GetUnits(Unit::Alliance::Enemy, IsAttackable());
if (enemy_units.empty())
{
ScoutWithUnit(*unit, Observation());
}
}
}
if (observation->GetFoodUsed() > (GetCurrentMaxSupply() - 5) && observation->GetGameLoop() > 15)
{
bool ShouldBuildPylon = true;
const Units NewUnits = Observation()->GetUnits(sc2::Unit::Alliance::Self, IsUnit(UNIT_TYPEID::PROTOSS_PYLON));
for (const auto &u : NewUnits)
{
if (u->build_progress < 1.0f)
{
// Pylon currently being built, no need to build another one
ShouldBuildPylon = false;
break;
}
}
if (ShouldBuildPylon)
{
TryBuildStructure(ABILITY_ID::BUILD_PYLON);
}
}
}
void CryptBot::ManageBattleGroups(const ObservationInterface* observation)
{
Units EnemyBuildings = observation->GetUnits(Unit::Alliance::Enemy, IsBuilding());
Units EnemyArmy = observation->GetUnits(Unit::Alliance::Enemy, IsArmy());
Units EnemyGroundArmy = observation->GetUnits(Unit::Alliance::Enemy, IsGroundArmy());
const Point2D nullpos = Point2D(0, 0);
for (auto &ThisBG : BattleGroups)
{
if (ThisBG.Members.empty())
{
continue;
}
if (!ThisBG.Attacking)
{
// Still building;
continue;
}
if (ThisBG.engaged_tag != 0)
{
const Unit *EngagedUnit = observation->GetUnit(ThisBG.engaged_tag);
if (EngagedUnit != nullptr)
{
// Finish killing this unit
continue;
}
}
const Unit *Primary = observation->GetUnit(ThisBG.Members.back());
if (Primary != nullptr)
{
int64_t AttackableUnit = 0;
if (Primary->unit_type.ToType() == UNIT_TYPEID::PROTOSS_DARKTEMPLAR)
{
AttackableUnit = FindNearestUnit(Primary->pos, EnemyArmy, ATTACK_TYPE::FLYING);
}
else
{
AttackableUnit = FindNearestUnit(Primary->pos, EnemyGroundArmy, ATTACK_TYPE::GROUND);
}
if (AttackableUnit == 0)
{
AttackableUnit = FindNearestUnit(Primary->pos, EnemyBuildings);
}
for (int64_t VoidRayTag : ThisBG.Members)
{
const Unit *VRUnit = observation->GetUnit(VoidRayTag);
if (VRUnit != nullptr)
{
if (AttackableUnit != 0)
{
/*
if (VRUnit->weapon_cooldown <= 0.0f)
{
Actions()->UnitCommand(VRUnit, ABILITY_ID::EFFECT_VOIDRAYPRISMATICALIGNMENT);
}
*/
Actions()->UnitCommand(VRUnit, ABILITY_ID::ATTACK, observation->GetUnit(AttackableUnit));
}
else
{
// Enter search pattern
if (Distance2D(VRUnit->pos, ThisBG.ScoutingTarget) < 5)
{
ThisBG.ScoutingTarget.x = 0.0f;
ThisBG.ScoutingTarget.y = 0.0f;
}
if ((ThisBG.ScoutingTarget.x == 0 && ThisBG.ScoutingTarget.y == 0) )
{
Point2D target_pos;
if (TryFindRandomPathableLocation(VRUnit->tag, target_pos)) {
Actions()->UnitCommand(VRUnit, ABILITY_ID::SMART, target_pos);
ThisBG.ScoutingTarget = target_pos;
return;
}
}
}
}
}
}
}
}
int64_t CryptBot::FindNearestUnit(const Point2D& start, Units UnitSet, ATTACK_TYPE AttackType) {
float distance = std::numeric_limits<float>::max();
int64_t ReturnedUnit = 0;
bool FoundUnit = false, FoundUnitType = false;
if (AttackType == ATTACK_TYPE::BOTH)
{
FoundUnitType = true;
}
for (const auto& u : UnitSet) {
float d = DistanceSquared2D(u->pos, start);
if (d < distance || FoundUnitType == false) {
FoundUnit = true;
if (AttackType == ATTACK_TYPE::BOTH)
{
distance = d;
ReturnedUnit = u->tag;
}
else if (FoundUnitType && d < distance)
{
ATTACK_TYPE UnitCanAttack = Strategy::CanAttack(u->unit_type.ToType());
if (UnitCanAttack == ATTACK_TYPE::BOTH || UnitCanAttack == AttackType)
{
distance = d;
ReturnedUnit = u->tag;
}
}
else if (FoundUnitType == false && d < distance)
{
distance = d;
ReturnedUnit = u->tag;
ATTACK_TYPE UnitCanAttack = Strategy::CanAttack(u->unit_type.ToType());
if (UnitCanAttack == ATTACK_TYPE::BOTH || UnitCanAttack == AttackType)
{
FoundUnitType = true;
}
}
}
}
if (!FoundUnit)
{
return 0;
}
return ReturnedUnit;
}
void CryptBot::OnUnitIdle(const Unit *unit) {
if (unit->tag == RushUnitTag && RushPylon == true)
{
ScoutingUnitTag = RushUnitTag;
TryBuildStructure(ABILITY_ID::BUILD_PYLON, UNIT_TYPEID::PROTOSS_PROBE, GetNearestBuildableLocationFor(ABILITY_ID::BUILD_PYLON, RushLocation, QueryType::None, PylonSearchParams), true);
RushPylon = false;
}
switch (unit->unit_type.ToType()) {
case UNIT_TYPEID::PROTOSS_PROBE: {
if (unit->tag != ScoutingUnitTag)
{
uint64_t valid_mineral_patch;
FindNearestMineralPatch(unit->pos, valid_mineral_patch);
Actions()->UnitCommand(unit, ABILITY_ID::HARVEST_GATHER, Observation()->GetUnit(valid_mineral_patch));
return;
}
}
}
}
bool CryptBot::BuildAvailableGeaser(AbilityID build_ability, UnitTypeID worker_type, Point2D base_location)
{
const ObservationInterface* observation = Observation();
Units geysers = observation->GetUnits(Unit::Alliance::Neutral, IsVespeneGeyser());
//only search within this radius
float minimum_distance = 15.0f;
Tag closestGeyster = 0;
for (const auto& geyser : geysers) {
float current_distance = Distance2D(base_location, geyser->pos);
if (current_distance < minimum_distance) {
if (Query()->Placement(build_ability, geyser->pos)) {
minimum_distance = current_distance;
closestGeyster = geyser->tag;
}
}
}
// In the case where there are no more available geysers nearby
if (closestGeyster == 0) {
return false;
}
return TryBuildStructure(build_ability, worker_type, closestGeyster);
}
bool CryptBot::FindNearestGeaser(const Point2D &start, uint64_t& target, float MaxDistance)
{
const ObservationInterface* observation = Observation();
float distance = MaxDistance;
Units geysers = observation->GetUnits(Unit::Alliance::Self, IsUnit(UNIT_TYPEID::PROTOSS_ASSIMILATOR));
for (const auto& u : geysers) {
if(u->assigned_harvesters < u->ideal_harvesters)
{
float d = DistanceSquared2D(u->pos, start);
if (d < distance ) {
distance = d;
target = u->tag;
}
}
}
if (distance == MaxDistance) {
return false;
}
return true;
}
size_t CryptBot::CountUnitType(const ObservationInterface* observation, UnitTypeID unit_type) {
return observation->GetUnits(Unit::Alliance::Self, IsUnit(unit_type)).size();
}
void CryptBot::EconStrat(const ObservationInterface *observation)
{
Units bases = observation->GetUnits(Unit::Alliance::Self, IsTownHall());
Units NearbyGeasers = observation->GetUnits(Unit::Alliance::Self, IsUnit(UNIT_TYPEID::PROTOSS_ASSIMILATOR));
Units Probes = observation->GetUnits(Unit::Alliance::Self, IsUnit(UNIT_TYPEID::PROTOSS_PROBE));
bool ShouldExpandBase = true;
int workerMin = 0;
if (bases.size() > 1)
{
workerMin = 3;
}
for (const auto& base : bases)
{
if (!base->orders.empty())
{
ShouldExpandBase = false;
// Already making a probe
continue;
}
int32_t CurrentGeysers = 0;
for (const auto& geyser : NearbyGeasers)
{
if (DistanceSquared2D(base->pos, geyser->pos) < MAX_GEASER_DISTANCE)
{
CurrentGeysers ++;
if (geyser->assigned_harvesters < geyser->ideal_harvesters)
{
for (const auto& probe : Probes)
{
if (probe->tag != ScoutingUnitTag)
{
if (probe->orders.empty())
{
Actions()->UnitCommand(probe, ABILITY_ID::HARVEST_GATHER, geyser);
break;
}
UnitOrder CurrentOrder = probe->orders.back();
if (CurrentOrder.ability_id == ABILITY_ID::HARVEST_GATHER)
{
if (CurrentOrder.target_unit_tag == 0)
{
Actions()->UnitCommand(probe, ABILITY_ID::HARVEST_GATHER, geyser);
break;
}
const Unit *TargetUnit = observation->GetUnit(CurrentOrder.target_unit_tag);
if (TargetUnit == nullptr || TargetUnit->unit_type == UNIT_TYPEID::NEUTRAL_MINERALFIELD)
{
Actions()->UnitCommand(probe, ABILITY_ID::HARVEST_GATHER, geyser);
break;
}
}
}
}
}
}
}
if (CurrentGeysers < 2 && observation->GetGameLoop() > 3000)
{
if ((base->assigned_harvesters + 6 + workerMin) >= base->ideal_harvesters && (base->build_progress == 1.0f)) {
BuildAvailableGeaser(ABILITY_ID::BUILD_ASSIMILATOR, UNIT_TYPEID::PROTOSS_PROBE, base->pos);
}
ShouldExpandBase = false;
}
if ((base->assigned_harvesters) < base->ideal_harvesters)
{
Actions()->UnitCommand(base, ABILITY_ID::TRAIN_PROBE);
if ((base->assigned_harvesters + workerMin) < base->ideal_harvesters)
{
ShouldExpandBase = false;
}
}
}
if (ExpandingFrame > 0 && observation->GetGameLoop() > (ExpandingFrame + 150))
{
Expanding = false;
ExpandingFrame = 0;
}
if (ShouldExpandBase && !Expanding && observation->GetGameLoop() > 3000)
{
Expanding = TryExpand(observation);
ExpandingFrame = observation->GetGameLoop();
}
}
bool CryptBot::TryExpand(const ObservationInterface* observation)
{
float minimum_distance = std::numeric_limits<float>::max();
Point3D closest_expansion;
for (const auto& expansion : expansions_) {
float current_distance = Distance3D(*StartPosition, expansion);
if (current_distance < .01f) {
continue;
}
if (current_distance < minimum_distance) {
if (Query()->Placement(ABILITY_ID::BUILD_NEXUS, expansion)) {
closest_expansion = expansion;
minimum_distance = current_distance;
}
}
}
//only update staging location up till 3 bases.
if (TryBuildStructure(ABILITY_ID::BUILD_NEXUS, UNIT_TYPEID::PROTOSS_PROBE, closest_expansion))
{
return true;
}
return false;
}
void CryptBot::ExecuteStrategy(const ObservationInterface *observation)
{
if (CurrentStrategy == nullptr)
{
return;
}
size_t gateway_count = CountUnitType(observation, UNIT_TYPEID::PROTOSS_GATEWAY) + CountUnitType(observation, UNIT_TYPEID::PROTOSS_WARPGATE);
if (gateway_count < 3)
{
if (observation->GetMinerals() > 150) {
TryBuildStructureNearPylon(ABILITY_ID::BUILD_GATEWAY, UNIT_TYPEID::PROTOSS_PROBE);
}
return;
}
}
void CryptBot::CheckScouting(const ObservationInterface *observation)
{
if (Scouting)
{
const Unit *ScoutingUnit = observation->GetUnit(ScoutingUnitTag);
if (ScoutingUnit == nullptr)// || ScoutingUnit->orders.empty())
{
Scouting = false;
}
}
if (!Scouting)
{
if (observation->GetUnits(sc2::Unit::Alliance::Enemy, IsTownHall()).empty())
{
if (ScoutingUnitTag != 0)
{
const Unit *NewScoutingUnit = observation->GetUnit(ScoutingUnitTag);
if (NewScoutingUnit != nullptr)
{
// ScoutWithUnit(*NewScoutingUnit, observation);
Scouting = true;
}
}
ScoutingUnitTag = GetAvailableWorker();
const Unit *NewScoutingUnit = observation->GetUnit(ScoutingUnitTag);
if (NewScoutingUnit != nullptr)
{
// ScoutWithUnit(*NewScoutingUnit, observation);
Scouting = true;
}
}
}
}
void CryptBot::OnStep() {
const ObservationInterface* observation = Observation();
if (!observation)
{
return;
}
//Throttle some behavior that can wait to avoid duplicate orders.
int frames_to_skip = 4;
if (observation->GetFoodUsed() >= observation->GetFoodCap()) {
frames_to_skip = 6;
}
int32_t CurrentGameLoop = observation->GetGameLoop();
if (observation->GetGameLoop() % frames_to_skip != 0) {
return;
}
if(FirstPylon && observation->GetMinerals() > 100)
{
TryBuildBasePylon();
FirstPylon = false;
}
else if (RushPylon && RushUnitTag == 0 && observation->GetMinerals() > 100)
{
RushUnitTag = GetAvailableWorker();
const Unit *RushUnit = observation->GetUnit(RushUnitTag);
Actions()->UnitCommand(RushUnit, ABILITY_ID::MOVE, RushLocation);
}
CurrentMaxSupply = GetCurrentMaxSupply();
if (RushLocation == Point2D(0.0f, 0.0f))
{
std::cout << "Null rush location";
}
CheckScouting(observation);
EconStrat(observation);
if (CurrentGameLoop < 7000 && !RushPylonDestroyed)
{
TryBuildCannonRush(observation);
}
else
{
TryBuildPylon(observation);
if (OpponentRace == sc2::Race::Terran && UseAltStrategy)
{
TryBuildAltStrategy(observation);
if (observation->GetFoodWorkers() > 18)
{
TryBuildAltArmy(observation);
ManageBattleGroups(observation);
}
}
else
{
TryBuildBuildings(observation);
if (observation->GetFoodWorkers() > 18)
{
TryBuildArmy(observation);
ManageBattleGroups(observation);
}
observation->GetUnitTypeData();
}
}
}
void CryptBot::TryBuildArmy(const ObservationInterface* observation)
{
if (observation->GetMinerals() < 250 || observation->GetVespene() < 150)
{
return;
}
Units Stargates = observation->GetUnits(Unit::Alliance::Self, IsUnit(UNIT_TYPEID::PROTOSS_STARGATE));
Units fleetbecons = observation->GetUnits(Unit::Alliance::Self, IsUnit(UNIT_TYPEID::PROTOSS_FLEETBEACON));
if (fleetbecons.size() > 0)
{
if (observation->GetMinerals() > 350 && observation->GetVespene() > 250)
{
for (const auto& Stargate : Stargates)
{
if (Stargate->orders.empty())
{
Actions()->UnitCommand(Stargate, ABILITY_ID::TRAIN_CARRIER);
}
}
}
}
else if (observation->GetMinerals() > 250 && observation->GetVespene() > 150)
{
for (const auto& Stargate : Stargates)
{
if (Stargate->orders.empty())
{
Actions()->UnitCommand(Stargate, ABILITY_ID::TRAIN_VOIDRAY);
}
}
}
}
void CryptBot::TryBuildAltArmy(const ObservationInterface* observation)
{
if (observation->GetMinerals() < 250 || observation->GetVespene() < 150)
{
return;
}
size_t dark_count = CountUnitType(observation, UNIT_TYPEID::PROTOSS_DARKSHRINE);
Units Gateways = observation->GetUnits(Unit::Alliance::Self, IsUnit(UNIT_TYPEID::PROTOSS_GATEWAY));
if (Gateways.size() > 0 && dark_count > 0)
{
if (observation->GetMinerals() > 350 && observation->GetVespene() > 250)
{
for (const auto& Gateway : Gateways)
{
if (Gateway->orders.empty())
{
Actions()->UnitCommand(Gateway, ABILITY_ID::TRAIN_DARKTEMPLAR);
}
}
}
}
}
void CryptBot::TryBuildCannonRush(const ObservationInterface* observation)
{
size_t forge_count = CountUnitType(observation, UNIT_TYPEID::PROTOSS_FORGE);
if (forge_count < 1)
{
if (observation->GetMinerals() > 150) {
TryBuildStructureNearPylon(ABILITY_ID::BUILD_FORGE, UNIT_TYPEID::PROTOSS_PROBE);
}
return;
}
// Defensive cannon first
if (observation->GetMinerals() > 150) {
Units Cannons = observation->GetUnits(Unit::Alliance::Self, IsUnit(UNIT_TYPEID::PROTOSS_PHOTONCANNON));
if (CurrentDefenseCannons < MaxDefenseCannons && Cannons.size() > 2)
{
TryBuildStructureNearPylon(ABILITY_ID::BUILD_PHOTONCANNON, UNIT_TYPEID::PROTOSS_PROBE);
}
else
{
if (CurrentOffenseno >= CANNONS_PER_PYLON)
{
Point2D BuildLocation = GetNearestBuildableLocationFor(ABILITY_ID::BUILD_PYLON, RushLocation, QueryType::None, PylonSearchParams);
TryBuildStructure(ABILITY_ID::BUILD_PYLON, UNIT_TYPEID::PROTOSS_PROBE, BuildLocation, true);
}
else
{
TryBuildStructureNearPylon(ABILITY_ID::BUILD_PHOTONCANNON, UNIT_TYPEID::PROTOSS_PROBE, RushLocation, true);
}
}
}
}
void CryptBot::TryBuildAltStrategy(const ObservationInterface* observation)
{
if (CurrentDefenseCannons < MaxDefenseCannons && observation->GetMinerals() > 150)
{
TryBuildStructureNearPylon(ABILITY_ID::BUILD_PHOTONCANNON, UNIT_TYPEID::PROTOSS_PROBE);
}
size_t gateway_count = CountUnitType(observation, UNIT_TYPEID::PROTOSS_GATEWAY) + CountUnitType(observation, UNIT_TYPEID::PROTOSS_WARPGATE);
if (gateway_count < 1)
{
if (observation->GetMinerals() > 150) {
TryBuildStructureNearPylon(ABILITY_ID::BUILD_GATEWAY, UNIT_TYPEID::PROTOSS_PROBE);
}
return;
}
size_t cybernetics_count = CountUnitType(observation, UNIT_TYPEID::PROTOSS_CYBERNETICSCORE);
if (cybernetics_count < 1)
{
if (observation->GetMinerals() > 150) {
TryBuildStructureNearPylon(ABILITY_ID::BUILD_CYBERNETICSCORE, UNIT_TYPEID::PROTOSS_PROBE);
}
return;
}
size_t twilight_count = CountUnitType(observation, UNIT_TYPEID::PROTOSS_TWILIGHTCOUNCIL);
if (twilight_count < 1)
{
if (observation->GetMinerals() > 150 && observation->GetVespene() > 100)
{
TryBuildStructureNearPylon(ABILITY_ID::BUILD_TWILIGHTCOUNCIL, UNIT_TYPEID::PROTOSS_PROBE);
}
return;
}
size_t dark_count = CountUnitType(observation, UNIT_TYPEID::PROTOSS_DARKSHRINE);
if (dark_count < 1)
{
if (observation->GetMinerals() > 150 && observation->GetVespene() > 100)
{
TryBuildStructureNearPylon(ABILITY_ID::BUILD_DARKSHRINE, UNIT_TYPEID::PROTOSS_PROBE);
}
return;
}
if (gateway_count < 4)
{
if (observation->GetMinerals() > 150) {
TryBuildStructureNearPylon(ABILITY_ID::BUILD_GATEWAY, UNIT_TYPEID::PROTOSS_PROBE);
}
return;
}
}
void CryptBot::TryBuildBuildings(const ObservationInterface* observation)
{
if (CurrentDefenseCannons < MaxDefenseCannons && observation->GetMinerals() > 150)
{
TryBuildStructureNearPylon(ABILITY_ID::BUILD_PHOTONCANNON, UNIT_TYPEID::PROTOSS_PROBE);
}
size_t gateway_count = CountUnitType(observation, UNIT_TYPEID::PROTOSS_GATEWAY) + CountUnitType(observation, UNIT_TYPEID::PROTOSS_WARPGATE);
if (gateway_count < 1)
{
if (observation->GetMinerals() > 150) {
TryBuildStructureNearPylon(ABILITY_ID::BUILD_GATEWAY, UNIT_TYPEID::PROTOSS_PROBE);
}
return;
}
size_t cybernetics_count = CountUnitType(observation, UNIT_TYPEID::PROTOSS_CYBERNETICSCORE);
if (cybernetics_count < 1)
{
if (observation->GetMinerals() > 150) {
TryBuildStructureNearPylon(ABILITY_ID::BUILD_CYBERNETICSCORE, UNIT_TYPEID::PROTOSS_PROBE);
}
return;
}/*
if (observation->GetMinerals() > 100)
{
TryBuildStructureNearPylon(ABILITY_ID::BUILD_SHIELDBATTERY, UNIT_TYPEID::PROTOSS_PROBE);
// return;
}*/
size_t stargate_count = CountUnitType(observation, UNIT_TYPEID::PROTOSS_STARGATE);
if (stargate_count < 3 && observation->GetMinerals() > 150 && observation->GetVespene() > 150) {
TryBuildStructureNearPylon(ABILITY_ID::BUILD_STARGATE, UNIT_TYPEID::PROTOSS_PROBE);
return;
}
size_t beacon_count = CountUnitType(observation, UNIT_TYPEID::PROTOSS_FLEETBEACON);
if (beacon_count < 1 && observation->GetMinerals() > 300 && observation->GetVespene() > 200)
{
TryBuildStructureNearPylon(ABILITY_ID::BUILD_FLEETBEACON, UNIT_TYPEID::PROTOSS_PROBE);
return;
}
else if (beacon_count > 0)
{
Units Motherships = observation->GetUnits(Unit::Alliance::Self, IsUnit(UNIT_TYPEID::PROTOSS_MOTHERSHIP));
if (Motherships.size() < 1 && observation->GetMinerals() > 400 && observation->GetVespene() > 300)
{
Units Nexuses = observation->GetUnits(Unit::Alliance::Self, IsUnit(UNIT_TYPEID::PROTOSS_NEXUS));
if (observation->GetMinerals() > 250 && observation->GetVespene() > 150)
{
for (const auto& Nexus : Nexuses)
{
const Unit *RandomProbe = GetAvailableWorkerUnit();
sc2::QueryInterface* query = Query();
sc2::AvailableAbilities AvailableUnits = query->GetAbilitiesForUnit(RandomProbe, true);
Actions()->UnitCommand(Nexus, ABILITY_ID::TRAIN_MOTHERSHIP);
}
}
}
}
Units fleetbecons = observation->GetUnits(Unit::Alliance::Self, IsUnit(UNIT_TYPEID::PROTOSS_FLEETBEACON));
if (!HasTrainedCarrierLaunch && observation->GetMinerals() > 150 && observation->GetVespene() > 150 && fleetbecons.size() > 0)
{
if (fleetbecons.back()->build_progress >= 1.0f)
{
Actions()->UnitCommand(fleetbecons.back(), ABILITY_ID::RESEARCH_INTERCEPTORGRAVITONCATAPULT);
HasTrainedCarrierLaunch = true;
}
}
Units batterys = observation->GetUnits(Unit::Alliance::Self, IsUnit(UNIT_TYPEID::PROTOSS_SHIELDBATTERY));
if (batterys.size() > 0 && batterys.front()->build_progress >= 1.0f)
{
sc2::QueryInterface* query = Query();
sc2::AvailableAbilities AvailableUnits = query->GetAbilitiesForUnit(batterys.front(), true);
return;
}
}
bool CryptBot::TryBuildStructureNearPylon(AbilityID ability_type_for_structure, UnitTypeID unit_type, Point2D NearPoint, bool UseScout)
{
const ObservationInterface* observation = Observation();
//Need to check to make sure its a pylon instead of a warp prism
std::vector<PowerSource> power_sources = observation->GetPowerSources();
if (power_sources.empty()) {
return false;
}
float distance = std::numeric_limits<float>::max();
PowerSource Closest(Point2D(0, 0),0,0);
for (const PowerSource &power : power_sources)
{
float d = Distance2D(power.position, NearPoint);
if (d < distance)
{
distance = d;
Closest = power;
}
}
Point2D BuildLocation = GetNearestBuildableLocationFor(ability_type_for_structure, NearPoint, QueryType::None, PylonSearchParams);
if (TryBuildStructure(ability_type_for_structure, unit_type, BuildLocation, UseScout))
{
return true;
}
return false;
}
void CryptBot::ExcludeRushPylons(std::vector<PowerSource> &PowerSources)
{
std::vector<PowerSource> NewPowerSources;
for (const PowerSource &RushPylon : PowerSources)
{
if (Distance2D(RushPylon.position, *StartPosition) < Distance2D(RushPylon.position, RushLocation))
{
NewPowerSources.push_back(RushPylon);
// PowerSources.erase(std::remove(PowerSources.begin(), PowerSources.end(), RushPylon), PowerSources.end());
}
}
PowerSources.clear();
PowerSources = NewPowerSources;
}
bool CryptBot::TryBuildStructureNearPylon(AbilityID ability_type_for_structure, UnitTypeID unit_type) {
const ObservationInterface* observation = Observation();
//Need to check to make sure its a pylon instead of a warp prism
std::vector<PowerSource> power_sources = observation->GetPowerSources();
if (power_sources.empty()) {
return false;
}
ExcludeRushPylons(power_sources);
srand(time(0));
const PowerSource& random_power_source = GetRandomEntry(power_sources);
if (observation->GetUnit(random_power_source.tag) != nullptr) {
if (observation->GetUnit(random_power_source.tag)->unit_type == UNIT_TYPEID::PROTOSS_WARPPRISM) {
return false;
}
}
else {
return false;
}
float radius = random_power_source.radius;
srand(time(0));
float rx = GetRandomScalar();
float ry = GetRandomScalar();
Point2D build_location = Point2D(random_power_source.position.x + rx * radius, random_power_source.position.y + ry * radius);
Point2D BuildLocation = GetNearestBuildableLocationFor(ability_type_for_structure, build_location, QueryType::None, PylonSearchParams);
return TryBuildStructure(ability_type_for_structure, unit_type, build_location);
}
bool CryptBot::TryBuildStructure(ABILITY_ID ability_type_for_structure, UNIT_TYPEID unit_type, Point2D TargetLocation, bool UseScout) {
const ObservationInterface* observation = Observation();
// If a unit already is building a supply structure of this type, do nothing.
// Also get an scv to build the structure.
const Unit *unit_to_build = nullptr;
Units units = observation->GetUnits(Unit::Alliance::Self, IsUnit(unit_type));
for (const auto& unit : units) {
if (unit->tag == ScoutingUnitTag)
{
if (UseScout)
{
for (const auto& order : unit->orders) {
if (order.ability_id == ability_type_for_structure) {
return false;
}
}
unit_to_build = unit;
break;
}
continue;
}
for (const auto& order : unit->orders) {
if (order.ability_id == ability_type_for_structure) {
return false;
}
}
unit_to_build = unit;
}
if (unit_to_build != nullptr)
{
Actions()->UnitCommand(unit_to_build,
ability_type_for_structure,
TargetLocation);
}
return true;
}
bool CryptBot::TryBuildBasePylon()
{
if (StartPosition == nullptr)
{
return false;
}
QueryType QType;
if (StartPosition->x > 100)
{
if (StartPosition->y > 100)
{
QType = MaxXMaxY;
}
else
{
QType = MaxXMinY;
}
}
else
{
if (StartPosition->y > 100)
{
QType = MinXMaxY;
}
else
{
QType = MinXMinY;
}
}
DefensePylon = GetNearestBuildableLocationFor(ABILITY_ID::BUILD_PYLON, *StartPosition, QType, PylonSearchParams);
TryBuildStructure(ABILITY_ID::BUILD_PYLON, UNIT_TYPEID::PROTOSS_PROBE, DefensePylon);
return true;
}
bool CryptBot::TryBuildStructure(ABILITY_ID ability_type_for_structure, UNIT_TYPEID unit_type) {
const ObservationInterface* observation = Observation();
// If a unit already is building a supply structure of this type, do nothing.
// Also get an scv to build the structure.
const Unit *unit_to_build = nullptr;
Units units = observation->GetUnits(Unit::Alliance::Self, IsUnit(unit_type));
for (const auto& unit : units) {
if (unit->tag == ScoutingUnitTag)
{
continue;
}
for (const auto& order : unit->orders) {
if (order.ability_id == ability_type_for_structure) {
return false;
}
}
unit_to_build = unit;
}
if (unit_to_build == nullptr)
{
return false;
}
float rx = 0.0f;// GetRandomScalar();
float ry = 0.0f; //GetRandomScalar();
Point2D build_location = Point2D(unit_to_build->pos.x + rx * 15.0f, unit_to_build->pos.y + ry * 15.0f);
Point2D BuildLocation = GetNearestBuildableLocationFor(ability_type_for_structure, build_location, QueryType::None, PylonSearchParams);
if (unit_to_build != nullptr)
{
Actions()->UnitCommand(unit_to_build,
ability_type_for_structure, BuildLocation);
}
return true;
}
bool CryptBot::TryBuildPylon(const ObservationInterface* observation) {
// If we are not supply capped, don't build a supply depot.
if (observation->GetFoodUsed() <= observation->GetFoodCap() - 2)
return false;
const Units NewUnits = Observation()->GetUnits(sc2::Unit::Alliance::Self, IsUnit(UNIT_TYPEID::PROTOSS_PYLON));
for (const auto &u : NewUnits)
{
if (u->build_progress < 1.0f)
{
// Pylon currently being built, no need to build another one
return false;
break;
}
}
// Try and build a depot. Find a random SCV and give it the order.
return TryBuildStructure(ABILITY_ID::BUILD_PYLON);
}
bool CryptBot::FindNearestMineralPatch(const Point2D& start, uint64_t& target) {
Units units = Observation()->GetUnits(Unit::Alliance::Neutral);
float distance = std::numeric_limits<float>::max();
for (const auto& u : units) {
if (u->unit_type == UNIT_TYPEID::NEUTRAL_MINERALFIELD) {
float d = DistanceSquared2D(u->pos, start);
if (d < distance) {
distance = d;
target = u->tag;
}
}
}
if (distance == std::numeric_limits<float>::max()) {
return false;
}
return true;
}
void CryptBot::ScoutWithUnit(Unit unit, const ObservationInterface* observation) {
Units enemy_units = observation->GetUnits(Unit::Alliance::Enemy, IsAttackable());
Point2D target_pos;
if (FindEnemyPosition(unit.tag, target_pos)) {
if (Distance2D(unit.pos, target_pos) < 20 && enemy_units.empty()) {
if (TryFindRandomPathableLocation(unit.tag, target_pos)) {
Actions()->UnitCommand(&unit, ABILITY_ID::SMART, target_pos);
return;
}
}
else if (!enemy_units.empty())
{
Actions()->UnitCommand(&unit, ABILITY_ID::ATTACK, enemy_units.front());
return;
}
Actions()->UnitCommand(&unit, ABILITY_ID::SMART, target_pos);
}
else {
if (TryFindRandomPathableLocation(unit.tag, target_pos)) {
Actions()->UnitCommand(&unit, ABILITY_ID::SMART, target_pos);
}
}
}
bool CryptBot::TryFindRandomPathableLocation(Tag tag, Point2D& target_pos) {
// First, find a random point inside the playable area of the map.
float playable_w = game_info_->playable_max.x - game_info_->playable_min.x;
float playable_h = game_info_->playable_max.y - game_info_->playable_min.y;
// The case where game_info_ does not provide a valid answer
if (playable_w == 0 || playable_h == 0) {
playable_w = 236;
playable_h = 228;
}
target_pos.x = playable_w * GetRandomFraction() + game_info_->playable_min.x;
target_pos.y = playable_h * GetRandomFraction() + game_info_->playable_min.y;
// Now send a pathing query from the unit to that point. Can also query from point to point,
// but using a unit tag wherever possible will be more accurate.
// Note: This query must communicate with the game to get a result which affects performance.
// Ideally batch up the queries (using PathingDistanceBatched) and do many at once.
float distance = Query()->PathingDistance(Observation()->GetUnit(tag), target_pos);
return distance > 0.1f;
}
// Tries to find a random location that can be pathed to on the map.
// Returns 'true' if a new, random location has been found that is pathable by the unit.
bool CryptBot::FindEnemyPosition(Tag tag, Point2D& target_pos) {
if (game_info_->enemy_start_locations.empty()) {
return false;
}
int32_t NextPos = rand() % game_info_->enemy_start_locations.size();
target_pos = game_info_->enemy_start_locations[NextPos];
return true;
}
const Unit *CryptBot::GetAvailableWorkerUnit()
{
const ObservationInterface* observation = Observation();
sc2::Units WorkerUnits = observation->GetUnits(Unit::Alliance::Self, IsUnit(UNIT_TYPEID::PROTOSS_PROBE));
if (WorkerUnits.empty())
{
return 0;
}
return WorkerUnits.back();
//TODO: Find a better way to get a worker unit
}
Tag CryptBot::GetAvailableWorker()
{
const ObservationInterface* observation = Observation();
sc2::Units WorkerUnits = observation->GetUnits(Unit::Alliance::Self, IsUnit(UNIT_TYPEID::PROTOSS_PROBE));
if (WorkerUnits.empty())
{
return 0;
}
return WorkerUnits.back()->tag;
//TODO: Find a better way to get a worker unit
}
//Try to build a structure based on tag, Used mostly for Vespene, since the pathing check will fail even though the geyser is "Pathable"
bool CryptBot::TryBuildStructure(AbilityID ability_type_for_structure, UnitTypeID unit_type, Tag location_tag) {
const ObservationInterface* observation = Observation();
Units workers = observation->GetUnits(Unit::Alliance::Self, IsUnit(unit_type));
const Unit* target = observation->GetUnit(location_tag);
if (workers.empty()) {
return false;
}
// Check to see if there is already a worker heading out to build it
for (const auto& worker : workers) {
for (const auto& order : worker->orders) {
if (order.ability_id == ability_type_for_structure) {
return false;
}
}
}
// If no worker is already building one, get a random worker to build one
srand(time(0));
const Unit *unit = GetRandomEntry(workers);
while (unit->tag == ScoutingUnitTag)
{
unit = GetRandomEntry(workers);
}
// Check to see if unit can build there
if (Query()->Placement(ability_type_for_structure, target->pos)) {
Actions()->UnitCommand(unit, ability_type_for_structure, target);
return true;
}
return false;
}
void *CreateNewAgent()
{
return (void *)new CryptBot();
}
const char *GetAgentName()
{
return "CryptBot";
}
int GetAgentRace()
{
return (int)sc2::Race::Protoss;
} | 30.991031 | 186 | 0.720192 | [
"vector"
] |
3c0e892c8736d4bdc8f9a0d515bbc32869b32dd6 | 18,362 | cpp | C++ | OpenGLProject/main.cpp | VertigoStr/OpenGL | cea3692a5d2a68bab1619c134e154f85d28dab5c | [
"WTFPL"
] | null | null | null | OpenGLProject/main.cpp | VertigoStr/OpenGL | cea3692a5d2a68bab1619c134e154f85d28dab5c | [
"WTFPL"
] | null | null | null | OpenGLProject/main.cpp | VertigoStr/OpenGL | cea3692a5d2a68bab1619c134e154f85d28dab5c | [
"WTFPL"
] | null | null | null | #include <glew.h>
#include <glfw3.h>
#include <fwd.hpp>
#include <glm.hpp>
#include <gtc/matrix_transform.hpp>
#include <gtc/type_ptr.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <sstream>
#include <iostream>
#include <SOIL.h>
#include "Utils.h"
#include "Camera.h"
#include "terrain.h"
#include "SkyBox.h"
#include "Model.h"
#include "Water.h"
#include "Text.h"
#include <irrKlang.h>
using namespace glm;
using namespace std;
using namespace irrklang;
#pragma comment(lib, "irrKlang.lib")
GLFWwindow* window;
const int SCREEN_WIDTH = 800, SCREEN_HEIGHT = 600;
Camera camera;
bool drawObjects = true;
bool drawWater = true;
bool drawTerrain = true;
bool drawSkyBox = true;
bool waterGeometry = false;
bool sound = true;
bool showMenu = true;
float waterSpeed = 0.01f;
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods);
int main(int argc, char** argv)
{
if (!glfwInit())
{
cout << "Failed to initialize GLFW" << endl;
return -1;
}
glfwWindowHint(GLFW_SAMPLES, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
window = glfwCreateWindow( SCREEN_WIDTH, SCREEN_HEIGHT, "Island", NULL, NULL);
if( window == NULL ){
cout << "Failed to open GLFW window.\n" << endl;
glfwTerminate();
return -1;
}
glfwSetWindowPos(window, 270, 90);
glfwMakeContextCurrent(window);
if (glewInit() != GLEW_OK) {
cout << "Failed to initialize GLEW\n" << endl;
return -1;
}
glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
glfwSetKeyCallback(window, key_callback);
glfwSetCursorPos(window, SCREEN_WIDTH/2, SCREEN_HEIGHT/2);
glClearColor(.2, .3, .3, 1.0);
camera.setCameraPosition(vec3(-64.0, 23.0, -25.0));
Terrain terrain(205.5f);
float worldParameters = 350;
Water water(worldParameters * 2, worldParameters * 2);
SkyBox cubemap(worldParameters);
vec3 waterPosition = vec3(-worldParameters, -13, -worldParameters);
Text text(SCREEN_WIDTH, SCREEN_HEIGHT);
ivec2 boxSize = ivec2(-500, 350);
GLuint program = LoadShaders("Shaders/Objects/vs.vert", "Shaders/Objects/fs.frag");
GLuint mvp = glGetUniformLocation(program, "MVP");
cout << "Load objects:" << endl;
cout << "========================================================================================" << endl;
Model tent1 ("Data/Objects/Tent_1/Tent_1.obj", program);
Model tent ("Data/Objects/Tent/tent.obj", program);
Model barrel ("Data/Objects/Barrel/Barrel.obj", program);
Model cannon ("Data/Objects/Cannon/cannon_mesh.obj", program);
Model house ("Data/Objects/Farmhouse/Farmhouse OBJ.obj", program);
Model ship ("Data/Objects/Ship/ship3.obj", program);
Model tree ("Data/Objects/Tree/needle01.obj", program);
Model lamp ("Data/Objects/Lamp/Petroleum_Lamp.obj", program);
GLuint cubeVao = LoadCube(program);
cout << "========================================================================================" << endl;
mat4 scaleObject[] = {
scale(mat4(1.0f), vec3(70.15f)), //ship
scale(mat4(1.0f), vec3(1.3f)), //cannon
scale(mat4(1.0f), vec3(0.20f)), //house
scale(mat4(1.0f), vec3(0.65f)), //tent1
scale(mat4(1.0f), vec3(3.5f)), //tent
scale(mat4(1.0f), vec3(0.15f)), //barrel
scale(mat4(1.0f), vec3(5.0f)), //tree
scale(mat4(1.0f), vec3(7.0f)), //tree
scale(mat4(1.0f), vec3(1.0f)), //lamp
scale(mat4(1.0f), vec3(1.2f)) //cube
};
vec3 positionObject[] = {
vec3(-62.3381, -11.5, -104.831), //ship
vec3(-35.164, -6.9, 44.328), //cannon
vec3(-35.4699, -6.9, 39.8163),
vec3(-35.7412, -6.35, 35.7012),
vec3(-36.0708, -5.87, 30.8904),
vec3(-36.3983, -5.87, 26.4434),
vec3(-36.7953, -6.16, 22.3239),
vec3(-37.1787, -6.10, 18.3257),
vec3(-8.21483, -0.991692, 42.3217), //house
vec3(-8.46408, -8.4955, -34.2052),
vec3(12.2195, -10.00723, -34.7814),
vec3(-28.41, -4.85463, 3.3742), //tent1
vec3(-29.1099, -6.5071, 58.6885), //tent
vec3(-35.164, -6.9, 43.328), //barrel
vec3(-35.4699, -6.9, 38.8163),
vec3(-35.7412, -6.35, 34.7012),
vec3(-36.0708, -5.87, 29.8904),
vec3(-36.3983, -5.87, 25.4434),
vec3(-36.7953, -6.16, 21.3239),
vec3(-37.1787, -6.10, 17.3257),
vec3(-5.6854, -9.92242, 68.0452), //tree
vec3(39.747, -9.95482, 56.9772),
vec3(72.9695, -9.95482, 59.22),
vec3(69.9275, -12.0354, 27.3984),
vec3(44.2057, -11.082, 14.3814),
vec3(-37.9309, -3.65, 8.99188), //cube
vec3(-24.4361, -8.0, 35.8615),
vec3(-24.4361, -6.8, 35.0105),
vec3(-24.5105, -8.0, 33.9723),
vec3(-10.0298, -8.90054, -39.4486),
vec3(17.2729, -10.07074, -35.8718),
vec3(-7.13707, -0.4, 46.5167),
vec3(-24.4361, -8.0, 35.0105)
};
vec3 pointLightPositions[] = {
vec3(-24.5585, -7.4, 33.7913),
vec3(-24.4391, -7.4, 36.2676),
vec3(-7.06688, 0.2, 46.5081),
vec3(-29.1083, -5.84039, 58.6775),
vec3(-37.9507, -3.1441, 9.01717),
vec3(-10.2281, -8.34472, -39.3235),
vec3(17.4582, -9.44262, -35.7065),
vec3(-35.48, -6.15831, 38.8325)
};
GLuint reflectionFrameBuffer = 0;
glGenFramebuffers(1, &reflectionFrameBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, reflectionFrameBuffer);
GLuint reflectionTexture = LoadFrameBufferTexture(SCREEN_WIDTH, SCREEN_HEIGHT);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, reflectionTexture, 0);
glDrawBuffer(GL_COLOR_ATTACHMENT0);
glReadBuffer(GL_NONE);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
#pragma region cube texture
GLuint diffuseMap, specularMap;
glGenTextures(1, &diffuseMap);
glGenTextures(1, &specularMap);
int width, height;
unsigned char* image;
image = SOIL_load_image("Data/Cube/container2.png", &width, &height, 0, SOIL_LOAD_RGB);
glBindTexture(GL_TEXTURE_2D, diffuseMap);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
glGenerateMipmap(GL_TEXTURE_2D);
SOIL_free_image_data(image);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST_MIPMAP_NEAREST);
image = SOIL_load_image("Data/Cube/container2_specular.png", &width, &height, 0, SOIL_LOAD_RGB);
glBindTexture(GL_TEXTURE_2D, specularMap);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
glGenerateMipmap(GL_TEXTURE_2D);
SOIL_free_image_data(image);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST_MIPMAP_NEAREST);
glBindTexture(GL_TEXTURE_2D, 0);
glUseProgram(program);
glUniform1i(glGetUniformLocation(program, "mdiffuse1"), 0);
glUniform1i(glGetUniformLocation(program, "mspecular1"), 1);
#pragma endregion
ISoundEngine* engine = createIrrKlangDevice();
if (!engine)
{
cout << "Sound library initialization error!" << endl;
return 0;
}
string txt[] =
{
"1 - objects(on/off)",
"2 - terrain(on/off)",
"3 - water(on/off)",
"4 - skybox(on/off)",
"5 - water geometry(on/off)",
"6 - sound(on/off)",
"+/- - change water speed"
};
mat4 mWorld = mat4(1.0f);
mat4 mView = mat4(1.0f);
mat4 mProjection = mat4(1.0f);
double time = 0.0;
double timeDiff = 0.0;
time = glfwGetTime();
string FPS;
std::stringstream sstm;
bool soundStart = false;
do
{
timeDiff = glfwGetTime() - time;
timeDiff = 1 / timeDiff;
sstm.str(std::string());
sstm << "FPS: " << timeDiff;
FPS = sstm.str();
sstm.str(std::string());
if (sound && !soundStart)
{
cout << "Sound on!" << endl;
engine->play2D("Data/Sound/geldern_night.mp3", true);
engine->play2D("Data/Sound/3D_River.mp3", true);
soundStart = true;
}
if (!sound && soundStart)
{
cout << "Sound off!" << endl;
engine->setAllSoundsPaused(true);
soundStart = false;
}
camera.Use();
mProjection = camera.getProjectionMatrix();
#pragma region reflection
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, reflectionFrameBuffer);
mWorld = mat4(1.0f);
mView = lookAt(vec3(-129.523, 624.225, -18.263), vec3(-129.246, 623.264, -18.2517), glm::vec3(0.0, 1.0, 0.0));
glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glCullFace(GL_FRONT);
glEnable(GL_CULL_FACE);
cubemap.Draw(mProjection, mView, mWorld);
glDisable(GL_CULL_FACE);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
#pragma endregion
mView = camera.getViewMatrix();
mWorld = mat4(1.0f);
glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glCullFace(GL_BACK);
glEnable(GL_CULL_FACE);
if (drawSkyBox)
cubemap.Draw(mProjection, mView, mWorld);
glEnable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
if (drawObjects)
{
#pragma region cubes
glUseProgram(program);
glUniform3f(glGetUniformLocation(program, "viewPos"), camera.getCameraPosition().x, camera.getCameraPosition().y, camera.getCameraPosition().z);
glUniform1f(glGetUniformLocation(program, "shininess"), 32.0f);
glUniform1i(glGetUniformLocation(program, "cube"), true);
glUniform3f(glGetUniformLocation(program, "dirLight.direction"), -0.2f, -1.0f, -0.3f);
glUniform3f(glGetUniformLocation(program, "dirLight.ambient"), 0.05f, 0.05f, 0.05f);
glUniform3f(glGetUniformLocation(program, "dirLight.diffuse"), 0.4f, 0.4f, 0.4f);
glUniform3f(glGetUniformLocation(program, "dirLight.specular"), 0.5f, 0.5f, 0.5f);
for (int i = 0; i < 8; i++)
{
sstm.str(std::string());
sstm << "pointLights[" << i << "].position";
glUniform3f(glGetUniformLocation(program, sstm.str().c_str()), pointLightPositions[i].x, pointLightPositions[i].y + 0.6f, pointLightPositions[i].z);
sstm.str(std::string());
sstm << "pointLights[" << i << "].ambient";
glUniform3f(glGetUniformLocation(program, sstm.str().c_str()), 0.05f, 0.05f, 0.05f);
sstm.str(std::string());
sstm << "pointLights[" << i << "].diffuse";
glUniform3f(glGetUniformLocation(program, sstm.str().c_str()), 0.8f, 0.8f, 0.8f);
sstm.str(std::string());
sstm << "pointLights[" << i << "].specular";
glUniform3f(glGetUniformLocation(program, sstm.str().c_str()), 1.0f, 1.0f, 1.0f);
sstm.str(std::string());
sstm << "pointLights[" << i << "].constant";
glUniform1f(glGetUniformLocation(program, sstm.str().c_str()), 1.0f);
sstm.str(std::string());
sstm << "pointLights[" << i << "].linear";
glUniform1f(glGetUniformLocation(program, sstm.str().c_str()), 0.09);
sstm.str(std::string());
sstm << "pointLights[" << i << "].quadratic";
glUniform1f(glGetUniformLocation(program, sstm.str().c_str()), 0.032);
}
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, diffuseMap);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, specularMap);
glBindVertexArray(cubeVao);
mat4 pv = mProjection * mView;
for (int i = 25; i < 35; i++)
{
mWorld = translate(mat4(1.0f), positionObject[i]);
glUniformMatrix4fv(glGetUniformLocation(program, "model"), 1, GL_FALSE, value_ptr(mWorld));
glUniformMatrix3fv(glGetUniformLocation(program, "TIM"), 1, GL_FALSE, value_ptr(mat3(transpose(inverse(mWorld)))));
glUniformMatrix4fv(glGetUniformLocation(program, "mvp"), 1, GL_FALSE, value_ptr(pv * mWorld * scaleObject[9]));
glDrawArrays(GL_TRIANGLES, 0, 36);
}
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, 0);
#pragma endregion
glUniform1i(glGetUniformLocation(program, "cube"), false);
mWorld = mat4(1.0f);
mWorld = translate(mWorld, positionObject[0]);
glUniformMatrix4fv(glGetUniformLocation(program, "model"), 1, GL_FALSE, value_ptr(mWorld));
glUniformMatrix3fv(glGetUniformLocation(program, "TIM"), 1, GL_FALSE, value_ptr(mat3(transpose(inverse(mWorld)))));
glUniformMatrix4fv(glGetUniformLocation(program, "mvp"), 1, GL_FALSE, value_ptr(pv * mWorld * scaleObject[0]));
ship.Draw(program);
mWorld = mat4(1.0f);
for(int i = 1; i < 8; i++)
{
mWorld = translate(mWorld, positionObject[i]);
mWorld = rotate(mWorld, 200.0f, vec3(0.0f, 1.0f, 0.0f));
glUniformMatrix4fv(glGetUniformLocation(program, "model"), 1, GL_FALSE, value_ptr(mWorld));
glUniformMatrix3fv(glGetUniformLocation(program, "TIM"), 1, GL_FALSE, value_ptr(mat3(transpose(inverse(mWorld)))));
glUniformMatrix4fv(glGetUniformLocation(program, "mvp"), 1, GL_FALSE, value_ptr(pv * mWorld * scaleObject[1]));
cannon.Draw(program);
mWorld = mat4(1.0f);
}
mWorld = mat4(1.0f);
mWorld = translate(mWorld, positionObject[8]);
mWorld = rotate(mWorld, 210.0f, vec3(0.0f, 1.0f, 0.0f));
glUniformMatrix4fv(glGetUniformLocation(program, "model"), 1, GL_FALSE, value_ptr(mWorld));
glUniformMatrix3fv(glGetUniformLocation(program, "TIM"), 1, GL_FALSE, value_ptr(mat3(transpose(inverse(mWorld)))));
glUniformMatrix4fv(glGetUniformLocation(program, "mvp"), 1, GL_FALSE, value_ptr(pv * mWorld * scaleObject[2]));
house.Draw(program);
mWorld = mat4(1.0f);
for (int i = 9; i < 11; i++)
{
mWorld = translate(mWorld, positionObject[i]);
mWorld = rotate(mWorld, 5.0f * i, vec3(0.0f, 1.0f, 0.0f));
glUniformMatrix4fv(glGetUniformLocation(program, "model"), 1, GL_FALSE, value_ptr(mWorld));
glUniformMatrix3fv(glGetUniformLocation(program, "TIM"), 1, GL_FALSE, value_ptr(mat3(transpose(inverse(mWorld)))));
glUniformMatrix4fv(glGetUniformLocation(program, "mvp"), 1, GL_FALSE, value_ptr(pv * mWorld * scaleObject[2]));
house.Draw(program);
mWorld = mat4(1.0f);
}
mWorld = mat4(1.0f);
mWorld = translate(mWorld, positionObject[11]);
mWorld = rotate(mWorld, -45.0f, vec3(0.0f, 1.0f, 0.0f));
glUniformMatrix4fv(glGetUniformLocation(program, "model"), 1, GL_FALSE, value_ptr(mWorld));
glUniformMatrix3fv(glGetUniformLocation(program, "TIM"), 1, GL_FALSE, value_ptr(mat3(transpose(inverse(mWorld)))));
glUniformMatrix4fv(glGetUniformLocation(program, "mvp"), 1, GL_FALSE, value_ptr(pv * mWorld * scaleObject[3]));
tent1.Draw(program);
mWorld = mat4(1.0f);
mWorld = translate(mWorld, positionObject[12]);
mWorld = rotate(mWorld, 180.0f, vec3(0.0f, 1.0f, 0.0f));
glUniformMatrix4fv(glGetUniformLocation(program, "model"), 1, GL_FALSE, value_ptr(mWorld));
glUniformMatrix3fv(glGetUniformLocation(program, "TIM"), 1, GL_FALSE, value_ptr(mat3(transpose(inverse(mWorld)))));
glUniformMatrix4fv(glGetUniformLocation(program, "mvp"), 1, GL_FALSE, value_ptr(pv * mWorld * scaleObject[4]));
tent.Draw(program);
for (int i = 12; i < 20; i++)
{
mWorld = mat4(1.0f);
mWorld = translate(mWorld, positionObject[i]);
mWorld = rotate(mWorld, 180.0f, vec3(0.0f, 1.0f, 0.0f));
glUniformMatrix4fv(glGetUniformLocation(program, "model"), 1, GL_FALSE, value_ptr(mWorld));
glUniformMatrix3fv(glGetUniformLocation(program, "TIM"), 1, GL_FALSE, value_ptr(mat3(transpose(inverse(mWorld)))));
glUniformMatrix4fv(glGetUniformLocation(program, "mvp"), 1, GL_FALSE, value_ptr(pv * mWorld * scaleObject[5]));
barrel.Draw(program);
}
for (int i = 20; i < 25; i++)
{
mWorld = mat4(1.0f);
mWorld = translate(mWorld, positionObject[i]);
mWorld = rotate(mWorld, 180.0f, vec3(0.0f, 1.0f, 0.0f));
glUniformMatrix4fv(glGetUniformLocation(program, "model"), 1, GL_FALSE, value_ptr(mWorld));
glUniformMatrix3fv(glGetUniformLocation(program, "TIM"), 1, GL_FALSE, value_ptr(mat3(transpose(inverse(mWorld)))));
glUniformMatrix4fv(glGetUniformLocation(program, "mvp"), 1, GL_FALSE, value_ptr(pv * mWorld * (i > 20 ? scaleObject[7] : scaleObject[6])));
tree.Draw(program);
}
for (int i = 0; i < 8; i++)
{
mWorld = mat4(1.0f);
mWorld = translate(mWorld, pointLightPositions[i]);
glUniformMatrix4fv(glGetUniformLocation(program, "model"), 1, GL_FALSE, value_ptr(mWorld));
glUniformMatrix3fv(glGetUniformLocation(program, "TIM"), 1, GL_FALSE, value_ptr(mat3(transpose(inverse(mWorld)))));
glUniformMatrix4fv(glGetUniformLocation(program, "mvp"), 1, GL_FALSE, value_ptr(pv * mWorld * scaleObject[8]));
lamp.Draw(program);
}
}
mWorld = mat4(1.0f);
glEnable(GL_CULL_FACE);
if (drawTerrain)
terrain.RenderTerrain(mProjection, mView, mWorld);
glDisable(GL_CULL_FACE);
if (drawWater)
{
mWorld = translate(mWorld, waterPosition);
water.Draw(mProjection, mView, mWorld, reflectionTexture, cubemap.getTextureId(), camera.getCameraPosition(), waterGeometry, waterSpeed);
}
glDisable(GL_DEPTH_TEST);
time = glfwGetTime();
if (showMenu)
text.RenderText(txt, FPS, boxSize, 25.0f, .3f, 7);
glfwPollEvents();
glfwSwapBuffers(window);
}
while( glfwGetKey(window, GLFW_KEY_ESCAPE ) != GLFW_PRESS &&
glfwWindowShouldClose(window) == 0 );
glfwTerminate();
engine->drop();
return 0;
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_1 && action == GLFW_PRESS)
drawObjects = !drawObjects;
if (key == GLFW_KEY_2 && action == GLFW_PRESS)
drawTerrain = !drawTerrain;
if (key == GLFW_KEY_3 && action == GLFW_PRESS)
drawWater = !drawWater;
if (key == GLFW_KEY_4 && action == GLFW_PRESS)
drawSkyBox = !drawSkyBox;
if (key == GLFW_KEY_5 && action == GLFW_PRESS)
waterGeometry = !waterGeometry;
if (glfwGetKey( window, GLFW_KEY_R ) == GLFW_PRESS)
{
vec3 r = vec3(camera.getCameraPosition() + camera.getDirection());
cout << "vec3(" << camera.getCameraPosition().x
<< ", " << camera.getCameraPosition().y
<< ", " << camera.getCameraPosition().z
<< "), vec3(" << r.x << ", " << r.y << ", " << r.z << ") " << endl;
}
if (key == GLFW_KEY_KP_ADD && action == GLFW_PRESS)
{
waterSpeed += waterSpeed >= 0.09 ? 0.0f : 0.01f;
}
if (key == GLFW_KEY_KP_SUBTRACT && action == GLFW_PRESS)
{
waterSpeed -= waterSpeed <= 0.01f ? 0.0f : 0.01f;
}
if (key == GLFW_KEY_6 && action == GLFW_PRESS)
{
sound = !sound;
}
if (key == GLFW_KEY_F1 && action == GLFW_PRESS)
{
showMenu = !showMenu;
}
} | 37.859794 | 152 | 0.678412 | [
"geometry",
"model"
] |
3c0f06fd31b4df6b38cb190986521f053eaff1af | 4,863 | cpp | C++ | source/EliteQuant/Services/Api/apiservice.cpp | xubingyue/EliteQuant_Cpp | 7f539c37d19e3208cca573f5a575dc4162b24880 | [
"Apache-2.0"
] | null | null | null | source/EliteQuant/Services/Api/apiservice.cpp | xubingyue/EliteQuant_Cpp | 7f539c37d19e3208cca573f5a575dc4162b24880 | [
"Apache-2.0"
] | null | null | null | source/EliteQuant/Services/Api/apiservice.cpp | xubingyue/EliteQuant_Cpp | 7f539c37d19e3208cca573f5a575dc4162b24880 | [
"Apache-2.0"
] | 1 | 2018-06-26T09:01:45.000Z | 2018-06-26T09:01:45.000Z | #include <atomic>
#include <assert.h>
#include <Common/Logger/logger.h>
#include <Common/Util/util.h>
#include <Common/Data/datamanager.h>
#include <Common/Order/ordermanager.h>
#include <Services/Api/apiservice.h>
#include <nanomsg/src/reqrep.h>
#include <nanomsg/src/pair.h>
#include <nanomsg/src/ws.h>
namespace EliteQuant
{
extern std::atomic<bool> gShutdown;
ApiServer::ApiServer() {
// message queue factory
if (CConfig::instance()._msgq == MSGQ::ZMQ) {
client_msg_pair_ = std::make_unique<CMsgqZmq>(MSGQ_PROTOCOL::PAIR, CConfig::instance().API_PORT);
client_data_pub_ = std::make_unique<CMsgqZmq>(MSGQ_PROTOCOL::PUB, CConfig::instance().API_ZMQ_DATA_PORT);
market_data_sub_ = std::make_unique<CMsgqNanomsg>(MSGQ_PROTOCOL::SUB, CConfig::instance().MKT_DATA_PUBSUB_PORT, false);
//brokerage_msg_pair_ = std::make_unique<CMsgqZmq>(MSGQ_PROTOCOL::PAIR, CConfig::instance().BROKERAGE_PAIR_PORT, false);
//bar_msg_sub_ = std::make_unique<CMsgqZmq>(MSGQ_PROTOCOL::SUB, CConfig::instance().BAR_AGGREGATOR_PUBSUB_PORT, false);
brokerage_msg_pair_ = std::make_unique<CMsgqNanomsg>(MSGQ_PROTOCOL::PAIR, CConfig::instance().BROKERAGE_PAIR_PORT, false);
bar_msg_sub_ = std::make_unique<CMsgqNanomsg>(MSGQ_PROTOCOL::SUB, CConfig::instance().BAR_AGGREGATOR_PUBSUB_PORT, false);
}
else {
client_msg_pair_ = std::make_unique<CMsgqNanomsg>(MSGQ_PROTOCOL::PAIR, CConfig::instance().API_PORT);
brokerage_msg_pair_ = std::make_unique<CMsgqNanomsg>(MSGQ_PROTOCOL::PAIR, CConfig::instance().BROKERAGE_PAIR_PORT, false);
bar_msg_sub_ = std::make_unique<CMsgqNanomsg>(MSGQ_PROTOCOL::SUB, CConfig::instance().BAR_AGGREGATOR_PUBSUB_PORT, false);
}
}
ApiServer::~ApiServer() {
PRINT_TO_FILE("INFO:[%s,%d][%s] %s\n", __FILE__, __LINE__, __FUNCTION__, "api service stopped.");
}
// 1. read from client
// 2. relay new bar // TODO: should it be here?
// 3. relay brokerage message
void ApiServer::run() {
PRINT_TO_FILE("INFO:[%s,%d][%s]api server started.\n", __FILE__, __LINE__, __FUNCTION__);
while (!gShutdown) {
onClientMessage(); // 1. read from client
onServerMessage(); // 2. relay brokerage message
if ((CConfig::instance()._msgq == MSGQ::ZMQ))
onDataMessage(); // 3. relay new bar
msleep(10);
}
}
void ApiServer::onClientMessage() {
string msgin = client_msg_pair_->recmsg();
if (msgin.empty())
{
return;
}
PRINT_TO_FILE_AND_CONSOLE("INFO:[%s,%d][%s]client msgin: %s\n", __FILE__, __LINE__, __FUNCTION__, msgin.c_str());
if (startwith(msgin, CConfig::instance().new_order_msg)) {
lock_guard<mutex> g(oid_mtx);
assert(long(m_orderId) >= 0); // start with 0
string oid = to_string(long(m_orderId));
m_orderId++;
brokerage_msg_pair_->sendmsg(string(msgin) + SERIALIZATION_SEPARATOR + oid);
}
else if (startwith(msgin, CConfig::instance().cancel_order_msg)) {
brokerage_msg_pair_->sendmsg(msgin); // passthrough
}
else if (startwith(msgin, CConfig::instance().order_status_msg)) {
string msgout;
vector<string> v = stringsplit(msgin, SERIALIZATION_SEPARATOR);
if (v.size() == 2) {
long oid = stol(v[1]);
//TODO send message back
}
}
else if (startwith(msgin, CConfig::instance().hist_msg)) {
brokerage_msg_pair_->sendmsg(msgin); // passthrough
}
else if (startwith(msgin, CConfig::instance().last_price_msg)) {
vector<string> v = stringsplit(msgin, SERIALIZATION_SEPARATOR); // 'p'|sym
string sym = v[1];
char msg[128] = {};
double value = DataManager::instance()._latestmarkets[sym].price_;
sprintf(msg, "p|%s|%d|%.2f", sym.c_str(), DataType::DT_TradePrice, value);
client_msg_pair_->sendmsg(msg);
}
else if (startwith(msgin, CConfig::instance().last_size_msg)) {
vector<string> v = stringsplit(msgin, SERIALIZATION_SEPARATOR); // 'z'|sym
string sym = v[1];
char msg[128] = {};
double value = DataManager::instance()._latestmarkets[sym].size_;
sprintf(msg, "z|%s|%d|%.2f", sym.c_str(), DataType::DT_TradeSize, value);
client_msg_pair_->sendmsg(msg);
}
else if (startwith(msgin, CConfig::instance().bar_msg)) {
vector<string> v = stringsplit(msgin, SERIALIZATION_SEPARATOR); // 'bx'|sym
string sym = v[1];
string msg;
msg = DataManager::instance()._60s[sym].serialize();
client_msg_pair_->sendmsg(msg);
}
else if (msgin == CConfig::instance().close_all_msg) {
brokerage_msg_pair_->sendmsg(msgin); // passthrough
}
}
void ApiServer::onServerMessage() {
string msg = brokerage_msg_pair_->recmsg();
if (!msg.empty()) {
client_msg_pair_->sendmsg(msg); // passthrough
}
}
void ApiServer::onDataMessage() {
string msg = market_data_sub_->recmsg();
if (!msg.empty()) {
client_data_pub_->sendmsg(msg); // passthrough
}
}
// microservice
void ApiService() {
ApiServer server;
server.run();
}
} | 34.246479 | 125 | 0.696895 | [
"vector"
] |
3c14b0e446eb801b1ac525536c9904e8f0a204e3 | 1,553 | cpp | C++ | 4th_semester/DA/Graph/main.cpp | mehakun/Labs | 0d42c97e8671d31b9cb49093686df7b8d4d62cfd | [
"MIT"
] | 3 | 2017-03-06T16:08:43.000Z | 2020-08-02T22:11:00.000Z | 4th_semester/DA/Graph/main.cpp | mehakun/Labs | 0d42c97e8671d31b9cb49093686df7b8d4d62cfd | [
"MIT"
] | null | null | null | 4th_semester/DA/Graph/main.cpp | mehakun/Labs | 0d42c97e8671d31b9cb49093686df7b8d4d62cfd | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <algorithm>
std::vector<std::vector<unsigned int> > graph;
std::vector<std::vector<unsigned int> > components;
std::vector<bool> visited;
void dfs(const size_t& node);
int main() {
unsigned int vertexAmount, edgeAmount, firstTmp, secondTmp;
std::cin >> vertexAmount >> edgeAmount;
graph = std::vector<std::vector<unsigned int> >(vertexAmount);
visited = std::vector<bool>(vertexAmount);
for (size_t i = 0; i < edgeAmount; ++i) {
std::cin >> firstTmp >> secondTmp;
graph[firstTmp - 1].push_back(secondTmp - 1);
graph[secondTmp - 1].push_back(firstTmp - 1);
}
for (size_t i = 0; i < vertexAmount; ++i) {
if (!visited[i]) {
components.emplace_back(std::vector<unsigned int>());
dfs(i);
}
}
size_t compSize = components.size();
for (size_t i = 0; i < compSize; ++i) {
std::sort(components[i].begin(), components[i].end());
}
std::sort(components.begin(), components.end(),
[](const std::vector<unsigned int>& a, const std::vector<unsigned int>& b) {
return a[0] < b[0];
});
for (size_t i = 0; i < compSize; ++i) {
std::cout << components[i][0] + 1;
for (size_t j = 1; j < components[i].size(); ++j) {
std::cout << ' ' << components[i][j] + 1;
}
std::cout << '\n';
}
return 0;
}
void dfs(const size_t& node) {
visited[node] = true;
components.back().push_back(node);
for (const auto& child: graph[node]) {
if (!visited[child]) dfs(child);
}
}
| 24.650794 | 88 | 0.588538 | [
"vector"
] |
3c170b25a1e49ec3a3fda9daa7f9cc5e4e4caf14 | 1,106 | cpp | C++ | 1061/B/prog.cpp | alexsyrom/codeforces | 54fabac82d2dac16429c6b6576830d20e47ed94c | [
"MIT"
] | null | null | null | 1061/B/prog.cpp | alexsyrom/codeforces | 54fabac82d2dac16429c6b6576830d20e47ed94c | [
"MIT"
] | null | null | null | 1061/B/prog.cpp | alexsyrom/codeforces | 54fabac82d2dac16429c6b6576830d20e47ed94c | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
template <class Class>
void Print(Class instance) {
std::cout << instance << std::endl;
}
void Print() {
std::cout << std::endl;
}
int main() {
std::ios_base::sync_with_stdio(false);
#ifdef LOCAL
std::ifstream input("input.txt");
std::ofstream output("output.txt");
#else
auto& input = std::cin;
auto& output = std::cout;
#endif
size_t n, m;
input >> n >> m;
if (n == 1) {
output << 0;
return 0;
}
std::vector<size_t> a(n);
for (size_t index = 0; index < n; ++index) {
input >> a[index];
}
std::sort(a.rbegin(), a.rend());
uint64_t answer = 0;
for (size_t index = 1; index < n; ++index) {
if (a[index - 1] < a[index]) {
answer += a[index] - a[index - 1];
a[index] = a[index - 1];
}
if (a[index - 1] <= 1) {
continue;
}
if (a[index - 1] == a[index]) {
answer++;
a[index]--;
}
answer += a[index];
}
output << answer;
return 0;
}
| 20.867925 | 48 | 0.461121 | [
"vector"
] |
3c201ec5bd4afb624989c526c575b0a3d4e5b64e | 14,193 | cpp | C++ | vehicle/OVMS.V3/components/vehicle_vweup/src/vehicle_vweup.cpp | Wil63/Open-Vehicle-Monitoring-System-3 | 781b863c91f74ece9a8943f48feb4f2d3ebe19f0 | [
"MIT"
] | 1 | 2020-08-03T18:35:40.000Z | 2020-08-03T18:35:40.000Z | vehicle/OVMS.V3/components/vehicle_vweup/src/vehicle_vweup.cpp | Wil63/Open-Vehicle-Monitoring-System-3 | 781b863c91f74ece9a8943f48feb4f2d3ebe19f0 | [
"MIT"
] | null | null | null | vehicle/OVMS.V3/components/vehicle_vweup/src/vehicle_vweup.cpp | Wil63/Open-Vehicle-Monitoring-System-3 | 781b863c91f74ece9a8943f48feb4f2d3ebe19f0 | [
"MIT"
] | 1 | 2020-08-03T18:35:41.000Z | 2020-08-03T18:35:41.000Z | /*
; Project: Open Vehicle Monitor System
; Date: 5th July 2018
;
; Changes:
; 1.0 Initial release
;
; (C) 2011 Michael Stegen / Stegen Electronics
; (C) 2011-2018 Mark Webb-Johnson
; (C) 2011 Sonny Chen @ EPRO/DX
;
; 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.
*/
/*
; Subproject: Integration of support for the VW e-UP
; Date: 15th March 2020
;
; Changes:
; 0.1.0 Initial code
: Code frame with correct TAG and vehicle/can registration
;
; 0.1.1 Started with some SOC capture demo code
;
; 0.1.2 Added VIN, speed, 12 volt battery detection
;
; 0.1.3 Added ODO (Dimitrie78), fixed speed
;
; 0.1.4 Added WLTP based ideal range, uncertain outdoor temperature
;
; 0.1.5 Finalized SOC calculation (sharkcow), added estimated range
;
; 0.1.6 Created a climate control first try, removed 12 volt battery status
;
; 0.1.7 Added status of doors
;
; 0.1.8 Added config page for the webfrontend. Features canwrite and modelyear.
; Differentiation between model years is now possible.
;
; 0.1.9 "Fixed" crash on climate control. Added A/C indicator.
; First shot on battery temperatur.
;
; 0.2.0 Added key detection and car_on / pollingstate routine
;
; 0.2.1 Removed battery temperature, corrected outdoor temperature
;
; 0.2.2 Collect VIN only once
;
; (C) 2020 Chris van der Meijden
;
; Big thanx to sharkcow and Dimitrie78.
*/
#include "ovms_log.h"
static const char *TAG = "v-vweup";
#define VERSION "0.1.9"
#include <stdio.h>
#include "pcp.h"
#include "vehicle_vweup.h"
#include "metrics_standard.h"
#include "ovms_webserver.h"
#include "ovms_events.h"
#include "ovms_metrics.h"
static const OvmsVehicle::poll_pid_t vwup_polls[] =
{
{ 0, 0, 0x00, 0x00, { 0, 0, 0 } }
};
void v_remoteCommandTimer(TimerHandle_t timer)
{
OvmsVehicleVWeUP* vwup = (OvmsVehicleVWeUP*) pvTimerGetTimerID(timer);
vwup->RemoteCommandTimer();
}
void v_ccDisableTimer(TimerHandle_t timer)
{
OvmsVehicleVWeUP* vwup = (OvmsVehicleVWeUP*) pvTimerGetTimerID(timer);
vwup->CcDisableTimer();
}
OvmsVehicleVWeUP::OvmsVehicleVWeUP()
{
ESP_LOGI(TAG, "Start VW e-Up vehicle module");
memset (m_vin,0,sizeof(m_vin));
RegisterCanBus(3,CAN_MODE_ACTIVE,CAN_SPEED_100KBPS);
MyConfig.RegisterParam("vwup", "VW e-Up", true, true);
ConfigChanged(NULL);
PollSetPidList(m_can3, vwup_polls);
PollSetState(0);
vin_part1 = false;
vin_part2 = false;
vin_part3 = false;
#ifdef CONFIG_OVMS_COMP_WEBSERVER
WebInit();
#endif
m_remoteCommandTimer = xTimerCreate("VW e-Up Remote Command", 100 / portTICK_PERIOD_MS, pdTRUE, this, v_remoteCommandTimer);
m_ccDisableTimer = xTimerCreate("VW e-Up CC Disable", 1000 / portTICK_PERIOD_MS, pdFALSE, this, v_ccDisableTimer);
}
OvmsVehicleVWeUP::~OvmsVehicleVWeUP()
{
ESP_LOGI(TAG, "Stop VW e-Up vehicle module");
#ifdef CONFIG_OVMS_COMP_WEBSERVER
WebDeInit();
#endif
}
bool OvmsVehicleVWeUP::SetFeature(int key, const char *value)
{
switch (key)
{
case 15:
{
int bits = atoi(value);
MyConfig.SetParamValueBool("vwup", "canwrite", (bits& 1)!=0);
return true;
}
default:
return OvmsVehicle::SetFeature(key, value);
}
}
const std::string OvmsVehicleVWeUP::GetFeature(int key)
{
switch (key)
{
case 15:
{
int bits =
( MyConfig.GetParamValueBool("vwup", "canwrite", false) ? 1 : 0);
char buf[4];
sprintf(buf, "%d", bits);
return std::string(buf);
}
default:
return OvmsVehicle::GetFeature(key);
}
}
void OvmsVehicleVWeUP::ConfigChanged(OvmsConfigParam* param)
{
ESP_LOGD(TAG, "VW e-Up reload configuration");
vwup_enable_write = MyConfig.GetParamValueBool("vwup", "canwrite", false);
vwup_modelyear = MyConfig.GetParamValueInt("vwup", "modelyear", DEFAULT_MODEL_YEAR);
}
void OvmsVehicleVWeUP::IncomingFrameCan3(CAN_frame_t* p_frame)
{
uint8_t *d = p_frame->data.u8;
// This will log all incoming frames
// ESP_LOGD(TAG, "IFC %03x 8 %02x %02x %02x %02x %02x %02x %02x %02x", p_frame->MsgID, d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7]);
switch (p_frame->MsgID) {
case 0x61A: // SOC. Is this different for > 2019 models?
StandardMetrics.ms_v_bat_soc->SetValue(d[7]/2.0);
if (vwup_modelyear >= 2020)
{
StandardMetrics.ms_v_bat_range_ideal->SetValue((260 * (d[7]/2.0)) / 100.0); // This is dirty. Based on WLTP only. Should be based on SOH.
} else {
StandardMetrics.ms_v_bat_range_ideal->SetValue((160 * (d[7]/2.0)) / 100.0); // This is dirty. Based on WLTP only. Should be based on SOH.
}
break;
case 0x52D: // KM range left (estimated).
if( d[0] != 0xFE )
StandardMetrics.ms_v_bat_range_est->SetValue(d[0]);
break;
case 0x65F: // VIN
switch (d[0]) {
case 0x00:
// Part 1
m_vin[0] = d[5];
m_vin[1] = d[6];
m_vin[2] = d[7];
vin_part1 = true;
break;
case 0x01:
// Part 2
if (vin_part1) {
m_vin[3] = d[1];
m_vin[4] = d[2];
m_vin[5] = d[3];
m_vin[6] = d[4];
m_vin[7] = d[5];
m_vin[8] = d[6];
m_vin[9] = d[7];
vin_part2 = true;
}
break;
case 0x02:
// Part 3 - VIN complete
if (vin_part2 && !vin_part3) {
m_vin[10] = d[1];
m_vin[11] = d[2];
m_vin[12] = d[3];
m_vin[13] = d[4];
m_vin[14] = d[5];
m_vin[15] = d[6];
m_vin[16] = d[7];
m_vin[17] = 0;
vin_part3 = true;
StandardMetrics.ms_v_vin->SetValue((string) m_vin);
}
break;
}
break;
case 0x65D: // ODO
StandardMetrics.ms_v_pos_odometer->SetValue( ((uint32_t)(d[3] & 0xf) << 12) | ((UINT)d[2] << 8) | d[1] );
break;
case 0x320: // Speed
// We need some awake message.
if (StandardMetrics.ms_v_env_awake->IsStale())
{
StandardMetrics.ms_v_env_awake->SetValue(false);
}
StandardMetrics.ms_v_pos_speed->SetValue(((d[4] << 8) + d[3]-1)/190);
break;
case 0x527: // Outdoor temperature - untested. Wrong ID? If right, d[4] or d[5]?
StandardMetrics.ms_v_env_temp->SetValue((d[5]/2)-50);
break;
case 0x3E3: // Cabin temperature
// We should use:
//
// StandardMetrics.ms_v_env_cabintemp->SetValue((d[2]-100)/2);
//
// which is not implemented in the app.
//
// So instead we use as a quick workaround the PEM temperature:
//
StandardMetrics.ms_v_inv_temp->SetValue((d[2]-100)/2);
break;
case 0x470: // Doors
StandardMetrics.ms_v_door_fl->SetValue((d[1] & 0x01) > 0);
StandardMetrics.ms_v_door_fr->SetValue((d[1] & 0x02) > 0);
break;
// Check for running remote hvac.
case 0x3E1:
if (d[4] > 0) {
StandardMetrics.ms_v_env_hvac->SetValue(true);
} else {
StandardMetrics.ms_v_env_hvac->SetValue(false);
}
break;
case 0x575: // Key position
switch (d[0]) {
case 0x00: // No key
vehicle_vweup_car_on(false);
break;
case 0x01: // Key in position 1, no ignition
vehicle_vweup_car_on(false);
break;
case 0x03: // Ignition is turned off
break;
case 0x05: // Ignition is turned on
break;
case 0x07: // Key in position 2, ignition on
vehicle_vweup_car_on(true);
break;
case 0x0F: // Key in position 3, start the engine
break;
}
break;
default:
// This will log all unknown incoming frames
// ESP_LOGD(TAG, "IFC %03x 8 %02x %02x %02x %02x %02x %02x %02x %02x", p_frame->MsgID, d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7]);
break;
}
}
// Takes care of setting all the state appropriate when the car is on
// or off.
//
void OvmsVehicleVWeUP::vehicle_vweup_car_on(bool isOn)
{
if (isOn && !StandardMetrics.ms_v_env_on->AsBool())
{
// Log once that car is being turned on
ESP_LOGI(TAG,"CAR IS ON");
StandardMetrics.ms_v_env_on->SetValue(true);
if (vwup_enable_write) PollSetState(1);
}
else if (!isOn && StandardMetrics.ms_v_env_on->AsBool())
{
// Log once that car is being turned off
ESP_LOGI(TAG,"CAR IS OFF");
StandardMetrics.ms_v_env_on->SetValue(false);
if (vwup_enable_write) PollSetState(0);
}
}
////////////////////////////////////////////////////////////////////////
// Send a RemoteCommand on the CAN bus.
//
// Does nothing if @command is out of range
// Begin of remote climate control template
//
// This is just a template and does nothing!
// We are missing the CAN ID's yet to make it work
void OvmsVehicleVWeUP::SendCommand(RemoteCommand command)
{
unsigned char data[8];
uint8_t length;
length = 8;
canbus *comfBus;
comfBus = m_can3;
switch (command)
{
// data values are wrong. We need to find the right ID's.
case ENABLE_CLIMATE_CONTROL:
ESP_LOGI(TAG, "Enable Climate Control");
// 0x767 04 2F 09 B5 02 55 55 55 climate on?
data[0] = 0x04;
data[1] = 0x2F;
data[2] = 0x09;
data[3] = 0xB5;
data[4] = 0x02;
data[5] = 0x55;
data[6] = 0x55;
data[7] = 0x55;
break;
case DISABLE_CLIMATE_CONTROL:
ESP_LOGI(TAG, "Disable Climate Control");
// 0x767 04 2F 09 B5 00 55 55 55 climate off?
data[0] = 0x04;
data[1] = 0x2F;
data[2] = 0x09;
data[3] = 0xB5;
data[4] = 0x00;
data[5] = 0x55;
data[6] = 0x55;
data[7] = 0x55;
break;
case AUTO_DISABLE_CLIMATE_CONTROL:
ESP_LOGI(TAG, "Auto Disable Climate Control");
// 0x767 04 2F 09 B5 00 55 55 55 climate off?
data[0] = 0x04;
data[1] = 0x2F;
data[2] = 0x09;
data[3] = 0xB5;
data[4] = 0x00;
data[5] = 0x55;
data[6] = 0x55;
data[7] = 0x55;
break;
default:
return;
}
// This crashes OVMS if not connected to the CAN bus!
// We need to find a way to check if we really are connected to the CAN bus.
// Till then, we disable this
//
// comfBus->WriteStandard(0x767, length, data);
}
////////////////////////////////////////////////////////////////////////
// implements the repeated sending of remote commands and releases
// EV SYSTEM ACTIVATION REQUEST after an appropriate amount of time
void OvmsVehicleVWeUP::RemoteCommandTimer()
{
ESP_LOGI(TAG, "RemoteCommandTimer %d", vwup_remote_command_ticker);
if (vwup_remote_command_ticker > 0)
{
vwup_remote_command_ticker--;
if (vwup_remote_command != AUTO_DISABLE_CLIMATE_CONTROL)
{
SendCommand(vwup_remote_command);
}
if (vwup_remote_command_ticker == 1 && vwup_remote_command == ENABLE_CLIMATE_CONTROL)
{
xTimerStart(m_ccDisableTimer, 0);
}
// vwup_remote_command_ticker is set to REMOTE_COMMAND_REPEAT_COUNT in
// RemoteCommandHandler() and we decrement it every 10th of a
// second, hence the following if statement evaluates to true
// ACTIVATION_REQUEST_TIME tenths after we start
//
// This mechanism is copied from the Nissan Leaf and it is completely
// uncertain, if this can be used for the VW e-Up this way.
}
else
{
xTimerStop(m_remoteCommandTimer, 0);
}
}
void OvmsVehicleVWeUP::CcDisableTimer()
{
ESP_LOGI(TAG, "CcDisableTimer");
SendCommand(AUTO_DISABLE_CLIMATE_CONTROL);
}
OvmsVehicle::vehicle_command_t OvmsVehicleVWeUP::RemoteCommandHandler(RemoteCommand command)
{
ESP_LOGI(TAG, "RemoteCommandHandler");
vwup_remote_command = command;
vwup_remote_command_ticker = REMOTE_COMMAND_REPEAT_COUNT;
xTimerStart(m_remoteCommandTimer, 0);
return Success;
}
OvmsVehicle::vehicle_command_t OvmsVehicleVWeUP::CommandHomelink(int button, int durationms)
{
ESP_LOGI(TAG, "CommandHomelink");
return NotImplemented;
}
OvmsVehicle::vehicle_command_t OvmsVehicleVWeUP::CommandClimateControl(bool climatecontrolon)
{
ESP_LOGI(TAG, "CommandClimateControl");
if (vwup_enable_write)
return RemoteCommandHandler(climatecontrolon ? ENABLE_CLIMATE_CONTROL : DISABLE_CLIMATE_CONTROL);
else return NotImplemented;
}
// End of remote climate contol template
void OvmsVehicleVWeUP::Ticker1(uint32_t ticker)
{
// This is just to be sure that we really have an asleep message. It has delay of 120 sec.
if (StandardMetrics.ms_v_env_awake->IsStale())
{
StandardMetrics.ms_v_env_awake->SetValue(false);
}
}
class OvmsVehicleVWeUPInit
{
public: OvmsVehicleVWeUPInit();
} OvmsVehicleVWeUPInit __attribute__ ((init_priority (9000)));
OvmsVehicleVWeUPInit::OvmsVehicleVWeUPInit()
{
ESP_LOGI(TAG, "Registering Vehicle: VW e-Up (9000)");
MyVehicleFactory.RegisterVehicle<OvmsVehicleVWeUP>("VWUP","VW e-Up");
}
| 29.263918 | 147 | 0.629747 | [
"model"
] |
3c2188bdc8333b77ef269d9b05ff8c7a5eae3852 | 1,000 | cpp | C++ | segmentedSieve.cpp | Bug-Warriors/Number_Theory | cf6498058ac1d958fb2ea671246c08ef6a00c1c2 | [
"MIT"
] | null | null | null | segmentedSieve.cpp | Bug-Warriors/Number_Theory | cf6498058ac1d958fb2ea671246c08ef6a00c1c2 | [
"MIT"
] | null | null | null | segmentedSieve.cpp | Bug-Warriors/Number_Theory | cf6498058ac1d958fb2ea671246c08ef6a00c1c2 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
#define endl "\n"
#define mod 1000000007
#define vi vector<ll>
#define pii pair<ll, ll>
#define vpii vector<pair<ll, ll>>
typedef unsigned long long int ull;
typedef long long ll;
#define N 1000000
bitset<N> isPrime;
void sieve(ll R){
R=(ll)floor(sqrt(R));
isPrime.set();
isPrime[0]=0;isPrime[1]=0;isPrime[2]=1;
for(ll i=2;i<=R;i++)if(isPrime[i]==1)for(ll j=i*i;j<=R;j+=i)isPrime[j]=0;
}
bitset<N> primes;
void segmentedSieve(ll L, ll R){
primes.set();
sieve(R);
for(ll i=2;i<sqrt(R);i++){
if(isPrime[i]==1){
ll j=L;
while(j%i!=0&&j<=R)j++;
for(;j<=R;j+=i)primes[j-L]=0;
}
}
}
int main(int argc, char const *argv[]){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll L, R;
cin>>L>>R;
segmentedSieve(L,R);
for(ll i=L;i<=R;i++)if(primes[i-L]==1)cout<<i<<" ";
return 0;
} | 22.222222 | 88 | 0.529 | [
"vector"
] |
3c24f93f8c301e72ab55b360b1e5682308507f73 | 8,740 | cpp | C++ | Third Party/newton-dynamics-master/packages/dCustomJoints/Custom6DOF.cpp | DashW/Ingenuity | f7944a9e8063beaa3dda31e8372d18b4147782e2 | [
"Zlib"
] | null | null | null | Third Party/newton-dynamics-master/packages/dCustomJoints/Custom6DOF.cpp | DashW/Ingenuity | f7944a9e8063beaa3dda31e8372d18b4147782e2 | [
"Zlib"
] | null | null | null | Third Party/newton-dynamics-master/packages/dCustomJoints/Custom6DOF.cpp | DashW/Ingenuity | f7944a9e8063beaa3dda31e8372d18b4147782e2 | [
"Zlib"
] | null | null | null | /* Copyright (c) <2009> <Newton Game Dynamics>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely
*/
// Custom6DOF.cpp: implementation of the Custom6DOF class.
//
//////////////////////////////////////////////////////////////////////
#include "CustomJointLibraryStdAfx.h"
#include "Custom6DOF.h"
//dInitRtti(Custom6DOF);
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
#define MIN_JOINT_PIN_LENGTH 50.0f
#define D_6DOF_ANGULAR_MAX_LINEAR_CORRECTION 0.5f
#define D_6DOF_ANGULAR_MAX_ANGULAR_CORRECTION 10.0f
Custom6DOF::Custom6DOF (const dMatrix& pinsAndPivotChildFrame, const dMatrix& pinsAndPivotParentFrame___, NewtonBody* const child, NewtonBody* const parent)
:CustomJoint(6, child, parent)
,m_minLinearLimits(0.0f, 0.0f, 0.0f, 0.0f)
,m_maxLinearLimits(0.0f, 0.0f, 0.0f, 0.0f)
,m_minAngularLimits(0.0f, 0.0f, 0.0f, 0.0f)
,m_maxAngularLimits(0.0f, 0.0f, 0.0f, 0.0f)
,m_pitch()
,m_yaw()
,m_roll()
{
CalculateLocalMatrix (pinsAndPivotChildFrame, m_localMatrix0, m_localMatrix1);
}
Custom6DOF::~Custom6DOF()
{
}
void Custom6DOF::SetLinearLimits (const dVector& minLinearLimits, const dVector& maxLinearLimits)
{
for (int i = 0; i < 3; i ++) {
m_minLinearLimits[i] = (dAbs (minLinearLimits[i]) < dFloat (1.0e-5f)) ? 0.0f : minLinearLimits[i];
m_maxLinearLimits[i] = (dAbs (maxLinearLimits[i]) < dFloat (1.0e-5f)) ? 0.0f : maxLinearLimits[i];
}
}
void Custom6DOF::SetAngularLimits (const dVector& minAngularLimits, const dVector& maxAngularLimits)
{
for (int i = 0; i < 3; i ++) {
m_minAngularLimits[i] = (dAbs (minAngularLimits[i]) < dFloat (1.0e-5f)) ? 0.0f : minAngularLimits[i];
m_maxAngularLimits[i] = (dAbs (maxAngularLimits[i]) < dFloat (1.0e-5f)) ? 0.0f : maxAngularLimits[i];
}
}
void Custom6DOF::GetLinearLimits (dVector& minLinearLimits, dVector& maxLinearLimits)
{
minLinearLimits = m_minLinearLimits;
maxLinearLimits = m_maxLinearLimits;
}
void Custom6DOF::GetAngularLimits (dVector& minAngularLimits, dVector& maxAngularLimits)
{
minAngularLimits = m_minAngularLimits;
maxAngularLimits = m_maxAngularLimits;
}
void Custom6DOF::GetInfo (NewtonJointRecord* const info) const
{
dFloat dist;
dMatrix matrix0;
dMatrix matrix1;
strcpy (info->m_descriptionType, "generic6dof");
info->m_attachBody_0 = m_body0;
info->m_attachBody_1 = m_body1;
// calculate the position of the pivot point and the Jacobian direction vectors, in global space.
CalculateGlobalMatrix (m_localMatrix0, m_localMatrix1, matrix0, matrix1);
dVector p0 (matrix0.m_posit);
dVector p1 (matrix1.m_posit);
dVector dp (p0 - p1);
for (int i = 0; i < 3; i ++) {
if (!((m_minLinearLimits[i] == 0.0f) && (m_maxLinearLimits[i] == 0.0f))) {
p1 += matrix1[i].Scale (dp % matrix1[i]);
}
}
for (int i = 0; i < 3; i ++) {
if ((m_minLinearLimits[i] == 0.0f) && (m_maxLinearLimits[i] == 0.0f)) {
info->m_minLinearDof[i] = 0.0f;
info->m_maxLinearDof[i] = 0.0f;
} else {
dist = dp % matrix1[i];
info->m_maxLinearDof[i] = m_maxLinearLimits[i] - dist;
info->m_minLinearDof[i] = m_minLinearLimits[i] - dist;
}
}
dVector eulerAngles (m_pitch.m_angle, m_yaw.m_angle, m_roll.m_angle, 0.0f);
for (int i = 0; i < 3; i ++) {
if ((m_minAngularLimits[i] == 0.0f) && (m_maxAngularLimits[i] == 0.0f)) {
info->m_minAngularDof[i] = 0.0f;
info->m_maxAngularDof[i] = 0.0f;
} else {
info->m_maxAngularDof[i] = (m_maxAngularLimits[i] - eulerAngles[i]) * 180.0f / 3.141592f;
info->m_minAngularDof[i] = (m_minAngularLimits[i] - eulerAngles[i]) * 180.0f / 3.141592f;
}
}
info->m_bodiesCollisionOn = GetBodiesCollisionState();
memcpy (info->m_attachmenMatrix_0, &m_localMatrix0, sizeof (dMatrix));
memcpy (info->m_attachmenMatrix_1, &m_localMatrix1, sizeof (dMatrix));
}
void Custom6DOF::SubmitConstraints (dFloat timestep, int threadIndex)
{
dMatrix matrix0;
dMatrix matrix1;
// calculate the position of the pivot point and the Jacobian direction vectors, in global space.
CalculateGlobalMatrix (m_localMatrix0, m_localMatrix1, matrix0, matrix1);
// add the linear limits
const dVector& p0 = matrix0.m_posit;
const dVector& p1 = matrix1.m_posit;
dVector dp (p0 - p1);
for (int i = 0; i < 3; i ++) {
if ((m_minLinearLimits[i] == 0.0f) && (m_maxLinearLimits[i] == 0.0f)) {
NewtonUserJointAddLinearRow (m_joint, &p0[0], &p1[0], &matrix0[i][0]);
NewtonUserJointSetRowStiffness (m_joint, 1.0f);
} else {
// it is a limited linear dof, check if it pass the limits
dFloat dist = dp % matrix1[i];
if (dist > m_maxLinearLimits[i]) {
dVector q1 (p1 + matrix1[i].Scale (m_maxLinearLimits[i]));
// clamp the error, so the not too much energy is added when constraint violation occurs
dFloat maxDist = (p0 - q1) % matrix1[i];
if (maxDist > D_6DOF_ANGULAR_MAX_LINEAR_CORRECTION) {
q1 = p0 - matrix1[i].Scale(D_6DOF_ANGULAR_MAX_LINEAR_CORRECTION);
}
NewtonUserJointAddLinearRow (m_joint, &p0[0], &q1[0], &matrix0[i][0]);
NewtonUserJointSetRowStiffness (m_joint, 1.0f);
// allow the object to return but not to kick going forward
NewtonUserJointSetRowMaximumFriction (m_joint, 0.0f);
} else if (dist < m_minLinearLimits[i]) {
dVector q1 (p1 + matrix1[i].Scale (m_minLinearLimits[i]));
// clamp the error, so the not too much energy is added when constraint violation occurs
dFloat maxDist = (p0 - q1) % matrix1[i];
if (maxDist < -D_6DOF_ANGULAR_MAX_LINEAR_CORRECTION) {
q1 = p0 - matrix1[i].Scale(-D_6DOF_ANGULAR_MAX_LINEAR_CORRECTION);
}
NewtonUserJointAddLinearRow (m_joint, &p0[0], &q1[0], &matrix0[i][0]);
NewtonUserJointSetRowStiffness (m_joint, 1.0f);
// allow the object to return but not to kick going forward
NewtonUserJointSetRowMinimumFriction (m_joint, 0.0f);
}
}
}
dVector euler0;
dVector euler1;
dMatrix localMatrix (matrix0 * matrix1.Inverse());
localMatrix.GetEulerAngles(euler0, euler1);
AngularIntegration pitchStep0 (AngularIntegration (euler0.m_x) - m_pitch);
AngularIntegration pitchStep1 (AngularIntegration (euler1.m_x) - m_pitch);
if (dAbs (pitchStep0.m_angle) > dAbs (pitchStep1.m_angle)) {
euler0 = euler1;
}
dVector euler (m_pitch.Update (euler0.m_x), m_yaw.Update (euler0.m_y), m_roll.Update (euler0.m_z), 0.0f);
//dTrace (("(%f %f %f) (%f %f %f)\n", m_pitch.m_angle * 180.0f / 3.141592f, m_yaw.m_angle * 180.0f / 3.141592f, m_roll.m_angle * 180.0f / 3.141592f, euler0.m_x * 180.0f / 3.141592f, euler0.m_y * 180.0f / 3.141592f, euler0.m_z * 180.0f / 3.141592f));
bool limitViolation = false;
for (int i = 0; i < 3; i ++) {
if (euler[i] < m_minAngularLimits[i]) {
limitViolation = true;
euler[i] = m_minAngularLimits[i];
} else if (euler[i] > m_maxAngularLimits[i]) {
limitViolation = true;
euler[i] = m_maxAngularLimits[i];
}
}
if (limitViolation) {
//dMatrix pyr (dPitchMatrix(m_pitch.m_angle) * dYawMatrix(m_yaw.m_angle) * dRollMatrix(m_roll.m_angle));
dMatrix p0y0r0 (dPitchMatrix(euler[0]) * dYawMatrix(euler[1]) * dRollMatrix(euler[2]));
dMatrix baseMatrix (p0y0r0 * matrix1);
dMatrix rotation (matrix0.Inverse() * baseMatrix);
dQuaternion quat (rotation);
if (quat.m_q0 > dFloat (0.99995f)) {
//dVector p0 (matrix0[3] + baseMatrix[1].Scale (MIN_JOINT_PIN_LENGTH));
//dVector p1 (matrix0[3] + baseMatrix[1].Scale (MIN_JOINT_PIN_LENGTH));
//NewtonUserJointAddLinearRow (m_joint, &p0[0], &p1[0], &baseMatrix[2][0]);
//NewtonUserJointSetRowMinimumFriction(m_joint, 0.0f);
//dVector q0 (matrix0[3] + baseMatrix[0].Scale (MIN_JOINT_PIN_LENGTH));
//NewtonUserJointAddLinearRow (m_joint, &q0[0], &q0[0], &baseMatrix[1][0]);
//NewtonUserJointAddLinearRow (m_joint, &q0[0], &q0[0], &baseMatrix[2][0]);
} else {
dMatrix basis (dGrammSchmidt (dVector (quat.m_q1, quat.m_q2, quat.m_q3, 0.0f)));
dVector p0 (matrix0[3] + basis[1].Scale (MIN_JOINT_PIN_LENGTH));
dVector p1 (matrix0[3] + rotation.RotateVector(basis[1].Scale (MIN_JOINT_PIN_LENGTH)));
NewtonUserJointAddLinearRow (m_joint, &p0[0], &p1[0], &basis[2][0]);
NewtonUserJointSetRowMinimumFriction(m_joint, 0.0f);
//dVector q0 (matrix0[3] + basis[0].Scale (MIN_JOINT_PIN_LENGTH));
//NewtonUserJointAddLinearRow (m_joint, &q0[0], &q0[0], &basis[1][0]);
//NewtonUserJointAddLinearRow (m_joint, &q0[0], &q0[0], &basis[2][0]);
}
}
}
| 36.569038 | 250 | 0.681236 | [
"object"
] |
3c2531157df4facd9bf12d438878c6dde758c066 | 2,344 | hxx | C++ | Code/Tools/Standalone/Source/Driller/FilteredListView.hxx | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-08-08T19:54:51.000Z | 2021-08-08T19:54:51.000Z | Code/Tools/Standalone/Source/Driller/FilteredListView.hxx | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | 2 | 2022-01-13T04:29:38.000Z | 2022-03-12T01:05:31.000Z | Code/Tools/Standalone/Source/Driller/FilteredListView.hxx | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"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
*
*/
#ifndef AZTOOLSFRAMEWORK_UI_UICORE_FILTEREDLISTVIEW_H
#define AZTOOLSFRAMEWORK_UI_UICORE_FILTEREDLISTVIEW_H
#if !defined(Q_MOC_RUN)
#include <AzCore/base.h>
#include <AzCore/Memory/SystemAllocator.h>
#pragma once
#include <QtWidgets/QWidget>
#include <QtWidgets/QListView>
#include <qstringlistmodel.h>
#include <qstringlist.h>
#include <qsortfilterproxymodel.h>
#endif
namespace Ui
{
class FilteredListView;
}
namespace Driller
{
// This widget allows for easy access to a filtered list view that can also be rearranged by the user.
// Useful for things like determining column order, or export fields.
class FilteredListView
: public QWidget
{
Q_OBJECT
// Apparently we can't just have a non-sorted model...
class FilteredProxyModel : public QSortFilterProxyModel
{
void sort(int column, Qt::SortOrder order)
{
(void) column; (void)order;
}
};
public:
AZ_CLASS_ALLOCATOR(FilteredListView, AZ::SystemAllocator,0);
explicit FilteredListView(QWidget* parent = nullptr);
~FilteredListView();
void addItem(const char* item);
void addItems(const QStringList& items);
void removeItem(const char* item);
void removeItems(const QStringList& items);
void clearItems();
void removeSelected();
void setFilterString(const char* filterString);
const char* getFilterString() const;
const QStringList& getAllItems() const;
void getSelectedItems(QStringList& selectedItems) const;
void enableCustomOrdering(bool enabled);
public slots:
void filterEdited(const QString& eventFilter);
void moveSelectionUp();
void moveSelectionDown();
private:
void setButtonsEnabled(bool enabled);
Ui::FilteredListView* m_gui;
bool m_enableCustomOrdering;
FilteredProxyModel m_filteredModel;
QStringListModel m_stringListModel;
QStringList m_stringList;
};
}
#endif
| 26.044444 | 106 | 0.666382 | [
"model",
"3d"
] |
3c2ff217032e9f83779d8be2d2873c0cf32b8f4c | 4,068 | cpp | C++ | src/core/Planet/PlanetTerrain.cpp | edisonlee0212/UniEngine | 62278ae811235179e6a1c24eb35acf73e400fe28 | [
"BSD-3-Clause"
] | 22 | 2020-05-18T02:37:09.000Z | 2022-03-13T18:44:30.000Z | src/core/Planet/PlanetTerrain.cpp | edisonlee0212/UniEngine | 62278ae811235179e6a1c24eb35acf73e400fe28 | [
"BSD-3-Clause"
] | null | null | null | src/core/Planet/PlanetTerrain.cpp | edisonlee0212/UniEngine | 62278ae811235179e6a1c24eb35acf73e400fe28 | [
"BSD-3-Clause"
] | 3 | 2020-12-21T01:21:03.000Z | 2021-09-06T08:07:41.000Z | #include <Planet/PlanetTerrain.hpp>
#include <Planet/PlanetTerrainSystem.hpp>
#include <yaml-cpp/yaml.h>
#include <EditorManager.hpp>
void Planet::PlanetTerrain::Serialize(YAML::Emitter &out)
{
out << YAML::Key << "PlanetInfo";
out << YAML::BeginMap;
out << YAML::Key << "MaxLodLevel" << YAML::Value << m_info.m_maxLodLevel;
out << YAML::Key << "LodDistance" << YAML::Value << m_info.m_lodDistance;
out << YAML::Key << "Radius" << YAML::Value << m_info.m_radius;
out << YAML::Key << "Index" << YAML::Value << m_info.m_index;
out << YAML::Key << "Resolution" << YAML::Value << m_info.m_resolution;
out << YAML::EndMap;
m_surfaceMaterial.Save("m_surfaceMaterial", out);
}
void Planet::PlanetTerrain::Deserialize(const YAML::Node &out)
{
auto info = out["PlanetInfo"];
PlanetInfo planetInfo;
planetInfo.m_maxLodLevel = info["MaxLodLevel"].as<unsigned>();
planetInfo.m_lodDistance = info["LodDistance"].as<double>();
planetInfo.m_radius = info["Radius"].as<double>();
planetInfo.m_index = info["Index"].as<unsigned>();
planetInfo.m_resolution = info["Resolution"].as<unsigned>();
SetPlanetInfo(planetInfo);
m_surfaceMaterial.Load("m_surfaceMaterial", out);
}
void Planet::PlanetTerrain::Init()
{
if(m_initialized) return;
m_sharedVertices = std::vector<Vertex>();
size_t resolution = m_info.m_resolution;
m_sharedVertices.resize(resolution * resolution);
m_sharedTriangles = std::vector<unsigned>();
m_sharedTriangles.resize((resolution - 1) * (resolution - 1) * 6);
size_t triIndex = 0;
for (size_t y = 0; y < resolution; y++)
{
for (size_t x = 0; x < resolution; x++)
{
size_t i = x + y * resolution;
m_sharedVertices[i].m_texCoords =
glm::vec2(static_cast<float>(x) / (resolution - 1), static_cast<float>(y) / (resolution - 1));
if (x != resolution - 1 && y != resolution - 1)
{
m_sharedTriangles[triIndex] = i;
m_sharedTriangles[triIndex + 1] = i + resolution + 1;
m_sharedTriangles[triIndex + 2] = i + resolution;
m_sharedTriangles[triIndex + 3] = i;
m_sharedTriangles[triIndex + 4] = i + 1;
m_sharedTriangles[triIndex + 5] = i + resolution + 1;
triIndex += 6;
}
}
}
m_chunks.clear();
m_chunks.push_back(
std::make_shared<TerrainChunk>(this, nullptr, 0, glm::ivec2(0), ChunkDirection::Root, glm::dvec3(1, 0, 0)));
m_chunks.push_back(
std::make_shared<TerrainChunk>(this, nullptr, 0, glm::ivec2(0), ChunkDirection::Root, glm::dvec3(0, 1, 0)));
m_chunks.push_back(
std::make_shared<TerrainChunk>(this, nullptr, 0, glm::ivec2(0), ChunkDirection::Root, glm::dvec3(0, 0, 1)));
m_chunks.push_back(
std::make_shared<TerrainChunk>(this, nullptr, 0, glm::ivec2(0), ChunkDirection::Root, glm::dvec3(-1, 0, 0)));
m_chunks.push_back(
std::make_shared<TerrainChunk>(this, nullptr, 0, glm::ivec2(0), ChunkDirection::Root, glm::dvec3(0, -1, 0)));
m_chunks.push_back(
std::make_shared<TerrainChunk>(this, nullptr, 0, glm::ivec2(0), ChunkDirection::Root, glm::dvec3(0, 0, -1)));
std::mutex m;
for (auto &chunk : m_chunks)
{
chunk->GenerateTerrain(m, chunk);
chunk->Active = true;
}
m_initialized = true;
}
void Planet::PlanetTerrain::OnInspect()
{
EditorManager::DragAndDropButton<Material>(m_surfaceMaterial, "Material");
}
void Planet::PlanetTerrain::PostCloneAction(const std::shared_ptr<IPrivateComponent> &target)
{
m_info = std::static_pointer_cast<Planet::PlanetTerrain>(target)->m_info;
m_initialized = false;
}
void Planet::PlanetTerrain::Start()
{
Init();
}
void Planet::PlanetTerrain::SetPlanetInfo(const PlanetInfo &planetInfo)
{
m_info = planetInfo;
m_initialized = false;
Init();
}
void Planet::PlanetTerrain::CollectAssetRef(std::vector<AssetRef> &list)
{
list.push_back(m_surfaceMaterial);
}
| 37.321101 | 117 | 0.637414 | [
"vector"
] |
3c34cdac167583aaecbec8315a20fec7746f0010 | 32,103 | cpp | C++ | artifact/storm/src/storm/solver/Z3LpSolver.cpp | glatteis/tacas21-artifact | 30b4f522bd3bdb4bebccbfae93f19851084a3db5 | [
"MIT"
] | null | null | null | artifact/storm/src/storm/solver/Z3LpSolver.cpp | glatteis/tacas21-artifact | 30b4f522bd3bdb4bebccbfae93f19851084a3db5 | [
"MIT"
] | null | null | null | artifact/storm/src/storm/solver/Z3LpSolver.cpp | glatteis/tacas21-artifact | 30b4f522bd3bdb4bebccbfae93f19851084a3db5 | [
"MIT"
] | 1 | 2022-02-05T12:39:53.000Z | 2022-02-05T12:39:53.000Z | #include "storm/solver/Z3LpSolver.h"
#include <numeric>
#include "storm/storage/expressions/LinearCoefficientVisitor.h"
#include "storm/settings/SettingsManager.h"
#include "storm/settings/modules/DebugSettings.h"
#include "storm/utility/macros.h"
#include "storm/utility/constants.h"
#include "storm/io/file.h"
#include "storm/storage/expressions/Expression.h"
#include "storm/storage/expressions/ExpressionManager.h"
#include "storm/exceptions/InvalidStateException.h"
#include "storm/exceptions/InvalidAccessException.h"
#include "storm/exceptions/InvalidArgumentException.h"
#include "storm/exceptions/NotImplementedException.h"
#include "storm/exceptions/ExpressionEvaluationException.h"
namespace storm {
namespace solver {
#ifdef STORM_HAVE_Z3_OPTIMIZE
template<typename ValueType>
Z3LpSolver<ValueType>::Z3LpSolver(std::string const& name, OptimizationDirection const& optDir) : LpSolver<ValueType>(optDir), isIncremental(false) {
z3::config config;
config.set("model", true);
context = std::unique_ptr<z3::context>(new z3::context(config));
solver = std::unique_ptr<z3::optimize>(new z3::optimize(*context));
expressionAdapter = std::unique_ptr<storm::adapters::Z3ExpressionAdapter>(new storm::adapters::Z3ExpressionAdapter(*this->manager, *context));
}
template<typename ValueType>
Z3LpSolver<ValueType>::Z3LpSolver(std::string const& name) : Z3LpSolver(name, OptimizationDirection::Minimize) {
// Intentionally left empty.
}
template<typename ValueType>
Z3LpSolver<ValueType>::Z3LpSolver(OptimizationDirection const& optDir) : Z3LpSolver("", optDir) {
// Intentionally left empty.
}
template<typename ValueType>
Z3LpSolver<ValueType>::Z3LpSolver() : Z3LpSolver("", OptimizationDirection::Minimize) {
// Intentionally left empty.
}
template<typename ValueType>
Z3LpSolver<ValueType>::~Z3LpSolver() {
// Intentionally left empty.
}
template<typename ValueType>
void Z3LpSolver<ValueType>::update() const {
// Since the model changed, we erase the optimality flag.
lastCheckObjectiveValue.reset(nullptr);
lastCheckModel.reset(nullptr);
this->currentModelHasBeenOptimized = false;
}
template<typename ValueType>
storm::expressions::Variable Z3LpSolver<ValueType>::addBoundedContinuousVariable(std::string const& name, ValueType lowerBound, ValueType upperBound, ValueType objectiveFunctionCoefficient) {
storm::expressions::Variable newVariable;
if (isIncremental) {
newVariable = this->manager->declareOrGetVariable(name, this->manager->getRationalType());
} else {
newVariable = this->manager->declareVariable(name, this->manager->getRationalType());
}
solver->add(expressionAdapter->translateExpression((newVariable.getExpression() >= this->manager->rational(lowerBound)) && (newVariable.getExpression() <= this->manager->rational(upperBound))));
if (!storm::utility::isZero(objectiveFunctionCoefficient)) {
optimizationSummands.push_back(this->manager->rational(objectiveFunctionCoefficient) * newVariable);
}
return newVariable;
}
template<typename ValueType>
storm::expressions::Variable Z3LpSolver<ValueType>::addLowerBoundedContinuousVariable(std::string const& name, ValueType lowerBound, ValueType objectiveFunctionCoefficient) {
storm::expressions::Variable newVariable;
if (isIncremental) {
newVariable = this->manager->declareOrGetVariable(name, this->manager->getRationalType());
} else {
newVariable = this->manager->declareVariable(name, this->manager->getRationalType());
}
solver->add(expressionAdapter->translateExpression(newVariable.getExpression() >= this->manager->rational(lowerBound)));
if (!storm::utility::isZero(objectiveFunctionCoefficient)) {
optimizationSummands.push_back(this->manager->rational(objectiveFunctionCoefficient) * newVariable);
}
return newVariable;
}
template<typename ValueType>
storm::expressions::Variable Z3LpSolver<ValueType>::addUpperBoundedContinuousVariable(std::string const& name, ValueType upperBound, ValueType objectiveFunctionCoefficient) {
storm::expressions::Variable newVariable;
if (isIncremental) {
newVariable = this->manager->declareOrGetVariable(name, this->manager->getRationalType());
} else {
newVariable = this->manager->declareVariable(name, this->manager->getRationalType());
}
solver->add(expressionAdapter->translateExpression(newVariable.getExpression() <= this->manager->rational(upperBound)));
if (!storm::utility::isZero(objectiveFunctionCoefficient)) {
optimizationSummands.push_back(this->manager->rational(objectiveFunctionCoefficient) * newVariable);
}
return newVariable;
}
template<typename ValueType>
storm::expressions::Variable Z3LpSolver<ValueType>::addUnboundedContinuousVariable(std::string const& name, ValueType objectiveFunctionCoefficient) {
storm::expressions::Variable newVariable;
if (isIncremental) {
newVariable = this->manager->declareOrGetVariable(name, this->manager->getRationalType());
} else {
newVariable = this->manager->declareVariable(name, this->manager->getRationalType());
}
if (!storm::utility::isZero(objectiveFunctionCoefficient)) {
optimizationSummands.push_back(this->manager->rational(objectiveFunctionCoefficient) * newVariable);
}
return newVariable;
}
template<typename ValueType>
storm::expressions::Variable Z3LpSolver<ValueType>::addBoundedIntegerVariable(std::string const& name, ValueType lowerBound, ValueType upperBound, ValueType objectiveFunctionCoefficient) {
storm::expressions::Variable newVariable;
if (isIncremental) {
newVariable = this->manager->declareOrGetVariable(name, this->manager->getIntegerType());
} else {
newVariable = this->manager->declareVariable(name, this->manager->getIntegerType());
}
solver->add(expressionAdapter->translateExpression((newVariable.getExpression() >= this->manager->rational(lowerBound)) && (newVariable.getExpression() <= this->manager->rational(upperBound))));
if (!storm::utility::isZero(objectiveFunctionCoefficient)) {
optimizationSummands.push_back(this->manager->rational(objectiveFunctionCoefficient) * newVariable);
}
return newVariable;
}
template<typename ValueType>
storm::expressions::Variable Z3LpSolver<ValueType>::addLowerBoundedIntegerVariable(std::string const& name, ValueType lowerBound, ValueType objectiveFunctionCoefficient) {
storm::expressions::Variable newVariable;
if (isIncremental) {
newVariable = this->manager->declareOrGetVariable(name, this->manager->getIntegerType());
} else {
newVariable = this->manager->declareVariable(name, this->manager->getIntegerType());
}
solver->add(expressionAdapter->translateExpression(newVariable.getExpression() >= this->manager->rational(lowerBound)));
if (!storm::utility::isZero(objectiveFunctionCoefficient)) {
optimizationSummands.push_back(this->manager->rational(objectiveFunctionCoefficient) * newVariable);
}
return newVariable;
}
template<typename ValueType>
storm::expressions::Variable Z3LpSolver<ValueType>::addUpperBoundedIntegerVariable(std::string const& name, ValueType upperBound, ValueType objectiveFunctionCoefficient) {
storm::expressions::Variable newVariable;
if (isIncremental) {
newVariable = this->manager->declareOrGetVariable(name, this->manager->getIntegerType());
} else {
newVariable = this->manager->declareVariable(name, this->manager->getIntegerType());
}
solver->add(expressionAdapter->translateExpression(newVariable.getExpression() <= this->manager->rational(upperBound)));
if (!storm::utility::isZero(objectiveFunctionCoefficient)) {
optimizationSummands.push_back(this->manager->rational(objectiveFunctionCoefficient) * newVariable);
}
return newVariable;
}
template<typename ValueType>
storm::expressions::Variable Z3LpSolver<ValueType>::addUnboundedIntegerVariable(std::string const& name, ValueType objectiveFunctionCoefficient) {
storm::expressions::Variable newVariable;
if (isIncremental) {
newVariable = this->manager->declareOrGetVariable(name, this->manager->getIntegerType());
} else {
newVariable = this->manager->declareVariable(name, this->manager->getIntegerType());
}
if (!storm::utility::isZero(objectiveFunctionCoefficient)) {
optimizationSummands.push_back(this->manager->rational(objectiveFunctionCoefficient) * newVariable);
}
return newVariable;
}
template<typename ValueType>
storm::expressions::Variable Z3LpSolver<ValueType>::addBinaryVariable(std::string const& name, ValueType objectiveFunctionCoefficient) {
storm::expressions::Variable newVariable;
if (isIncremental) {
newVariable = this->manager->declareOrGetVariable(name, this->manager->getIntegerType());
} else {
newVariable = this->manager->declareVariable(name, this->manager->getIntegerType());
}
solver->add(expressionAdapter->translateExpression((newVariable.getExpression() >= this->manager->rational(storm::utility::zero<storm::RationalNumber>())) && (newVariable.getExpression() <= this->manager->rational(storm::utility::one<storm::RationalNumber>()))));
if (!storm::utility::isZero(objectiveFunctionCoefficient)) {
optimizationSummands.push_back(this->manager->rational(objectiveFunctionCoefficient) * newVariable);
}
return newVariable;
}
template<typename ValueType>
void Z3LpSolver<ValueType>::addConstraint(std::string const& name, storm::expressions::Expression const& constraint) {
STORM_LOG_THROW(constraint.isRelationalExpression(), storm::exceptions::InvalidArgumentException, "Illegal constraint is not a relational expression.");
STORM_LOG_THROW(constraint.getOperator() != storm::expressions::OperatorType::NotEqual, storm::exceptions::InvalidArgumentException, "Illegal constraint uses inequality operator.");
solver->add(expressionAdapter->translateExpression(constraint));
}
template<typename ValueType>
void Z3LpSolver<ValueType>::optimize() const {
// First incorporate all recent changes.
this->update();
// Invoke push() as we want to be able to erase the current optimization function after checking
solver->push();
// Solve the optimization problem depending on the optimization direction
storm::expressions::Expression optimizationFunction = storm::expressions::sum(optimizationSummands);
z3::optimize::handle optFuncHandle = this->getOptimizationDirection() == OptimizationDirection::Minimize ? solver->minimize(expressionAdapter->translateExpression(optimizationFunction)) : solver->maximize(expressionAdapter->translateExpression(optimizationFunction));
z3::check_result chkRes = solver->check();
STORM_LOG_THROW(chkRes != z3::unknown, storm::exceptions::InvalidStateException, "Unable to solve LP problem with Z3: Check result is unknown.");
// We need to store the resulting information at this point. Otherwise, the information would be lost after calling pop() ...
// Check feasibility
lastCheckInfeasible = (chkRes == z3::unsat);
if (lastCheckInfeasible) {
lastCheckUnbounded = false;
} else {
// Get objective result
lastCheckObjectiveValue = std::make_unique<z3::expr>(solver->upper(optFuncHandle));
// Check boundedness
STORM_LOG_ASSERT(lastCheckObjectiveValue->is_app(), "Failed to convert Z3 expression. Encountered unknown expression type.");
lastCheckUnbounded = (lastCheckObjectiveValue->decl().decl_kind() != Z3_OP_ANUM);
if (lastCheckUnbounded) {
lastCheckObjectiveValue.reset(nullptr);
} else {
// Assert that the upper approximation equals the lower one
STORM_LOG_ASSERT(std::string(Z3_get_numeral_string(*context, *lastCheckObjectiveValue)) == std::string(Z3_get_numeral_string(*context, solver->lower(optFuncHandle))), "Lower and Upper Approximation of z3LPSolver result do not match.");
lastCheckModel = std::make_unique<z3::model>(solver->get_model());
}
}
solver->pop(); // removes current optimization function
this->currentModelHasBeenOptimized = true;
}
template<typename ValueType>
bool Z3LpSolver<ValueType>::isInfeasible() const {
STORM_LOG_THROW(this->currentModelHasBeenOptimized, storm::exceptions::InvalidStateException, "Illegal call to Z3LpSolver<ValueType>::isInfeasible: model has not been optimized.");
return lastCheckInfeasible;
}
template<typename ValueType>
bool Z3LpSolver<ValueType>::isUnbounded() const {
STORM_LOG_THROW(this->currentModelHasBeenOptimized, storm::exceptions::InvalidStateException, "Illegal call to Z3LpSolver<ValueType>::isUnbounded: model has not been optimized.");
return lastCheckUnbounded;
}
template<typename ValueType>
bool Z3LpSolver<ValueType>::isOptimal() const {
STORM_LOG_THROW(this->currentModelHasBeenOptimized, storm::exceptions::InvalidStateException, "Illegal call to Z3LpSolver<ValueType>::isOptimal: model has not been optimized.");
return !lastCheckInfeasible && !lastCheckUnbounded;
}
template<typename ValueType>
storm::expressions::Expression Z3LpSolver<ValueType>::getValue(storm::expressions::Variable const& variable) const {
STORM_LOG_ASSERT(variable.getManager() == this->getManager(), "Requested variable is managed by a different manager.");
if (!this->isOptimal()) {
STORM_LOG_THROW(!this->isInfeasible(), storm::exceptions::InvalidAccessException, "Unable to get Z3 solution from infeasible model.");
STORM_LOG_THROW(!this->isUnbounded(), storm::exceptions::InvalidAccessException, "Unable to get Z3 solution from unbounded model.");
STORM_LOG_THROW(false, storm::exceptions::InvalidAccessException, "Unable to get Z3 solution from unoptimized model.");
}
STORM_LOG_ASSERT(lastCheckModel, "Model has not been stored.");
z3::expr z3Var = this->expressionAdapter->translateExpression(variable);
return this->expressionAdapter->translateExpression(lastCheckModel->eval(z3Var, true));
}
template<typename ValueType>
ValueType Z3LpSolver<ValueType>::getContinuousValue(storm::expressions::Variable const& variable) const {
storm::expressions::Expression value = getValue(variable);
if (value.getBaseExpression().isIntegerLiteralExpression()) {
return storm::utility::convertNumber<ValueType>(value.getBaseExpression().asIntegerLiteralExpression().getValue());
}
STORM_LOG_THROW(value.getBaseExpression().isRationalLiteralExpression(), storm::exceptions::ExpressionEvaluationException, "Expected a rational literal while obtaining the value of a continuous variable. Got " << value << "instead.");
return storm::utility::convertNumber<ValueType>(value.getBaseExpression().asRationalLiteralExpression().getValue());
}
template<typename ValueType>
int_fast64_t Z3LpSolver<ValueType>::getIntegerValue(storm::expressions::Variable const& variable) const {
storm::expressions::Expression value = getValue(variable);
STORM_LOG_THROW(value.getBaseExpression().isIntegerLiteralExpression(), storm::exceptions::ExpressionEvaluationException, "Expected an integer literal while obtaining the value of an integer variable. Got " << value << "instead.");
return value.getBaseExpression().asIntegerLiteralExpression().getValue();
}
template<typename ValueType>
bool Z3LpSolver<ValueType>::getBinaryValue(storm::expressions::Variable const& variable) const {
storm::expressions::Expression value = getValue(variable);
// Binary variables are in fact represented as integer variables!
STORM_LOG_THROW(value.getBaseExpression().isIntegerLiteralExpression(), storm::exceptions::ExpressionEvaluationException, "Expected an integer literal while obtaining the value of a binary variable. Got " << value << "instead.");
int_fast64_t val = value.getBaseExpression().asIntegerLiteralExpression().getValue();
STORM_LOG_THROW((val==0 || val==1), storm::exceptions::ExpressionEvaluationException, "Tried to get a binary value for a variable that is neither 0 nor 1.");
return val == 1;
}
template<typename ValueType>
ValueType Z3LpSolver<ValueType>::getObjectiveValue() const {
if (!this->isOptimal()) {
STORM_LOG_THROW(!this->isInfeasible(), storm::exceptions::InvalidAccessException, "Unable to get Z3 solution from infeasible model.");
STORM_LOG_THROW(!this->isUnbounded(), storm::exceptions::InvalidAccessException, "Unable to get Z3 solution from unbounded model.");
STORM_LOG_THROW(false, storm::exceptions::InvalidAccessException, "Unable to get Z3 solution from unoptimized model.");
}
STORM_LOG_ASSERT(lastCheckObjectiveValue, "Objective value has not been stored.");
storm::expressions::Expression result = this->expressionAdapter->translateExpression(*lastCheckObjectiveValue);
if (result.getBaseExpression().isIntegerLiteralExpression()) {
return storm::utility::convertNumber<ValueType>(result.getBaseExpression().asIntegerLiteralExpression().getValue());
}
STORM_LOG_THROW(result.getBaseExpression().isRationalLiteralExpression(), storm::exceptions::ExpressionEvaluationException, "Expected a rational literal while obtaining the objective result. Got " << result << "instead.");
return storm::utility::convertNumber<ValueType>(result.getBaseExpression().asRationalLiteralExpression().getValue());
}
template<typename ValueType>
void Z3LpSolver<ValueType>::writeModelToFile(std::string const& filename) const {
std::ofstream stream;
storm::utility::openFile(filename, stream);
stream << Z3_optimize_to_string(*context, *solver);
storm::utility::closeFile(stream);
}
template<typename ValueType>
void Z3LpSolver<ValueType>::push() {
incrementaOptimizationSummandIndicators.push_back(optimizationSummands.size());
solver->push();
}
template<typename ValueType>
void Z3LpSolver<ValueType>::pop() {
STORM_LOG_ASSERT(!incrementaOptimizationSummandIndicators.empty(), "Tried to pop() without push()ing first.");
solver->pop();
// Delete summands of the optimization function that have been added since the last call to push()
optimizationSummands.resize(incrementaOptimizationSummandIndicators.back());
incrementaOptimizationSummandIndicators.pop_back();
isIncremental = true;
}
template<typename ValueType>
void Z3LpSolver<ValueType>::setMaximalMILPGap(ValueType const&, bool) {
// Since the solver is always exact, setting a gap has no effect.
// Intentionally left empty.
}
template<typename ValueType>
ValueType Z3LpSolver<ValueType>::getMILPGap(bool relative) const {
// Since the solver is precise, the milp gap is always zero.
return storm::utility::zero<ValueType>();
}
#else
template<typename ValueType>
Z3LpSolver<ValueType>::Z3LpSolver(std::string const&, OptimizationDirection const&) {
throw storm::exceptions::NotImplementedException() << "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that requires this support.";
}
template<typename ValueType>
Z3LpSolver<ValueType>::Z3LpSolver(std::string const&) {
throw storm::exceptions::NotImplementedException() << "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that requires this support.";
}
template<typename ValueType>
Z3LpSolver<ValueType>::Z3LpSolver(OptimizationDirection const&) {
throw storm::exceptions::NotImplementedException() << "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that requires this support.";
}
template<typename ValueType>
Z3LpSolver<ValueType>::Z3LpSolver() {
throw storm::exceptions::NotImplementedException() << "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that requires this support.";
}
template<typename ValueType>
Z3LpSolver<ValueType>::~Z3LpSolver() {
}
template<typename ValueType>
storm::expressions::Variable Z3LpSolver<ValueType>::addBoundedContinuousVariable(std::string const&, ValueType, ValueType, ValueType) {
throw storm::exceptions::NotImplementedException() << "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that requires this support.";
}
template<typename ValueType>
storm::expressions::Variable Z3LpSolver<ValueType>::addLowerBoundedContinuousVariable(std::string const&, ValueType, ValueType ) {
throw storm::exceptions::NotImplementedException() << "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that requires this support."; }
template<typename ValueType>
storm::expressions::Variable Z3LpSolver<ValueType>::addUpperBoundedContinuousVariable(std::string const&, ValueType, ValueType ) {
throw storm::exceptions::NotImplementedException() << "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that requires this support.";
}
template<typename ValueType>
storm::expressions::Variable Z3LpSolver<ValueType>::addUnboundedContinuousVariable(std::string const&, ValueType ) {
throw storm::exceptions::NotImplementedException() << "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that requires this support.";
}
template<typename ValueType>
storm::expressions::Variable Z3LpSolver<ValueType>::addBoundedIntegerVariable(std::string const&, ValueType, ValueType, ValueType) {
throw storm::exceptions::NotImplementedException() << "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that requires this support.";
}
template<typename ValueType>
storm::expressions::Variable Z3LpSolver<ValueType>::addLowerBoundedIntegerVariable(std::string const&, ValueType, ValueType) {
throw storm::exceptions::NotImplementedException() << "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that requires this support.";
}
template<typename ValueType>
storm::expressions::Variable Z3LpSolver<ValueType>::addUpperBoundedIntegerVariable(std::string const&, ValueType, ValueType) {
throw storm::exceptions::NotImplementedException() << "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that requires this support.";
}
template<typename ValueType>
storm::expressions::Variable Z3LpSolver<ValueType>::addUnboundedIntegerVariable(std::string const&, ValueType) {
throw storm::exceptions::NotImplementedException() << "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that requires this support.";
}
template<typename ValueType>
storm::expressions::Variable Z3LpSolver<ValueType>::addBinaryVariable(std::string const&, ValueType) {
throw storm::exceptions::NotImplementedException() << "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that requires this support.";
}
template<typename ValueType>
void Z3LpSolver<ValueType>::update() const {
throw storm::exceptions::NotImplementedException() << "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that requires this support.";
}
template<typename ValueType>
void Z3LpSolver<ValueType>::addConstraint(std::string const&, storm::expressions::Expression const&) {
throw storm::exceptions::NotImplementedException() << "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that requires this support.";
}
template<typename ValueType>
void Z3LpSolver<ValueType>::optimize() const {
throw storm::exceptions::NotImplementedException() << "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that requires this support.";
}
template<typename ValueType>
bool Z3LpSolver<ValueType>::isInfeasible() const {
throw storm::exceptions::NotImplementedException() << "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that requires this support.";
}
template<typename ValueType>
bool Z3LpSolver<ValueType>::isUnbounded() const {
throw storm::exceptions::NotImplementedException() << "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that requires this support.";
}
template<typename ValueType>
bool Z3LpSolver<ValueType>::isOptimal() const {
throw storm::exceptions::NotImplementedException() << "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that requires this support.";
}
template<typename ValueType>
storm::expressions::Expression Z3LpSolver<ValueType>::getValue(storm::expressions::Variable const& variable) const {
throw storm::exceptions::NotImplementedException() << "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that requires this support.";
}
template<typename ValueType>
ValueType Z3LpSolver<ValueType>::getContinuousValue(storm::expressions::Variable const&) const {
throw storm::exceptions::NotImplementedException() << "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that requires this support.";
}
template<typename ValueType>
int_fast64_t Z3LpSolver<ValueType>::getIntegerValue(storm::expressions::Variable const&) const {
throw storm::exceptions::NotImplementedException() << "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that requires this support.";
}
template<typename ValueType>
bool Z3LpSolver<ValueType>::getBinaryValue(storm::expressions::Variable const&) const {
throw storm::exceptions::NotImplementedException() << "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that requires this support.";
}
template<typename ValueType>
ValueType Z3LpSolver<ValueType>::getObjectiveValue() const {
throw storm::exceptions::NotImplementedException() << "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that requires this support.";
}
template<typename ValueType>
void Z3LpSolver<ValueType>::writeModelToFile(std::string const& filename) const {
throw storm::exceptions::NotImplementedException() << "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that requires this support.";
}
template<typename ValueType>
void Z3LpSolver<ValueType>::push() {
throw storm::exceptions::NotImplementedException() << "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that requires this support.";
}
template<typename ValueType>
void Z3LpSolver<ValueType>::pop() {
throw storm::exceptions::NotImplementedException() << "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that requires this support.";
}
template<typename ValueType>
void Z3LpSolver<ValueType>::setMaximalMILPGap(ValueType const& gap, bool relative) {
throw storm::exceptions::NotImplementedException() << "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that requires this support.";
}
template<typename ValueType>
ValueType Z3LpSolver<ValueType>::getMILPGap(bool relative) const {
throw storm::exceptions::NotImplementedException() << "This version of storm was compiled without Z3 or the version of Z3 does not support optimization. Yet, a method was called that requires this support.";
}
#endif
template class Z3LpSolver<double>;
template class Z3LpSolver<storm::RationalNumber>;
}
}
| 62.947059 | 280 | 0.682678 | [
"model"
] |
3c375deccd97321eb8da3cb4d679c452b828ba79 | 4,002 | cpp | C++ | PhysX_3.4/Source/SimulationController/src/ScRigidCore.cpp | RyanTorant/simple-physx | a065a9c734c134074c63c80a9109a398b22d040c | [
"Unlicense"
] | 1 | 2019-12-09T16:03:55.000Z | 2019-12-09T16:03:55.000Z | PhysX_3.4/Source/SimulationController/src/ScRigidCore.cpp | RyanTorant/simple-physx | a065a9c734c134074c63c80a9109a398b22d040c | [
"Unlicense"
] | null | null | null | PhysX_3.4/Source/SimulationController/src/ScRigidCore.cpp | RyanTorant/simple-physx | a065a9c734c134074c63c80a9109a398b22d040c | [
"Unlicense"
] | null | null | null | // This code contains NVIDIA Confidential Information and is disclosed to you
// under a form of NVIDIA software license agreement provided separately to you.
//
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// proprietary rights in and to this software and related documentation and
// any modifications thereto. Any use, reproduction, disclosure, or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA Corporation is strictly prohibited.
//
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2008-2018 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "ScBodyCore.h"
#include "ScStaticCore.h"
#include "ScRigidSim.h"
#include "ScShapeSim.h"
#include "ScScene.h"
#include "ScPhysics.h"
using namespace physx;
Sc::RigidCore::RigidCore(const PxActorType::Enum type)
: ActorCore(type, PxActorFlag::eVISUALIZATION, PX_DEFAULT_CLIENT, 0, 0)
{
}
Sc::RigidCore::~RigidCore()
{
}
void Sc::RigidCore::addShapeToScene(ShapeCore& shapeCore)
{
Sc::RigidSim* sim = getSim();
PX_ASSERT(sim);
if(!sim)
return;
sim->getScene().addShape(*sim, shapeCore, NULL);
}
void Sc::RigidCore::removeShapeFromScene(ShapeCore& shapeCore, bool wakeOnLostTouch)
{
Sc::RigidSim* sim = getSim();
if(!sim)
return;
Sc::ShapeSim& s = sim->getSimForShape(shapeCore);
sim->getScene().removeShape(s, wakeOnLostTouch);
}
void Sc::RigidCore::onShapeChange(Sc::ShapeCore& shape, ShapeChangeNotifyFlags notifyFlags, PxShapeFlags oldShapeFlags, bool forceBoundsUpdate)
{
// DS: We pass flags to avoid searching multiple times or exposing RigidSim outside SC, and this form is
// more convenient for the Scb::Shape::syncState method. If we start hitting this a lot we should do it
// a different way, but shape modification after insertion is rare.
Sc::RigidSim* sim = getSim();
if(!sim)
return;
Sc::ShapeSim& s = sim->getSimForShape(shape);
if(notifyFlags & ShapeChangeNotifyFlag::eGEOMETRY)
s.onVolumeOrTransformChange(forceBoundsUpdate);
if(notifyFlags & ShapeChangeNotifyFlag::eMATERIAL)
s.onMaterialChange();
if(notifyFlags & ShapeChangeNotifyFlag::eRESET_FILTERING)
s.onResetFiltering();
if(notifyFlags & ShapeChangeNotifyFlag::eSHAPE2BODY)
s.onVolumeOrTransformChange(forceBoundsUpdate);
if(notifyFlags & ShapeChangeNotifyFlag::eFILTERDATA)
s.onFilterDataChange();
if(notifyFlags & ShapeChangeNotifyFlag::eFLAGS)
s.onFlagChange(oldShapeFlags);
if(notifyFlags & ShapeChangeNotifyFlag::eCONTACTOFFSET)
s.onContactOffsetChange();
if(notifyFlags & ShapeChangeNotifyFlag::eRESTOFFSET)
s.onRestOffsetChange();
}
Sc::RigidSim* Sc::RigidCore::getSim() const
{
return static_cast<RigidSim*>(Sc::ActorCore::getSim());
}
PxActor* Sc::RigidCore::getPxActor() const
{
return Ps::pointerOffset<PxActor*>(const_cast<Sc::RigidCore*>(this), Sc::gOffsetTable.scCore2PxActor[getActorCoreType()]);
}
| 37.754717 | 143 | 0.774113 | [
"shape"
] |
3c39aef788e8a4dd67f02185b0e7ede1a50bd0d8 | 1,752 | hpp | C++ | src/utils.hpp | Yuki-cpp/yuki-http | 07fc0d194ab528f4554aef25813c565a9fce6542 | [
"MIT"
] | null | null | null | src/utils.hpp | Yuki-cpp/yuki-http | 07fc0d194ab528f4554aef25813c565a9fce6542 | [
"MIT"
] | null | null | null | src/utils.hpp | Yuki-cpp/yuki-http | 07fc0d194ab528f4554aef25813c565a9fce6542 | [
"MIT"
] | null | null | null | #pragma once
#include <cstddef>
/**
* @brief Namespace used to define callbacks used internaly bu cURL
*
*/
namespace yuki::http::callbacks
{
/**
* @brief Function passed as callback to cURL to receive data.
*
* This function receive data from cURL and fills a yuki::http::response object with it.
*
* @warning Headers are received via the header_callback(void *data, std::size_t size, std::size_t data_size, void *user_data) function.
*
* @param data p_data: Data to write into the response.
* @param size p_size: Unused. cURL always set it to 1
* @param data_size p_data_size: Data size in bytes.
* @param user_data p_user_data: Pointer to the object that will receive the data. \a must be pointing to a yuki::http::response object.
* @return std::size_t : Number of bytes read or 0 in case of error.
*/
std::size_t write_callback(void *data, std::size_t size, std::size_t data_size, void *user_data);
/**
* @brief Function passed as callback to cURL to receive headers.
*
* This function receive headers from cURL and fills a yuki::http::response object with it.
* It processes a single header line and is called by cURL as many time as needed.
*
* @warning data is received via the write_callback(void *data, std::size_t size, std::size_t data_size, void *user_data) function.
*
* @param data p_data: Header line in the forme of key:value or key.
* @param size p_size: Size of an element in bytes.
* @param data_size p_data_size: Number of elements.
* @param user_data p_user_data: Pointer to the object to which append the header. \a must be pointing to a yuki::http::response object.
* @return std::size_t : \a Must always return 0.
*/
std::size_t header_callback(void *data, std::size_t size, std::size_t data_size, void *user_data);
}
| 37.276596 | 135 | 0.743151 | [
"object"
] |
3c3a5bab294617767bb839e6c4acfaa73361fb51 | 7,040 | cc | C++ | Archive/Stroika_FINAL_for_STERL_1992/Tools/Portable/Flunger/Sources/Flunger.cc | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 28 | 2015-09-22T21:43:32.000Z | 2022-02-28T01:35:01.000Z | Archive/Stroika_FINAL_for_STERL_1992/Tools/Portable/Flunger/Sources/Flunger.cc | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 98 | 2015-01-22T03:21:27.000Z | 2022-03-02T01:47:00.000Z | Archive/Stroika_FINAL_for_STERL_1992/Tools/Portable/Flunger/Sources/Flunger.cc | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 4 | 2019-02-21T16:45:25.000Z | 2022-02-18T13:40:04.000Z | /* Copyright(c) Sophist Solutions Inc. 1990-1992. All rights reserved */
/*
* $Header: /fuji/lewis/RCS/Flunger.cc,v 1.1 1992/09/08 18:24:32 lewis Exp $
*
* TODO:
*
* Changes:
* $Log: Flunger.cc,v $
// Revision 1.1 1992/09/08 18:24:32 lewis
// Initial revision
//
*
*
*
*/
#if qIncludeRCSIDs
static const char rcsid[] = "$Header: /fuji/lewis/RCS/Flunger.cc,v 1.1 1992/09/08 18:24:32 lewis Exp $";
#endif
#include <fstream.h>
#include <strstream.h>
#include "OSRenamePre.hh"
#if qMacOS
#include <CursorCtl.h>
#elif qUnixOS
#include <unistd.h>
#endif
#include "OSRenamePost.hh"
#include "Debug.hh"
#include "File.hh"
#include "Mapping_HashTable.hh"
#include "StreamUtils.hh"
#include "MPWObj.hh"
#include "Flunger.hh"
#if !qRealTemplatesAvailable
AbMappingDeclare (UInt16, String);
Mapping_HTDeclare(UInt16,String);
AbMappingImplement (UInt16, String);
Mapping_HTImplement1(UInt16,String);
Mapping_HTImplement2(UInt16,String);
Mapping_HTImplement3(UInt16,String);
#endif /*!qRealTemplatesAvailable*/
class MyMPWObjectFile : public MPWObjectFile {
public:
MyMPWObjectFile ();
nonvirtual AbSequence(MPWObjRecord)& GetRecords ();
override MPWObjRecord ReadOneRecord (RecordType type, istream& from);
override void WriteOneRecord (const MPWObjRecord& rec, ostream& to);
nonvirtual void PrintModules ();
private:
Mapping_HashTable (UInt16, String) fIDToStringTable;
nonvirtual void ProcessDictionaryRecord (const DictionaryRecord& dictRec);
};
static CollectionSize HashFunction (const UInt16& key)
{
return (key);
}
MyMPWObjectFile::MyMPWObjectFile ():
MPWObjectFile (),
fIDToStringTable (&HashFunction, 1001)
{
}
AbSequence(MPWObjRecord)& MyMPWObjectFile::GetRecords ()
{
return (MPWObjectFile::GetRecords ());
}
MPWObjRecord MyMPWObjectFile::ReadOneRecord (RecordType type, istream& from)
{
#if qMacOS
::SpinCursor(1);
#endif
MPWObjRecord r = MPWObjectFile::ReadOneRecord (type, from);
if (r.GetRecordType () == eDictionary) {
ProcessDictionaryRecord (DictionaryRecord (r));
}
return (r);
}
void MyMPWObjectFile::WriteOneRecord (const MPWObjRecord& rec, ostream& to)
{
#if qMacOS
::SpinCursor(1);
#endif
MPWObjectFile::WriteOneRecord (rec, to);
}
void MyMPWObjectFile::PrintModules ()
{
ForEach (MPWObjRecord, it, GetRecords ().operator Iterator(MPWObjRecord)* ()) {
if (it.Current ().GetRecordType () == eModule) {
UInt16 moduleID = ModuleRecord (it.Current ()).GetModuleID ();
String name;
if (fIDToStringTable.Lookup (moduleID, &name)) {
if (name == kEmptyString) {
name = "<Anonymous>";
}
}
else {
cerr << "module ID not in dictionary!!! #" << moduleID << newline;
}
cout << "Module " << moduleID << " '" << name << "'" << newline;
#if qMacOS
::SpinCursor(1);
#endif
}
}
}
void MyMPWObjectFile::ProcessDictionaryRecord (const DictionaryRecord& dictRec)
{
if (dictRec.LinkIDs ()) {
UInt16 i = 0;
ForEach (String, it, dictRec.GetStrings ().operator Iterator(String)* ()) {
fIDToStringTable.Enter (dictRec.GetFirstID () + i, it.Current ());
i++;
}
}
}
/*
********************************************************************************
******************************** FlungeFile ************************************
********************************************************************************
*/
#if qPathNameBroke
void FlungeFile (const String& fromFile, const String& toFile, ostream& diagnosticOut, Boolean verbose)
#else
void FlungeFile (const PathName& fromFile, const PathName& toFile, ostream& diagnosticOut, Boolean verbose)
#endif
{
#if qPathNameBroke
char buf1 [1024];
char buf2 [1024];
int fromFD = ::open (fromFile.ToCStringTrunc (buf1, sizeof (buf1)), O_RDONLY);
int toFD = ::open (toFile.ToCStringTrunc (buf2, sizeof (buf2)), O_RDWR | O_CREAT);
#else
int fromFD = FileSystem::Get ().Open (fromFile, O_RDONLY);
int toFD = FileSystem::Get ().Open (toFile, O_RDWR | O_CREAT);
#endif
ifstream in = fromFD;
fstream out = toFD;
MyMPWObjectFile objFile;
if (verbose) diagnosticOut << "Reading object file... '" << fromFile << "'" << newline;
#if qMacOS
::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);
::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);
::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);
::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);
::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);
::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);
::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);
::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);
::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);
::SpinCursor(10);::SpinCursor(10);::SpinCursor(10);::SpinCursor(10);::SpinCursor(10);
::SpinCursor(10);::SpinCursor(10);::SpinCursor(10);::SpinCursor(10);::SpinCursor(10);
::SpinCursor(10);::SpinCursor(10);::SpinCursor(10);::SpinCursor(10);::SpinCursor(10);
::SpinCursor(10);::SpinCursor(10);::SpinCursor(10);::SpinCursor(10);::SpinCursor(10);
::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);
::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);
::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);
::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);
::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);
::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);
::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);
::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);
::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);
::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);
::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);
::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);
::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);
::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);
::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);::SpinCursor(1);
#endif
objFile.ReadFrom (in);
if (verbose) diagnosticOut << "Read " << objFile.GetRecords ().GetLength () << " records (pad not included)." << newline;
objFile.PrintModules ();
if (verbose) diagnosticOut << "Writing object file... '" << toFile << "'" << newline;
objFile.WriteTo (out);
if (verbose) diagnosticOut << "Wrote " << objFile.GetRecords ().GetLength () << " records (pad not included)." << newline;
::close (fromFD);
out.flush ();
::close (toFD);
}
// For gnuemacs:
// Local Variables: ***
// mode:C++ ***
// tab-width:4 ***
// End: ***
| 31.150442 | 123 | 0.658807 | [
"object"
] |
3c4ffb2cbd771c1f65b9bfa0b5ab2461aa3e7299 | 3,166 | hpp | C++ | include/data_structures/bit_vectors/support/bps_support_naive.hpp | jonas-ellert/xss-real | 0a526af5a7f29c42ceb52c2920581e62592373b0 | [
"MIT"
] | 4 | 2019-07-25T10:00:44.000Z | 2021-11-09T22:29:36.000Z | include/data_structures/bit_vectors/support/bps_support_naive.hpp | jonas-ellert/xss-real | 0a526af5a7f29c42ceb52c2920581e62592373b0 | [
"MIT"
] | null | null | null | include/data_structures/bit_vectors/support/bps_support_naive.hpp | jonas-ellert/xss-real | 0a526af5a7f29c42ceb52c2920581e62592373b0 | [
"MIT"
] | null | null | null | // Copyright (c) 2019 Jonas Ellert
//
// 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 <util/common.hpp>
template <typename bp_type>
class bps_support_naive {
private:
const bp_type& bp_;
std::vector<uint64_t> select_open_;
std::vector<uint64_t> select_close_;
public:
bps_support_naive(const bp_type& bp)
: bp_(bp),
select_open_((bp_.size() >> 1) + 1),
select_close_((bp_.size() >> 1) + 1) {
uint64_t ones = 0;
uint64_t zeros = 0;
for (uint64_t i = 0; i < bp_.size(); ++i) {
if (bp_[i])
select_open_[++ones] = i;
else
select_close_[++zeros] = i;
}
}
xssr_always_inline uint64_t enclose(const uint64_t bps_idx) const {
uint64_t result = bps_idx;
uint64_t excess = (bp_[result]) ? 1 : 2;
while (excess > 0) {
if (bp_[--result])
--excess;
else
++excess;
}
return result;
}
xssr_always_inline uint64_t find_close(const uint64_t bps_idx) const {
uint64_t result = bps_idx;
uint64_t excess = (bp_[result]) ? 1 : 0;
while (excess > 0) {
if (bp_[++result])
++excess;
else
--excess;
}
return result;
}
xssr_always_inline uint64_t parent_distance(const uint64_t bps_idx) const {
const uint64_t bps_idx_open_parent = enclose(bps_idx);
return (bps_idx - bps_idx_open_parent + 1) >> 1;
}
xssr_always_inline uint64_t subtree_size(const uint64_t bps_idx) const {
const uint64_t bps_idx_close_nss = find_close(bps_idx);
return (bps_idx_close_nss - bps_idx + 1) >> 1;
}
xssr_always_inline uint64_t
previous_value(const uint64_t preorder_number) const {
const uint64_t bps_idx_open_node = select_open_[preorder_number + 2];
const uint64_t parent_dist = parent_distance(bps_idx_open_node);
return preorder_number - parent_dist;
}
xssr_always_inline uint64_t next_value(const uint64_t preorder_number) const {
const uint64_t bps_idx_open_node = select_open_[preorder_number + 2];
const uint64_t subtree = subtree_size(bps_idx_open_node);
return preorder_number + subtree;
}
}; | 34.043011 | 80 | 0.698358 | [
"vector"
] |
3c552b647606e51354710658bbf302cd82dbb4d4 | 2,307 | cpp | C++ | src/condor_negotiator.V6/main.cpp | kurhula/HTCondor | 457d077e91900cd899b6254c4f0c8f582a70d0ea | [
"Apache-2.0"
] | null | null | null | src/condor_negotiator.V6/main.cpp | kurhula/HTCondor | 457d077e91900cd899b6254c4f0c8f582a70d0ea | [
"Apache-2.0"
] | null | null | null | src/condor_negotiator.V6/main.cpp | kurhula/HTCondor | 457d077e91900cd899b6254c4f0c8f582a70d0ea | [
"Apache-2.0"
] | 1 | 2021-02-20T15:22:30.000Z | 2021-02-20T15:22:30.000Z | /***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "subsystem_info.h"
#include "matchmaker.h"
#if defined(WANT_CONTRIB) && defined(WITH_MANAGEMENT)
#if defined(HAVE_DLOPEN) || defined(WIN32)
#include "NegotiatorPlugin.h"
#endif
#endif
// the matchmaker object
Matchmaker matchMaker;
void usage(char* name)
{
dprintf( D_ALWAYS, "Usage: %s [-f] [-t] [-n negotiator_name]", name);
exit( 1 );
}
void main_init (int argc, char *argv[])
{
const char *neg_name = NULL;
for ( int i = 1; i < argc; i++ ) {
if ( argv[i][0] == '-' && argv[i][1] == 'n' && (i + 1) < argc ) {
neg_name = argv[i + 1];
i++;
} else {
usage(argv[0]);
}
}
// read in params
matchMaker.initialize (neg_name);
}
void main_shutdown_graceful()
{
matchMaker.invalidateNegotiatorAd();
#if defined(WANT_CONTRIB) && defined(WITH_MANAGEMENT)
#if defined(HAVE_DLOPEN) || defined(WIN32)
NegotiatorPluginManager::Shutdown();
#endif
#endif
DC_Exit(0);
}
void main_shutdown_fast()
{
matchMaker.invalidateNegotiatorAd();
#if defined(WANT_CONTRIB) && defined(WITH_MANAGEMENT)
#if defined(HAVE_DLOPEN) || defined(WIN32)
NegotiatorPluginManager::Shutdown();
#endif
#endif
DC_Exit(0);
}
void
main_config()
{
matchMaker.reinitialize ();
}
int
main( int argc, char **argv )
{
set_mySubSystem( "NEGOTIATOR", SUBSYSTEM_TYPE_NEGOTIATOR );
dc_main_init = main_init;
dc_main_config = main_config;
dc_main_shutdown_fast = main_shutdown_fast;
dc_main_shutdown_graceful = main_shutdown_graceful;
return dc_main( argc, argv );
}
| 23.783505 | 75 | 0.671435 | [
"object"
] |
3c5571b643e71199655f4c10bb67afc21004ce9a | 2,569 | hh | C++ | Engine/spcCore/graphics/irendermesh.hh | marcellfischbach/SpiceEngine | e25e1e4145b7afaea9179bb8e33e4d184bd407c4 | [
"BSD-3-Clause"
] | null | null | null | Engine/spcCore/graphics/irendermesh.hh | marcellfischbach/SpiceEngine | e25e1e4145b7afaea9179bb8e33e4d184bd407c4 | [
"BSD-3-Clause"
] | 1 | 2021-09-09T12:51:56.000Z | 2021-09-09T12:51:56.000Z | Engine/spcCore/graphics/irendermesh.hh | marcellfischbach/SpiceEngine | e25e1e4145b7afaea9179bb8e33e4d184bd407c4 | [
"BSD-3-Clause"
] | null | null | null |
#pragma once
#include <spcCore/coreexport.hh>
#include <spcCore/class.hh>
#include <spcCore/types.hh>
#include <spcCore/math/boundingbox.hh>
#include <spcCore/math/vector2f.hh>
#include <spcCore/math/vector3f.hh>
#include <spcCore/math/vector4f.hh>
#include <spcCore/math/color4f.hh>
#include <spcCore/graphics/erenderpass.hh>
#include <vector>
namespace spc
{
struct iDevice;
class VertexDeclaration;
SPC_CLASS()
struct SPC_CORE_API iRenderMesh : SPC_SUPER(iObject)
{
SPC_CLASS_GEN;
~iRenderMesh() override = default;
SPC_NODISCARD virtual const BoundingBox &GetBoundingBox() const = 0;
SPC_NODISCARD virtual const VertexDeclaration &GetVertexDeclaration () const = 0;
virtual void Render(iDevice * graphics, eRenderPass pass) = 0;
#if _DEBUG
SPC_NODISCARD virtual Size GetNumberOfTriangles() const = 0;
#endif
};
SPC_CLASS()
struct SPC_CORE_API iRenderMeshGenerator : SPC_SUPER(iObject)
{
SPC_CLASS_GEN;
~iRenderMeshGenerator() override = default;
virtual void SetVertices(const std::vector<Vector2f> & vertices) = 0;
virtual void SetVertices(const std::vector<Vector3f> & vertices) = 0;
virtual void SetVertices(const std::vector<Vector4f> & vertices) = 0;
virtual void SetNormals(const std::vector<Vector3f> & normals) = 0;
virtual void SetColors(const std::vector<Color4f> & colors) = 0;
virtual void SetTangents(const std::vector<Vector3f> & tangents) = 0;
virtual void SetUV0(const std::vector<Vector2f> & uv) = 0;
virtual void SetUV0(const std::vector<Vector3f> & uv) = 0;
virtual void SetUV1(const std::vector<Vector2f> & uv) = 0;
virtual void SetUV2(const std::vector<Vector2f> & uv) = 0;
virtual void SetUV3(const std::vector<Vector2f> & uv) = 0;
virtual void SetIndices(const std::vector<UInt32> & indices) = 0;
SPC_NODISCARD virtual iRenderMesh* Generate() = 0;
};
SPC_CLASS()
struct SPC_CORE_API iRenderMeshGeneratorFactory : SPC_SUPER(iObject)
{
SPC_CLASS_GEN;
~iRenderMeshGeneratorFactory() override = default;
SPC_NODISCARD virtual iRenderMeshGenerator* Create() = 0;
};
SPC_CLASS()
struct SPC_CORE_API iRenderMeshBatchGenerator : SPC_SUPER(iObject)
{
SPC_CLASS_GEN;
~iRenderMeshBatchGenerator() override = default;
virtual void Add(const iRenderMesh* mesh, const Matrix4f &matrix) = 0;
SPC_NODISCARD virtual iRenderMesh* Generate() = 0;
};
SPC_CLASS()
struct SPC_CORE_API iRenderMeshBatchGeneratorFactory : SPC_SUPER(iObject)
{
SPC_CLASS_GEN;
~iRenderMeshBatchGeneratorFactory() override = default;
SPC_NODISCARD virtual iRenderMeshBatchGenerator* Create() = 0;
};
} | 26.760417 | 83 | 0.754379 | [
"mesh",
"render",
"vector"
] |
3c557b351bed50779b4a359cb0f5b6042b4fc614 | 2,284 | cpp | C++ | fbhackcup/2015/round2/10/10.cpp | mathemage/CompetitiveProgramming | fe39017e3b017f9259f9c1e6385549270940be64 | [
"MIT"
] | 2 | 2015-08-18T09:51:19.000Z | 2019-01-29T03:18:10.000Z | fbhackcup/2015/round2/10/10.cpp | mathemage/CompetitiveProgramming | fe39017e3b017f9259f9c1e6385549270940be64 | [
"MIT"
] | null | null | null | fbhackcup/2015/round2/10/10.cpp | mathemage/CompetitiveProgramming | fe39017e3b017f9259f9c1e6385549270940be64 | [
"MIT"
] | null | null | null | /* ========================================
ID: mathema6
TASK: 10
LANG: C++11
(...for USACO solutions)
* File Name : 10.cpp
* Creation Date : 24-01-2015
* Last Modified :
* Created By : Karel Ha <mathemage@gmail.com>
* URL : https://www.facebook.com/hackercup/problems.php?pid=193964420699886&round=323882677799153
* Points Gained (in case of online contest) : 10 -> got a T-shirt :D
==========================================*/
#include <bits/stdc++.h>
using namespace std;
#define FOR(I,A,B) for(int I = (A); I < (B); ++I)
#define REP(I,N) FOR(I,0,N)
#define ALL(A) (A).begin(), (A).end()
#define ERR(args...) { vector<string> _v = split(#args, ','); err(_v.begin(), args); }
vector<string> split(const string& s, char c) {
vector<string> v;
stringstream ss(s);
string x;
while (getline(ss, x, c))
v.emplace_back(x);
return move(v);
}
void err(vector<string>::iterator it) {}
template<typename T, typename... Args>
void err(vector<string>::iterator it, T a, Args... args) {
cout << it -> substr((*it)[0] == ' ', it -> length()) << " = " << a << '\n';
err(++it, args...);
}
int t,n;
int main() {
cin >> t;
REP(i,t) {
printf("Case #%d: ", i+1);
cin >> n;
vector<int> perm(n);
REP(j,n) cin >> perm[j];
int head, tail;
int b=0, t=n-1;
head = tail = perm[b++];
bool ok = true;
while (b <= t) {
if (perm[b] == head + 1) {
head = perm[b++];
} else if (perm[b] == tail - 1) {
tail = perm[b++];
} else if (perm[t] == head + 1) {
head = perm[t--];
} else if (perm[t] == tail - 1) {
tail = perm[t--];
} else {
ok = false;
break;
}
}
if (ok) {
cout << "yes\n";
continue;
}
b=0, t=n-1;
head = tail = perm[t--];
ok = true;
while (b <= t) {
if (perm[b] == head + 1) {
head = perm[b++];
} else if (perm[b] == tail - 1) {
tail = perm[b++];
} else if (perm[t] == head + 1) {
head = perm[t--];
} else if (perm[t] == tail - 1) {
tail = perm[t--];
} else {
ok = false;
break;
}
}
if (ok) {
cout << "yes\n";
continue;
}
cout << "no\n";
}
return 0;
}
| 21.752381 | 100 | 0.460158 | [
"vector"
] |
3c5801696c6db9d54ec71c560bd3f06dd419c707 | 7,604 | cpp | C++ | src/lowlevel/ansBatch.cpp | tabtre/nvcomp | a6e4e64a177e07cd2e5c8c5e07bb66ffefceae84 | [
"BSD-3-Clause"
] | null | null | null | src/lowlevel/ansBatch.cpp | tabtre/nvcomp | a6e4e64a177e07cd2e5c8c5e07bb66ffefceae84 | [
"BSD-3-Clause"
] | null | null | null | src/lowlevel/ansBatch.cpp | tabtre/nvcomp | a6e4e64a177e07cd2e5c8c5e07bb66ffefceae84 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2017-2021, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of NVIDIA CORPORATION nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "nvcomp/ans.h"
#include "Check.h"
#include "CudaUtils.h"
#include "common.h"
#include "nvcomp.h"
#include "nvcomp.hpp"
#include "type_macros.h"
#include <cassert>
#include <iostream>
#include <list>
#include <map>
#include <mutex>
#include <sstream>
#include <vector>
#ifdef ENABLE_ANS
#include "ans.h"
#endif
using namespace nvcomp;
#define MAYBE_UNUSED(x) (void)(x)
nvcompStatus_t nvcompBatchedANSDecompressGetTempSize(
const size_t num_chunks,
const size_t max_uncompressed_chunk_size,
size_t* const temp_bytes)
{
#ifdef ENABLE_ANS
CHECK_NOT_NULL(temp_bytes);
ans::decompressGetTempSize(num_chunks, max_uncompressed_chunk_size, temp_bytes);
return nvcompSuccess;
#else
(void)num_chunks;
(void)max_uncompressed_chunk_size;
(void)temp_bytes;
std::cerr << "ERROR: nvcomp configured without GPU ANS support\n"
<< "Please check the README for configuration instructions" << std::endl;
return nvcompErrorNotSupported;
#endif
}
nvcompStatus_t nvcompBatchedANSDecompressAsync(
const void* const* device_compressed_ptrs,
const size_t* device_compressed_bytes,
const size_t* device_uncompressed_bytes,
size_t* device_actual_uncompressed_bytes,
size_t batch_size,
void* const device_temp_ptr,
const size_t temp_bytes,
void* const* device_uncompressed_ptr,
nvcompStatus_t* device_statuses,
cudaStream_t stream)
{
#ifdef ENABLE_ANS
try {
ans::decompressAsync(
CudaUtils::device_pointer(device_compressed_ptrs),
CudaUtils::device_pointer(device_compressed_bytes),
CudaUtils::device_pointer(device_uncompressed_bytes),
device_actual_uncompressed_bytes ? CudaUtils::device_pointer(device_actual_uncompressed_bytes) : nullptr,
0, batch_size, device_temp_ptr, temp_bytes,
CudaUtils::device_pointer(device_uncompressed_ptr),
device_statuses ? CudaUtils::device_pointer(device_statuses) : nullptr,
stream);
} catch (const std::exception& e) {
return Check::exception_to_error(e, "nvcompBatchedANSDecompressAsync()");
}
return nvcompSuccess;
#else
(void)device_compressed_ptrs;
(void)device_compressed_bytes;
(void)device_uncompressed_bytes;
(void)device_actual_uncompressed_bytes;
(void)batch_size;
(void)device_temp_ptr;
(void)temp_bytes;
(void)device_uncompressed_ptr;
(void)device_statuses;
(void)stream;
std::cerr << "ERROR: nvcomp configured without GPU ANS support\n"
<< "Please check the README for configuration instructions" << std::endl;
return nvcompErrorNotSupported;
#endif
}
nvcompStatus_t nvcompBatchedANSCompressGetTempSize(
size_t batch_size,
size_t max_chunk_size,
nvcompBatchedANSOpts_t /* format_opts */,
size_t* temp_bytes)
{
#ifdef ENABLE_ANS
CHECK_NOT_NULL(temp_bytes);
ans::compressGetTempSize(batch_size, max_chunk_size, temp_bytes);
return nvcompSuccess;
#else
(void)batch_size;
(void)max_chunk_size;
(void)temp_bytes;
std::cerr << "ERROR: nvcomp configured without GPU ANS support\n"
<< "Please check the README for configuration instructions" << std::endl;
return nvcompErrorNotSupported;
#endif
}
nvcompStatus_t nvcompBatchedANSCompressGetMaxOutputChunkSize(
size_t max_chunk_size,
nvcompBatchedANSOpts_t /* format_opts */,
size_t* max_compressed_size)
{
#ifdef ENABLE_ANS
CHECK_NOT_NULL(max_compressed_size);
ans::compressGetMaxOutputChunkSize(max_chunk_size, max_compressed_size);
return nvcompSuccess;
#else
(void)max_chunk_size;
(void)max_compressed_size;
std::cerr << "ERROR: nvcomp configured without GPU ANS support\n"
<< "Please check the README for configuration instructions" << std::endl;
return nvcompErrorNotSupported;
#endif
}
nvcompStatus_t nvcompBatchedANSCompressAsync(
const void* const* device_uncompressed_ptr,
const size_t* device_uncompressed_bytes,
size_t max_uncompressed_chunk_bytes,
size_t batch_size,
void* device_temp_ptr,
size_t temp_bytes,
void* const* device_compressed_ptr,
size_t* device_compressed_bytes,
nvcompBatchedANSOpts_t format_opts,
cudaStream_t stream)
{
#ifdef ENABLE_ANS
assert(format_opts.type == nvcompANSType_t::nvcomp_rANS);
MAYBE_UNUSED(format_opts);
ans::ansType_t ans_type = ans::ansType_t::rANS;
try {
ans::compressAsync(
ans_type,
CudaUtils::device_pointer(device_uncompressed_ptr),
CudaUtils::device_pointer(device_uncompressed_bytes),
max_uncompressed_chunk_bytes,
batch_size,
device_temp_ptr,
temp_bytes,
CudaUtils::device_pointer(device_compressed_ptr),
CudaUtils::device_pointer(device_compressed_bytes),
stream);
} catch (const std::exception& e) {
return Check::exception_to_error(e, "nvcompBatchedANSCompressAsync()");
}
return nvcompSuccess;
#else
(void)device_uncompressed_ptr;
(void)device_uncompressed_bytes;
(void)max_uncompressed_chunk_bytes;
(void)batch_size;
(void)device_temp_ptr;
(void)temp_bytes;
(void)device_compressed_ptr;
(void)device_compressed_bytes;
(void)format_opts;
(void)stream;
std::cerr << "ERROR: nvcomp configured without GPU ANS support\n"
<< "Please check the README for configuration instructions" << std::endl;
return nvcompErrorNotSupported;
#endif
}
nvcompStatus_t nvcompBatchedANSGetDecompressSizeAsync(
const void* const* device_compressed_ptrs,
const size_t* /* device_compressed_bytes */,
size_t* device_uncompressed_bytes,
size_t batch_size,
cudaStream_t stream) {
#ifdef ENABLE_ANS
ans::getDecompressSizeAsync(
device_compressed_ptrs,
device_uncompressed_bytes,
batch_size,
stream);
return nvcompSuccess;
#else
(void)device_compressed_ptrs;
(void)device_uncompressed_bytes;
(void)batch_size;
(void)stream;
std::cerr << "ERROR: nvcomp configured without GPU ANS support\n"
<< "Please check the README for configuration instructions" << std::endl;
return nvcompErrorNotSupported;
#endif
}
| 33.350877 | 111 | 0.754077 | [
"vector"
] |
3c5f4d748edc97390d8f572e33cb39a2aab3a06d | 3,235 | cpp | C++ | SFMLGameOfLife/PlayState.cpp | MatthewMcDade13/SFMLGameOfLife | fa020e3cc415d704f9dd43286aa12607d8b57cbe | [
"Zlib"
] | 1 | 2017-12-17T23:22:46.000Z | 2017-12-17T23:22:46.000Z | SFMLGameOfLife/PlayState.cpp | MatthewMcDade13/SFMLGameOfLife | fa020e3cc415d704f9dd43286aa12607d8b57cbe | [
"Zlib"
] | null | null | null | SFMLGameOfLife/PlayState.cpp | MatthewMcDade13/SFMLGameOfLife | fa020e3cc415d704f9dd43286aa12607d8b57cbe | [
"Zlib"
] | null | null | null | #include "stdafx.h"
#include "PlayState.h"
#include "StateManager.h"
#include "Context.h"
#include "GameSettings.h"
#include "Grid.h"
#include "Cell.h"
#include "GameSpeed.h"
using namespace std;
PlayState::PlayState(StateManager* manager, GameSettings* settings)
: State(manager), m_settings(settings),
m_genDelay(0.1f), m_gameSpeed(GameSpeed::Fast),
m_bAddCells(true), m_grid(nullptr)
{
}
PlayState::~PlayState()
{
}
void PlayState::update(float deltaTime)
{
if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
sf::Vector2i mousePos = sf::Mouse::getPosition(*m_stateManager->getContext()->window);
const int mouseX = mousePos.x;
const int mouseY = mousePos.y;
const sf::Vector2i gridSize = (sf::Vector2i)m_grid->getSize();
// Only get cell being click on if mouse click is within area of grid
if ((mouseX <= gridSize.x && mouseX >= 0) &&
mouseY <= gridSize.y && mouseY >= 0)
{
Cell& cell = m_grid->getCell(mousePos.x / m_grid->getCellSize(), mousePos.y / m_grid->getCellSize());
if (m_bAddCells)
{
cell.birth();
}
else
{
cell.die();
}
}
}
if (!m_bPaused && m_genClock.getElapsedTime().asSeconds() >= (m_genDelay * deltaTime))
{
m_genClock.restart();
updateCells();
}
}
void PlayState::draw(sf::RenderWindow & window)
{
window.draw(*m_grid);
}
void PlayState::activate()
{
}
void PlayState::deactivate()
{
}
void PlayState::onCreate()
{
m_grid = make_unique<Grid>(m_settings->gridWidth, m_settings->gridHeight, m_settings->cellSize);
}
void PlayState::onDestroy()
{
}
void PlayState::handleInput(const sf::Event & event)
{
if (event.type == sf::Event::KeyReleased)
{
if (event.key.code == sf::Keyboard::E)
{
m_bAddCells = !m_bAddCells;
}
if (event.key.code == sf::Keyboard::P)
{
m_bPaused = !m_bPaused;
}
if (event.key.code == sf::Keyboard::Right)
{
GameSpeed gs = m_gameSpeed;
int nextSpeed = static_cast<int>(gs);
nextSpeed++;
if (nextSpeed <= static_cast<int>(GameSpeed::Full))
{
gs++;
m_gameSpeed = gs;
}
setGenerationDelay(m_gameSpeed);
}
if (event.key.code == sf::Keyboard::Left)
{
GameSpeed gs = m_gameSpeed;
int nextSpeed = static_cast<int>(gs);
nextSpeed--;
if (nextSpeed >= static_cast<int>(GameSpeed::Slow))
{
gs--;
m_gameSpeed = gs;
}
setGenerationDelay(m_gameSpeed);
}
if (event.key.code == sf::Keyboard::R)
{
m_grid->randomizeCells();
}
if (event.key.code == sf::Keyboard::C)
{
m_grid->clearCells();
}
}
}
void PlayState::updateCells()
{
std::vector<CellState>& prevStates = m_grid->getCellStates();
for (size_t i = 0; i < m_grid->getCells().size(); i++)
{
(*m_grid)[i].update(prevStates, *m_grid);
}
//parallelFor(0, m_grid->getCells().size(), [this, &prevStates](int i) {
// (*m_grid)[i].update(prevStates, *m_grid);
//});
}
void PlayState::setGenerationDelay(GameSpeed gs)
{
switch (gs)
{
case GameSpeed::Slow: m_genDelay = 8.f; break;
case GameSpeed::SlowMedium: m_genDelay = 6.f; break;
case GameSpeed::Medium: m_genDelay = 4.5f; break;
case GameSpeed::MediumFast: m_genDelay = 3.f; break;
case GameSpeed::Fast: m_genDelay = 1.5f; break;
case GameSpeed::Full: m_genDelay = 0.f; break;
}
}
| 19.72561 | 104 | 0.654405 | [
"vector"
] |
3c6420d3bfa67fd30f000f01c6e57c1b3e469c84 | 15,670 | cc | C++ | examples/other-fattree.cc | kphf1995cm/P4Simulator | f0c79f0af6f25fa2422b98e3b6ecb05a34377056 | [
"Apache-2.0"
] | 4 | 2018-07-21T00:47:22.000Z | 2021-09-23T08:55:35.000Z | examples/other-fattree.cc | kphf1995cm/P4Simulator | f0c79f0af6f25fa2422b98e3b6ecb05a34377056 | [
"Apache-2.0"
] | null | null | null | examples/other-fattree.cc | kphf1995cm/P4Simulator | f0c79f0af6f25fa2422b98e3b6ecb05a34377056 | [
"Apache-2.0"
] | 1 | 2020-11-05T04:43:22.000Z | 2020-11-05T04:43:22.000Z | /*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Authors: Linh Vu <linhvnl89@gmail.com>, Daji Wong <wong0204@e.ntu.edu.sg>
*/
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include <unistd.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <unordered_map>
#include "ns3/flow-monitor-module.h"
#include "ns3/bridge-helper.h"
#include "ns3/bridge-net-device.h"
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h"
#include "ns3/ipv4-global-routing-helper.h"
#include "ns3/csma-module.h"
#include "ns3/ipv4-nix-vector-helper.h"
//#include "ns3/random-variable.h"
/*
- This work goes along with the paper "Towards Reproducible Performance Studies of Datacenter Network Architectures Using An Open-Source Simulation Approach"
- The code is constructed in the following order:
1. Creation of Node Containers
2. Initialize settings for On/Off Application
3. Connect hosts to edge switches
4. Connect edge switches to aggregate switches
5. Connect aggregate switches to core switches
6. Start Simulation
- Addressing scheme:
1. Address of host: 10.pod.switch.0 /24
2. Address of edge and aggregation switch: 10.pod.switch.0 /16
3. Address of core switch: 10.(group number + k).switch.0 /8
(Note: there are k/2 group of core switch)
- On/Off Traffic of the simulation: addresses of client and server are randomly selected everytime
- Simulation Settings:
- Number of pods (k): 4-24 (run the simulation with varying values of k)
- Number of nodes: 16-3456
- Simulation running time: 100 seconds
- Packet size: 1024 bytes
- Data rate for packet sending: 1 Mbps
- Data rate for device channel: 1000 Mbps
- Delay time for device: 0.001 ms
- Communication pairs selection: Random Selection with uniform probability
- Traffic flow pattern: Exponential random traffic
- Routing protocol: Nix-Vector
- Statistics Output:
- Flowmonitor XML output file: Fat-tree.xml is located in the /statistics folder
*/
using namespace ns3;
using namespace std;
NS_LOG_COMPONENT_DEFINE("p4-example");
static void SinkRx(Ptr<const Packet> p, const Address &ad) {
std::cout << "Rx" << "Received from " << ad << std::endl;
}
unsigned long getTickCount(void)
{
unsigned long currentTime = 0;
#ifdef WIN32
currentTime = GetTickCount();
#endif
struct timeval current;
gettimeofday(¤t, NULL);
currentTime = current.tv_sec * 1000 + current.tv_usec / 1000;
#ifdef OS_VXWORKS
ULONGA timeSecond = tickGet() / sysClkRateGet();
ULONGA timeMilsec = tickGet() % sysClkRateGet() * 1000 / sysClkRateGet();
currentTime = timeSecond * 1000 + timeMilsec;
#endif
return currentTime;
}
// Function to create address string from numbers
//
char * toString(int a, int b, int c, int d) {
int first = a;
int second = b;
int third = c;
int fourth = d;
char *address = new char[30];
char firstOctet[30], secondOctet[30], thirdOctet[30], fourthOctet[30];
//address = firstOctet.secondOctet.thirdOctet.fourthOctet;
bzero(address, 30);
snprintf(firstOctet, 10, "%d", first);
strcat(firstOctet, ".");
snprintf(secondOctet, 10, "%d", second);
strcat(secondOctet, ".");
snprintf(thirdOctet, 10, "%d", third);
strcat(thirdOctet, ".");
snprintf(fourthOctet, 10, "%d", fourth);
strcat(thirdOctet, fourthOctet);
strcat(secondOctet, thirdOctet);
strcat(firstOctet, secondOctet);
strcat(address, firstOctet);
return address;
}
struct SwitchInfo_t
{
public:
SwitchInfo_t()
:packetNum(0)
{}
unsigned long packetNum;
std::unordered_map<unsigned long, unsigned int> tupleNum;
};
typedef std::unordered_map<unsigned long, unsigned int>::iterator TupleIter_t;
void ShowSwitchInfo(SwitchInfo_t& s )
{
std::cout << "Packet Num:" << s.packetNum << std::endl;
std::cout << "Packet Tuple Num:(format tupleHash packetNum)" << std::endl;
for (TupleIter_t iter = s.tupleNum.begin(); iter != s.tupleNum.end(); iter++)
{
std::cout << iter->first << iter->second << std::endl;
}
}
// Main function
//
int
main(int argc, char *argv[])
{
unsigned long start = getTickCount();
//LogComponentEnable ("P4Example", LOG_LEVEL_LOGIC);
//LogComponentEnable ("P4Helper", LOG_LEVEL_LOGIC);
// LogComponentEnable ("P4NetDevice", LOG_LEVEL_LOGIC);
//LogComponentEnable("BridgeNetDevice", LOG_LEVEL_LOGIC);
//LogComponentEnable("PointToPointNetDevice", LOG_LEVEL_LOGIC);
//LogComponentEnable("CsmaNetDevice",LOG_LEVEL_LOGIC);
int pod = 4;
CommandLine cmd;
cmd.AddValue("pod", "Numbers of pod", pod);
cmd.Parse(argc, argv);
//=========== Define parameters based on value of k ===========//
//
int k = pod; // number of ports per switch
int num_pod = k; // number of pod
int num_host = (k / 2); // number of hosts under a switch
int num_edge = (k / 2); // number of edge switch in a pod
int num_bridge = num_edge; // number of bridge in a pod
int num_agg = (k / 2); // number of aggregation switch in a pod
int num_group = k / 2; // number of group of core switches
int num_core = (k / 2); // number of core switch in a group
int total_host = k*k*k / 4; // number of hosts in the entire network
//char filename [] = "Fat-tree.xml";// filename for Flow Monitor xml output file
// Define variables for On/Off Application
// These values will be used to serve the purpose that addresses of server and client are selected randomly
// Note: the format of host's address is 10.pod.switch.(host+2)
//
//int podRand = 0; //
//int swRand = 0; // Random values for servers' address
//int hostRand = 0; //
//int rand1 =0; //
//int rand2 =0; // Random values for clients' address
//int rand3 =0; //
// Initialize other variables
//
int i = 0;
int j = 0;
int h = 0;
// Initialize parameters for On/Off application
//
//int port = 9;
int packetSize = 1024; // 1024 bytes
char dataRate_OnOff[] = "1Mbps";
unsigned int maxBytes = packetSize; // unlimited
// Initialize parameters for Csma and PointToPoint protocol
//
char dataRate[] = "1000Mbps"; // 1Gbps
int delay = 0.001; // 0.001 ms
// Output some useful information
//
std::cout << "Value of k = " << k << "\n";
std::cout << "Total number of hosts = " << total_host << "\n";
std::cout << "Number of hosts under each switch = " << num_host << "\n";
std::cout << "Number of edge switch under each pod = " << num_edge << "\n";
std::cout << "------------- " << "\n";
// Initialize Internet Stack and Routing Protocols
//
InternetStackHelper internet;
Ipv4NixVectorHelper nixRouting;
Ipv4StaticRoutingHelper staticRouting;
Ipv4ListRoutingHelper list;
list.Add(staticRouting, 0);
list.Add(nixRouting, 10);
internet.SetRoutingHelper(list);
//=========== Creation of Node Containers ===========//
//
NodeContainer core[num_group]; // NodeContainer for core switches
for (i = 0; i<num_group; i++) {
core[i].Create(num_core);
internet.Install(core[i]);
}
NodeContainer agg[num_pod]; // NodeContainer for aggregation switches
for (i = 0; i<num_pod; i++) {
agg[i].Create(num_agg);
internet.Install(agg[i]);
}
NodeContainer edge[num_pod]; // NodeContainer for edge switches
for (i = 0; i<num_pod; i++) {
edge[i].Create(num_bridge);
internet.Install(edge[i]);
}
NodeContainer bridge[num_pod]; // NodeContainer for edge bridges
for (i = 0; i<num_pod; i++) {
bridge[i].Create(num_bridge);
internet.Install(bridge[i]);
}
NodeContainer host[num_pod][num_bridge]; // NodeContainer for hosts
for (i = 0; i<k; i++) {
for (j = 0; j<num_bridge; j++) {
host[i][j].Create(num_host);
internet.Install(host[i][j]);
}
}
//=========== Initialize settings for On/Off Application ===========//
//
// Generate traffics for the simulation
//
ApplicationContainer app[total_host];
char *addr;
//add = toString(10, 0, 0, 2);
int half_host_num = total_host / 2;
half_host_num=1;
for (int client_i = 0; client_i < half_host_num; client_i++)
{
int server_i = total_host - client_i - 1;
int s_p, s_q, s_t;
s_p = server_i / (num_edge*num_host);
s_q = (server_i - s_p*num_edge*num_host) / num_host;
s_t = server_i%num_host;
//std::cout<<client_i<<" "<<server_i<<std::endl;
//std::cout<<s_p<<" "<<s_q<<" "<<s_t<<std::endl;
int p, q, t;
p = client_i / (num_edge*num_host);
q = (client_i - p*num_edge*num_host) / num_host;
t = client_i%num_host;
//std::cout<<p<<" "<<q<<" "<<t<<std::endl;
addr = toString(10, s_p, s_q, s_t + 2);
//OnOffHelper oo = OnOffHelper("ns3::TcpSocketFactory", Address(InetSocketAddress(Ipv4Address(addr), port))); // ip address of server
InetSocketAddress dst=InetSocketAddress(Ipv4Address(addr));
OnOffHelper oo = OnOffHelper("ns3::TcpSocketFactory",dst); // ip address of server
oo.SetAttribute("PacketSize", UintegerValue(packetSize));
oo.SetAttribute("DataRate", StringValue(dataRate_OnOff));
oo.SetAttribute("MaxBytes", UintegerValue(maxBytes));
NodeContainer onoff;
onoff.Add(host[p][q].Get(t));
app[client_i] = oo.Install(onoff);
PacketSinkHelper sink = PacketSinkHelper("ns3::TcpSocketFactory",dst);
ApplicationContainer sinkApp = sink.Install(host[s_p][s_q].Get(s_t));
sinkApp.Start(Seconds(0.0));
sinkApp.Stop(Seconds(101.0));
}
std::cout << "Finished creating On/Off traffic" << "\n";
// Inintialize Address Helper
//
Ipv4AddressHelper address;
// Initialize PointtoPoint helper
//
PointToPointHelper p2p;
p2p.SetDeviceAttribute("DataRate", StringValue(dataRate));
p2p.SetChannelAttribute("Delay", TimeValue(MilliSeconds(delay)));
// Initialize Csma helper
//
CsmaHelper csma;
csma.SetChannelAttribute("DataRate", StringValue(dataRate));
csma.SetChannelAttribute("Delay", TimeValue(MilliSeconds(delay)));
//=========== Connect edge switches to hosts ===========//
//
NetDeviceContainer hostSw[num_pod][num_bridge];
NetDeviceContainer bridgeDevices[num_pod][num_bridge];
Ipv4InterfaceContainer ipContainer[num_pod][num_bridge];
for (i = 0; i<num_pod; i++) {
for (j = 0; j<num_bridge; j++) {
//NetDeviceContainer link1 = csma.Install(NodeContainer(edge[i].Get(j), bridge[i].Get(j)));
std::vector<Ptr<CsmaNetDevice>> link3=csma.InstallSelf(NodeContainer(edge[i].Get(j), bridge[i].Get(j)));
NetDeviceContainer link1;
link1.Add(link3[0]);
link1.Add(link3[1]);
hostSw[i][j].Add(link1.Get(0));
bridgeDevices[i][j].Add(link1.Get(1));
for (h = 0; h< num_host; h++) {
NetDeviceContainer link2 = csma.Install(NodeContainer(host[i][j].Get(h), bridge[i].Get(j)));
hostSw[i][j].Add(link2.Get(0));
bridgeDevices[i][j].Add(link2.Get(1));
}
BridgeHelper bHelper;
bHelper.Install(bridge[i].Get(j), bridgeDevices[i][j]);
//Assign address
char *subnet;
subnet = toString(10, i, j, 0);
address.SetBase(subnet, "255.255.255.0");
ipContainer[i][j] = address.Assign(hostSw[i][j]);
}
}
std::cout << "Finished connecting edge switches and hosts " << "\n";
//=========== Connect aggregate switches to edge switches ===========//
//
NetDeviceContainer ae[num_pod][num_agg][num_edge];
Ipv4InterfaceContainer ipAeContainer[num_pod][num_agg][num_edge];
for (i = 0; i<num_pod; i++) {
for (j = 0; j<num_agg; j++) {
for (h = 0; h<num_edge; h++) {
ae[i][j][h] = p2p.Install(agg[i].Get(j), edge[i].Get(h));
int second_octet = i;
int third_octet = j + (k / 2);
int fourth_octet;
if (h == 0) fourth_octet = 1;
else fourth_octet = h * 2 + 1;
//Assign subnet
char *subnet;
subnet = toString(10, second_octet, third_octet, 0);
//Assign base
char *base;
base = toString(0, 0, 0, fourth_octet);
address.SetBase(subnet, "255.255.255.0", base);
ipAeContainer[i][j][h] = address.Assign(ae[i][j][h]);
}
}
}
std::cout << "Finished connecting aggregation switches and edge switches " << "\n";
//=========== Connect core switches to aggregate switches ===========//
//
NetDeviceContainer ca[num_group][num_core][num_pod];
Ipv4InterfaceContainer ipCaContainer[num_group][num_core][num_pod];
int fourth_octet = 1;
for (i = 0; i<num_group; i++) {
for (j = 0; j < num_core; j++) {
fourth_octet = 1;
for (h = 0; h < num_pod; h++) {
ca[i][j][h] = p2p.Install(core[i].Get(j), agg[h].Get(i));
int second_octet = k + i;
int third_octet = j;
//Assign subnet
char *subnet;
subnet = toString(10, second_octet, third_octet, 0);
//Assign base
char *base;
base = toString(0, 0, 0, fourth_octet);
address.SetBase(subnet, "255.255.255.0", base);
ipCaContainer[i][j][h] = address.Assign(ca[i][j][h]);
fourth_octet += 2;
}
}
}
std::cout << "Finished connecting core switches and aggregation switches " << "\n";
std::cout << "------------- " << "\n";
//=========== Show Switch Received Packet Num ===========//
//
/*SwitchInfo_t coreInfos[num_group][num_core];
SwitchInfo_t aggInfos[num_pod][num_agg];
SwitchInfo_t edgeInfos[num_pod][num_edge];
std::unordered_map<unsigned long, unsigned int> tempTupleNum;
//unsigned long tempPacketNum;
Ptr<PointToPointNetDevice> tempNetDevice;
for (i = 0; i < num_group; i++)
{
for (j = 0; j < num_core; j++)
{
for (h = 0; h < num_pod; h++)
{
tempNetDevice = (Ptr<PointToPointNetDevice>)ca[i][j][h].Get(0);
coreInfos[i][j].packetNum += tempNetDevice->m_packetNum;
tempTupleNum = tempNetDevice->m_tupleNum;
for (TupleIter_t iter = tempTupleNum.begin(); iter != tempTupleNum.end(); iter++)
{
unsigned long key = iter->first;
unsigned int value = iter->second;
coreInfos[i][j].tupleNum[key] += value;
}
}
ShowSwitchInfo(coreInfos[i][j]);
}
}*/
//=========== Start the simulation ===========//
//
std::cout << "Start Simulation.. " << "\n";
// start server sink
// PacketSinkHelper sink = PacketSinkHelper("ns3::TcpSocketFactory", Ipv4Address(add));
// ApplicationContainer sinkApp = sink.Install(host[0][0].Get(0));
// sinkApp.Start(Seconds(0.0));
// sinkApp.Stop(Seconds(101.0));
// start client onoff
for (i = 0; i<total_host; i++) {
app[i].Start(Seconds(1.0));
app[i].Stop(Seconds(100.0));
}
Ipv4GlobalRoutingHelper::PopulateRoutingTables();
// Calculate Throughput using Flowmonitor
//
// FlowMonitorHelper flowmon;
// Ptr<FlowMonitor> monitor = flowmon.InstallAll();
// Run simulation.
//
unsigned long simulate_start = getTickCount();
NS_LOG_INFO("Run Simulation.");
Simulator::Stop(Seconds(101.0));
Config::ConnectWithoutContext("/NodeList/3/ApplicationList/0/$ns3::PacketSink/Rx",
MakeCallback(&SinkRx));
Packet::EnablePrinting ();
Simulator::Run();
// monitor->CheckForLostPackets ();
// monitor->SerializeToXmlFile(filename, true, true);
std::cout << "Simulation finished " << "\n";
Simulator::Destroy();
NS_LOG_INFO("Done.");
unsigned long end = getTickCount();
std::cout << "Simulate Running time: " << end - simulate_start << "ms" << std::endl;
std::cout << "Running time: " << end - start << "ms" << std::endl;
return 0;
}
| 32.577963 | 157 | 0.672049 | [
"vector"
] |
3c65f22c5c356db3a70c5cecb3ce2813cef477ea | 2,017 | cpp | C++ | src/chrono_models/vehicle/sedan/Sedan_Driveline2WD.cpp | zzhou292/chrono-collision | c2a20e171bb0eb8819636d370887aa32d68547c6 | [
"BSD-3-Clause"
] | 1 | 2020-01-18T02:39:17.000Z | 2020-01-18T02:39:17.000Z | src/chrono_models/vehicle/sedan/Sedan_Driveline2WD.cpp | zzhou292/chrono-collision | c2a20e171bb0eb8819636d370887aa32d68547c6 | [
"BSD-3-Clause"
] | null | null | null | src/chrono_models/vehicle/sedan/Sedan_Driveline2WD.cpp | zzhou292/chrono-collision | c2a20e171bb0eb8819636d370887aa32d68547c6 | [
"BSD-3-Clause"
] | 1 | 2019-07-16T00:23:00.000Z | 2019-07-16T00:23:00.000Z | // =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Alessandro Tasora, Radu Serban, Asher Elmquist
// =============================================================================
//
// Sedan 2WD driveline model based on ChShaft objects.
//
// =============================================================================
#include "chrono_models/vehicle/sedan/Sedan_Driveline2WD.h"
namespace chrono {
namespace vehicle {
namespace sedan {
// -----------------------------------------------------------------------------
// Static variables
// -----------------------------------------------------------------------------
const double Sedan_Driveline2WD::m_driveshaft_inertia = 0.5;
const double Sedan_Driveline2WD::m_differentialbox_inertia = 0.6;
const double Sedan_Driveline2WD::m_conicalgear_ratio = -0.2;
const double Sedan_Driveline2WD::m_differential_ratio = -1;
const double Sedan_Driveline2WD::m_axle_differential_locking_limit = 100;
// -----------------------------------------------------------------------------
// Constructor of the Sedan_Driveline2WD.
// the direction of the motor block is along the X axis, while the directions of
// the axles is along the Y axis (relative to the chassis coordinate frame),
// -----------------------------------------------------------------------------
Sedan_Driveline2WD::Sedan_Driveline2WD(const std::string& name) : ChShaftsDriveline2WD(name) {
SetMotorBlockDirection(ChVector<>(1, 0, 0));
SetAxleDirection(ChVector<>(0, 1, 0));
}
} // end namespace sedan
} // end namespace vehicle
} // end namespace chrono
| 41.163265 | 94 | 0.518592 | [
"model"
] |
3c6e55b775f86543c6bc77fd0dd934cce9edf26b | 2,024 | cpp | C++ | igraph-0.6.5/optional/simpleraytracer/Shape.cpp | bestephe/res-sim | a251816c457259c38aab15081e959905783dcaa4 | [
"BSD-2-Clause"
] | 3 | 2017-09-05T03:06:12.000Z | 2019-04-28T13:17:11.000Z | igraph-0.6.5/optional/simpleraytracer/Shape.cpp | bestephe/res-sim | a251816c457259c38aab15081e959905783dcaa4 | [
"BSD-2-Clause"
] | null | null | null | igraph-0.6.5/optional/simpleraytracer/Shape.cpp | bestephe/res-sim | a251816c457259c38aab15081e959905783dcaa4 | [
"BSD-2-Clause"
] | 1 | 2019-03-05T06:24:02.000Z | 2019-03-05T06:24:02.000Z | #include "Shape.h"
#include "unit_limiter.h"
Shape::Shape()
{
mName = 0;
mAmbientReflectivity = .6;
mSpecularReflectivity = 0;
mDiffuseReflectivity = 0;
mSpecularSize = 64;
}
Shape::~Shape()
{}
int Shape::Name() const
{
return mName;
}
void Shape::Name(int vName)
{
mName = vName;
}
const Color& Shape::ShapeColor() const
{
return mShapeColor;
}
void Shape::ShapeColor(const Color& rColor)
{
mShapeColor = rColor;
}
double Shape::AmbientReflectivity() const
{
return mAmbientReflectivity;
}
double Shape::SpecularReflectivity() const
{
return mSpecularReflectivity;
}
double Shape::DiffuseReflectivity() const
{
return mDiffuseReflectivity;
}
void Shape::AmbientReflectivity(double rReflectivity)
{
mAmbientReflectivity = unit_limiter(rReflectivity);
}
void Shape::SpecularReflectivity(double rReflectivity)
{
mSpecularReflectivity = unit_limiter(rReflectivity);
}
void Shape::DiffuseReflectivity(double rReflectivity)
{
mDiffuseReflectivity = unit_limiter(rReflectivity);
}
Ray Shape::Reflect(const Point& rReflectFrom, const Ray& rIncidentRay) const
{
Ray result; // the reflected ray
Vector result_direction; // the reflected direction vector
Vector incident_unit = rIncidentRay.Direction().Normalize();
Vector normal = this->Normal(rReflectFrom, rIncidentRay.Origin() );
if ( !normal.IsSameDirection(incident_unit) )
normal.ReverseDirection(); // we want the normal in the same direction of the incident ray.
result.Origin(rReflectFrom);
result.Direction( normal*2.0*normal.Dot(incident_unit) - incident_unit );
/*
if ( normal.Dot(rIncidentRay.Direction().Normalize()) < 0.0 )
normal.ReverseDirection();
result.Origin(rReflectFrom);
result.Direction((normal*2.0) - rIncidentRay.Direction().Normalize());
*/
return result;
}
const string& Shape::Type() const
{
return mType;
}
void Shape::Type(const string& rType)
{
mType = rType;
}
int Shape::SpecularSize() const
{
return mSpecularSize;
}
void Shape::SpecularSize(int vSpecularSize)
{
mSpecularSize = vSpecularSize;
}
| 19.650485 | 93 | 0.750988 | [
"shape",
"vector"
] |
3c6f7d450f6f234daf6456251ad77c7a298b6b33 | 1,926 | cpp | C++ | oi/vijos/P1906/main.cpp | Riteme/test | b511d6616a25f4ae8c3861e2029789b8ee4dcb8d | [
"BSD-Source-Code"
] | 3 | 2018-08-30T09:43:20.000Z | 2019-12-03T04:53:43.000Z | oi/vijos/P1906/main.cpp | Riteme/test | b511d6616a25f4ae8c3861e2029789b8ee4dcb8d | [
"BSD-Source-Code"
] | null | null | null | oi/vijos/P1906/main.cpp | Riteme/test | b511d6616a25f4ae8c3861e2029789b8ee4dcb8d | [
"BSD-Source-Code"
] | null | null | null | #include <cstring>
#include <cstdio>
#include <list>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
#define L 2
#define MOD 10007
#define N 200010
struct P {
P(int V, int D) {
v = V;
d = D;
}
int v;
int d;
}; // struct P
static vector<int> G[N];
static int W[N];
static bool marked[N];
static int max = 0;
static int sum = 0;
static int n;
void BFS() {
queue<P> p;
for (int i = 1; i <= n; i++) {
memset(marked, false, sizeof(bool) * N);
marked[i] = true;
p.push(P(i, 0));
while (!p.empty()) {
P v = p.front();
p.pop();
if (v.d == L) {
int s = W[i] * W[v.v];
sum = (sum + s) % MOD;
if (::max < s) { ::max = s; }
} else {
for (vector<int>::iterator beg = G[v.v].begin();
beg != G[v.v].end();
beg++) {
if (!marked[*beg]) {
p.push(P(*beg, v.d + 1));
marked[*beg] = true;
}
} // for
}
} // while
} // for
}
inline int Read(void) {
int result = 0;
char c;
c = getchar();
while (c == ' ' or c == '\n') { c = getchar(); } // while
while (c != ' ' and c != '\n') {
result = result * 10 + (c - '0');
c = getchar();
} // while
return result;
}
int main() {
// scanf("%d", &n);
n = Read();
for (int i = 1; i <= n - 1; i++) {
int u, v;
u = Read();
v = Read();
// scanf("%d %d", &u, &v);
G[u].push_back(v);
G[v].push_back(u);
} // for
for (int i = 1; i <= n; i++) {
W[i] = Read();
// scanf("%d", &W[i]);
} // for
BFS();
printf("%d %d", ::max, sum);
return 0;
} // function main
| 18.169811 | 64 | 0.379543 | [
"vector"
] |
3c74e8f296067e1078a50bcf7ccb3b721ee582b0 | 538 | hpp | C++ | VS2019 Solution/Snake/Board.hpp | Toggy-Smith/Snake | 270c9d757dd8f4d3d4851ea1a67ecbd9afc26b1c | [
"MIT"
] | null | null | null | VS2019 Solution/Snake/Board.hpp | Toggy-Smith/Snake | 270c9d757dd8f4d3d4851ea1a67ecbd9afc26b1c | [
"MIT"
] | null | null | null | VS2019 Solution/Snake/Board.hpp | Toggy-Smith/Snake | 270c9d757dd8f4d3d4851ea1a67ecbd9afc26b1c | [
"MIT"
] | null | null | null | #ifndef BOARD_HPP
#define BOARD_HPP
#include "Food.hpp"
#include "Snake.hpp"
#include "SFML/Graphics.hpp"
class Board
{
public:
void initialise(sf::RenderWindow *window);
void update(sf::RenderWindow *window);
void render(sf::RenderWindow *window);
sf::RectangleShape boardBackground;
int boardSize = 20;
int tileSize = 32;
Food food;
Snake snake;
sf::Font font;
sf::RectangleShape messageBox;
sf::Text gameOverText;
sf::Text gameWonText;
sf::Text snakeLengthText;
sf::Text pressEnterText;
};
#endif | 15.823529 | 44 | 0.713755 | [
"render"
] |
3c7817316ed68d1a8357791777298a7797f278a2 | 29,444 | cc | C++ | engine/source/platformWin32/winInput.cc | itsasc/Necromantia | f41dfa045eb2c3500320767553d75f83df10e6f9 | [
"MIT"
] | null | null | null | engine/source/platformWin32/winInput.cc | itsasc/Necromantia | f41dfa045eb2c3500320767553d75f83df10e6f9 | [
"MIT"
] | null | null | null | engine/source/platformWin32/winInput.cc | itsasc/Necromantia | f41dfa045eb2c3500320767553d75f83df10e6f9 | [
"MIT"
] | null | null | null | //-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "platformWin32/platformWin32.h"
#include "platform/platformInput.h"
#include "platform/platformVideo.h"
#include "platformWin32/winDirectInput.h"
#include "platform/event.h"
#include "console/console.h"
#include "platform/platformInput_ScriptBinding.h"
#include "winInput_ScriptBinding.h"
// Static class variables:
InputManager* Input::smManager;
bool Input::smActive;
CursorManager* Input::smCursorManager = 0; //*** DAW: Added
U8 Input::smModifierKeys; //*** DAW: Added
bool Input::smLastKeyboardActivated;
bool Input::smLastMouseActivated;
bool Input::smLastJoystickActivated;
static void fillAsciiTable();
//------------------------------------------------------------------------------
//
// This function gets the standard ASCII code corresponding to our key code
// and the existing modifier key state.
//
//------------------------------------------------------------------------------
struct AsciiData
{
struct KeyData
{
U16 ascii;
bool isDeadChar;
};
KeyData upper;
KeyData lower;
KeyData goofy;
};
#define NUM_KEYS ( KEY_OEM_102 + 1 )
#define KEY_FIRST KEY_ESCAPE
static AsciiData AsciiTable[NUM_KEYS];
//------------------------------------------------------------------------------
void Input::init()
{
Con::printSeparator();
Con::printf( "Input Initialization:" );
destroy();
smActive = false;
smLastKeyboardActivated = true;
smLastMouseActivated = true;
smLastJoystickActivated = true;
OSVERSIONINFO OSVersionInfo;
dMemset( &OSVersionInfo, 0, sizeof( OSVERSIONINFO ) );
OSVersionInfo.dwOSVersionInfoSize = sizeof( OSVERSIONINFO );
if ( GetVersionEx( &OSVersionInfo ) )
{
if ( !( OSVersionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT && OSVersionInfo.dwMajorVersion < 5 ) )
{
smManager = new DInputManager;
if ( !smManager->enable() )
{
Con::printf( " DirectInput not enabled." );
delete smManager;
smManager = NULL;
}
else
{
DInputManager::init();
Con::printf( " DirectInput enabled." );
}
}
else
Con::printf( " WinNT detected -- DirectInput not enabled." );
}
// Startup the Cursor Manager
if(!smCursorManager)
{
smCursorManager = new CursorManager();
if(smCursorManager)
{
// Add the arrow cursor to the stack
smCursorManager->pushCursor(CursorManager::curArrow);
}
else
{
Con::printf(" Cursor Manager not enabled.");
}
}
// Init the current modifier keys
setModifierKeys(0);
fillAsciiTable();
Con::printf( "" );
}
//------------------------------------------------------------------------------
static void fillAsciiTable()
{
//HKL layout = GetKeyboardLayout( 0 );
U8 state[256];
U16 ascii[2];
U32 dikCode, vKeyCode, keyCode;
S32 result;
dMemset( &AsciiTable, 0, sizeof( AsciiTable ) );
dMemset( &state, 0, sizeof( state ) );
for ( keyCode = KEY_FIRST; keyCode < NUM_KEYS; keyCode++ )
{
ascii[0] = ascii[1] = 0;
dikCode = Key_to_DIK( keyCode );
if ( dikCode )
{
//vKeyCode = MapVirtualKeyEx( dikCode, 1, layout );
vKeyCode = MapVirtualKey( dikCode, 1 );
// Lower case:
ascii[0] = ascii[1] = 0;
//result = ToAsciiEx( vKeyCode, dikCode, state, ascii, 0, layout );
result = ToAscii( vKeyCode, dikCode, state, ascii, 0 );
if ( result == 2 )
AsciiTable[keyCode].lower.ascii = ascii[1] ? ascii[1] : ( ascii[0] >> 8 );
else if ( result == 1 )
AsciiTable[keyCode].lower.ascii = ascii[0];
else if ( result < 0 )
{
AsciiTable[keyCode].lower.ascii = ascii[0];
AsciiTable[keyCode].lower.isDeadChar = true;
// Need to clear the dead character from the keyboard layout:
//ToAsciiEx( vKeyCode, dikCode, state, ascii, 0, layout );
ToAscii( vKeyCode, dikCode, state, ascii, 0 );
}
// Upper case:
ascii[0] = ascii[1] = 0;
state[VK_SHIFT] = 0x80;
//result = ToAsciiEx( vKeyCode, dikCode, state, ascii, 0, layout );
result = ToAscii( vKeyCode, dikCode, state, ascii, 0 );
if ( result == 2 )
AsciiTable[keyCode].upper.ascii = ascii[1] ? ascii[1] : ( ascii[0] >> 8 );
else if ( result == 1 )
AsciiTable[keyCode].upper.ascii = ascii[0];
else if ( result < 0 )
{
AsciiTable[keyCode].upper.ascii = ascii[0];
AsciiTable[keyCode].upper.isDeadChar = true;
// Need to clear the dead character from the keyboard layout:
//ToAsciiEx( vKeyCode, dikCode, state, ascii, 0, layout );
ToAscii( vKeyCode, dikCode, state, ascii, 0 );
}
state[VK_SHIFT] = 0;
// Foreign mod case:
ascii[0] = ascii[1] = 0;
state[VK_CONTROL] = 0x80;
state[VK_MENU] = 0x80;
//result = ToAsciiEx( vKeyCode, dikCode, state, ascii, 0, layout );
result = ToAscii( vKeyCode, dikCode, state, ascii, 0 );
if ( result == 2 )
AsciiTable[keyCode].goofy.ascii = ascii[1] ? ascii[1] : ( ascii[0] >> 8 );
else if ( result == 1 )
AsciiTable[keyCode].goofy.ascii = ascii[0];
else if ( result < 0 )
{
AsciiTable[keyCode].goofy.ascii = ascii[0];
AsciiTable[keyCode].goofy.isDeadChar = true;
// Need to clear the dead character from the keyboard layout:
//ToAsciiEx( vKeyCode, dikCode, state, ascii, 0, layout );
ToAscii( vKeyCode, dikCode, state, ascii, 0 );
}
state[VK_CONTROL] = 0;
state[VK_MENU] = 0;
}
}
}
//------------------------------------------------------------------------------
U16 Input::getKeyCode( U16 asciiCode )
{
U16 keyCode = 0;
U16 i;
// This is done three times so the lowerkey will always
// be found first. Some foreign keyboards have duplicate
// chars on some keys.
for ( i = KEY_FIRST; i < NUM_KEYS && !keyCode; i++ )
{
if ( AsciiTable[i].lower.ascii == asciiCode )
{
keyCode = i;
break;
};
}
for ( i = KEY_FIRST; i < NUM_KEYS && !keyCode; i++ )
{
if ( AsciiTable[i].upper.ascii == asciiCode )
{
keyCode = i;
break;
};
}
for ( i = KEY_FIRST; i < NUM_KEYS && !keyCode; i++ )
{
if ( AsciiTable[i].goofy.ascii == asciiCode )
{
keyCode = i;
break;
};
}
return( keyCode );
}
//------------------------------------------------------------------------------
U16 Input::getAscii( U16 keyCode, KEY_STATE keyState )
{
if ( keyCode >= NUM_KEYS )
return 0;
switch ( keyState )
{
case STATE_LOWER:
return AsciiTable[keyCode].lower.ascii;
case STATE_UPPER:
return AsciiTable[keyCode].upper.ascii;
case STATE_GOOFY:
return AsciiTable[keyCode].goofy.ascii;
default:
return(0);
}
}
//------------------------------------------------------------------------------
void Input::destroy()
{
if ( smManager && smManager->isEnabled() )
{
smManager->disable();
delete smManager;
smManager = NULL;
}
}
//------------------------------------------------------------------------------
bool Input::enable()
{
if ( smManager && !smManager->isEnabled() )
return( smManager->enable() );
return( false );
}
//------------------------------------------------------------------------------
void Input::disable()
{
if ( smManager && smManager->isEnabled() )
smManager->disable();
}
//------------------------------------------------------------------------------
void Input::activate()
{
#ifdef UNICODE
winState.imeHandle = ImmGetContext( winState.appWindow );
ImmReleaseContext( winState.appWindow, winState.imeHandle );
#endif
DInputDevice::resetModifierKeys();
if ( !Con::getBoolVariable( "$enableDirectInput" ) )
return;
if ( smManager && smManager->isEnabled() && !smActive )
{
Con::printf( "Activating DirectInput..." );
smActive = true;
DInputManager* dInputManager = dynamic_cast<DInputManager*>( smManager );
if ( dInputManager )
{
if ( dInputManager->isKeyboardEnabled() && smLastKeyboardActivated )
dInputManager->activateKeyboard();
if ( Video::isFullScreen() )
{
// DirectInput Mouse Hook-Up:
if ( dInputManager->isMouseEnabled() && smLastMouseActivated )
dInputManager->activateMouse();
}
else
dInputManager->deactivateMouse();
if ( dInputManager->isJoystickEnabled() && smLastJoystickActivated )
dInputManager->activateJoystick();
}
}
}
//------------------------------------------------------------------------------
void Input::deactivate()
{
if ( smManager && smManager->isEnabled() && smActive )
{
DInputManager* dInputManager = dynamic_cast<DInputManager*>( smManager );
if ( dInputManager )
{
smLastKeyboardActivated = dInputManager->isKeyboardActive();
smLastMouseActivated = dInputManager->isMouseActive();
smLastJoystickActivated = dInputManager->isJoystickActive();
dInputManager->deactivateKeyboard();
dInputManager->deactivateMouse();
dInputManager->deactivateJoystick();
}
smActive = false;
Con::printf( "DirectInput deactivated." );
}
}
//------------------------------------------------------------------------------
void Input::reactivate()
{
// This is soo hacky...
SetForegroundWindow( winState.appWindow );
PostMessage( winState.appWindow, WM_ACTIVATE, WA_ACTIVE, NULL );
}
//------------------------------------------------------------------------------
bool Input::isEnabled()
{
if ( smManager )
return smManager->isEnabled();
return false;
}
//------------------------------------------------------------------------------
bool Input::isActive()
{
return smActive;
}
//------------------------------------------------------------------------------
void Input::process()
{
if ( smManager && smManager->isEnabled() && smActive )
smManager->process();
}
//------------------------------------------------------------------------------
// Accesses the global input manager to see if its mouse is enabled
bool Input::isMouseEnabled()
{
DInputManager* dInputManager = dynamic_cast<DInputManager*>( smManager );
if ( !dInputManager || !dInputManager->isEnabled() )
return( false );
if (dInputManager->isMouseEnabled() && dInputManager->isMouseActive() )
return( true );
return false;
}
//------------------------------------------------------------------------------
// Accesses the global input manager to see if its keyboard is enabled
bool Input::isKeyboardEnabled()
{
DInputManager* dInputManager = dynamic_cast<DInputManager*>( smManager );
if ( !dInputManager || !dInputManager->isEnabled() )
return( false );
if ( dInputManager->isKeyboardEnabled() && dInputManager->isKeyboardActive() )
return( true );
return false;
}
//------------------------------------------------------------------------------
// Access the global input manager and enables its mouse
void Input::enableMouse()
{
DInputManager::enableMouse();
}
//------------------------------------------------------------------------------
// Access the global input manager and disables its mouse
void Input::disableMouse()
{
DInputManager::disableMouse();
}
//------------------------------------------------------------------------------
// Access the global input manager and enables its keyboard
void Input::enableKeyboard()
{
DInputManager::enableKeyboard();
}
//------------------------------------------------------------------------------
// Access the global input manager and enables its keyboard
void Input::disableKeyboard()
{
DInputManager::disableKeyboard();
}
//------------------------------------------------------------------------------
bool Input::activateKeyboard()
{
DInputManager* mgr = dynamic_cast<DInputManager*>( Input::getManager() );
if ( mgr )
return( mgr->activateKeyboard() );
return( false );
}
//------------------------------------------------------------------------------
void Input::deactivateKeyboard()
{
DInputManager* mgr = dynamic_cast<DInputManager*>( Input::getManager() );
if ( mgr )
mgr->deactivateKeyboard();
}
//------------------------------------------------------------------------------
bool Input::enableJoystick()
{
return( DInputManager::enableJoystick() );
}
//------------------------------------------------------------------------------
void Input::disableJoystick()
{
DInputManager::disableJoystick();
}
//------------------------------------------------------------------------------
void Input::echoInputState()
{
DInputManager* mgr = dynamic_cast<DInputManager*>( Input::getManager() );
if ( mgr && mgr->isEnabled() )
{
Con::printf( "DirectInput is enabled %s.", Input::isActive() ? "and active" : "but inactive" );
Con::printf( "- Keyboard is %sabled and %sactive.",
mgr->isKeyboardEnabled() ? "en" : "dis",
mgr->isKeyboardActive() ? "" : "in" );
Con::printf( "- Mouse is %sabled and %sactive.",
mgr->isMouseEnabled() ? "en" : "dis",
mgr->isMouseActive() ? "" : "in" );
Con::printf( "- Joystick is %sabled and %sactive.",
mgr->isJoystickEnabled() ? "en" : "dis",
mgr->isJoystickActive() ? "" : "in" );
Con::printf( "- Xinput is %sabled and %sactive.",
mgr->isXInputEnabled() ? "en" : "dis",
mgr->isXInputActive() ? "" : "in" );
}
else
{
Con::printf( "DirectInput is not enabled." );
}
}
//------------------------------------------------------------------------------
void Input::setCursorPos(S32 x, S32 y)
{
POINT pt;
pt.x = x;
pt.y = y;
ClientToScreen(winState.appWindow, &pt);
SetCursorPos(pt.x, pt.y);
}
//------------------------------------------------------------------------------
// Set the cursor to draw (true) or not (false)
void Input::setCursorState(bool on)
{
ShowCursor(on);
}
//------------------------------------------------------------------------------
static struct { U32 id; LPTSTR resourceID; } sgCursorShapeMap[]=
{
{ CursorManager::curArrow, IDC_ARROW },
{ CursorManager::curWait, IDC_WAIT },
{ CursorManager::curPlus, IDC_CROSS },
{ CursorManager::curResizeVert, IDC_SIZEWE },
{ CursorManager::curResizeHorz, IDC_SIZENS },
{ CursorManager::curResizeAll, IDC_SIZEALL },
{ CursorManager::curIBeam, IDC_IBEAM },
{ CursorManager::curResizeNESW, IDC_SIZENESW },
{ CursorManager::curResizeNWSE, IDC_SIZENWSE },
{ 0, 0 },
};
void Input::setCursorShape(U32 cursorID)
{
LPTSTR resourceID = NULL;
for(S32 i = 0;sgCursorShapeMap[i].resourceID != NULL;++i)
{
if(cursorID == sgCursorShapeMap[i].id)
{
resourceID = sgCursorShapeMap[i].resourceID;
break;
}
}
if(resourceID == NULL)
return;
HCURSOR cur = LoadCursor(NULL, resourceID);
if(cur)
SetCursor(cur);
}
//------------------------------------------------------------------------------
// Functions to change the cursor shape using the Input class.
void Input::pushCursor(S32 cursorID)
{
CursorManager* cm = getCursorManager();
if(cm)
cm->pushCursor(cursorID);
}
void Input::popCursor()
{
CursorManager* cm = getCursorManager();
if(cm)
cm->popCursor();
}
void Input::refreshCursor()
{
CursorManager* cm = getCursorManager();
if(cm)
cm->refreshCursor();
}
//------------------------------------------------------------------------------
U32 Input::getDoubleClickTime()
{
return GetDoubleClickTime();
}
S32 Input::getDoubleClickWidth()
{
return GetSystemMetrics(SM_CXDOUBLECLK);
}
S32 Input::getDoubleClickHeight()
{
return GetSystemMetrics(SM_CYDOUBLECLK);
}
//------------------------------------------------------------------------------
InputManager* Input::getManager()
{
return( smManager );
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
static U8 VcodeRemap[256] =
{
0, // 0x00
0, // 0x01 VK_LBUTTON
0, // 0x02 VK_RBUTTON
0, // 0x03 VK_CANCEL
0, // 0x04 VK_MBUTTON
0, // 0x05
0, // 0x06
0, // 0x07
KEY_BACKSPACE, // 0x08 VK_BACK
KEY_TAB, // 0x09 VK_TAB
0, // 0x0A
0, // 0x0B
0, // 0x0C VK_CLEAR
KEY_RETURN, // 0x0D VK_RETURN
0, // 0x0E
0, // 0x0F
KEY_SHIFT, // 0x10 VK_SHIFT
KEY_CONTROL, // 0x11 VK_CONTROL
KEY_ALT, // 0x12 VK_MENU
KEY_PAUSE, // 0x13 VK_PAUSE
KEY_CAPSLOCK, // 0x14 VK_CAPITAL
0, // 0x15 VK_KANA, VK_HANGEUL, VK_HANGUL
0, // 0x16
0, // 0x17 VK_JUNJA
0, // 0x18 VK_FINAL
0, // 0x19 VK_HANJA, VK_KANJI
0, // 0x1A
KEY_ESCAPE, // 0x1B VK_ESCAPE
0, // 0x1C VK_CONVERT
0, // 0x1D VK_NONCONVERT
0, // 0x1E VK_ACCEPT
0, // 0x1F VK_MODECHANGE
KEY_SPACE, // 0x20 VK_SPACE
KEY_PAGE_UP, // 0x21 VK_PRIOR
KEY_PAGE_DOWN, // 0x22 VK_NEXT
KEY_END, // 0x23 VK_END
KEY_HOME, // 0x24 VK_HOME
KEY_LEFT, // 0x25 VK_LEFT
KEY_UP, // 0x26 VK_UP
KEY_RIGHT, // 0x27 VK_RIGHT
KEY_DOWN, // 0x28 VK_DOWN
0, // 0x29 VK_SELECT
KEY_PRINT, // 0x2A VK_PRINT
0, // 0x2B VK_EXECUTE
0, // 0x2C VK_SNAPSHOT
KEY_INSERT, // 0x2D VK_INSERT
KEY_DELETE, // 0x2E VK_DELETE
KEY_HELP, // 0x2F VK_HELP
KEY_0, // 0x30 VK_0 VK_0 thru VK_9 are the same as ASCII '0' thru '9' (// 0x30 - // 0x39)
KEY_1, // 0x31 VK_1
KEY_2, // 0x32 VK_2
KEY_3, // 0x33 VK_3
KEY_4, // 0x34 VK_4
KEY_5, // 0x35 VK_5
KEY_6, // 0x36 VK_6
KEY_7, // 0x37 VK_7
KEY_8, // 0x38 VK_8
KEY_9, // 0x39 VK_9
0, // 0x3A
0, // 0x3B
0, // 0x3C
0, // 0x3D
0, // 0x3E
0, // 0x3F
0, // 0x40
KEY_A, // 0x41 VK_A VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (// 0x41 - // 0x5A)
KEY_B, // 0x42 VK_B
KEY_C, // 0x43 VK_C
KEY_D, // 0x44 VK_D
KEY_E, // 0x45 VK_E
KEY_F, // 0x46 VK_F
KEY_G, // 0x47 VK_G
KEY_H, // 0x48 VK_H
KEY_I, // 0x49 VK_I
KEY_J, // 0x4A VK_J
KEY_K, // 0x4B VK_K
KEY_L, // 0x4C VK_L
KEY_M, // 0x4D VK_M
KEY_N, // 0x4E VK_N
KEY_O, // 0x4F VK_O
KEY_P, // 0x50 VK_P
KEY_Q, // 0x51 VK_Q
KEY_R, // 0x52 VK_R
KEY_S, // 0x53 VK_S
KEY_T, // 0x54 VK_T
KEY_U, // 0x55 VK_U
KEY_V, // 0x56 VK_V
KEY_W, // 0x57 VK_W
KEY_X, // 0x58 VK_X
KEY_Y, // 0x59 VK_Y
KEY_Z, // 0x5A VK_Z
KEY_WIN_LWINDOW, // 0x5B VK_LWIN
KEY_WIN_RWINDOW, // 0x5C VK_RWIN
KEY_WIN_APPS, // 0x5D VK_APPS
0, // 0x5E
0, // 0x5F
KEY_NUMPAD0, // 0x60 VK_NUMPAD0
KEY_NUMPAD1, // 0x61 VK_NUMPAD1
KEY_NUMPAD2, // 0x62 VK_NUMPAD2
KEY_NUMPAD3, // 0x63 VK_NUMPAD3
KEY_NUMPAD4, // 0x64 VK_NUMPAD4
KEY_NUMPAD5, // 0x65 VK_NUMPAD5
KEY_NUMPAD6, // 0x66 VK_NUMPAD6
KEY_NUMPAD7, // 0x67 VK_NUMPAD7
KEY_NUMPAD8, // 0x68 VK_NUMPAD8
KEY_NUMPAD9, // 0x69 VK_NUMPAD9
KEY_MULTIPLY, // 0x6A VK_MULTIPLY
KEY_ADD, // 0x6B VK_ADD
KEY_SEPARATOR, // 0x6C VK_SEPARATOR
KEY_SUBTRACT, // 0x6D VK_SUBTRACT
KEY_DECIMAL, // 0x6E VK_DECIMAL
KEY_DIVIDE, // 0x6F VK_DIVIDE
KEY_F1, // 0x70 VK_F1
KEY_F2, // 0x71 VK_F2
KEY_F3, // 0x72 VK_F3
KEY_F4, // 0x73 VK_F4
KEY_F5, // 0x74 VK_F5
KEY_F6, // 0x75 VK_F6
KEY_F7, // 0x76 VK_F7
KEY_F8, // 0x77 VK_F8
KEY_F9, // 0x78 VK_F9
KEY_F10, // 0x79 VK_F10
KEY_F11, // 0x7A VK_F11
KEY_F12, // 0x7B VK_F12
KEY_F13, // 0x7C VK_F13
KEY_F14, // 0x7D VK_F14
KEY_F15, // 0x7E VK_F15
KEY_F16, // 0x7F VK_F16
KEY_F17, // 0x80 VK_F17
KEY_F18, // 0x81 VK_F18
KEY_F19, // 0x82 VK_F19
KEY_F20, // 0x83 VK_F20
KEY_F21, // 0x84 VK_F21
KEY_F22, // 0x85 VK_F22
KEY_F23, // 0x86 VK_F23
KEY_F24, // 0x87 VK_F24
0, // 0x88
0, // 0x89
0, // 0x8A
0, // 0x8B
0, // 0x8C
0, // 0x8D
0, // 0x8E
0, // 0x8F
KEY_NUMLOCK, // 0x90 VK_NUMLOCK
KEY_SCROLLLOCK, // 0x91 VK_OEM_SCROLL
0, // 0x92
0, // 0x93
0, // 0x94
0, // 0x95
0, // 0x96
0, // 0x97
0, // 0x98
0, // 0x99
0, // 0x9A
0, // 0x9B
0, // 0x9C
0, // 0x9D
0, // 0x9E
0, // 0x9F
KEY_LSHIFT, // 0xA0 VK_LSHIFT
KEY_RSHIFT, // 0xA1 VK_RSHIFT
KEY_LCONTROL, // 0xA2 VK_LCONTROL
KEY_RCONTROL, // 0xA3 VK_RCONTROL
KEY_LALT, // 0xA4 VK_LMENU
KEY_RALT, // 0xA5 VK_RMENU
0, // 0xA6
0, // 0xA7
0, // 0xA8
0, // 0xA9
0, // 0xAA
0, // 0xAB
0, // 0xAC
0, // 0xAD
0, // 0xAE
0, // 0xAF
0, // 0xB0
0, // 0xB1
0, // 0xB2
0, // 0xB3
0, // 0xB4
0, // 0xB5
0, // 0xB6
0, // 0xB7
0, // 0xB8
0, // 0xB9
KEY_SEMICOLON, // 0xBA VK_OEM_1
KEY_EQUALS, // 0xBB VK_OEM_PLUS
KEY_COMMA, // 0xBC VK_OEM_COMMA
KEY_MINUS, // 0xBD VK_OEM_MINUS
KEY_PERIOD, // 0xBE VK_OEM_PERIOD
KEY_SLASH, // 0xBF VK_OEM_2
KEY_TILDE, // 0xC0 VK_OEM_3
0, // 0xC1
0, // 0xC2
0, // 0xC3
0, // 0xC4
0, // 0xC5
0, // 0xC6
0, // 0xC7
0, // 0xC8
0, // 0xC9
0, // 0xCA
0, // 0xCB
0, // 0xCC
0, // 0xCD
0, // 0xCE
0, // 0xCF
0, // 0xD0
0, // 0xD1
0, // 0xD2
0, // 0xD3
0, // 0xD4
0, // 0xD5
0, // 0xD6
0, // 0xD7
0, // 0xD8
0, // 0xD9
0, // 0xDA
KEY_LBRACKET, // 0xDB VK_OEM_4
KEY_BACKSLASH, // 0xDC VK_OEM_5
KEY_RBRACKET, // 0xDD VK_OEM_6
KEY_APOSTROPHE, // 0xDE VK_OEM_7
0, // 0xDF VK_OEM_8
0, // 0xE0
0, // 0xE1 VK_OEM_AX AX key on Japanese AX keyboard
KEY_OEM_102, // 0xE2 VK_OEM_102
0, // 0xE3
0, // 0xE4
0, // 0xE5 VK_PROCESSKEY
0, // 0xE6
0, // 0xE7
0, // 0xE8
0, // 0xE9
0, // 0xEA
0, // 0xEB
0, // 0xEC
0, // 0xED
0, // 0xEE
0, // 0xEF
0, // 0xF0
0, // 0xF1
0, // 0xF2
0, // 0xF3
0, // 0xF4
0, // 0xF5
0, // 0xF6 VK_ATTN
0, // 0xF7 VK_CRSEL
0, // 0xF8 VK_EXSEL
0, // 0xF9 VK_EREOF
0, // 0xFA VK_PLAY
0, // 0xFB VK_ZOOM
0, // 0xFC VK_NONAME
0, // 0xFD VK_PA1
0, // 0xFE VK_OEM_CLEAR
0 // 0xFF
};
//------------------------------------------------------------------------------
//
// This function translates a virtual key code to our corresponding internal
// key code using the preceding table.
//
//------------------------------------------------------------------------------
U8 TranslateOSKeyCode(U8 vcode)
{
return VcodeRemap[vcode];
}
//-----------------------------------------------------------------------------
// Clipboard functions
const char* Platform::getClipboard()
{
HGLOBAL hGlobal;
LPVOID pGlobal;
//make sure we can access the clipboard
if (!IsClipboardFormatAvailable(CF_TEXT))
return "";
if (!OpenClipboard(NULL))
return "";
hGlobal = GetClipboardData(CF_TEXT);
pGlobal = GlobalLock(hGlobal);
S32 cbLength = strlen((char *)pGlobal);
char *returnBuf = Con::getReturnBuffer(cbLength + 1);
strcpy(returnBuf, (char *)pGlobal);
returnBuf[cbLength] = '\0';
GlobalUnlock(hGlobal);
CloseClipboard();
//note - this function never returns NULL
return returnBuf;
}
//-----------------------------------------------------------------------------
bool Platform::setClipboard(const char *text)
{
if (!text)
return false;
//make sure we can access the clipboard
if (!OpenClipboard(NULL))
return false;
S32 cbLength = strlen(text);
HGLOBAL hGlobal;
LPVOID pGlobal;
hGlobal = GlobalAlloc(GHND, cbLength + 1);
pGlobal = GlobalLock (hGlobal);
strcpy((char *)pGlobal, text);
GlobalUnlock(hGlobal);
EmptyClipboard();
SetClipboardData(CF_TEXT, hGlobal);
CloseClipboard();
return true;
}
| 30.993684 | 112 | 0.461079 | [
"shape"
] |
3c79f29183690e792315047c7b040427aea47263 | 3,027 | cpp | C++ | bigNum.cpp | SUSTYuxiao/MyCodeWareHouse | 82fe2e5a05d8331f6282abc1b1cc15d8e0933de2 | [
"MIT"
] | null | null | null | bigNum.cpp | SUSTYuxiao/MyCodeWareHouse | 82fe2e5a05d8331f6282abc1b1cc15d8e0933de2 | [
"MIT"
] | null | null | null | bigNum.cpp | SUSTYuxiao/MyCodeWareHouse | 82fe2e5a05d8331f6282abc1b1cc15d8e0933de2 | [
"MIT"
] | null | null | null | //
// Created by 张鹏霄 on 2018/5/13.
//
// 大数运算
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool isnot_legal(const string &str)
{
if( !( (str[0]-'0' > 0 && str[0]-'0' < 10) || str[0] == '-') )
return true;
for (int i = 1; i < str.size()-1; ++i)
{
if(!(str[i]-'0' > 0 && str[i]-'0' < 10))
return true;
}
return false;
}
bool _compare(const string &left, const string &right)
{
if(left.size() > right.size())
return true;
if(left.size() < right.size())
return false;
for (int j = 0; j < left.size() ; --j)
{
if(left[j] > right[j])
return true;
else if(left[j] < right[j])
return false;
}
return true;//相等
}
string _add(string &left, string &right, string op)
{
string ret;
ret.resize(left.size(), '0');
//加法
int carry = 0;//进位
int tmp = 0;
for (int k = 0; k < left.size(); ++k)
{
tmp = left[k]-'0' + right[k]-'0' + carry;
carry = tmp / 10;
ret[k] = char((tmp % 10) + '0');
}
if (carry)
ret += "1";
ret += op;//添加符号
reverse(ret.begin(), ret.end());
return ret;
}
string _sub(string &left, string &right, string op)
{
string ret;
ret.resize(left.size(), '0');
//减法
for (int k = 0; k < left.size(); ++k)
{
if (left[k] < right[k])
{
left[k+1] -= 1;
left[k] += 10;
}
ret[k] = left[k] - right[k] + '0';
}
ret += op;//添加符号
reverse(ret.begin(), ret.end());
return ret;
}
string _start(string &left, string &right)
{
//初始化
string ret;
string _left = left;
string _right = right;
string op ="";
enum way {ADD, SUB};
way _way = ADD;
//判断浮点数 TODO
// string *big = &_left;
// string *small = &_right;
// size_t leftsize = _left.size()-1 -_left.rfind('.');
// size_t rightsize = _left.size()-1 -_left.rfind('.');
//判断合法
if (isnot_legal(left) || isnot_legal(right))
{
exit(-1);
}
//判断所有可能性
if(left[0] == '-' && right[0] == '-') //全为负数
{
_left = left.substr(1);
_right = right.substr(1);
op = "-";
}
else if (left[0] != '-' && right[0] != '-') //全为正数
;
else
{
_way = SUB;
if(left[0] == '-')
{
_left = left.substr(1);
swap(_left, _right);
}
if(right[0] == '-')
_right = right.substr(1);
if (!_compare(_left, _right))
{
swap(_left, _right);
op = "-";
}
}
//处理数据
reverse(_left.begin(), _left.end());
reverse(_right.begin(), _right.end());
if (_left.size() > _right.size())
_right.resize(_left.size(), '0');
else
_left.resize(_right.size(), '0');
switch (_way)
{
case ADD:
return _add(_left, _right, op);
case SUB:
return _add(_left, _right, op);
}
} | 20.046358 | 67 | 0.460192 | [
"vector"
] |
3c7b39e2e439801e2d2b949d81e45ab149c02cf9 | 4,824 | cc | C++ | core/ps/table/sparse_table.cc | felixbrf/tensornet | f45a04f5afe990154a15c24d387386370332821e | [
"Apache-2.0"
] | null | null | null | core/ps/table/sparse_table.cc | felixbrf/tensornet | f45a04f5afe990154a15c24d387386370332821e | [
"Apache-2.0"
] | null | null | null | core/ps/table/sparse_table.cc | felixbrf/tensornet | f45a04f5afe990154a15c24d387386370332821e | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2020, Qihoo, 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 "core/ps/table/sparse_table.h"
#include <set>
#include <string>
#include <butil/containers/flat_map.h>
#include <butil/logging.h>
#include <butil/object_pool.h>
#include "core/ps/optimizer/optimizer_kernel.h"
#include "core/ps/ps_cluster.h"
namespace tensornet {
SparseTable::SparseTable(const OptimizerBase* opt, int dimension)
: opt_(opt)
, dim_(dimension) {
CHECK(opt_ != nullptr);
op_kernel_ = opt_->CreateSparseOptKernel(dim_);
}
void SparseTable::SetHandle(uint32_t handle) {
CHECK(handle_ == 0) << "sparse table handle has already set:" << handle_;
handle_ = handle;
}
void SparseTable::Pull(const SparsePullRequest* req, SparsePullResponse* resp) {
resp->set_table_handle(req->table_handle());
CHECK_EQ(dim_, req->dim());
resp->set_dim(req->dim());
for (int i = 0; i < req->signs_size(); ++i) {
SparseWeightInfo weight_info;
uint64_t sign = req->signs(i);
if (false == op_kernel_->GetWeight(sign, weight_info)) {
weight_info.weight = nullptr;
weight_info.version = 0;
CHECK(op_kernel_->NewSignWithWeight(sign, weight_info));
CHECK(nullptr != weight_info.weight);
}
VariableWeight* weight = resp->add_weight();
weight->set_sign(sign);
weight->set_version(weight_info.version);
// weight_info.weight size is guaranteed by op_kernel_ same with dim_
for (int j = 0; j < dim_; j++) {
weight->add_w(weight_info.weight[j]);
}
}
}
void SparseTable::Push(const SparsePushRequest* req, SparsePushResponse* resp) {
CHECK_EQ(dim_, req->dim());
std::vector<float> grad(dim_);
for (int i = 0; i < req->weight_size(); i++) {
const VariableWeight& weight = req->weight(i);
CHECK_EQ(weight.w_size(), dim_);
for (int j = 0; j < weight.w_size(); j++) {
grad[j] = weight.w(j);
}
SparseGradInfo grad_info;
grad_info.grad = grad.data();
grad_info.show = weight.show();
grad_info.version = weight.version();
op_kernel_->Apply(weight.sign(), grad_info);
}
}
void SparseTable::Save(const std::string& filepath) const {
butil::Timer timer(butil::Timer::STARTED);
int shard_id = PsCluster::Instance()->Rank();
std::string file = filepath + "/sparse_table/" + std::to_string(GetHandle())
+ "/rank_" + std::to_string(shard_id);
op_kernel_->Serialized(file);
timer.stop();
LOG(INFO) << "SparseTable save. rank:" << shard_id
<< " table_id:" << GetHandle()
<< " latency:" << timer.s_elapsed() << "s"
<< " keys_count:" << op_kernel_->KeyCount();
}
void SparseTable::Load(const std::string& filepath) const {
butil::Timer timer(butil::Timer::STARTED);
int shard_id = PsCluster::Instance()->Rank();
std::string file = filepath + "/sparse_table/" + std::to_string(GetHandle())
+ "/rank_" + std::to_string(shard_id);
op_kernel_->DeSerialized(file);
timer.stop();
LOG(INFO) << "SparseTable load. rank:" << shard_id
<< " table_id:" << GetHandle()
<< " latency:" << timer.s_elapsed() << "s"
<< " keys_count:" << op_kernel_->KeyCount();
}
void SparseTable::ShowDecay() const {
op_kernel_->ShowDecay();
}
SparseTableRegistry* SparseTableRegistry::Instance() {
static SparseTableRegistry instance;
return &instance;
}
SparseTable* SparseTableRegistry::Get(uint32_t table_handle) {
CHECK(table_handle < tables_.size())
<< " table_handle:" << table_handle << " table size:" << tables_.size();
return tables_[table_handle];
}
uint32_t SparseTableRegistry::Register(SparseTable* table) {
const std::lock_guard<std::mutex> lock(mu_);
uint32_t table_handle = tables_.size();
tables_.emplace_back(table);
return table_handle;
}
SparseTable* CreateSparseTable(const OptimizerBase* opt, int dimension) {
SparseTable* table = new SparseTable(opt, dimension);
table->SetHandle(SparseTableRegistry::Instance()->Register(table));
return table;
}
} // namespace tensornet
| 29.595092 | 80 | 0.639718 | [
"vector"
] |
3c7e4154cf09dd10e0f7d6a48f976e60df71be44 | 1,734 | cpp | C++ | kattis_done/pebblesolitaire.cpp | heiseish/Competitive-Programming | e4dd4db83c38e8837914562bc84bc8c102e68e34 | [
"MIT"
] | 5 | 2019-03-17T01:33:19.000Z | 2021-06-25T09:50:45.000Z | kattis_done/pebblesolitaire.cpp | heiseish/Competitive-Programming | e4dd4db83c38e8837914562bc84bc8c102e68e34 | [
"MIT"
] | null | null | null | kattis_done/pebblesolitaire.cpp | heiseish/Competitive-Programming | e4dd4db83c38e8837914562bc84bc8c102e68e34 | [
"MIT"
] | null | null | null | /**
Justice isn’t something that you can just proclaim. It’s a feeling you should keep near your heart.
*/
#include <bits/stdc++.h>
#define forn(i, l, r) for(int i=l;i<=r;i++)
#define all(v) v.begin(),v.end()
#define pb push_back
#define nd second
#define st first
#define sz(x) (int)x.size()
#define UNIQUE(v) (v).resize(unique(all(v)) - (v).begin())
#define mp make_pair
#define debug(x) cout<<#x<<" --> "<<x<<endl;
using namespace std;
typedef long long ll;
typedef long double ld;
typedef vector<int> vi;
typedef vector<long long> vll;
typedef vector<pair<int, int> > vpi;
typedef pair<int, int> pi;
typedef pair<ll, ll> pll;
typedef vector<pll> vpll;
const int INF = 1 << 30;
/**
Start coding from here
*/
int ans;
int dp[1 << 12];
void play(int state) {
if (dp[state] != -1) return;
dp[state] = 1;
bool can = false;
forn(i,0,11) {
if (state & (1 << i)) {
if (i <= 9 && (state & (1 << (i + 1)) && !(state & (1 << (i + 2))))) {
int pos = state;
pos &= ~(1 << i);
pos &= ~(1 << (i + 1));
pos |= (1 << (i + 2));
play(pos);
can = true;
}
if (i >= 2 && (state & (1 << (i - 1)) && !(state & (1 << (i - 2))))) {
int pos = state;
pos &= ~(1 << i);
pos &= ~(1 << (i - 1));
pos |= (1 << (i - 2));
play(pos);
can = true;
}
}
}
if (!can) ans = min(ans, __builtin_popcount(state));
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(0);
#ifdef LOCAL_PROJECT
freopen("input.txt","r",stdin);
#endif
int tc;
cin>>tc;
while(tc--) {
string s;
cin>>s;
int state = 0;
for (auto &ch : s) {
if (ch == 'o') state+=1;
state <<=1;
}
state >>=1;
ans = INF;
memset(dp, -1, sizeof dp);
play(state);
cout << ans << '\n';
}
return 0;
}
| 21.675 | 107 | 0.538062 | [
"vector"
] |
3c81245c13618dd979b49a87d64669f03470f881 | 591 | hpp | C++ | cpp/include/Utils.hpp | florianvazelle/AnimeML | 5808a09de8be0a308d40107777430cc886ad076c | [
"Unlicense"
] | null | null | null | cpp/include/Utils.hpp | florianvazelle/AnimeML | 5808a09de8be0a308d40107777430cc886ad076c | [
"Unlicense"
] | null | null | null | cpp/include/Utils.hpp | florianvazelle/AnimeML | 5808a09de8be0a308d40107777430cc886ad076c | [
"Unlicense"
] | null | null | null | #pragma once
#include <algorithm>
#include <random>
#include <vector>
namespace ml {
static double rand(double min = 0, double max = 1) {
double f = ((double)std::rand()) / ((double)RAND_MAX);
return min + f * (max - min);
}
template <typename T> static void random_shuffle(std::vector<T>& vec) {
std::random_device rng;
std::mt19937 urng(rng());
std::shuffle(vec.begin(), vec.end(), urng);
}
static inline bool double_equals(double a, double b, double epsilon = 0.001) { return std::abs(a - b) < epsilon; }
}; // namespace ml | 29.55 | 118 | 0.607445 | [
"vector"
] |
3c85b04f55308930bf3e2f10878aa697c94c2610 | 5,034 | cpp | C++ | Samples/ExtendedExecution/cpp/Scenario2_SavingDataReason.xaml.cpp | leenachaudhari/Windows-universal-samples | 42f82931c53581a5a63d80b133774b4dad6546b6 | [
"MIT"
] | 1 | 2018-12-25T14:44:06.000Z | 2018-12-25T14:44:06.000Z | Samples/ExtendedExecution/cpp/Scenario2_SavingDataReason.xaml.cpp | leenachaudhari/Windows-universal-samples | 42f82931c53581a5a63d80b133774b4dad6546b6 | [
"MIT"
] | null | null | null | Samples/ExtendedExecution/cpp/Scenario2_SavingDataReason.xaml.cpp | leenachaudhari/Windows-universal-samples | 42f82931c53581a5a63d80b133774b4dad6546b6 | [
"MIT"
] | 1 | 2020-02-26T05:02:08.000Z | 2020-02-26T05:02:08.000Z | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#include "pch.h"
#include "Scenario2_SavingDataReason.xaml.h"
using namespace SDKTemplate;
using namespace Concurrency;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::ApplicationModel;
using namespace Windows::ApplicationModel::ExtendedExecution;
using namespace Windows::UI::Core;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Navigation;
SavingDataReason::SavingDataReason()
{
InitializeComponent();
}
void SavingDataReason::OnNavigatedTo(NavigationEventArgs^ e)
{
// Add a suspension handler in order to request a SavingData Extended Execution.
suspendingToken = App::Current->Suspending += ref new SuspendingEventHandler(this, &SavingDataReason::OnSuspending);
}
void SavingDataReason::OnNavigatingFrom(NavigatingCancelEventArgs^ e)
{
App::Current->Suspending -= suspendingToken;
}
void SavingDataReason::OnSuspending(Object^ sender, SuspendingEventArgs^ args)
{
SuspendingDeferral^ suspendDeferral = args->SuspendingOperation->GetDeferral();
rootPage->NotifyUser("", NotifyType::StatusMessage);
auto session = ref new ExtendedExecutionSession();
session->Reason = ExtendedExecutionReason::SavingData;
session->Description = "Pretending to save data to slow storage.";
EventRegistrationToken revokedToken = session->Revoked += ref new TypedEventHandler<Object^, ExtendedExecutionRevokedEventArgs^>(this, &SavingDataReason::ExtendedExecutionSessionRevoked);
create_task(session->RequestExtensionAsync()).then([this](ExtendedExecutionResult result)
{
switch (result)
{
case ExtendedExecutionResult::Allowed:
// We can perform a longer save operation (e.g., upload to the cloud).
MainPage::DisplayToast("Performing a long save operation.");
cancellationTokenSource = cancellation_token_source();
return Helpers::DelayAsync(Helpers::TimeSpanFromSeconds(10), cancellationTokenSource.get_token())
.then([this]()
{
MainPage::DisplayToast("Still saving.");
return Helpers::DelayAsync(Helpers::TimeSpanFromSeconds(10), cancellationTokenSource.get_token());
}).then([this]()
{
MainPage::DisplayToast("Long save complete.");
}).then([this](task<void> previousTask)
{
try
{
// Raise the cancellation exception if the task was canceled.
previousTask.get();
}
catch (const task_canceled&)
{
// The extended execution was revoked before we could finish the long save operation.
}
});
break;
default:
case ExtendedExecutionResult::Denied:
// We must perform a fast save operation.
MainPage::DisplayToast("Performing a fast save operation.");
return Helpers::DelayAsync(Helpers::TimeSpanFromSeconds(1)).then([this]()
{
MainPage::DisplayToast("Fast save complete.");
});
break;
}
}).then([this, session, revokedToken, suspendDeferral]()
{
session->Revoked -= revokedToken;
delete session;
suspendDeferral->Complete();
});
}
void SavingDataReason::ExtendedExecutionSessionRevoked(Object^ sender, ExtendedExecutionRevokedEventArgs^ args)
{
// If session is revoked, make the OnSuspending event handler stop or the application will be terminated.
cancellationTokenSource.cancel();
Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, args]()
{
switch (args->Reason)
{
case ExtendedExecutionRevokedReason::Resumed:
// A resumed app has returned to the foreground
rootPage->NotifyUser("Extended execution revoked due to returning to foreground.", NotifyType::StatusMessage);
break;
case ExtendedExecutionRevokedReason::SystemPolicy:
// An app can be in the foreground or background when a revocation due to system policy occurs
MainPage::DisplayToast("Extended execution revoked due to system policy.");
rootPage->NotifyUser("Extended execution revoked due to system policy.", NotifyType::StatusMessage);
break;
}
}));
}
| 40.596774 | 192 | 0.639452 | [
"object"
] |
3c86ac868291ccd073bb5deb827452109ddda5f5 | 35,261 | cpp | C++ | source/direct3d9/Mesh.cpp | HeavenWu/slimdx | e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac | [
"MIT"
] | 85 | 2015-04-06T05:37:10.000Z | 2022-03-22T19:53:03.000Z | source/direct3d9/Mesh.cpp | HeavenWu/slimdx | e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac | [
"MIT"
] | 10 | 2016-03-17T11:18:24.000Z | 2021-05-11T09:21:43.000Z | source/direct3d9/Mesh.cpp | HeavenWu/slimdx | e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac | [
"MIT"
] | 45 | 2015-09-14T03:54:01.000Z | 2022-03-22T19:53:09.000Z | #include "stdafx.h"
/*
* Copyright (c) 2007-2012 SlimDX Group
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <d3d9.h>
#include <d3dx9.h>
#include <vcclr.h>
#include "../stack_array.h"
#include "../ComObject.h"
#include "../Utilities.h"
#include "../DataStream.h"
#include "Direct3D9Exception.h"
#include "Device.h"
#include "Texture.h"
#include "IndexBuffer.h"
#include "VertexBuffer.h"
#include "Mesh.h"
#include "SkinInfo.h"
using namespace System;
using namespace System::IO;
using namespace System::Drawing;
using namespace System::Runtime::InteropServices;
namespace SlimDX
{
namespace Direct3D9
{
Mesh::Mesh( SlimDX::Direct3D9::Device^ device, int numFaces, int numVertices, MeshFlags options, array<VertexElement>^ vertexDeclaration )
{
ID3DXMesh* mesh = NULL;
pin_ptr<VertexElement> pinnedDecl = &vertexDeclaration[0];
HRESULT hr = D3DXCreateMesh( numFaces, numVertices, static_cast<DWORD>( options ),
reinterpret_cast<D3DVERTEXELEMENT9*>( pinnedDecl ), device->InternalPointer, &mesh );
if( RECORD_D3D9( hr ).IsFailure )
throw gcnew Direct3D9Exception( Result::Last );
Construct(mesh);
}
Mesh::Mesh( SlimDX::Direct3D9::Device^ device, int numFaces, int numVertices, MeshFlags options, SlimDX::Direct3D9::VertexFormat fvf )
{
ID3DXMesh* mesh = NULL;
HRESULT hr = D3DXCreateMeshFVF( numFaces, numVertices, static_cast<DWORD>( options ),
static_cast<DWORD>( fvf ), device->InternalPointer, &mesh );
if( RECORD_D3D9( hr ).IsFailure )
throw gcnew Direct3D9Exception( Result::Last );
Construct(mesh);
}
Mesh^ Mesh::FromMemory_Internal( SlimDX::Direct3D9::Device^ device, const void* memory, DWORD size, MeshFlags flags )
{
ID3DXMesh* mesh = NULL;
ID3DXBuffer* adjacencyBuffer = NULL;
ID3DXBuffer* materialBuffer = NULL;
ID3DXBuffer* instanceBuffer = NULL;
DWORD materialCount = 0;
HRESULT hr = D3DXLoadMeshFromXInMemory( memory, size, static_cast<DWORD>( flags ), device->InternalPointer,
&adjacencyBuffer, &materialBuffer, &instanceBuffer, &materialCount, &mesh );
if( RECORD_D3D9( hr ).IsFailure )
return nullptr;
Mesh^ result = Mesh::FromPointer( mesh );
result->SetAdjacency( Utilities::ReadRange<int>( adjacencyBuffer, mesh->GetNumFaces() * 3 ) );
result->SetMaterials( ExtendedMaterial::FromBuffer( materialBuffer, materialCount ) );
result->SetEffects( EffectInstance::FromBuffer( instanceBuffer, materialCount ) );
materialBuffer->Release();
instanceBuffer->Release();
return result;
}
Mesh^ Mesh::FromMemory( SlimDX::Direct3D9::Device^ device, array<Byte>^ memory, MeshFlags flags )
{
pin_ptr<unsigned char> pinnedMemory = &memory[0];
return Mesh::FromMemory_Internal( device, pinnedMemory, static_cast<DWORD>( memory->Length ), flags );
}
Mesh^ Mesh::FromStream( SlimDX::Direct3D9::Device^ device, Stream^ stream, MeshFlags flags )
{
DataStream^ ds = nullptr;
array<Byte>^ data = Utilities::ReadStream( stream, &ds );
if( data == nullptr )
{
DWORD size = static_cast<DWORD>( ds->RemainingLength );
return Mesh::FromMemory_Internal( device, ds->SeekToEnd(), size, flags );
}
return Mesh::FromMemory( device, data, flags );
}
Mesh^ Mesh::FromFile( SlimDX::Direct3D9::Device^ device, String^ fileName, MeshFlags flags )
{
ID3DXMesh* mesh = NULL;
ID3DXBuffer* adjacencyBuffer = NULL;
ID3DXBuffer* materialBuffer = NULL;
ID3DXBuffer* instanceBuffer = NULL;
DWORD materialCount = 0;
pin_ptr<const wchar_t> pinnedFileName = PtrToStringChars( fileName );
HRESULT hr = D3DXLoadMeshFromX( pinnedFileName, static_cast<DWORD>( flags ), device->InternalPointer,
&adjacencyBuffer, &materialBuffer, &instanceBuffer, &materialCount, &mesh );
if( RECORD_D3D9( hr ).IsFailure )
return nullptr;
Mesh^ result = Mesh::FromPointer( mesh );
result->SetAdjacency( Utilities::ReadRange<int>( adjacencyBuffer, mesh->GetNumFaces() * 3 ) );
result->SetMaterials( ExtendedMaterial::FromBuffer( materialBuffer, materialCount ) );
result->SetEffects( EffectInstance::FromBuffer( instanceBuffer, materialCount ) );
materialBuffer->Release();
instanceBuffer->Release();
return result;
}
Mesh^ Mesh::FromXFile( SlimDX::Direct3D9::Device^ device, XFileData^ xfile, MeshFlags flags )
{
ID3DXMesh* mesh = NULL;
ID3DXSkinInfo* skin = NULL;
ID3DXBuffer* adjacencyBuffer = NULL;
ID3DXBuffer* materialBuffer = NULL;
ID3DXBuffer* instanceBuffer = NULL;
DWORD materialCount = 0;
HRESULT hr = D3DXLoadSkinMeshFromXof( xfile->InternalPointer, static_cast<DWORD>( flags ), device->InternalPointer,
&adjacencyBuffer, &materialBuffer, &instanceBuffer, &materialCount, &skin, &mesh );
if( RECORD_D3D9( hr ).IsFailure )
return nullptr;
Mesh^ result = Mesh::FromPointer( mesh );
result->SetAdjacency( Utilities::ReadRange<int>( adjacencyBuffer, mesh->GetNumFaces() * 3 ) );
result->SetMaterials( ExtendedMaterial::FromBuffer( materialBuffer, materialCount ) );
result->SetEffects( EffectInstance::FromBuffer( instanceBuffer, materialCount ) );
materialBuffer->Release();
instanceBuffer->Release();
result->SkinInfo = SlimDX::Direct3D9::SkinInfo::FromPointer( skin );
return result;
}
Result Mesh::ComputeTangentFrame( TangentOptions options )
{
HRESULT hr = D3DXComputeTangentFrame( InternalPointer, static_cast<DWORD>( options ) );
return RECORD_D3D9( hr );
}
Mesh^ Mesh::CreateBox( SlimDX::Direct3D9::Device^ device, float width, float height, float depth )
{
ID3DXMesh *result = NULL;
ID3DXBuffer *adj = NULL;
HRESULT hr = D3DXCreateBox( device->InternalPointer, width, height, depth, &result, &adj );
if( RECORD_D3D9( hr ).IsFailure )
return nullptr;
Mesh^ mesh = Mesh::FromPointer( result );
mesh->SetAdjacency( Utilities::ReadRange<int>( adj, result->GetNumFaces() * 3 ) );
return mesh;
}
Mesh^ Mesh::CreateCylinder( SlimDX::Direct3D9::Device^ device, float radius1, float radius2, float length, int slices, int stacks )
{
ID3DXMesh *result = NULL;
ID3DXBuffer *adj = NULL;
HRESULT hr = D3DXCreateCylinder( device->InternalPointer, radius1, radius2, length, slices, stacks, &result, &adj );
if( RECORD_D3D9( hr ).IsFailure )
return nullptr;
Mesh^ mesh = Mesh::FromPointer( result );
mesh->SetAdjacency( Utilities::ReadRange<int>( adj, result->GetNumFaces() * 3 ) );
return mesh;
}
Mesh^ Mesh::CreateSphere( SlimDX::Direct3D9::Device^ device, float radius, int slices, int stacks )
{
ID3DXMesh *result = NULL;
ID3DXBuffer *adj = NULL;
HRESULT hr = D3DXCreateSphere( device->InternalPointer, radius, slices, stacks, &result, &adj );
if( RECORD_D3D9( hr ).IsFailure )
return nullptr;
Mesh^ mesh = Mesh::FromPointer( result );
mesh->SetAdjacency( Utilities::ReadRange<int>( adj, result->GetNumFaces() * 3 ) );
return mesh;
}
Mesh^ Mesh::CreateTeapot( SlimDX::Direct3D9::Device^ device )
{
ID3DXMesh *result = NULL;
ID3DXBuffer *adj = NULL;
HRESULT hr = D3DXCreateTeapot( device->InternalPointer, &result, &adj );
if( RECORD_D3D9( hr ).IsFailure )
return nullptr;
Mesh^ mesh = Mesh::FromPointer( result );
mesh->SetAdjacency( Utilities::ReadRange<int>( adj, result->GetNumFaces() * 3 ) );
return mesh;
}
Mesh^ Mesh::CreateTorus( SlimDX::Direct3D9::Device^ device, float innerRadius, float outerRadius, int sides, int rings )
{
ID3DXMesh *result = NULL;
ID3DXBuffer *adj = NULL;
HRESULT hr = D3DXCreateTorus( device->InternalPointer, innerRadius, outerRadius, sides, rings, &result, &adj );
if( RECORD_D3D9( hr ).IsFailure )
return nullptr;
Mesh^ mesh = Mesh::FromPointer( result );
mesh->SetAdjacency( Utilities::ReadRange<int>( adj, result->GetNumFaces() * 3 ) );
return mesh;
}
Mesh^ Mesh::CreateText( SlimDX::Direct3D9::Device^ device, Font^ font, String^ text, float deviation, float extrusion, [Out] array<GlyphMetricsFloat>^% glyphMetrics )
{
ID3DXMesh *result = NULL;
ID3DXBuffer *adj = NULL;
glyphMetrics = gcnew array<GlyphMetricsFloat>( text->Length );
pin_ptr<const wchar_t> pinnedText = PtrToStringChars( text );
pin_ptr<GlyphMetricsFloat> pinnedMetrics = &glyphMetrics[0];
HDC hdc = CreateCompatibleDC( NULL );
HFONT newFont;
HFONT oldFont;
if( hdc == NULL )
throw gcnew OutOfMemoryException();
newFont = static_cast<HFONT>( font->ToHfont().ToPointer() );
oldFont = static_cast<HFONT>( SelectObject( hdc, newFont ) );
HRESULT hr = D3DXCreateText( device->InternalPointer, hdc, reinterpret_cast<LPCWSTR>( pinnedText ),
deviation, extrusion, &result, &adj, reinterpret_cast<LPGLYPHMETRICSFLOAT>( pinnedMetrics ) );
SelectObject( hdc, oldFont );
DeleteObject( newFont );
DeleteDC( hdc );
if( RECORD_D3D9( hr ).IsFailure )
{
glyphMetrics = nullptr;
return nullptr;
}
Mesh^ mesh = Mesh::FromPointer( result );
mesh->SetAdjacency( Utilities::ReadRange<int>( adj, result->GetNumFaces() * 3 ) );
return mesh;
}
Mesh^ Mesh::CreateText( SlimDX::Direct3D9::Device^ device, Font^ font, String^ text, float deviation, float extrusion )
{
ID3DXMesh *result = NULL;
ID3DXBuffer *adj = NULL;
pin_ptr<const wchar_t> pinnedText = PtrToStringChars( text );
HDC hdc = CreateCompatibleDC( NULL );
HFONT newFont;
HFONT oldFont;
if( hdc == NULL )
throw gcnew OutOfMemoryException();
newFont = static_cast<HFONT>( font->ToHfont().ToPointer() );
oldFont = static_cast<HFONT>( SelectObject( hdc, newFont ) );
HRESULT hr = D3DXCreateText( device->InternalPointer, hdc, reinterpret_cast<LPCWSTR>( pinnedText ),
deviation, extrusion, &result, &adj, NULL );
SelectObject( hdc, oldFont );
DeleteObject( newFont );
DeleteDC( hdc );
if( RECORD_D3D9( hr ).IsFailure )
return nullptr;
Mesh^ mesh = Mesh::FromPointer( result );
mesh->SetAdjacency( Utilities::ReadRange<int>( adj, result->GetNumFaces() * 3 ) );
return mesh;
}
DataStream^ Mesh::LockAttributeBuffer( LockFlags flags )
{
DWORD *data = NULL;
int faceCount = InternalPointer->GetNumFaces();
HRESULT hr = InternalPointer->LockAttributeBuffer( static_cast<DWORD>( flags ), &data );
if( RECORD_D3D9( hr ).IsFailure )
return nullptr;
bool readOnly = (flags & LockFlags::ReadOnly) == LockFlags::ReadOnly;
return gcnew DataStream( data, faceCount * sizeof( DWORD ), true, !readOnly, false );
}
Result Mesh::UnlockAttributeBuffer()
{
HRESULT hr = InternalPointer->UnlockAttributeBuffer();
return RECORD_D3D9( hr );
}
Result Mesh::SetAttributeTable( array<AttributeRange>^ table )
{
pin_ptr<AttributeRange> pinnedTable = &table[0];
HRESULT hr = InternalPointer->SetAttributeTable( reinterpret_cast<const D3DXATTRIBUTERANGE*>( pinnedTable ), table->Length );
return RECORD_D3D9( hr );
}
Result Mesh::OptimizeInPlace( MeshOptimizeFlags flags, [Out] array<int>^% faceRemap, [Out] array<int>^% vertexRemap )
{
ID3DXBuffer *buffer = NULL;
DWORD *adjacencyIn = NULL;
DWORD *adjacencyOutPtr = NULL;
stack_array<DWORD> adjacencyOut = stackalloc( DWORD, FaceCount * 3 );
array<int>^ adjacency = GetAdjacency();
pin_ptr<int> pinnedAdjIn;
faceRemap = gcnew array<int>( FaceCount );
pin_ptr<int> pinnedFR = &faceRemap[0];
if( adjacency != nullptr )
{
pinnedAdjIn = &adjacency[0];
adjacencyIn = reinterpret_cast<DWORD*>( pinnedAdjIn );
adjacencyOutPtr = &adjacencyOut[0];
}
HRESULT hr = InternalPointer->OptimizeInplace( static_cast<DWORD>( flags ), adjacencyIn,
adjacencyOutPtr, reinterpret_cast<DWORD*>( pinnedFR ), &buffer );
if( RECORD_D3D9( hr ).IsFailure )
{
faceRemap = nullptr;
vertexRemap = nullptr;
SetAdjacency( NULL );
}
else
{
vertexRemap = Utilities::ReadRange<int>( buffer, VertexCount );
if( adjacencyOutPtr != NULL )
SetAdjacency( &adjacencyOut[0] );
else
SetAdjacency( NULL );
}
return Result::Last;
}
Result Mesh::OptimizeInPlace( MeshOptimizeFlags flags )
{
DWORD *adjacencyIn = NULL;
DWORD *adjacencyOutPtr = NULL;
stack_array<DWORD> adjacencyOut = stackalloc( DWORD, FaceCount * 3 );
array<int>^ adjacency = GetAdjacency();
pin_ptr<int> pinnedAdjIn;
if( adjacency != nullptr )
{
pinnedAdjIn = &adjacency[0];
adjacencyIn = reinterpret_cast<DWORD*>( pinnedAdjIn );
adjacencyOutPtr = &adjacencyOut[0];
}
HRESULT hr = InternalPointer->OptimizeInplace( static_cast<DWORD>( flags ), adjacencyIn,
adjacencyOutPtr, NULL, NULL );
RECORD_D3D9( hr );
if( FAILED( hr ) )
SetAdjacency( NULL );
else
{
if( adjacencyOutPtr != NULL )
SetAdjacency( &adjacencyOut[0] );
else
SetAdjacency( NULL );
}
return Result::Last;
}
Mesh^ Mesh::Optimize( MeshOptimizeFlags flags, [Out] array<int>^% faceRemap, [Out] array<int>^% vertexRemap )
{
ID3DXMesh *result = NULL;
ID3DXBuffer *buffer = NULL;
DWORD *adjacencyIn = NULL;
DWORD *adjacencyOutPtr = NULL;
stack_array<DWORD> adjacencyOut = stackalloc( DWORD, FaceCount * 3 );
array<int>^ adjacency = GetAdjacency();
pin_ptr<int> pinnedAdjIn;
faceRemap = gcnew array<int>( FaceCount );
pin_ptr<int> pinnedFR = &faceRemap[0];
if( adjacency != nullptr )
{
pinnedAdjIn = &adjacency[0];
adjacencyIn = reinterpret_cast<DWORD*>( pinnedAdjIn );
adjacencyOutPtr = &adjacencyOut[0];
}
HRESULT hr = InternalPointer->Optimize( static_cast<DWORD>( flags ), adjacencyIn,
adjacencyOutPtr, reinterpret_cast<DWORD*>( pinnedFR ), &buffer, &result );
if( RECORD_D3D9( hr ).IsFailure )
{
faceRemap = nullptr;
vertexRemap = nullptr;
return nullptr;
}
Mesh^ mesh = Mesh::FromPointer( result );
vertexRemap = Utilities::ReadRange<int>( buffer, VertexCount );
if( adjacencyOutPtr != NULL )
mesh->SetAdjacency( &adjacencyOut[0] );
return mesh;
}
Mesh^ Mesh::Optimize( MeshOptimizeFlags flags )
{
ID3DXMesh *result = NULL;
DWORD *adjacencyIn = NULL;
DWORD *adjacencyOutPtr = NULL;
stack_array<DWORD> adjacencyOut = stackalloc( DWORD, FaceCount * 3 );
array<int>^ adjacency = GetAdjacency();
pin_ptr<int> pinnedAdjIn;
if( adjacency != nullptr )
{
pinnedAdjIn = &adjacency[0];
adjacencyIn = reinterpret_cast<DWORD*>( pinnedAdjIn );
adjacencyOutPtr = &adjacencyOut[0];
}
HRESULT hr = InternalPointer->Optimize( static_cast<DWORD>( flags ), adjacencyIn,
adjacencyOutPtr, NULL, NULL, &result );
if( RECORD_D3D9( hr ).IsFailure )
return nullptr;
Mesh^ mesh = Mesh::FromPointer( result );
if( adjacencyOutPtr != NULL )
mesh->SetAdjacency( &adjacencyOut[0] );
return mesh;
}
Mesh^ Mesh::Clean( CleanType type, [Out] String^% errorsAndWarnings )
{
ID3DXMesh *result = NULL;
ID3DXBuffer *errors = NULL;
DWORD *adjacencyIn = NULL;
DWORD *adjacencyOutPtr = NULL;
stack_array<DWORD> adjacencyOut = stackalloc( DWORD, FaceCount * 3 );
array<int>^ adjacency = GetAdjacency();
pin_ptr<int> pinnedAdjIn;
if( adjacency != nullptr )
{
pinnedAdjIn = &adjacency[0];
adjacencyIn = reinterpret_cast<DWORD*>( pinnedAdjIn );
adjacencyOutPtr = &adjacencyOut[0];
}
HRESULT hr = D3DXCleanMesh( static_cast<D3DXCLEANTYPE>( type ), InternalPointer,
adjacencyIn, &result, adjacencyOutPtr, &errors );
if( RECORD_D3D9( hr ).IsFailure )
{
errorsAndWarnings = nullptr;
return nullptr;
}
errorsAndWarnings = Utilities::BufferToString( errors );
Mesh^ mesh = Mesh::FromPointer( result );
if( adjacencyOutPtr != NULL )
mesh->SetAdjacency( &adjacencyOut[0] );
return mesh;
}
Mesh^ Mesh::Clean( CleanType type )
{
ID3DXMesh *result = NULL;
DWORD *adjacencyIn = NULL;
DWORD *adjacencyOutPtr = NULL;
stack_array<DWORD> adjacencyOut = stackalloc( DWORD, FaceCount * 3 );
array<int>^ adjacency = GetAdjacency();
pin_ptr<int> pinnedAdjIn;
if( adjacency != nullptr )
{
pinnedAdjIn = &adjacency[0];
adjacencyIn = reinterpret_cast<DWORD*>( pinnedAdjIn );
adjacencyOutPtr = &adjacencyOut[0];
}
HRESULT hr = D3DXCleanMesh( static_cast<D3DXCLEANTYPE>( type ), InternalPointer,
&adjacencyIn[0], &result, adjacencyOutPtr, NULL );
if( RECORD_D3D9( hr ).IsFailure )
return nullptr;
Mesh^ mesh = Mesh::FromPointer( result );
if( adjacencyOutPtr != NULL )
mesh->SetAdjacency( &adjacencyOut[0] );
return mesh;
}
void Mesh::GenerateAdjacency( float epsilon )
{
array<int>^ adj = BaseMesh::GenerateAdjacency( epsilon );
SetAdjacency( adj );
}
String^ Mesh::Validate()
{
ID3DXBuffer *errorBuffer = NULL;
DWORD *adjacencyIn = NULL;
pin_ptr<int> pinnedAdj;
String^ errors = nullptr;
array<int>^ adjacency = GetAdjacency();
if( adjacency != nullptr )
{
pinnedAdj = &adjacency[0];
adjacencyIn = reinterpret_cast<DWORD*>( pinnedAdj );
}
D3DXValidMesh( InternalPointer, adjacencyIn, &errorBuffer );
errors = Utilities::BufferToString( errorBuffer );
return errors;
}
void Mesh::SetAdjacency( DWORD *adj )
{
if( adj == NULL )
adjacency = nullptr;
else
{
adjacency = gcnew array<int>( FaceCount * 3 );
for( int i = 0; i < FaceCount * 3; i++ )
adjacency[i] = adj[i];
}
}
Result Mesh::ComputeNormals()
{
DWORD *adjacencyIn = NULL;
pin_ptr<int> pinnedAdj;
array<int>^ adjacency = GetAdjacency();
if( adjacency != nullptr )
{
pinnedAdj = &adjacency[0];
adjacencyIn = reinterpret_cast<DWORD*>( pinnedAdj );
}
HRESULT hr = D3DXComputeNormals( InternalPointer, adjacencyIn );
return RECORD_D3D9( hr );
}
Result Mesh::ComputeTangent( int textureStage, int tangentIndex, int binormalIndex, bool wrap )
{
array<int>^ adjacency = GetAdjacency();
DWORD *adjacencyIn = NULL;
pin_ptr<int> pinnedAdj;
if( adjacency != nullptr )
{
pinnedAdj = &adjacency[0];
adjacencyIn = reinterpret_cast<DWORD*>( pinnedAdj );
}
HRESULT hr = D3DXComputeTangent( InternalPointer, textureStage, tangentIndex, binormalIndex, wrap, adjacencyIn );
return RECORD_D3D9( hr );
}
Mesh^ Mesh::ComputeTangentFrame( int textureInSemantic, int textureInIndex, int partialOutSemanticU,
int partialOutIndexU, int partialOutSemanticV, int partialOutIndexV, int normalOutSemantic,
int normalOutIndex, TangentOptions options, float partialEdgeThreshold,
float singularPointThreshold, float normalEdgeThreshold, [Out] array<int>^% vertexMapping )
{
ID3DXMesh *result = NULL;
ID3DXBuffer *vertex = NULL;
array<int>^ adjacency = GetAdjacency();
DWORD *adjacencyIn = NULL;
pin_ptr<int> pinnedAdj;
if( adjacency != nullptr )
{
pinnedAdj = &adjacency[0];
adjacencyIn = reinterpret_cast<DWORD*>( pinnedAdj );
}
HRESULT hr = D3DXComputeTangentFrameEx( InternalPointer, textureInSemantic, textureInIndex,
partialOutSemanticU, partialOutIndexU, partialOutSemanticV, partialOutIndexV, normalOutSemantic,
normalOutIndex, static_cast<DWORD>( options ), adjacencyIn,
partialEdgeThreshold, singularPointThreshold, normalEdgeThreshold, &result, &vertex );
if( RECORD_D3D9( hr ).IsFailure )
{
vertexMapping = nullptr;
return nullptr;
}
vertexMapping = Utilities::ReadRange<int>( vertex, result->GetNumVertices() );
if( (options & TangentOptions::GenerateInPlace) == TangentOptions::GenerateInPlace )
return this;
return Mesh::FromPointer( result );
}
Mesh^ Mesh::ComputeTangentFrame( int textureInSemantic, int textureInIndex, int partialOutSemanticU,
int partialOutIndexU, int partialOutSemanticV, int partialOutIndexV, int normalOutSemantic,
int normalOutIndex, TangentOptions options, float partialEdgeThreshold,
float singularPointThreshold, float normalEdgeThreshold )
{
ID3DXMesh *result = NULL;
array<int>^ adjacency = GetAdjacency();
DWORD *adjacencyIn = NULL;
pin_ptr<int> pinnedAdj;
if( adjacency != nullptr )
{
pinnedAdj = &adjacency[0];
adjacencyIn = reinterpret_cast<DWORD*>( pinnedAdj );
}
HRESULT hr = D3DXComputeTangentFrameEx( InternalPointer, textureInSemantic, textureInIndex,
partialOutSemanticU, partialOutIndexU, partialOutSemanticV, partialOutIndexV, normalOutSemantic,
normalOutIndex, static_cast<DWORD>( options ), adjacencyIn,
partialEdgeThreshold, singularPointThreshold, normalEdgeThreshold, &result, NULL );
if( RECORD_D3D9( hr ).IsFailure )
return nullptr;
if( (options & TangentOptions::GenerateInPlace) == TangentOptions::GenerateInPlace )
return this;
return Mesh::FromPointer( result );
}
Mesh^ Mesh::Concatenate( SlimDX::Direct3D9::Device^ device, array<Mesh^>^ meshes, MeshFlags options, array<Matrix>^ geometryTransforms,
array<Matrix>^ textureTransforms, array<VertexElement>^ vertexDeclaration )
{
ID3DXMesh *result = NULL;
D3DXMATRIX *geoXForms = NULL;
D3DXMATRIX *textureXForms = NULL;
D3DVERTEXELEMENT9 *decl = NULL;
pin_ptr<Matrix> pinnedGeo = nullptr;
pin_ptr<Matrix> pinnedTexture = nullptr;
pin_ptr<VertexElement> pinnedDecl = nullptr;
stack_array<ID3DXMesh*> input = stackalloc( ID3DXMesh*, meshes->Length );
for( int i = 0; i < meshes->Length; i++ )
input[i] = meshes[i]->InternalPointer;
if( geometryTransforms != nullptr )
{
pinnedGeo = &geometryTransforms[0];
geoXForms = reinterpret_cast<D3DXMATRIX*>( pinnedGeo );
}
if( textureTransforms != nullptr )
{
pinnedTexture = &textureTransforms[0];
textureXForms = reinterpret_cast<D3DXMATRIX*>( pinnedTexture );
}
if( vertexDeclaration != nullptr )
{
pinnedDecl = &vertexDeclaration[0];
decl = reinterpret_cast<D3DVERTEXELEMENT9*>( pinnedDecl );
}
HRESULT hr = D3DXConcatenateMeshes( &input[0], meshes->Length, static_cast<DWORD>( options ), geoXForms,
textureXForms, decl, device->InternalPointer, &result );
if( RECORD_D3D9( hr ).IsFailure )
return nullptr;
return Mesh::FromPointer( result );
}
Mesh^ Mesh::Concatenate( SlimDX::Direct3D9::Device^ device, array<Mesh^>^ meshes, MeshFlags options, array<Matrix>^ geometryTransforms,
array<Matrix>^ textureTransforms )
{
ID3DXMesh *result = NULL;
D3DXMATRIX *geoXForms = NULL;
D3DXMATRIX *textureXForms = NULL;
pin_ptr<Matrix> pinnedGeo = nullptr;
pin_ptr<Matrix> pinnedTexture = nullptr;
stack_array<ID3DXMesh*> input = stackalloc( ID3DXMesh*, meshes->Length );
for( int i = 0; i < meshes->Length; i++ )
input[i] = meshes[i]->InternalPointer;
if( geometryTransforms != nullptr )
{
pinnedGeo = &geometryTransforms[0];
geoXForms = reinterpret_cast<D3DXMATRIX*>( pinnedGeo );
}
if( textureTransforms != nullptr )
{
pinnedTexture = &textureTransforms[0];
textureXForms = reinterpret_cast<D3DXMATRIX*>( pinnedTexture );
}
HRESULT hr = D3DXConcatenateMeshes( &input[0], meshes->Length, static_cast<DWORD>( options ), geoXForms,
textureXForms, NULL, device->InternalPointer, &result );
if( RECORD_D3D9( hr ).IsFailure )
return nullptr;
return Mesh::FromPointer( result );
}
Mesh^ Mesh::Concatenate( SlimDX::Direct3D9::Device^ device, array<Mesh^>^ meshes, MeshFlags options )
{
ID3DXMesh *result = NULL;
stack_array<ID3DXMesh*> input = stackalloc( ID3DXMesh*, meshes->Length );
for( int i = 0; i < meshes->Length; i++ )
input[i] = meshes[i]->InternalPointer;
HRESULT hr = D3DXConcatenateMeshes( &input[0], meshes->Length, static_cast<DWORD>( options ), NULL,
NULL, NULL, device->InternalPointer, &result );
if( RECORD_D3D9( hr ).IsFailure )
return nullptr;
return Mesh::FromPointer( result );
}
Result Mesh::ToXFile( Mesh^ mesh, String^ fileName, XFileFormat format, CharSet charSet )
{
pin_ptr<const wchar_t> pinnedName = PtrToStringChars( fileName );
array<int>^ adjacency = mesh->GetAdjacency();
array<ExtendedMaterial>^ materials = mesh->GetMaterials();
array<EffectInstance>^ effects = mesh->GetEffects();
DWORD *adjacencyIn = NULL;
D3DXMATERIAL *materialPtr = NULL;
D3DXEFFECTINSTANCE *effectPtr = NULL;
stack_array<D3DXMATERIAL> nativeMaterials;
stack_array<D3DXEFFECTINSTANCE> nativeEffects;
pin_ptr<int> pinnedAdj;
int length = 0;
if( adjacency != nullptr )
{
pinnedAdj = &adjacency[0];
adjacencyIn = reinterpret_cast<DWORD*>( pinnedAdj );
}
if( materials != nullptr )
{
length = materials->Length;
nativeMaterials = stack_array<D3DXMATERIAL>( length );
for( int i = 0; i < length; i++ )
nativeMaterials[i] = ExtendedMaterial::ToUnmanaged( materials[i] );
materialPtr = &nativeMaterials[0];
}
if( effects != nullptr )
{
nativeEffects = stack_array<D3DXEFFECTINSTANCE>( effects->Length );
for( int i = 0; i < effects->Length; i++ )
nativeEffects[i] = EffectInstance::ToUnmanaged( effects[i] );
effectPtr = &nativeEffects[0];
}
DWORD f = static_cast<DWORD>( format );
if( charSet == CharSet::Unicode )
f |= D3DXF_FILESAVE_TOWFILE;
else
f |= D3DXF_FILESAVE_TOFILE;
HRESULT hr = D3DXSaveMeshToX( reinterpret_cast<LPCWSTR>( pinnedName ), mesh->InternalPointer,
adjacencyIn, materialPtr, effectPtr, length, f );
if( materials != nullptr )
{
for( int i = 0; i < length; i++ )
Utilities::FreeNativeString( nativeMaterials[i].pTextureFilename );
}
if( effects != nullptr )
{
for( int i = 0; i < effects->Length; i++ )
{
for( UINT j = 0; j < nativeEffects[i].NumDefaults; j++ )
Utilities::FreeNativeString( nativeEffects[i].pDefaults[j].pParamName );
delete[] nativeEffects[i].pDefaults;
}
}
return RECORD_D3D9( hr );
}
Result Mesh::ToXFile( Mesh^ mesh, String^ fileName, XFileFormat format )
{
return ToXFile( mesh, fileName, format, CharSet::Auto );
}
Mesh^ Mesh::Simplify( Mesh^ mesh, array<AttributeWeights>^ attributeWeights,
array<float>^ vertexWeights, int minimumValue, MeshSimplification options )
{
ID3DXMesh *result = NULL;
DWORD *adjacencyIn = NULL;
pin_ptr<int> pinnedAdj;
array<int>^ adjacency = mesh->GetAdjacency();
if( adjacency != nullptr )
{
pinnedAdj = &adjacency[0];
adjacencyIn = reinterpret_cast<DWORD*>( pinnedAdj );
}
pin_ptr<float> pinnedVW = &vertexWeights[0];
pin_ptr<AttributeWeights> pinnedAW = &attributeWeights[0];
HRESULT hr = D3DXSimplifyMesh( mesh->InternalPointer, adjacencyIn,
reinterpret_cast<const D3DXATTRIBUTEWEIGHTS*>( pinnedAW ), reinterpret_cast<const FLOAT*>( pinnedVW ),
minimumValue, static_cast<DWORD>( options ), &result );
if( RECORD_D3D9( hr ).IsFailure )
return nullptr;
return Mesh::FromPointer( result );
}
Mesh^ Mesh::Simplify( Mesh^ mesh, array<AttributeWeights>^ attributeWeights,
int minimumValue, MeshSimplification options )
{
ID3DXMesh *result = NULL;
DWORD *adjacencyIn = NULL;
pin_ptr<int> pinnedAdj;
array<int>^ adjacency = mesh->GetAdjacency();
if( adjacency != nullptr )
{
pinnedAdj = &adjacency[0];
adjacencyIn = reinterpret_cast<DWORD*>( pinnedAdj );
}
pin_ptr<AttributeWeights> pinnedAW = &attributeWeights[0];
HRESULT hr = D3DXSimplifyMesh( mesh->InternalPointer, adjacencyIn,
reinterpret_cast<const D3DXATTRIBUTEWEIGHTS*>( pinnedAW ), NULL,
minimumValue, static_cast<DWORD>( options ), &result );
if( RECORD_D3D9( hr ).IsFailure )
return nullptr;
return Mesh::FromPointer( result );
}
Mesh^ Mesh::Simplify( Mesh^ mesh, int minimumValue, MeshSimplification options )
{
ID3DXMesh *result = NULL;
DWORD *adjacencyIn = NULL;
array<int>^ adjacency = mesh->GetAdjacency();
pin_ptr<int> pinnedAdj;
if( adjacency != nullptr )
{
pinnedAdj = &adjacency[0];
adjacencyIn = reinterpret_cast<DWORD*>( pinnedAdj );
}
HRESULT hr = D3DXSimplifyMesh( mesh->InternalPointer, adjacencyIn,
NULL, NULL, minimumValue, static_cast<DWORD>( options ), &result );
if( RECORD_D3D9( hr ).IsFailure )
return nullptr;
return Mesh::FromPointer( result );
}
Mesh^ Mesh::TessellateNPatches( Mesh^ mesh, float segmentCount, bool quadraticInterpolation )
{
ID3DXMesh *result = NULL;
ID3DXBuffer *adjacencyOut = NULL;
DWORD *adjacencyIn = NULL;
array<int>^ adjacency = mesh->GetAdjacency();
pin_ptr<int> pinnedAdj;
if( adjacency != nullptr )
{
pinnedAdj = &adjacency[0];
adjacencyIn = reinterpret_cast<DWORD*>( pinnedAdj );
}
HRESULT hr = D3DXTessellateNPatches( mesh->InternalPointer, adjacencyIn, segmentCount,
quadraticInterpolation, &result, &adjacencyOut );
if( RECORD_D3D9( hr ).IsFailure )
return nullptr;
Mesh^ newMesh = Mesh::FromPointer( result );
newMesh->SetAdjacency( Utilities::ReadRange<int>( adjacencyOut, result->GetNumFaces() * 3 ) );
return newMesh;
}
Result Mesh::TessellateRectanglePatch( SlimDX::Direct3D9::VertexBuffer^ vertexBuffer, array<float>^ segmentCounts,
array<VertexElement>^ vertexDeclaration, RectanglePatchInfo rectanglePatchInfo )
{
pin_ptr<float> pinnedSegments = &segmentCounts[0];
pin_ptr<VertexElement> pinnedDeclaration = &vertexDeclaration[0];
HRESULT hr = D3DXTessellateRectPatch( vertexBuffer->InternalPointer, reinterpret_cast<const FLOAT*>( pinnedSegments ),
reinterpret_cast<const D3DVERTEXELEMENT9*>( pinnedDeclaration ), reinterpret_cast<const D3DRECTPATCH_INFO*>( &rectanglePatchInfo ),
InternalPointer );
return RECORD_D3D9( hr );
}
Result Mesh::TessellateTrianglePatch( SlimDX::Direct3D9::VertexBuffer^ vertexBuffer, array<float>^ segmentCounts,
array<VertexElement>^ vertexDeclaration, TrianglePatchInfo trianglePatchInfo )
{
pin_ptr<float> pinnedSegments = &segmentCounts[0];
pin_ptr<VertexElement> pinnedDeclaration = &vertexDeclaration[0];
HRESULT hr = D3DXTessellateTriPatch( vertexBuffer->InternalPointer, reinterpret_cast<const FLOAT*>( pinnedSegments ),
reinterpret_cast<const D3DVERTEXELEMENT9*>( pinnedDeclaration ), reinterpret_cast<const D3DTRIPATCH_INFO*>( &trianglePatchInfo ),
InternalPointer );
return RECORD_D3D9( hr );
}
Result Mesh::WeldVertices( WeldFlags flags, WeldEpsilons epsilons, [Out] array<int>^% faceRemap, [Out] array<int>^% vertexRemap )
{
ID3DXBuffer *buffer = NULL;
DWORD *adjIn = NULL;
DWORD *adjOut = NULL;
stack_array<DWORD> adjacencyOut = stackalloc( DWORD, FaceCount * 3 );
array<int>^ adjacency = GetAdjacency();
pin_ptr<int> pinnedAdjIn;
faceRemap = gcnew array<int>( FaceCount );
pin_ptr<int> pinnedFR = &faceRemap[0];
if( adjacency != nullptr )
{
pinnedAdjIn = &adjacency[0];
adjIn = reinterpret_cast<DWORD*>( pinnedAdjIn );
adjOut = &adjacencyOut[0];
}
HRESULT hr = D3DXWeldVertices( InternalPointer, static_cast<DWORD>( flags ),
reinterpret_cast<const D3DXWELDEPSILONS*>( &epsilons ), adjIn, adjOut,
reinterpret_cast<DWORD*>( pinnedFR ), &buffer );
if( RECORD_D3D9( hr ).IsFailure )
{
faceRemap = nullptr;
vertexRemap = nullptr;
return Result::Last;
}
vertexRemap = Utilities::ReadRange<int>( buffer, VertexCount );
if( adjOut != NULL )
SetAdjacency( &adjacencyOut[0] );
return Result::Last;
}
Result Mesh::WeldVertices( WeldFlags flags, [Out] array<int>^% faceRemap, [Out] array<int>^% vertexRemap )
{
ID3DXBuffer *buffer = NULL;
DWORD *adjIn = NULL;
DWORD *adjOut = NULL;
stack_array<DWORD> adjacencyOut = stackalloc( DWORD, FaceCount * 3 );
array<int>^ adjacency = GetAdjacency();
pin_ptr<int> pinnedAdjIn;
faceRemap = gcnew array<int>( FaceCount );
pin_ptr<int> pinnedFR = &faceRemap[0];
if( adjacency != nullptr )
{
pinnedAdjIn = &adjacency[0];
adjIn = reinterpret_cast<DWORD*>( pinnedAdjIn );
adjOut = &adjacencyOut[0];
}
HRESULT hr = D3DXWeldVertices( InternalPointer, static_cast<DWORD>( flags ), NULL, adjIn, adjOut,
reinterpret_cast<DWORD*>( pinnedFR ), &buffer );
if( RECORD_D3D9( hr ).IsFailure )
{
faceRemap = nullptr;
vertexRemap = nullptr;
return Result::Last;
}
vertexRemap = Utilities::ReadRange<int>( buffer, VertexCount );
if( adjOut != NULL )
SetAdjacency( &adjacencyOut[0] );
return Result::Last;
}
Result Mesh::WeldVertices( WeldFlags flags, WeldEpsilons epsilons )
{
DWORD *adjIn = NULL;
DWORD *adjOut = NULL;
stack_array<DWORD> adjacencyOut = stackalloc( DWORD, FaceCount * 3 );
array<int>^ adjacency = GetAdjacency();
pin_ptr<int> pinnedAdjIn;
if( adjacency != nullptr )
{
pinnedAdjIn = &adjacency[0];
adjIn = reinterpret_cast<DWORD*>( pinnedAdjIn );
adjOut = &adjacencyOut[0];
}
HRESULT hr = D3DXWeldVertices( InternalPointer, static_cast<DWORD>( flags ),
reinterpret_cast<const D3DXWELDEPSILONS*>( &epsilons ), adjIn, adjOut, NULL, NULL );
if( RECORD_D3D9( hr ).IsFailure )
return Result::Last;
if( adjOut != NULL )
SetAdjacency( &adjacencyOut[0] );
return Result::Last;
}
Result Mesh::WeldVertices( WeldFlags flags )
{
DWORD *adjIn = NULL;
DWORD *adjOut = NULL;
stack_array<DWORD> adjacencyOut = stackalloc( DWORD, FaceCount * 3 );
array<int>^ adjacency = GetAdjacency();
pin_ptr<int> pinnedAdjIn;
if( adjacency != nullptr )
{
pinnedAdjIn = &adjacency[0];
adjIn = reinterpret_cast<DWORD*>( pinnedAdjIn );
adjOut = &adjacencyOut[0];
}
HRESULT hr = D3DXWeldVertices( InternalPointer, static_cast<DWORD>( flags ), NULL, adjIn, adjOut, NULL, NULL );
if( RECORD_D3D9( hr ).IsFailure )
return Result::Last;
if( adjOut != NULL )
SetAdjacency( &adjacencyOut[0] );
return Result::Last;
}
}
}
| 30.715157 | 168 | 0.685573 | [
"mesh"
] |
3c88c61e688bd08d5f50c1bd9a5cc556e6d42595 | 24,380 | cpp | C++ | IBEngine/IBJobs.cpp | Raz290/IceBox | f0dacd03eda597d685b6c3f521ff944c7469048a | [
"MIT"
] | null | null | null | IBEngine/IBJobs.cpp | Raz290/IceBox | f0dacd03eda597d685b6c3f521ff944c7469048a | [
"MIT"
] | null | null | null | IBEngine/IBJobs.cpp | Raz290/IceBox | f0dacd03eda597d685b6c3f521ff944c7469048a | [
"MIT"
] | null | null | null | #include "IBJobs.h"
#include "IBPlatform.h"
#include "IBLogging.h"
#include <string.h>
/*
## Multi-threading
Multi-threading is a fairly involved and complicated topic.
As a result, we'll quickly gloss over out-of-order processors and compiler reordering.
### Out-of-order processors
"Modern" CPU processors are typically out-of-order processors.
You can think of an in-order processor as a simple machine that consumes
instructions in the order that they arrived. Instead, an out-of-order processor
can start executing instructions that are further down the pipe
if the instructions they depend on has already completed execution.
As an example, imagine that we're feeding our processor with some instructions: A, B, C, D
If instruction B depends on instruction A, then our processor has to execute A then B
However, if instruction C does not depend on instruction A or B and does not need the same
execution unit as the other 2 (maybe it simply uses a memory unit instead of the ALU)
Then it can execute while A is executing or while B is executing.
This is important because this means that our store could theoretically
complete before another store instruction. (Say instruction B was a store instruction).
As a result, if C completed before B, then a thread could see the changes to C but the changes to B
might not be visible yet. (This is not the case for intel's CPUs as of this writting, however moving to a weaker memory model would make this the case)
You can guarantee that B has completed it's store to memory by inserting a store fence in between B and C.
Something like this:
B
Store Fence
C
This would assure that all stores before the store fence are completed before C is executed.
This is useful if we have a flag that tells our other threads that data is ready.
### Compiler Reordering
It is also possible for our compiler to change the ordering of our instructions if it determines that it could improve performance.
As a result, the compiler might say "I would like to move C before B to improve performance".
In some scenarios, you want to make sure that the order in which you read/write things is maintained.
As a result you can add a compiler barrier to assure that specific instructions aren't reordered accross a boundary.
Typically, using a store fence or load fence will achieve the same results as a pure compiler barrier.
### Volatile Store/Load
You'll noticed that we use volatileStore and volatileLoad quite a bit here.
This is because our compiler can decide to optimize a load away, load it once or not load it at all
if it thinks it will not impact the single-threaded behaviour of the program.
volatileLoad and volatileStore is a way of telling the compiler "Don't optimize this load, it might have changed because of someone else"
### Job Systems
Now that we've spoken a little bit about some of the intricacies of multi-threading, we can talk about our job system.
The purpose of a job system is to minimize the creation of threads and to instead break up work
into a series of small chunks of work. "Jobs"
The reason we don't want to be creating and destroying threads continuously is because
this has a substantial performance impact. Instead, we want to create our threads beforehand
and feed them work as we have it.
We feed work through a set of worker thread specific queues that store a list of all the jobs that a
worker thread is expected to complete. We want a queue per thread in order to reduce contention.
If we were to include a global list, all threads would have to compete with each other to pull something
off of our global queue. This would require either a lock-free approach to the global queue or a global lock.
Both are acceptable, however, if we have a single queue per worker
then our threads can pull from the queue without any atomic operations or locks.
This also means that they don't have to "try again" if a thread has preempted them to the global queue.
A potential downside, is that some threads might have a lighter workload than others and having to wait for longer periods of time.
If that ends up being the case, we can look into implementing a job stealing algorithm where a thread
can pull work from another thread if it runs out of work for a while.
### Job Queues
Our job queue is implemented as a fixed sized ring buffer.
This means that the queue cannot be resized. Which allows us to avoid having to deal with
the challenges of resizing the queue.
Our queue has 2 indices, a consumer index and a producer index.
The consumer index is in charge of retrieving work from the queue
and the producer index is in charge of assing work to the queue.
Our approach is implemented in a lock free manner using this algorithm:
The consumer (worker thread) is the only one that can move the consumer index forward. This means that
it can do so without doing any atomic operations,
The consumer will move the consumer index forward once it has completed the work assigned to that index.
As a result, if there is no work at the index, the consumer will simply wait for work to appear there.
This means that the producer (threads launching jobs) must feed the consumer sequentially.
This approach of our consumer waiting for work to appear allows our consumer to be fairly lenient to work
taking some time to appear in it's queue.
The producer side of our queue is where we introduce some atomic operations to assure that no threads
introduce a race condition.
The idea for our approach is fairly simple. Our thread will simply iterate through each worker
and determine if that worker has some space in it's queue.
If it has space, it will try to commit a slot by moving the producer index forward.
If it succeeds at moving its producer index forward, that means the previous index is now commited
and it can write data to it safely.
We can guarantee this behaviour using a compare and exchange.
Once we know we can safely write to an index, we want the transfer of data to be as simple as possible.
If we have to send a lot of data, our consumer would have to be notified when all of the data has been written.
Thankfully, we only write a single pointer to the shared slot in the queue.
We can expect this operation to be atomic and the consumer thread should not see any partial writes. (Needs source)
Once our pointer has been written, we want to wake up our waiting thread (it might have gone to sleep while waiting to save cycles and allow the OS to switch to a more useful thread.)
### References
https://preshing.com/20120625/memory-ordering-at-compile-time/
https://stackoverflow.com/questions/4537753/when-should-i-use-mm-sfence-mm-lfence-and-mm-mfence
*/
namespace
{
uint32_t const WorkerCount = IB::processorCount();
constexpr uint32_t MaxJobCount = 1024;
#pragma warning(disable : 4324) // We don't care about the padding complaint here.
struct alignas(64) Job
{
alignas(16) uint8_t Data[IB::MaxJobDataSize];
void* Func = nullptr;
uint32_t Generation = 0;
uint32_t QueueIndex = IB::AllJobQueues;
};
#pragma warning(default : 4324)
struct JobQueue
{
Job *Jobs[MaxJobCount] = {}; // Mark as volatile, we don't want to cache our loads.
uint32_t Producer = 0; // Represents where we're going to write next
uint32_t Consumer = 0; // Represents where we're going to read next, advance before reading
};
struct WorkerThread
{
JobQueue Queue;
IB::ThreadHandle Thread;
IB::ThreadEvent SleepEvent;
bool Alive = false;
};
constexpr uint32_t MaxWorkerCount = 64;
WorkerThread Workers[MaxWorkerCount];
constexpr uint32_t MaxJobPoolCount = MaxJobCount * MaxWorkerCount;
Job JobPool[MaxJobPoolCount] = {};
constexpr uint32_t MaxWaitCount = 1 << 16;
constexpr uint32_t MaxJobWaiters = 10;
struct
{
uint64_t Waiters[MaxJobPoolCount][MaxJobWaiters];
uint32_t WaitCounts[MaxWaitCount];
} WaitList;
Job* takeJob(IB::JobDesc desc)
{
Job *job = nullptr;
// Get a job from our pool
// Many threads can be trying to pull from the pool at the same time
// Assure that we can commit one of the elements to ourselves using a compare exchange
uint32_t jobIndex = 0;
for (; jobIndex < MaxJobPoolCount; jobIndex++)
{
// Everyone is trying to get a job from the pool, make sure that we've taken it with a compare exchange.
if (atomicCompareExchange(&JobPool[jobIndex].Func, nullptr, desc.Func) == nullptr)
{
IB::threadAcquire(); // Assure that generation loads aren't run speculatively
job = &JobPool[jobIndex];
break;
}
}
// Our job is free to be written to at this point.
IB_ASSERT(job != nullptr, "Failed to get a job from the job pool!");
static_assert(sizeof(job->Data) == sizeof(desc.JobData), "Job description data size doesn't match job data size.");
memcpy(job->Data, desc.JobData, sizeof(desc.JobData));
job->QueueIndex = desc.QueueIndex;
return job;
}
thread_local uint32_t NextWorker = 0;
void commitJob(Job* job)
{
// Keep trying to allocator to various workers.
// If all the worker queues are full, then we'll iterate until they aren't.
// If this ends up being a problem, we can add a thread event to make our thread sleep.
uint32_t commitedWorkerIndex = UINT32_MAX;
uint32_t commitedJobIndex = UINT32_MAX;
while (commitedWorkerIndex == UINT32_MAX) // Until we've commited to a worker.
{
// Simply increment our value, use the modulo as our indexing.
uint32_t worker = (job->QueueIndex == IB::AllJobQueues ? NextWorker++ : job->QueueIndex) % WorkerCount;
// If our queue has space, try to commit our slot by doing a compare and exchange.
// If it succeeds then we've commited our producer index and moved the index forward.
// This will be visible to the worker thread,
// however it will simply wait to make sure that it has a job to do before
// it moves on to the next element.
uint32_t currentProducerIndex = IB::volatileLoad(&Workers[worker].Queue.Producer);
uint32_t nextProducerIndex = (currentProducerIndex + 1) % MaxJobCount;
while (nextProducerIndex != IB::volatileLoad(&Workers[worker].Queue.Consumer)) // Do we still have space in this queue? Keep trying.
{
if (IB::atomicCompareExchange(&Workers[worker].Queue.Producer, currentProducerIndex, nextProducerIndex) == currentProducerIndex)
{
// If we succesfuly commited to our producer index, we can use these indices.
commitedWorkerIndex = worker;
commitedJobIndex = currentProducerIndex;
break;
}
else
{
currentProducerIndex = IB::volatileLoad(&Workers[worker].Queue.Producer);
nextProducerIndex = (currentProducerIndex + 1) % MaxJobCount;
}
}
}
// If our thread is preempted before we set out job,
// then our worker thread will simply sleep until the job has actually been written to the variable.
// We will then wake it up after we're done writting it out.
IB_ASSERT(Workers[commitedWorkerIndex].Queue.Jobs[commitedJobIndex] == nullptr, "We're expecting our job to be null here! Did someone write to it before us?!?");
IB::volatileStore(&Workers[commitedWorkerIndex].Queue.Jobs[commitedJobIndex], job);
IB::threadRelease(); // Assure our writes are globally visible before this event
IB::signalThreadEvent(Workers[commitedWorkerIndex].SleepEvent); // Signal our sleeping worker
}
void waitJob(Job* job, IB::JobHandle* dependencies, uint32_t dependencyCount)
{
// Try to commit a wait counter for our dependency count.
uint32_t waitIndex = 0;
for (; waitIndex < MaxWaitCount; waitIndex++)
{
if (IB::atomicCompareExchange(&WaitList.WaitCounts[waitIndex], 0, dependencyCount + 1) == 0)
{
break;
}
}
IB_ASSERT(waitIndex != MaxWaitCount, "Failed to commit a wait counter!");
// Add our job to the wait list of all our dependencies
for (uint32_t dep = 0; dep < dependencyCount; dep++)
{
uint32_t sourceJobIndex = dependencies[dep].Value & 0xFFFFFFFF;
uint32_t sourceJobGeneration = dependencies[dep].Value >> 32;
uint16_t jobIndex = static_cast<uint16_t>(job - JobPool);
uint64_t waitHandle = ((static_cast<uint64_t>(sourceJobGeneration) + 1) << 32) | (waitIndex << 16) | jobIndex;
uint32_t listIndex = UINT32_MAX;
while (listIndex == UINT32_MAX)
{
for (uint32_t i = 0; i < MaxJobWaiters; i++)
{
if (IB::atomicCompareExchange(&WaitList.Waiters[sourceJobIndex][i], 0, waitHandle) == 0)
{
listIndex = i;
break;
}
}
}
// At this point, we could get preempted and the dependency jobs could take our job from the wait list
// If our job has moved on from our generation, that means it's complete.
// We need to do our generation check after adding to the list because if we add to the list after our job
// this situation could occur:
// - Our generation check fails
// - Dependency job preempts us and completes
// - We add our job to the list
// Now we won't get our job completed.
// With the add to the list first, if that occurs we get:
// - We add to the list
// - Job completes and removes from the list
// or
// - We add to the list
// - Generation check fails
// - Job completes and removes from the list
if (JobPool[sourceJobIndex].Generation > sourceJobGeneration)
{
// At this point, there's 3 possibilities.
// 1. No one is contending with us, we simply clear our wait index and commit our job
// 2. The job preempted us and commited the job for us
// 3. The job preempted us, commited the job for us and then someone else added their job to the list
// waitHandle cannot be equal to our handle for another job at this point because we've taken that job
// index from the job pool.
if (IB::atomicCompareExchange(&WaitList.Waiters[sourceJobIndex][listIndex], waitHandle, 0) == waitHandle)
{
IB_ASSERT(WaitList.WaitCounts[waitIndex] != 1, "Value should be above 1. 1 is our final value.");
if (IB::atomicDecrement(&WaitList.WaitCounts[waitIndex]) == 1)
{
commitJob(job);
// only once we've commited our job do we return the wait count to the pool.
IB::volatileStore<uint32_t>(&WaitList.WaitCounts[waitIndex], 0);
}
}
}
}
}
void workerFunc(void *data)
{
WorkerThread *worker = reinterpret_cast<WorkerThread *>(data);
JobQueue *queue = &worker->Queue;
while (true)
{
while (IB::volatileLoad(&queue->Jobs[queue->Consumer]) == nullptr && IB::volatileLoad(&worker->Alive))
{
// Give it a few iterations, we might just be writting the value to this index.
bool breakEarly = false;
for (uint32_t i = 0; i < 32; i++)
{
if (IB::volatileLoad(&queue->Jobs[queue->Consumer]) != nullptr || !IB::volatileLoad(&worker->Alive))
{
breakEarly = true;
break;
}
}
if (breakEarly)
{
break;
}
// Should go to sleep here after a few iterations.
// Possible behaviour for this wait:
// - No work is available, next signal will wake us when we add work
// - Work is available but not visible to us yet, signal will wake us when it's visible
// - Signal has been sent for a previous chunk of work
// Say we signaled for Consumer - 1,
// If we signaled for that index and it wasn't consumed
// then we'll simply reset the event
// and return to the iteration to wait for the next signal
// There are no states (that I can think of) that will leave us waiting for a signal
// even if there is work available.
waitOnThreadEvent(worker->SleepEvent);
IB::threadAcquire(); // Assure our loads aren't run before this event
}
if (!IB::volatileLoad(&worker->Alive))
{
break;
}
Job *job = IB::volatileLoad(&queue->Jobs[queue->Consumer]);
// Note that our job might have marked itself for continuation while it's also active in another thread.
// If it was put to sleep in this result, it will simply be removed from the queue
// As a result, it should behave correctly if the job completes before it is even put to sleep.
// If putting to sleep has side effects in the future, the API might have to be re-thought
IB::JobResult result = reinterpret_cast<IB::JobFunc *>(job->Func)(job->Data);
// Queue management
{
IB::volatileStore<Job *volatile>(&queue->Jobs[queue->Consumer], nullptr);
// Make sure other threads see our writes to the job queue before we move our consumer index forward.
// This fence is not necessary, but having it allows us to have some extra
// asserts on the producer side to make sure producers aren't stomping on each other.
IB::threadRelease();
IB::volatileStore(&queue->Consumer, (queue->Consumer + 1) % MaxJobCount);
}
// A sleeping job will not be returned to the job pool and waiting
// jobs will not be signaled.
if (result == IB::JobResult::Complete)
{
// Thread pool management
uint32_t generation = IB::volatileLoad(&job->Generation);
{
IB::volatileStore(&job->Generation, generation + 1);
// Assure that our generation increment is visible before we return our job to the pool
// If it wasn't, our job could be pulled from the pool,
// and a handle created with the wrong generation index.
IB::threadRelease();
IB::volatileStore<void *volatile>(&job->Func, nullptr); // Returns our job to the pool
}
// Attempt to signal all our waiting jobs
uint32_t jobIndex = static_cast<uint32_t>(job - JobPool);
for (uint32_t i = 0; i < MaxJobWaiters; i++)
{
uint64_t waitHandle = IB::volatileLoad(&WaitList.Waiters[jobIndex][i]);
// If we fail this branch and move on,
// and then the continueJob writes to that slot for this job,
// then that means our generation index was already incremented.
// and as a result the continueJob function will immediatly commit the waiting job.
if (waitHandle != 0)
{
uint32_t targetGeneration = (waitHandle >> 32) - 1; // We added 1 to our generation to make sure that our handle is non zero
uint32_t theirIndex = (waitHandle & 0xFFFF);
uint32_t waitIndex = (waitHandle >> 16) & 0xFFFF;
if (targetGeneration == generation)
{
// Attempt to take the job from the list of waiters.
// If we failed to take it, ignore it,
// it means the job was committed by the "continueJob" call.
if (IB::atomicCompareExchange(&WaitList.Waiters[jobIndex][i], waitHandle, 0) == waitHandle)
{
IB_ASSERT(WaitList.WaitCounts[waitIndex] != 1, "Value should be above 1. 1 is our final value.");
if (IB::atomicDecrement(&WaitList.WaitCounts[waitIndex]) == 1)
{
commitJob(&JobPool[theirIndex]);
IB::volatileStore<uint32_t>(&WaitList.WaitCounts[waitIndex], 0);
}
}
}
}
}
}
}
}
} // namespace
namespace IB
{
void initJobSystem()
{
memset(&WaitList, 0, sizeof(WaitList)); // Zero at runtime. Compiler hates zeroing this out.
for (uint32_t i = 0; i < WorkerCount; i++)
{
Workers[i].Alive = true;
Workers[i].Thread = createThread(&workerFunc, &Workers[i]);
Workers[i].SleepEvent = createThreadEvent();
}
}
void killJobSystem()
{
ThreadHandle threads[MaxWorkerCount];
for (uint32_t i = 0; i < WorkerCount; i++)
{
volatileStore(&Workers[i].Alive, false);
threads[i] = Workers[i].Thread;
IB::threadRelease();
IB::signalThreadEvent(Workers[i].SleepEvent);
}
waitOnThreads(threads, WorkerCount);
for (uint32_t i = 0; i < WorkerCount; i++)
{
destroyThread(Workers[i].Thread);
destroyThreadEvent(Workers[i].SleepEvent);
}
}
JobHandle reserveJob(JobDesc desc)
{
Job* job = takeJob(desc);
return { (static_cast<uint64_t>(job->Generation) << 32) | static_cast<uint32_t>(job - JobPool) };
}
JobHandle continueJob(JobDesc desc, JobHandle* dependencies, uint32_t dependencyCount)
{
Job* job = takeJob(desc);
// Retrieve our job generation before we potentially commit our job.
// if might execute and complete before we even reach our return.
uint32_t jobGeneration = volatileLoad(&job->Generation);
waitJob(job, dependencies, dependencyCount);
return { (static_cast<uint64_t>(jobGeneration) << 32) | static_cast<uint32_t>(job - JobPool) };
}
void continueJob(JobHandle handle, JobHandle* dependencies, uint32_t dependencyCount)
{
uint32_t jobIndex = handle.Value & 0xFFFFFFFF;
uint32_t generation = handle.Value >> 32;
Job* job = &JobPool[jobIndex];
IB_ASSERT(job->Generation == generation, "Asking to continue a job that was completed. Did we put it to sleep?");
waitJob(job, dependencies, dependencyCount);
}
void launchJob(JobHandle handle)
{
uint32_t jobIndex = handle.Value & 0xFFFFFFFF;
uint32_t generation = handle.Value >> 32;
Job* job = &JobPool[jobIndex];
IB_ASSERT(job->Generation == generation, "Asking to continue a job that was completed. Did we put it to sleep?");
commitJob(job);
}
JobHandle launchJob(JobDesc desc)
{
Job* job = takeJob(desc);
// Grab our job generation before we commit it.
// The job generation might increment if we get preempted before our return.
uint32_t jobGeneration = volatileLoad(&job->Generation);
commitJob(job);
return { (static_cast<uint64_t>(jobGeneration) << 32) | static_cast<uint32_t>(job - JobPool) };
}
} // namespace IB
| 48.277228 | 183 | 0.63064 | [
"model"
] |
3c8976d16dc4d2cd27135fa683b4e7ae90f95514 | 638 | cpp | C++ | LeetCode/Solutions/LC0057.cpp | Mohammed-Shoaib/HackerRank-Problems | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | [
"MIT"
] | 54 | 2019-05-13T12:13:09.000Z | 2022-02-27T02:59:00.000Z | LeetCode/Solutions/LC0057.cpp | Mohammed-Shoaib/HackerRank-Problems | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | [
"MIT"
] | 2 | 2020-10-02T07:16:43.000Z | 2020-10-19T04:36:19.000Z | LeetCode/Solutions/LC0057.cpp | Mohammed-Shoaib/HackerRank-Problems | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | [
"MIT"
] | 20 | 2020-05-26T09:48:13.000Z | 2022-03-18T15:18:27.000Z | /*
Problem Statement: https://leetcode.com/problems/insert-interval/
Time: O(n)
Space: O(n)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
vector<vector<int>> res;
for (vector<int>& v: intervals) {
if (v[1] < newInterval[0])
res.push_back(v);
else if (newInterval[1] < v[0]) {
res.push_back(newInterval);
newInterval = v;
} else {
newInterval[0] = min(v[0], newInterval[0]);
newInterval[1] = max(v[1], newInterval[1]);
}
}
res.push_back(newInterval);
return res;
}
}; | 22.785714 | 87 | 0.645768 | [
"vector"
] |
3c89cb7005a8158fc5308b5ed7f6282f062d3191 | 73,998 | cpp | C++ | Blizzlike/Trinity/Scripts/Spells/spell_item.cpp | 499453466/Lua-Other | 43fd2b72405faf3f2074fd2a2706ef115d16faa6 | [
"Unlicense"
] | 2 | 2015-06-23T16:26:32.000Z | 2019-06-27T07:45:59.000Z | Blizzlike/Trinity/Scripts/Spells/spell_item.cpp | Eduardo-Silla/Lua-Other | db610f946dbcaf81b3de9801f758e11a7bf2753f | [
"Unlicense"
] | null | null | null | Blizzlike/Trinity/Scripts/Spells/spell_item.cpp | Eduardo-Silla/Lua-Other | db610f946dbcaf81b3de9801f758e11a7bf2753f | [
"Unlicense"
] | 3 | 2015-01-10T18:22:59.000Z | 2021-04-27T21:28:28.000Z | /*
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Scripts for spells with SPELLFAMILY_GENERIC spells used by items.
* Ordered alphabetically using scriptname.
* Scriptnames of files in this file should be prefixed with "spell_item_".
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "SpellScript.h"
#include "SpellAuraEffects.h"
#include "SkillDiscovery.h"
// Generic script for handling item dummy effects which trigger another spell.
class spell_item_trigger_spell : public SpellScriptLoader
{
private:
uint32 _triggeredSpellId;
public:
spell_item_trigger_spell(const char* name, uint32 triggeredSpellId) : SpellScriptLoader(name), _triggeredSpellId(triggeredSpellId) { }
class spell_item_trigger_spell_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_trigger_spell_SpellScript);
private:
uint32 _triggeredSpellId;
public:
spell_item_trigger_spell_SpellScript(uint32 triggeredSpellId) : SpellScript(), _triggeredSpellId(triggeredSpellId) { }
bool Validate(SpellInfo const* /*spellEntry*/)
{
if (!sSpellMgr->GetSpellInfo(_triggeredSpellId))
return false;
return true;
}
void HandleDummy(SpellEffIndex /*effIndex*/)
{
Unit* caster = GetCaster();
if (Item* item = GetCastItem())
caster->CastSpell(caster, _triggeredSpellId, true, item);
}
void Register()
{
OnEffectHit += SpellEffectFn(spell_item_trigger_spell_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_trigger_spell_SpellScript(_triggeredSpellId);
}
};
// http://www.wowhead.com/item=6522 Deviate Fish
// 8063 Deviate Fish
enum DeviateFishSpells
{
SPELL_SLEEPY = 8064,
SPELL_INVIGORATE = 8065,
SPELL_SHRINK = 8066,
SPELL_PARTY_TIME = 8067,
SPELL_HEALTHY_SPIRIT = 8068,
};
class spell_item_deviate_fish : public SpellScriptLoader
{
public:
spell_item_deviate_fish() : SpellScriptLoader("spell_item_deviate_fish") { }
class spell_item_deviate_fish_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_deviate_fish_SpellScript);
bool Load()
{
return GetCaster()->GetTypeId() == TYPEID_PLAYER;
}
bool Validate(SpellInfo const* /*spellEntry*/)
{
for (uint32 spellId = SPELL_SLEEPY; spellId <= SPELL_HEALTHY_SPIRIT; ++spellId)
if (!sSpellMgr->GetSpellInfo(spellId))
return false;
return true;
}
void HandleDummy(SpellEffIndex /*effIndex*/)
{
Unit* caster = GetCaster();
uint32 spellId = urand(SPELL_SLEEPY, SPELL_HEALTHY_SPIRIT);
caster->CastSpell(caster, spellId, true, NULL);
}
void Register()
{
OnEffectHit += SpellEffectFn(spell_item_deviate_fish_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_deviate_fish_SpellScript();
}
};
// http://www.wowhead.com/item=47499 Flask of the North
// 67019 Flask of the North
enum FlaskOfTheNorthSpells
{
SPELL_FLASK_OF_THE_NORTH_SP = 67016,
SPELL_FLASK_OF_THE_NORTH_AP = 67017,
SPELL_FLASK_OF_THE_NORTH_STR = 67018,
};
class spell_item_flask_of_the_north : public SpellScriptLoader
{
public:
spell_item_flask_of_the_north() : SpellScriptLoader("spell_item_flask_of_the_north") { }
class spell_item_flask_of_the_north_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_flask_of_the_north_SpellScript);
bool Validate(SpellInfo const* /*spellEntry*/)
{
if (!sSpellMgr->GetSpellInfo(SPELL_FLASK_OF_THE_NORTH_SP) || !sSpellMgr->GetSpellInfo(SPELL_FLASK_OF_THE_NORTH_AP) || !sSpellMgr->GetSpellInfo(SPELL_FLASK_OF_THE_NORTH_STR))
return false;
return true;
}
void HandleDummy(SpellEffIndex /*effIndex*/)
{
Unit* caster = GetCaster();
std::vector<uint32> possibleSpells;
switch (caster->getClass())
{
case CLASS_WARLOCK:
case CLASS_MAGE:
case CLASS_PRIEST:
possibleSpells.push_back(SPELL_FLASK_OF_THE_NORTH_SP);
break;
case CLASS_DEATH_KNIGHT:
case CLASS_WARRIOR:
possibleSpells.push_back(SPELL_FLASK_OF_THE_NORTH_STR);
break;
case CLASS_ROGUE:
case CLASS_HUNTER:
possibleSpells.push_back(SPELL_FLASK_OF_THE_NORTH_AP);
break;
case CLASS_DRUID:
case CLASS_PALADIN:
possibleSpells.push_back(SPELL_FLASK_OF_THE_NORTH_SP);
possibleSpells.push_back(SPELL_FLASK_OF_THE_NORTH_STR);
break;
case CLASS_SHAMAN:
possibleSpells.push_back(SPELL_FLASK_OF_THE_NORTH_SP);
possibleSpells.push_back(SPELL_FLASK_OF_THE_NORTH_AP);
break;
}
caster->CastSpell(caster, possibleSpells[irand(0, (possibleSpells.size() - 1))], true, NULL);
}
void Register()
{
OnEffectHit += SpellEffectFn(spell_item_flask_of_the_north_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_flask_of_the_north_SpellScript();
}
};
// http://www.wowhead.com/item=10645 Gnomish Death Ray
// 13280 Gnomish Death Ray
enum GnomishDeathRay
{
SPELL_GNOMISH_DEATH_RAY_SELF = 13493,
SPELL_GNOMISH_DEATH_RAY_TARGET = 13279,
};
class spell_item_gnomish_death_ray : public SpellScriptLoader
{
public:
spell_item_gnomish_death_ray() : SpellScriptLoader("spell_item_gnomish_death_ray") { }
class spell_item_gnomish_death_ray_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_gnomish_death_ray_SpellScript);
bool Validate(SpellInfo const* /*spellEntry*/)
{
if (!sSpellMgr->GetSpellInfo(SPELL_GNOMISH_DEATH_RAY_SELF) || !sSpellMgr->GetSpellInfo(SPELL_GNOMISH_DEATH_RAY_TARGET))
return false;
return true;
}
void HandleDummy(SpellEffIndex /*effIndex*/)
{
Unit* caster = GetCaster();
if (Unit* target = GetHitUnit())
{
if (urand(0, 99) < 15)
caster->CastSpell(caster, SPELL_GNOMISH_DEATH_RAY_SELF, true, NULL); // failure
else
caster->CastSpell(target, SPELL_GNOMISH_DEATH_RAY_TARGET, true, NULL);
}
}
void Register()
{
OnEffectHitTarget += SpellEffectFn(spell_item_gnomish_death_ray_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_gnomish_death_ray_SpellScript();
}
};
// http://www.wowhead.com/item=27388 Mr. Pinchy
// 33060 Make a Wish
enum MakeAWish
{
SPELL_MR_PINCHYS_BLESSING = 33053,
SPELL_SUMMON_MIGHTY_MR_PINCHY = 33057,
SPELL_SUMMON_FURIOUS_MR_PINCHY = 33059,
SPELL_TINY_MAGICAL_CRAWDAD = 33062,
SPELL_MR_PINCHYS_GIFT = 33064,
};
class spell_item_make_a_wish : public SpellScriptLoader
{
public:
spell_item_make_a_wish() : SpellScriptLoader("spell_item_make_a_wish") { }
class spell_item_make_a_wish_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_make_a_wish_SpellScript);
bool Load()
{
return GetCaster()->GetTypeId() == TYPEID_PLAYER;
}
bool Validate(SpellInfo const* /*spellEntry*/)
{
if (!sSpellMgr->GetSpellInfo(SPELL_MR_PINCHYS_BLESSING) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_MIGHTY_MR_PINCHY) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_FURIOUS_MR_PINCHY) || !sSpellMgr->GetSpellInfo(SPELL_TINY_MAGICAL_CRAWDAD) || !sSpellMgr->GetSpellInfo(SPELL_MR_PINCHYS_GIFT))
return false;
return true;
}
void HandleDummy(SpellEffIndex /*effIndex*/)
{
Unit* caster = GetCaster();
uint32 spellId = SPELL_MR_PINCHYS_GIFT;
switch (urand(1, 5))
{
case 1: spellId = SPELL_MR_PINCHYS_BLESSING; break;
case 2: spellId = SPELL_SUMMON_MIGHTY_MR_PINCHY; break;
case 3: spellId = SPELL_SUMMON_FURIOUS_MR_PINCHY; break;
case 4: spellId = SPELL_TINY_MAGICAL_CRAWDAD; break;
}
caster->CastSpell(caster, spellId, true, NULL);
}
void Register()
{
OnEffectHit += SpellEffectFn(spell_item_make_a_wish_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_make_a_wish_SpellScript();
}
};
// http://www.wowhead.com/item=32686 Mingo's Fortune Giblets
// 40802 Mingo's Fortune Generator
class spell_item_mingos_fortune_generator : public SpellScriptLoader
{
public:
spell_item_mingos_fortune_generator() : SpellScriptLoader("spell_item_mingos_fortune_generator") { }
class spell_item_mingos_fortune_generator_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_mingos_fortune_generator_SpellScript);
void HandleDummy(SpellEffIndex effIndex)
{
// Selecting one from Bloodstained Fortune item
uint32 newitemid;
switch (urand(1, 20))
{
case 1: newitemid = 32688; break;
case 2: newitemid = 32689; break;
case 3: newitemid = 32690; break;
case 4: newitemid = 32691; break;
case 5: newitemid = 32692; break;
case 6: newitemid = 32693; break;
case 7: newitemid = 32700; break;
case 8: newitemid = 32701; break;
case 9: newitemid = 32702; break;
case 10: newitemid = 32703; break;
case 11: newitemid = 32704; break;
case 12: newitemid = 32705; break;
case 13: newitemid = 32706; break;
case 14: newitemid = 32707; break;
case 15: newitemid = 32708; break;
case 16: newitemid = 32709; break;
case 17: newitemid = 32710; break;
case 18: newitemid = 32711; break;
case 19: newitemid = 32712; break;
case 20: newitemid = 32713; break;
default:
return;
}
CreateItem(effIndex, newitemid);
}
void Register()
{
OnEffectHit += SpellEffectFn(spell_item_mingos_fortune_generator_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_mingos_fortune_generator_SpellScript();
}
};
// http://www.wowhead.com/item=10720 Gnomish Net-o-Matic Projector
// 13120 Net-o-Matic
enum NetOMaticSpells
{
SPELL_NET_O_MATIC_TRIGGERED1 = 16566,
SPELL_NET_O_MATIC_TRIGGERED2 = 13119,
SPELL_NET_O_MATIC_TRIGGERED3 = 13099,
};
class spell_item_net_o_matic : public SpellScriptLoader
{
public:
spell_item_net_o_matic() : SpellScriptLoader("spell_item_net_o_matic") { }
class spell_item_net_o_matic_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_net_o_matic_SpellScript);
bool Validate(SpellInfo const* /*spellEntry*/)
{
if (!sSpellMgr->GetSpellInfo(SPELL_NET_O_MATIC_TRIGGERED1) || !sSpellMgr->GetSpellInfo(SPELL_NET_O_MATIC_TRIGGERED2) || !sSpellMgr->GetSpellInfo(SPELL_NET_O_MATIC_TRIGGERED3))
return false;
return true;
}
void HandleDummy(SpellEffIndex /*effIndex*/)
{
if (Unit* target = GetHitUnit())
{
uint32 spellId = SPELL_NET_O_MATIC_TRIGGERED3;
uint32 roll = urand(0, 99);
if (roll < 2) // 2% for 30 sec self root (off-like chance unknown)
spellId = SPELL_NET_O_MATIC_TRIGGERED1;
else if (roll < 4) // 2% for 20 sec root, charge to target (off-like chance unknown)
spellId = SPELL_NET_O_MATIC_TRIGGERED2;
GetCaster()->CastSpell(target, spellId, true, NULL);
}
}
void Register()
{
OnEffectHitTarget += SpellEffectFn(spell_item_net_o_matic_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_net_o_matic_SpellScript();
}
};
// http://www.wowhead.com/item=8529 Noggenfogger Elixir
// 16589 Noggenfogger Elixir
enum NoggenfoggerElixirSpells
{
SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED1 = 16595,
SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED2 = 16593,
SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED3 = 16591,
};
class spell_item_noggenfogger_elixir : public SpellScriptLoader
{
public:
spell_item_noggenfogger_elixir() : SpellScriptLoader("spell_item_noggenfogger_elixir") { }
class spell_item_noggenfogger_elixir_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_noggenfogger_elixir_SpellScript);
bool Load()
{
return GetCaster()->GetTypeId() == TYPEID_PLAYER;
}
bool Validate(SpellInfo const* /*spellEntry*/)
{
if (!sSpellMgr->GetSpellInfo(SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED1) || !sSpellMgr->GetSpellInfo(SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED2) || !sSpellMgr->GetSpellInfo(SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED3))
return false;
return true;
}
void HandleDummy(SpellEffIndex /*effIndex*/)
{
Unit* caster = GetCaster();
uint32 spellId = SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED3;
switch (urand(1, 3))
{
case 1: spellId = SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED1; break;
case 2: spellId = SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED2; break;
}
caster->CastSpell(caster, spellId, true, NULL);
}
void Register()
{
OnEffectHit += SpellEffectFn(spell_item_noggenfogger_elixir_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_noggenfogger_elixir_SpellScript();
}
};
// http://www.wowhead.com/item=6657 Savory Deviate Delight
// 8213 Savory Deviate Delight
enum SavoryDeviateDelight
{
SPELL_FLIP_OUT_MALE = 8219,
SPELL_FLIP_OUT_FEMALE = 8220,
SPELL_YAAARRRR_MALE = 8221,
SPELL_YAAARRRR_FEMALE = 8222,
};
class spell_item_savory_deviate_delight : public SpellScriptLoader
{
public:
spell_item_savory_deviate_delight() : SpellScriptLoader("spell_item_savory_deviate_delight") { }
class spell_item_savory_deviate_delight_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_savory_deviate_delight_SpellScript);
bool Load()
{
return GetCaster()->GetTypeId() == TYPEID_PLAYER;
}
bool Validate(SpellInfo const* /*spellEntry*/)
{
for (uint32 spellId = SPELL_FLIP_OUT_MALE; spellId <= SPELL_YAAARRRR_FEMALE; ++spellId)
if (!sSpellMgr->GetSpellInfo(spellId))
return false;
return true;
}
void HandleDummy(SpellEffIndex /*effIndex*/)
{
Unit* caster = GetCaster();
uint32 spellId = 0;
switch (urand(1, 2))
{
// Flip Out - ninja
case 1: spellId = (caster->getGender() == GENDER_MALE ? SPELL_FLIP_OUT_MALE : SPELL_FLIP_OUT_FEMALE); break;
// Yaaarrrr - pirate
case 2: spellId = (caster->getGender() == GENDER_MALE ? SPELL_YAAARRRR_MALE : SPELL_YAAARRRR_FEMALE); break;
}
caster->CastSpell(caster, spellId, true, NULL);
}
void Register()
{
OnEffectHit += SpellEffectFn(spell_item_savory_deviate_delight_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_savory_deviate_delight_SpellScript();
}
};
// http://www.wowhead.com/item=7734 Six Demon Bag
// 14537 Six Demon Bag
enum SixDemonBagSpells
{
SPELL_FROSTBOLT = 11538,
SPELL_POLYMORPH = 14621,
SPELL_SUMMON_FELHOUND_MINION = 14642,
SPELL_FIREBALL = 15662,
SPELL_CHAIN_LIGHTNING = 21179,
SPELL_ENVELOPING_WINDS = 25189,
};
class spell_item_six_demon_bag : public SpellScriptLoader
{
public:
spell_item_six_demon_bag() : SpellScriptLoader("spell_item_six_demon_bag") { }
class spell_item_six_demon_bag_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_six_demon_bag_SpellScript);
bool Validate(SpellInfo const* /*spellEntry*/)
{
if (!sSpellMgr->GetSpellInfo(SPELL_FROSTBOLT) || !sSpellMgr->GetSpellInfo(SPELL_POLYMORPH) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_FELHOUND_MINION) || !sSpellMgr->GetSpellInfo(SPELL_FIREBALL) || !sSpellMgr->GetSpellInfo(SPELL_CHAIN_LIGHTNING) || !sSpellMgr->GetSpellInfo(SPELL_ENVELOPING_WINDS))
return false;
return true;
}
void HandleDummy(SpellEffIndex /*effIndex*/)
{
Unit* caster = GetCaster();
if (Unit* target = GetHitUnit())
{
uint32 spellId = 0;
uint32 rand = urand(0, 99);
if (rand < 25) // Fireball (25% chance)
spellId = SPELL_FIREBALL;
else if (rand < 50) // Frostball (25% chance)
spellId = SPELL_FROSTBOLT;
else if (rand < 70) // Chain Lighting (20% chance)
spellId = SPELL_CHAIN_LIGHTNING;
else if (rand < 80) // Polymorph (10% chance)
{
spellId = SPELL_POLYMORPH;
if (urand(0, 100) <= 30) // 30% chance to self-cast
target = caster;
}
else if (rand < 95) // Enveloping Winds (15% chance)
spellId = SPELL_ENVELOPING_WINDS;
else // Summon Felhund minion (5% chance)
{
spellId = SPELL_SUMMON_FELHOUND_MINION;
target = caster;
}
caster->CastSpell(target, spellId, true, GetCastItem());
}
}
void Register()
{
OnEffectHitTarget += SpellEffectFn(spell_item_six_demon_bag_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_six_demon_bag_SpellScript();
}
};
// http://www.wowhead.com/item=44012 Underbelly Elixir
// 59640 Underbelly Elixir
enum UnderbellyElixirSpells
{
SPELL_UNDERBELLY_ELIXIR_TRIGGERED1 = 59645,
SPELL_UNDERBELLY_ELIXIR_TRIGGERED2 = 59831,
SPELL_UNDERBELLY_ELIXIR_TRIGGERED3 = 59843,
};
class spell_item_underbelly_elixir : public SpellScriptLoader
{
public:
spell_item_underbelly_elixir() : SpellScriptLoader("spell_item_underbelly_elixir") { }
class spell_item_underbelly_elixir_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_underbelly_elixir_SpellScript);
bool Load()
{
return GetCaster()->GetTypeId() == TYPEID_PLAYER;
}
bool Validate(SpellInfo const* /*spellEntry*/)
{
if (!sSpellMgr->GetSpellInfo(SPELL_UNDERBELLY_ELIXIR_TRIGGERED1) || !sSpellMgr->GetSpellInfo(SPELL_UNDERBELLY_ELIXIR_TRIGGERED2) || !sSpellMgr->GetSpellInfo(SPELL_UNDERBELLY_ELIXIR_TRIGGERED3))
return false;
return true;
}
void HandleDummy(SpellEffIndex /*effIndex*/)
{
Unit* caster = GetCaster();
uint32 spellId = SPELL_UNDERBELLY_ELIXIR_TRIGGERED3;
switch (urand(1, 3))
{
case 1: spellId = SPELL_UNDERBELLY_ELIXIR_TRIGGERED1; break;
case 2: spellId = SPELL_UNDERBELLY_ELIXIR_TRIGGERED2; break;
}
caster->CastSpell(caster, spellId, true, NULL);
}
void Register()
{
OnEffectHit += SpellEffectFn(spell_item_underbelly_elixir_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_underbelly_elixir_SpellScript();
}
};
enum eShadowmourneVisuals
{
SPELL_SHADOWMOURNE_VISUAL_LOW = 72521,
SPELL_SHADOWMOURNE_VISUAL_HIGH = 72523,
SPELL_SHADOWMOURNE_CHAOS_BANE_BUFF = 73422,
};
class spell_item_shadowmourne : public SpellScriptLoader
{
public:
spell_item_shadowmourne() : SpellScriptLoader("spell_item_shadowmourne") { }
class spell_item_shadowmourne_AuraScript : public AuraScript
{
PrepareAuraScript(spell_item_shadowmourne_AuraScript);
bool Validate(SpellInfo const* /*spellEntry*/)
{
if (!sSpellMgr->GetSpellInfo(SPELL_SHADOWMOURNE_VISUAL_LOW) || !sSpellMgr->GetSpellInfo(SPELL_SHADOWMOURNE_VISUAL_HIGH) || !sSpellMgr->GetSpellInfo(SPELL_SHADOWMOURNE_CHAOS_BANE_BUFF))
return false;
return true;
}
void OnStackChange(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/)
{
Unit* target = GetTarget();
switch (GetStackAmount())
{
case 1:
target->CastSpell(target, SPELL_SHADOWMOURNE_VISUAL_LOW, true);
break;
case 6:
target->RemoveAurasDueToSpell(SPELL_SHADOWMOURNE_VISUAL_LOW);
target->CastSpell(target, SPELL_SHADOWMOURNE_VISUAL_HIGH, true);
break;
case 10:
target->RemoveAurasDueToSpell(SPELL_SHADOWMOURNE_VISUAL_HIGH);
target->CastSpell(target, SPELL_SHADOWMOURNE_CHAOS_BANE_BUFF, true);
break;
default:
break;
}
}
void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/)
{
Unit* target = GetTarget();
target->RemoveAurasDueToSpell(SPELL_SHADOWMOURNE_VISUAL_LOW);
target->RemoveAurasDueToSpell(SPELL_SHADOWMOURNE_VISUAL_HIGH);
}
void Register()
{
AfterEffectApply += AuraEffectApplyFn(spell_item_shadowmourne_AuraScript::OnStackChange, EFFECT_0, SPELL_AURA_MOD_STAT, AuraEffectHandleModes(AURA_EFFECT_HANDLE_REAL | AURA_EFFECT_HANDLE_REAPPLY));
AfterEffectRemove += AuraEffectRemoveFn(spell_item_shadowmourne_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_MOD_STAT, AURA_EFFECT_HANDLE_REAL);
}
};
AuraScript* GetAuraScript() const
{
return new spell_item_shadowmourne_AuraScript();
}
};
enum AirRifleSpells
{
SPELL_AIR_RIFLE_HOLD_VISUAL = 65582,
SPELL_AIR_RIFLE_SHOOT = 67532,
SPELL_AIR_RIFLE_SHOOT_SELF = 65577,
};
class spell_item_red_rider_air_rifle : public SpellScriptLoader
{
public:
spell_item_red_rider_air_rifle() : SpellScriptLoader("spell_item_red_rider_air_rifle") { }
class spell_item_red_rider_air_rifle_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_red_rider_air_rifle_SpellScript);
bool Validate(SpellInfo const* /*spell*/)
{
if (!sSpellMgr->GetSpellInfo(SPELL_AIR_RIFLE_HOLD_VISUAL) || !sSpellMgr->GetSpellInfo(SPELL_AIR_RIFLE_SHOOT) || !sSpellMgr->GetSpellInfo(SPELL_AIR_RIFLE_SHOOT_SELF))
return false;
return true;
}
void HandleScript(SpellEffIndex effIndex)
{
PreventHitDefaultEffect(effIndex);
Unit* caster = GetCaster();
if (Unit* target = GetHitUnit())
{
caster->CastSpell(caster, SPELL_AIR_RIFLE_HOLD_VISUAL, true);
// needed because this spell shares GCD with its triggered spells (which must not be cast with triggered flag)
if (Player* player = caster->ToPlayer())
player->GetGlobalCooldownMgr().CancelGlobalCooldown(GetSpellInfo());
if (urand(0, 4))
caster->CastSpell(target, SPELL_AIR_RIFLE_SHOOT, false);
else
caster->CastSpell(caster, SPELL_AIR_RIFLE_SHOOT_SELF, false);
}
}
void Register()
{
OnEffectHitTarget += SpellEffectFn(spell_item_red_rider_air_rifle_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_red_rider_air_rifle_SpellScript();
}
};
enum GenericData
{
SPELL_ARCANITE_DRAGONLING = 19804,
SPELL_BATTLE_CHICKEN = 13166,
SPELL_MECHANICAL_DRAGONLING = 4073,
SPELL_MITHRIL_MECHANICAL_DRAGONLING = 12749,
};
enum CreateHeartCandy
{
ITEM_HEART_CANDY_1 = 21818,
ITEM_HEART_CANDY_2 = 21817,
ITEM_HEART_CANDY_3 = 21821,
ITEM_HEART_CANDY_4 = 21819,
ITEM_HEART_CANDY_5 = 21816,
ITEM_HEART_CANDY_6 = 21823,
ITEM_HEART_CANDY_7 = 21822,
ITEM_HEART_CANDY_8 = 21820,
};
class spell_item_create_heart_candy : public SpellScriptLoader
{
public:
spell_item_create_heart_candy() : SpellScriptLoader("spell_item_create_heart_candy") { }
class spell_item_create_heart_candy_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_create_heart_candy_SpellScript);
void HandleScript(SpellEffIndex effIndex)
{
PreventHitDefaultEffect(effIndex);
if (Player* target = GetHitPlayer())
{
static const uint32 items[] = {ITEM_HEART_CANDY_1, ITEM_HEART_CANDY_2, ITEM_HEART_CANDY_3, ITEM_HEART_CANDY_4, ITEM_HEART_CANDY_5, ITEM_HEART_CANDY_6, ITEM_HEART_CANDY_7, ITEM_HEART_CANDY_8};
target->AddItem(items[urand(0, 7)], 1);
}
}
void Register()
{
OnEffectHitTarget += SpellEffectFn(spell_item_create_heart_candy_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_create_heart_candy_SpellScript();
}
};
class spell_item_book_of_glyph_mastery : public SpellScriptLoader
{
public:
spell_item_book_of_glyph_mastery() : SpellScriptLoader("spell_item_book_of_glyph_mastery") {}
class spell_item_book_of_glyph_mastery_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_book_of_glyph_mastery_SpellScript);
bool Load()
{
return GetCaster()->GetTypeId() == TYPEID_PLAYER;
}
SpellCastResult CheckRequirement()
{
if (HasDiscoveredAllSpells(GetSpellInfo()->Id, GetCaster()->ToPlayer()))
{
SetCustomCastResultMessage(SPELL_CUSTOM_ERROR_LEARNED_EVERYTHING);
return SPELL_FAILED_CUSTOM_ERROR;
}
return SPELL_CAST_OK;
}
void Register()
{
OnCheckCast += SpellCheckCastFn(spell_item_book_of_glyph_mastery_SpellScript::CheckRequirement);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_book_of_glyph_mastery_SpellScript();
}
};
enum GiftOfTheHarvester
{
NPC_GHOUL = 28845,
MAX_GHOULS = 5,
};
class spell_item_gift_of_the_harvester : public SpellScriptLoader
{
public:
spell_item_gift_of_the_harvester() : SpellScriptLoader("spell_item_gift_of_the_harvester") {}
class spell_item_gift_of_the_harvester_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_gift_of_the_harvester_SpellScript);
SpellCastResult CheckRequirement()
{
std::list<Creature*> ghouls;
GetCaster()->GetAllMinionsByEntry(ghouls, NPC_GHOUL);
if (ghouls.size() >= MAX_GHOULS)
{
SetCustomCastResultMessage(SPELL_CUSTOM_ERROR_TOO_MANY_GHOULS);
return SPELL_FAILED_CUSTOM_ERROR;
}
return SPELL_CAST_OK;
}
void Register()
{
OnCheckCast += SpellCheckCastFn(spell_item_gift_of_the_harvester_SpellScript::CheckRequirement);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_gift_of_the_harvester_SpellScript();
}
};
enum Sinkholes
{
NPC_SOUTH_SINKHOLE = 25664,
NPC_NORTHEAST_SINKHOLE = 25665,
NPC_NORTHWEST_SINKHOLE = 25666,
};
class spell_item_map_of_the_geyser_fields : public SpellScriptLoader
{
public:
spell_item_map_of_the_geyser_fields() : SpellScriptLoader("spell_item_map_of_the_geyser_fields") {}
class spell_item_map_of_the_geyser_fields_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_map_of_the_geyser_fields_SpellScript);
SpellCastResult CheckSinkholes()
{
Unit* caster = GetCaster();
if (caster->FindNearestCreature(NPC_SOUTH_SINKHOLE, 30.0f, true) ||
caster->FindNearestCreature(NPC_NORTHEAST_SINKHOLE, 30.0f, true) ||
caster->FindNearestCreature(NPC_NORTHWEST_SINKHOLE, 30.0f, true))
return SPELL_CAST_OK;
SetCustomCastResultMessage(SPELL_CUSTOM_ERROR_MUST_BE_CLOSE_TO_SINKHOLE);
return SPELL_FAILED_CUSTOM_ERROR;
}
void Register()
{
OnCheckCast += SpellCheckCastFn(spell_item_map_of_the_geyser_fields_SpellScript::CheckSinkholes);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_map_of_the_geyser_fields_SpellScript();
}
};
enum VanquishedClutchesSpells
{
SPELL_CRUSHER = 64982,
SPELL_CONSTRICTOR = 64983,
SPELL_CORRUPTOR = 64984,
};
class spell_item_vanquished_clutches : public SpellScriptLoader
{
public:
spell_item_vanquished_clutches() : SpellScriptLoader("spell_item_vanquished_clutches") { }
class spell_item_vanquished_clutches_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_vanquished_clutches_SpellScript);
bool Validate(SpellInfo const* /*spellEntry*/)
{
if (!sSpellMgr->GetSpellInfo(SPELL_CRUSHER) || !sSpellMgr->GetSpellInfo(SPELL_CONSTRICTOR) || !sSpellMgr->GetSpellInfo(SPELL_CORRUPTOR))
return false;
return true;
}
void HandleDummy(SpellEffIndex /*effIndex*/)
{
uint32 spellId = RAND(SPELL_CRUSHER, SPELL_CONSTRICTOR, SPELL_CORRUPTOR);
Unit* caster = GetCaster();
caster->CastSpell(caster, spellId, true);
}
void Register()
{
OnEffectHit += SpellEffectFn(spell_item_vanquished_clutches_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_vanquished_clutches_SpellScript();
}
};
enum AshbringerSounds
{
SOUND_ASHBRINGER_1 = 8906, // "I was pure once"
SOUND_ASHBRINGER_2 = 8907, // "Fought for righteousness"
SOUND_ASHBRINGER_3 = 8908, // "I was once called Ashbringer"
SOUND_ASHBRINGER_4 = 8920, // "Betrayed by my order"
SOUND_ASHBRINGER_5 = 8921, // "Destroyed by Kel'Thuzad"
SOUND_ASHBRINGER_6 = 8922, // "Made to serve"
SOUND_ASHBRINGER_7 = 8923, // "My son watched me die"
SOUND_ASHBRINGER_8 = 8924, // "Crusades fed his rage"
SOUND_ASHBRINGER_9 = 8925, // "Truth is unknown to him"
SOUND_ASHBRINGER_10 = 8926, // "Scarlet Crusade is pure no longer"
SOUND_ASHBRINGER_11 = 8927, // "Balnazzar's crusade corrupted my son"
SOUND_ASHBRINGER_12 = 8928, // "Kill them all!"
};
class spell_item_ashbringer : public SpellScriptLoader
{
public:
spell_item_ashbringer() : SpellScriptLoader("spell_item_ashbringer") {}
class spell_item_ashbringer_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_ashbringer_SpellScript);
bool Load()
{
return GetCaster()->GetTypeId() == TYPEID_PLAYER;
}
void OnDummyEffect(SpellEffIndex effIndex)
{
PreventHitDefaultEffect(effIndex);
Player* player = GetCaster()->ToPlayer();
uint32 sound_id = RAND( SOUND_ASHBRINGER_1, SOUND_ASHBRINGER_2, SOUND_ASHBRINGER_3, SOUND_ASHBRINGER_4, SOUND_ASHBRINGER_5, SOUND_ASHBRINGER_6,
SOUND_ASHBRINGER_7, SOUND_ASHBRINGER_8, SOUND_ASHBRINGER_9, SOUND_ASHBRINGER_10, SOUND_ASHBRINGER_11, SOUND_ASHBRINGER_12 );
// Ashbringers effect (spellID 28441) retriggers every 5 seconds, with a chance of making it say one of the above 12 sounds
if (urand(0, 60) < 1)
player->PlayDirectSound(sound_id, player);
}
void Register()
{
OnEffectHit += SpellEffectFn(spell_item_ashbringer_SpellScript::OnDummyEffect, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_ashbringer_SpellScript();
}
};
enum MagicEater
{
SPELL_WILD_MAGIC = 58891,
SPELL_WELL_FED_1 = 57288,
SPELL_WELL_FED_2 = 57139,
SPELL_WELL_FED_3 = 57111,
SPELL_WELL_FED_4 = 57286,
SPELL_WELL_FED_5 = 57291,
};
class spell_magic_eater_food : public SpellScriptLoader
{
public:
spell_magic_eater_food() : SpellScriptLoader("spell_magic_eater_food") {}
class spell_magic_eater_food_AuraScript : public AuraScript
{
PrepareAuraScript(spell_magic_eater_food_AuraScript);
void HandleTriggerSpell(AuraEffect const* /*aurEff*/)
{
PreventDefaultAction();
Unit* target = GetTarget();
switch (urand(0, 5))
{
case 0:
target->CastSpell(target, SPELL_WILD_MAGIC, true);
break;
case 1:
target->CastSpell(target, SPELL_WELL_FED_1, true);
break;
case 2:
target->CastSpell(target, SPELL_WELL_FED_2, true);
break;
case 3:
target->CastSpell(target, SPELL_WELL_FED_3, true);
break;
case 4:
target->CastSpell(target, SPELL_WELL_FED_4, true);
break;
case 5:
target->CastSpell(target, SPELL_WELL_FED_5, true);
break;
}
}
void Register()
{
OnEffectPeriodic += AuraEffectPeriodicFn(spell_magic_eater_food_AuraScript::HandleTriggerSpell, EFFECT_1, SPELL_AURA_PERIODIC_TRIGGER_SPELL);
}
};
AuraScript* GetAuraScript() const
{
return new spell_magic_eater_food_AuraScript();
}
};
class spell_item_shimmering_vessel : public SpellScriptLoader
{
public:
spell_item_shimmering_vessel() : SpellScriptLoader("spell_item_shimmering_vessel") { }
class spell_item_shimmering_vessel_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_shimmering_vessel_SpellScript);
void HandleDummy(SpellEffIndex /* effIndex */)
{
if (Creature* target = GetHitCreature())
target->setDeathState(JUST_RESPAWNED);
}
void Register()
{
OnEffectHitTarget += SpellEffectFn(spell_item_shimmering_vessel_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_shimmering_vessel_SpellScript();
}
};
enum PurifyHelboarMeat
{
SPELL_SUMMON_PURIFIED_HELBOAR_MEAT = 29277,
SPELL_SUMMON_TOXIC_HELBOAR_MEAT = 29278,
};
class spell_item_purify_helboar_meat : public SpellScriptLoader
{
public:
spell_item_purify_helboar_meat() : SpellScriptLoader("spell_item_purify_helboar_meat") { }
class spell_item_purify_helboar_meat_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_purify_helboar_meat_SpellScript);
bool Load()
{
return GetCaster()->GetTypeId() == TYPEID_PLAYER;
}
bool Validate(SpellInfo const* /*spell*/)
{
if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_PURIFIED_HELBOAR_MEAT) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_TOXIC_HELBOAR_MEAT))
return false;
return true;
}
void HandleDummy(SpellEffIndex /* effIndex */)
{
Unit* caster = GetCaster();
caster->CastSpell(caster, roll_chance_i(50) ? SPELL_SUMMON_PURIFIED_HELBOAR_MEAT : SPELL_SUMMON_TOXIC_HELBOAR_MEAT, true, NULL);
}
void Register()
{
OnEffectHitTarget += SpellEffectFn(spell_item_purify_helboar_meat_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_purify_helboar_meat_SpellScript();
}
};
enum CrystalPrison
{
OBJECT_IMPRISONED_DOOMGUARD = 179644,
};
class spell_item_crystal_prison_dummy_dnd : public SpellScriptLoader
{
public:
spell_item_crystal_prison_dummy_dnd() : SpellScriptLoader("spell_item_crystal_prison_dummy_dnd") { }
class spell_item_crystal_prison_dummy_dnd_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_crystal_prison_dummy_dnd_SpellScript);
bool Validate(SpellInfo const* /*spell*/)
{
if (!sObjectMgr->GetGameObjectTemplate(OBJECT_IMPRISONED_DOOMGUARD))
return false;
return true;
}
void HandleDummy(SpellEffIndex /* effIndex */)
{
if (Creature* target = GetHitCreature())
if (target->isDead() && !target->isPet())
{
GetCaster()->SummonGameObject(OBJECT_IMPRISONED_DOOMGUARD, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), target->GetOrientation(), 0, 0, 0, 0, uint32(target->GetRespawnTime()-time(NULL)));
target->DespawnOrUnsummon();
}
}
void Register()
{
OnEffectHitTarget += SpellEffectFn(spell_item_crystal_prison_dummy_dnd_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_crystal_prison_dummy_dnd_SpellScript();
}
};
enum ReindeerTransformation
{
SPELL_FLYING_REINDEER_310 = 44827,
SPELL_FLYING_REINDEER_280 = 44825,
SPELL_FLYING_REINDEER_60 = 44824,
SPELL_REINDEER_100 = 25859,
SPELL_REINDEER_60 = 25858,
};
class spell_item_reindeer_transformation : public SpellScriptLoader
{
public:
spell_item_reindeer_transformation() : SpellScriptLoader("spell_item_reindeer_transformation") { }
class spell_item_reindeer_transformation_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_reindeer_transformation_SpellScript);
bool Validate(SpellInfo const* /*spell*/)
{
if (!sSpellMgr->GetSpellInfo(SPELL_FLYING_REINDEER_310) || !sSpellMgr->GetSpellInfo(SPELL_FLYING_REINDEER_280)
|| !sSpellMgr->GetSpellInfo(SPELL_FLYING_REINDEER_60) || !sSpellMgr->GetSpellInfo(SPELL_REINDEER_100)
|| !sSpellMgr->GetSpellInfo(SPELL_REINDEER_60))
return false;
return true;
}
void HandleDummy(SpellEffIndex /* effIndex */)
{
Unit* caster = GetCaster();
if (caster->HasAuraType(SPELL_AURA_MOUNTED))
{
float flyspeed = caster->GetSpeedRate(MOVE_FLIGHT);
float speed = caster->GetSpeedRate(MOVE_RUN);
caster->RemoveAurasByType(SPELL_AURA_MOUNTED);
//5 different spells used depending on mounted speed and if mount can fly or not
if (flyspeed >= 4.1f)
// Flying Reindeer
caster->CastSpell(caster, SPELL_FLYING_REINDEER_310, true); //310% flying Reindeer
else if (flyspeed >= 3.8f)
// Flying Reindeer
caster->CastSpell(caster, SPELL_FLYING_REINDEER_280, true); //280% flying Reindeer
else if (flyspeed >= 1.6f)
// Flying Reindeer
caster->CastSpell(caster, SPELL_FLYING_REINDEER_60, true); //60% flying Reindeer
else if (speed >= 2.0f)
// Reindeer
caster->CastSpell(caster, SPELL_REINDEER_100, true); //100% ground Reindeer
else
// Reindeer
caster->CastSpell(caster, SPELL_REINDEER_60, true); //60% ground Reindeer
}
}
void Register()
{
OnEffectHitTarget += SpellEffectFn(spell_item_reindeer_transformation_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_reindeer_transformation_SpellScript();
}
};
enum NighInvulnerability
{
SPELL_NIGH_INVULNERABILITY = 30456,
SPELL_COMPLETE_VULNERABILITY = 30457,
};
class spell_item_nigh_invulnerability : public SpellScriptLoader
{
public:
spell_item_nigh_invulnerability() : SpellScriptLoader("spell_item_nigh_invulnerability") { }
class spell_item_nigh_invulnerability_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_nigh_invulnerability_SpellScript);
bool Validate(SpellInfo const* /*spell*/)
{
if (!sSpellMgr->GetSpellInfo(SPELL_NIGH_INVULNERABILITY) || !sSpellMgr->GetSpellInfo(SPELL_COMPLETE_VULNERABILITY))
return false;
return true;
}
void HandleDummy(SpellEffIndex /* effIndex */)
{
Unit* caster = GetCaster();
if (Item* castItem = GetCastItem())
{
if (roll_chance_i(86)) // Nigh-Invulnerability - success
caster->CastSpell(caster, SPELL_NIGH_INVULNERABILITY, true, castItem);
else // Complete Vulnerability - backfire in 14% casts
caster->CastSpell(caster, SPELL_COMPLETE_VULNERABILITY, true, castItem);
}
}
void Register()
{
OnEffectHitTarget += SpellEffectFn(spell_item_nigh_invulnerability_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_nigh_invulnerability_SpellScript();
}
};
enum Poultryzer
{
SPELL_POULTRYIZER_SUCCESS = 30501,
SPELL_POULTRYIZER_BACKFIRE = 30504,
};
class spell_item_poultryizer : public SpellScriptLoader
{
public:
spell_item_poultryizer() : SpellScriptLoader("spell_item_poultryizer") { }
class spell_item_poultryizer_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_poultryizer_SpellScript);
bool Validate(SpellInfo const* /*spell*/)
{
if (!sSpellMgr->GetSpellInfo(SPELL_POULTRYIZER_SUCCESS) || !sSpellMgr->GetSpellInfo(SPELL_POULTRYIZER_BACKFIRE))
return false;
return true;
}
void HandleDummy(SpellEffIndex /* effIndex */)
{
if (GetCastItem() && GetHitUnit())
GetCaster()->CastSpell(GetHitUnit(), roll_chance_i(80) ? SPELL_POULTRYIZER_SUCCESS : SPELL_POULTRYIZER_BACKFIRE , true, GetCastItem());
}
void Register()
{
OnEffectHitTarget += SpellEffectFn(spell_item_poultryizer_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_poultryizer_SpellScript();
}
};
enum SocretharsStone
{
SPELL_SOCRETHAR_TO_SEAT = 35743,
SPELL_SOCRETHAR_FROM_SEAT = 35744,
};
class spell_item_socrethars_stone : public SpellScriptLoader
{
public:
spell_item_socrethars_stone() : SpellScriptLoader("spell_item_socrethars_stone") { }
class spell_item_socrethars_stone_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_socrethars_stone_SpellScript);
bool Load()
{
return (GetCaster()->GetAreaId() == 3900 || GetCaster()->GetAreaId() == 3742);
}
bool Validate(SpellInfo const* /*spell*/)
{
if (!sSpellMgr->GetSpellInfo(SPELL_SOCRETHAR_TO_SEAT) || !sSpellMgr->GetSpellInfo(SPELL_SOCRETHAR_FROM_SEAT))
return false;
return true;
}
void HandleDummy(SpellEffIndex /* effIndex */)
{
Unit* caster = GetCaster();
switch (caster->GetAreaId())
{
case 3900:
caster->CastSpell(caster, SPELL_SOCRETHAR_TO_SEAT, true);
break;
case 3742:
caster->CastSpell(caster, SPELL_SOCRETHAR_FROM_SEAT, true);
break;
default:
return;
}
}
void Register()
{
OnEffectHitTarget += SpellEffectFn(spell_item_socrethars_stone_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_socrethars_stone_SpellScript();
}
};
enum DemonBroiledSurprise
{
QUEST_SUPER_HOT_STEW = 11379,
SPELL_CREATE_DEMON_BROILED_SURPRISE = 43753,
NPC_ABYSSAL_FLAMEBRINGER = 19973,
};
class spell_item_demon_broiled_surprise : public SpellScriptLoader
{
public:
spell_item_demon_broiled_surprise() : SpellScriptLoader("spell_item_demon_broiled_surprise") { }
class spell_item_demon_broiled_surprise_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_demon_broiled_surprise_SpellScript);
bool Validate(SpellInfo const* /*spell*/)
{
if (!sSpellMgr->GetSpellInfo(SPELL_CREATE_DEMON_BROILED_SURPRISE) || !sObjectMgr->GetCreatureTemplate(NPC_ABYSSAL_FLAMEBRINGER) || !sObjectMgr->GetQuestTemplate(QUEST_SUPER_HOT_STEW))
return false;
return true;
}
bool Load()
{
return GetCaster()->GetTypeId() == TYPEID_PLAYER;
}
void HandleDummy(SpellEffIndex /* effIndex */)
{
Unit* player = GetCaster();
player->CastSpell(player, SPELL_CREATE_DEMON_BROILED_SURPRISE, false);
}
SpellCastResult CheckRequirement()
{
Player* player = GetCaster()->ToPlayer();
if (player->GetQuestStatus(QUEST_SUPER_HOT_STEW) != QUEST_STATUS_INCOMPLETE)
return SPELL_FAILED_CANT_DO_THAT_RIGHT_NOW;
if (Creature* creature = player->FindNearestCreature(NPC_ABYSSAL_FLAMEBRINGER, 10, false))
if (creature->isDead())
return SPELL_CAST_OK;
return SPELL_FAILED_NOT_HERE;
}
void Register()
{
OnEffectHitTarget += SpellEffectFn(spell_item_demon_broiled_surprise_SpellScript::HandleDummy, EFFECT_1, SPELL_EFFECT_DUMMY);
OnCheckCast += SpellCheckCastFn(spell_item_demon_broiled_surprise_SpellScript::CheckRequirement);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_demon_broiled_surprise_SpellScript();
}
};
enum CompleteRaptorCapture
{
SPELL_RAPTOR_CAPTURE_CREDIT = 42337,
};
class spell_item_complete_raptor_capture : public SpellScriptLoader
{
public:
spell_item_complete_raptor_capture() : SpellScriptLoader("spell_item_complete_raptor_capture") { }
class spell_item_complete_raptor_capture_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_complete_raptor_capture_SpellScript);
bool Validate(SpellInfo const* /*spell*/)
{
if (!sSpellMgr->GetSpellInfo(SPELL_RAPTOR_CAPTURE_CREDIT))
return false;
return true;
}
void HandleDummy(SpellEffIndex /* effIndex */)
{
Unit* caster = GetCaster();
if (GetHitCreature())
{
GetHitCreature()->DespawnOrUnsummon();
//cast spell Raptor Capture Credit
caster->CastSpell(caster, SPELL_RAPTOR_CAPTURE_CREDIT, true, NULL);
}
}
void Register()
{
OnEffectHitTarget += SpellEffectFn(spell_item_complete_raptor_capture_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_complete_raptor_capture_SpellScript();
}
};
enum ImpaleLeviroth
{
NPC_LEVIROTH = 26452,
SPELL_LEVIROTH_SELF_IMPALE = 49882,
};
class spell_item_impale_leviroth : public SpellScriptLoader
{
public:
spell_item_impale_leviroth() : SpellScriptLoader("spell_item_impale_leviroth") { }
class spell_item_impale_leviroth_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_impale_leviroth_SpellScript);
bool Validate(SpellInfo const* /*spell*/)
{
if (!sObjectMgr->GetCreatureTemplate(NPC_LEVIROTH))
return false;
return true;
}
void HandleDummy(SpellEffIndex /* effIndex */)
{
if (Unit* target = GetHitCreature())
if (target->GetEntry() == NPC_LEVIROTH && !target->HealthBelowPct(95))
target->CastSpell(target, SPELL_LEVIROTH_SELF_IMPALE, true);
}
void Register()
{
OnEffectHitTarget += SpellEffectFn(spell_item_impale_leviroth_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_impale_leviroth_SpellScript();
}
};
enum BrewfestMountTransformation
{
SPELL_MOUNT_RAM_100 = 43900,
SPELL_MOUNT_RAM_60 = 43899,
SPELL_MOUNT_KODO_100 = 49379,
SPELL_MOUNT_KODO_60 = 49378,
SPELL_BREWFEST_MOUNT_TRANSFORM = 49357,
SPELL_BREWFEST_MOUNT_TRANSFORM_REVERSE = 52845,
};
class spell_item_brewfest_mount_transformation : public SpellScriptLoader
{
public:
spell_item_brewfest_mount_transformation() : SpellScriptLoader("spell_item_brewfest_mount_transformation") { }
class spell_item_brewfest_mount_transformation_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_brewfest_mount_transformation_SpellScript);
bool Validate(SpellInfo const* /*spell*/)
{
if (!sSpellMgr->GetSpellInfo(SPELL_MOUNT_RAM_100) || !sSpellMgr->GetSpellInfo(SPELL_MOUNT_RAM_60) || !sSpellMgr->GetSpellInfo(SPELL_MOUNT_KODO_100) || !sSpellMgr->GetSpellInfo(SPELL_MOUNT_KODO_60))
return false;
return true;
}
void HandleDummy(SpellEffIndex /* effIndex */)
{
Player* caster = GetCaster()->ToPlayer();
if (caster->HasAuraType(SPELL_AURA_MOUNTED))
{
caster->RemoveAurasByType(SPELL_AURA_MOUNTED);
uint32 spell_id;
switch (GetSpellInfo()->Id)
{
case SPELL_BREWFEST_MOUNT_TRANSFORM:
if (caster->GetSpeedRate(MOVE_RUN) >= 2.0f)
spell_id = caster->GetTeam() == ALLIANCE ? SPELL_MOUNT_RAM_100 : SPELL_MOUNT_KODO_100;
else
spell_id = caster->GetTeam() == ALLIANCE ? SPELL_MOUNT_RAM_60 : SPELL_MOUNT_KODO_60;
break;
case SPELL_BREWFEST_MOUNT_TRANSFORM_REVERSE:
if (caster->GetSpeedRate(MOVE_RUN) >= 2.0f)
spell_id = caster->GetTeam() == HORDE ? SPELL_MOUNT_RAM_100 : SPELL_MOUNT_KODO_100;
else
spell_id = caster->GetTeam() == HORDE ? SPELL_MOUNT_RAM_60 : SPELL_MOUNT_KODO_60;
break;
default:
return;
}
caster->CastSpell(caster, spell_id, true);
}
}
void Register()
{
OnEffectHitTarget += SpellEffectFn(spell_item_brewfest_mount_transformation_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_brewfest_mount_transformation_SpellScript();
}
};
enum NitroBoots
{
SPELL_NITRO_BOOTS_SUCCESS = 54861,
SPELL_NITRO_BOOTS_BACKFIRE = 46014,
};
class spell_item_nitro_boots : public SpellScriptLoader
{
public:
spell_item_nitro_boots() : SpellScriptLoader("spell_item_nitro_boots") { }
class spell_item_nitro_boots_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_nitro_boots_SpellScript);
bool Load()
{
if (!GetCastItem())
return false;
return true;
}
bool Validate(SpellInfo const* /*spell*/)
{
if (!sSpellMgr->GetSpellInfo(SPELL_NITRO_BOOTS_SUCCESS) || !sSpellMgr->GetSpellInfo(SPELL_NITRO_BOOTS_BACKFIRE))
return false;
return true;
}
void HandleDummy(SpellEffIndex /* effIndex */)
{
Unit* caster = GetCaster();
caster->CastSpell(caster, roll_chance_i(95) ? SPELL_NITRO_BOOTS_SUCCESS : SPELL_NITRO_BOOTS_BACKFIRE, true, GetCastItem());
}
void Register()
{
OnEffectHitTarget += SpellEffectFn(spell_item_nitro_boots_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_nitro_boots_SpellScript();
}
};
enum TeachLanguage
{
SPELL_LEARN_GNOMISH_BINARY = 50242,
SPELL_LEARN_GOBLIN_BINARY = 50246,
};
class spell_item_teach_language : public SpellScriptLoader
{
public:
spell_item_teach_language() : SpellScriptLoader("spell_item_teach_language") { }
class spell_item_teach_language_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_teach_language_SpellScript);
bool Load()
{
return GetCaster()->GetTypeId() == TYPEID_PLAYER;
}
bool Validate(SpellInfo const* /*spell*/)
{
if (!sSpellMgr->GetSpellInfo(SPELL_LEARN_GNOMISH_BINARY) || !sSpellMgr->GetSpellInfo(SPELL_LEARN_GOBLIN_BINARY))
return false;
return true;
}
void HandleDummy(SpellEffIndex /* effIndex */)
{
Player* caster = GetCaster()->ToPlayer();
if (roll_chance_i(34))
caster->CastSpell(caster,caster->GetTeam() == ALLIANCE ? SPELL_LEARN_GNOMISH_BINARY : SPELL_LEARN_GOBLIN_BINARY, true);
}
void Register()
{
OnEffectHitTarget += SpellEffectFn(spell_item_teach_language_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_teach_language_SpellScript();
}
};
enum RocketBoots
{
SPELL_ROCKET_BOOTS_PROC = 30452,
};
class spell_item_rocket_boots : public SpellScriptLoader
{
public:
spell_item_rocket_boots() : SpellScriptLoader("spell_item_rocket_boots") { }
class spell_item_rocket_boots_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_rocket_boots_SpellScript);
bool Load()
{
return GetCaster()->GetTypeId() == TYPEID_PLAYER;
}
bool Validate(SpellInfo const* /*spell*/)
{
if (!sSpellMgr->GetSpellInfo(SPELL_ROCKET_BOOTS_PROC))
return false;
return true;
}
void HandleDummy(SpellEffIndex /* effIndex */)
{
Player* caster = GetCaster()->ToPlayer();
if (Battleground* bg = caster->GetBattleground())
bg->EventPlayerDroppedFlag(caster);
caster->RemoveSpellCooldown(SPELL_ROCKET_BOOTS_PROC);
caster->CastSpell(caster, SPELL_ROCKET_BOOTS_PROC, true, NULL);
}
SpellCastResult CheckCast()
{
if (GetCaster()->IsInWater())
return SPELL_FAILED_ONLY_ABOVEWATER;
return SPELL_CAST_OK;
}
void Register()
{
OnCheckCast += SpellCheckCastFn(spell_item_rocket_boots_SpellScript::CheckCast);
OnEffectHitTarget += SpellEffectFn(spell_item_rocket_boots_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_rocket_boots_SpellScript();
}
};
enum PygmyOil
{
SPELL_PYGMY_OIL_PYGMY_AURA = 53806,
SPELL_PYGMY_OIL_SMALLER_AURA = 53805,
};
class spell_item_pygmy_oil : public SpellScriptLoader
{
public:
spell_item_pygmy_oil() : SpellScriptLoader("spell_item_pygmy_oil") { }
class spell_item_pygmy_oil_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_pygmy_oil_SpellScript);
bool Validate(SpellInfo const* /*spell*/)
{
if (!sSpellMgr->GetSpellInfo(SPELL_PYGMY_OIL_PYGMY_AURA) || !sSpellMgr->GetSpellInfo(SPELL_PYGMY_OIL_SMALLER_AURA))
return false;
return true;
}
void HandleDummy(SpellEffIndex /* effIndex */)
{
Unit* caster = GetCaster();
if (Aura* aura = caster->GetAura(SPELL_PYGMY_OIL_PYGMY_AURA))
aura->RefreshDuration();
else
{
aura = caster->GetAura(SPELL_PYGMY_OIL_SMALLER_AURA);
if (!aura || aura->GetStackAmount() < 5 || !roll_chance_i(50))
caster->CastSpell(caster, SPELL_PYGMY_OIL_SMALLER_AURA, true);
else
{
aura->Remove();
caster->CastSpell(caster, SPELL_PYGMY_OIL_PYGMY_AURA, true);
}
}
}
void Register()
{
OnEffectHitTarget += SpellEffectFn(spell_item_pygmy_oil_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_pygmy_oil_SpellScript();
}
};
class spell_item_unusual_compass : public SpellScriptLoader
{
public:
spell_item_unusual_compass() : SpellScriptLoader("spell_item_unusual_compass") { }
class spell_item_unusual_compass_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_unusual_compass_SpellScript);
void HandleDummy(SpellEffIndex /* effIndex */)
{
Unit* caster = GetCaster();
caster->SetOrientation(frand(0.0f, 62832.0f) / 10000.0f);
caster->SendMovementFlagUpdate();
}
void Register()
{
OnEffectHitTarget += SpellEffectFn(spell_item_unusual_compass_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_unusual_compass_SpellScript();
}
};
enum ChickenCover
{
SPELL_CHICKEN_NET = 51959,
SPELL_CAPTURE_CHICKEN_ESCAPE = 51037,
QUEST_CHICKEN_PARTY = 12702,
QUEST_FLOWN_THE_COOP = 12532,
};
class spell_item_chicken_cover : public SpellScriptLoader
{
public:
spell_item_chicken_cover() : SpellScriptLoader("spell_item_chicken_cover") { }
class spell_item_chicken_cover_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_chicken_cover_SpellScript);
bool Load()
{
return GetCaster()->GetTypeId() == TYPEID_PLAYER;
}
bool Validate(SpellInfo const* /*spell*/)
{
if (!sSpellMgr->GetSpellInfo(SPELL_CHICKEN_NET) || !sSpellMgr->GetSpellInfo(SPELL_CAPTURE_CHICKEN_ESCAPE) || !sObjectMgr->GetQuestTemplate(QUEST_CHICKEN_PARTY) || !sObjectMgr->GetQuestTemplate(QUEST_FLOWN_THE_COOP))
return false;
return true;
}
void HandleDummy(SpellEffIndex /* effIndex */)
{
Player* caster = GetCaster()->ToPlayer();
if (Unit* target = GetHitUnit())
{
if (!target->HasAura(SPELL_CHICKEN_NET) && (caster->GetQuestStatus(QUEST_CHICKEN_PARTY) == QUEST_STATUS_INCOMPLETE || caster->GetQuestStatus(QUEST_FLOWN_THE_COOP) == QUEST_STATUS_INCOMPLETE))
{
caster->CastSpell(caster, SPELL_CAPTURE_CHICKEN_ESCAPE, true);
target->Kill(target);
}
}
}
void Register()
{
OnEffectHitTarget += SpellEffectFn(spell_item_chicken_cover_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_chicken_cover_SpellScript();
}
};
enum Refocus
{
SPELL_AIMED_SHOT = 19434,
SPELL_MULTISHOT = 2643,
SPELL_VOLLEY = 42243,
};
class spell_item_refocus : public SpellScriptLoader
{
public:
spell_item_refocus() : SpellScriptLoader("spell_item_refocus") { }
class spell_item_refocus_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_refocus_SpellScript);
void HandleDummy(SpellEffIndex /*effIndex*/)
{
Player* caster = GetCaster()->ToPlayer();
if (!caster || caster->getClass() != CLASS_HUNTER)
return;
if (caster->HasSpellCooldown(SPELL_AIMED_SHOT))
caster->RemoveSpellCooldown(SPELL_AIMED_SHOT, true);
if (caster->HasSpellCooldown(SPELL_MULTISHOT))
caster->RemoveSpellCooldown(SPELL_MULTISHOT, true);
if (caster->HasSpellCooldown(SPELL_VOLLEY))
caster->RemoveSpellCooldown(SPELL_VOLLEY, true);
}
void Register()
{
OnEffectHitTarget += SpellEffectFn(spell_item_refocus_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_refocus_SpellScript();
}
};
class spell_item_muisek_vessel : public SpellScriptLoader
{
public:
spell_item_muisek_vessel() : SpellScriptLoader("spell_item_muisek_vessel") { }
class spell_item_muisek_vessel_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_muisek_vessel_SpellScript);
void HandleDummy(SpellEffIndex /*effIndex*/)
{
if (Creature* target = GetHitCreature())
if (target->isDead())
target->DespawnOrUnsummon();
}
void Register()
{
OnEffectHitTarget += SpellEffectFn(spell_item_muisek_vessel_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_muisek_vessel_SpellScript();
}
};
enum GreatmothersSoulcather
{
SPELL_FORCE_CAST_SUMMON_GNOME_SOUL = 46486,
};
class spell_item_greatmothers_soulcatcher : public SpellScriptLoader
{
public:
spell_item_greatmothers_soulcatcher() : SpellScriptLoader("spell_item_greatmothers_soulcatcher") { }
class spell_item_greatmothers_soulcatcher_SpellScript : public SpellScript
{
PrepareSpellScript(spell_item_greatmothers_soulcatcher_SpellScript);
void HandleDummy(SpellEffIndex /*effIndex*/)
{
if (GetHitUnit())
GetCaster()->CastSpell(GetCaster(),SPELL_FORCE_CAST_SUMMON_GNOME_SOUL);
}
void Register()
{
OnEffectHitTarget += SpellEffectFn(spell_item_greatmothers_soulcatcher_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_item_greatmothers_soulcatcher_SpellScript();
}
};
void AddSC_item_spell_scripts()
{
// 23074 Arcanite Dragonling
new spell_item_trigger_spell("spell_item_arcanite_dragonling", SPELL_ARCANITE_DRAGONLING);
// 23133 Gnomish Battle Chicken
new spell_item_trigger_spell("spell_item_gnomish_battle_chicken", SPELL_BATTLE_CHICKEN);
// 23076 Mechanical Dragonling
new spell_item_trigger_spell("spell_item_mechanical_dragonling", SPELL_MECHANICAL_DRAGONLING);
// 23075 Mithril Mechanical Dragonling
new spell_item_trigger_spell("spell_item_mithril_mechanical_dragonling", SPELL_MITHRIL_MECHANICAL_DRAGONLING);
new spell_item_deviate_fish();
new spell_item_flask_of_the_north();
new spell_item_gnomish_death_ray();
new spell_item_make_a_wish();
new spell_item_mingos_fortune_generator();
new spell_item_net_o_matic();
new spell_item_noggenfogger_elixir();
new spell_item_savory_deviate_delight();
new spell_item_six_demon_bag();
new spell_item_underbelly_elixir();
new spell_item_shadowmourne();
new spell_item_red_rider_air_rifle();
new spell_item_create_heart_candy();
new spell_item_book_of_glyph_mastery();
new spell_item_gift_of_the_harvester();
new spell_item_map_of_the_geyser_fields();
new spell_item_vanquished_clutches();
new spell_item_ashbringer();
new spell_magic_eater_food();
new spell_item_refocus();
new spell_item_shimmering_vessel();
new spell_item_purify_helboar_meat();
new spell_item_crystal_prison_dummy_dnd();
new spell_item_reindeer_transformation();
new spell_item_nigh_invulnerability();
new spell_item_poultryizer();
new spell_item_socrethars_stone();
new spell_item_demon_broiled_surprise();
new spell_item_complete_raptor_capture();
new spell_item_impale_leviroth();
new spell_item_brewfest_mount_transformation();
new spell_item_nitro_boots();
new spell_item_teach_language();
new spell_item_rocket_boots();
new spell_item_pygmy_oil();
new spell_item_unusual_compass();
new spell_item_chicken_cover();
new spell_item_muisek_vessel();
new spell_item_greatmothers_soulcatcher();
}
| 35.886518 | 312 | 0.591502 | [
"vector"
] |
3c8bd678c47f662d2b6c9bbf2cc6357b2a270617 | 8,128 | cpp | C++ | src/backends/cl/test/ClImportTensorHandleTests.cpp | tuanhe/armnn | 8a4bd6671d0106dfb788b8c9019f2f9646770f8d | [
"MIT"
] | 1 | 2021-07-03T23:46:08.000Z | 2021-07-03T23:46:08.000Z | src/backends/cl/test/ClImportTensorHandleTests.cpp | tuanhe/armnn | 8a4bd6671d0106dfb788b8c9019f2f9646770f8d | [
"MIT"
] | null | null | null | src/backends/cl/test/ClImportTensorHandleTests.cpp | tuanhe/armnn | 8a4bd6671d0106dfb788b8c9019f2f9646770f8d | [
"MIT"
] | null | null | null | //
// Copyright © 2021 Arm Ltd and Contributors. All rights reserved.
// SPDX-License-Identifier: MIT
//
#include <arm_compute/runtime/CL/functions/CLActivationLayer.h>
#include <cl/ClImportTensorHandle.hpp>
#include <cl/ClImportTensorHandleFactory.hpp>
#include <cl/test/ClContextControlFixture.hpp>
#include <boost/test/unit_test.hpp>
#include <armnn/IRuntime.hpp>
#include <armnn/INetwork.hpp>
using namespace armnn;
BOOST_AUTO_TEST_SUITE(ClImportTensorHandleTests)
BOOST_FIXTURE_TEST_CASE(ClMallocImport, ClContextControlFixture)
{
ClImportTensorHandleFactory handleFactory(static_cast<MemorySourceFlags>(MemorySource::Malloc),
static_cast<MemorySourceFlags>(MemorySource::Malloc));
TensorInfo info({ 1, 24, 16, 3 }, DataType::Float32);
unsigned int numElements = info.GetNumElements();
// create TensorHandle for memory import
auto handle = handleFactory.CreateTensorHandle(info);
// Get CLtensor
arm_compute::CLTensor& tensor = PolymorphicDowncast<ClImportTensorHandle*>(handle.get())->GetTensor();
// Create and configure activation function
const arm_compute::ActivationLayerInfo act_info(arm_compute::ActivationLayerInfo::ActivationFunction::RELU);
arm_compute::CLActivationLayer act_func;
act_func.configure(&tensor, nullptr, act_info);
// Allocate user memory
const size_t totalBytes = tensor.info()->total_size();
const size_t alignment =
arm_compute::CLKernelLibrary::get().get_device().getInfo<CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE>();
size_t space = totalBytes + alignment + alignment;
auto testData = std::make_unique<uint8_t[]>(space);
void* alignedPtr = testData.get();
BOOST_CHECK(std::align(alignment, totalBytes, alignedPtr, space));
// Import memory
BOOST_CHECK(handle->Import(alignedPtr, armnn::MemorySource::Malloc));
// Input with negative values
auto* typedPtr = reinterpret_cast<float*>(alignedPtr);
std::fill_n(typedPtr, numElements, -5.0f);
// Execute function and sync
act_func.run();
arm_compute::CLScheduler::get().sync();
// Validate result by checking that the output has no negative values
for(unsigned int i = 0; i < numElements; ++i)
{
BOOST_TEST(typedPtr[i] >= 0);
}
}
BOOST_FIXTURE_TEST_CASE(ClIncorrectMemorySourceImport, ClContextControlFixture)
{
ClImportTensorHandleFactory handleFactory(static_cast<MemorySourceFlags>(MemorySource::Malloc),
static_cast<MemorySourceFlags>(MemorySource::Malloc));
TensorInfo info({ 1, 24, 16, 3 }, DataType::Float32);
// create TensorHandle for memory import
auto handle = handleFactory.CreateTensorHandle(info);
// Get CLtensor
arm_compute::CLTensor& tensor = PolymorphicDowncast<ClImportTensorHandle*>(handle.get())->GetTensor();
// Allocate user memory
const size_t totalBytes = tensor.info()->total_size();
const size_t alignment =
arm_compute::CLKernelLibrary::get().get_device().getInfo<CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE>();
size_t space = totalBytes + alignment + alignment;
auto testData = std::make_unique<uint8_t[]>(space);
void* alignedPtr = testData.get();
BOOST_CHECK(std::align(alignment, totalBytes, alignedPtr, space));
// Import memory
BOOST_CHECK_THROW(handle->Import(alignedPtr, armnn::MemorySource::Undefined), MemoryImportException);
}
BOOST_FIXTURE_TEST_CASE(ClInvalidMemorySourceImport, ClContextControlFixture)
{
MemorySource invalidMemSource = static_cast<MemorySource>(256);
ClImportTensorHandleFactory handleFactory(static_cast<MemorySourceFlags>(invalidMemSource),
static_cast<MemorySourceFlags>(invalidMemSource));
TensorInfo info({ 1, 2, 2, 1 }, DataType::Float32);
// create TensorHandle for memory import
auto handle = handleFactory.CreateTensorHandle(info);
// Allocate user memory
std::vector<float> inputData
{
1.0f, 2.0f, 3.0f, 4.0f
};
// Import non-support memory
BOOST_CHECK_THROW(handle->Import(inputData.data(), invalidMemSource), MemoryImportException);
}
BOOST_FIXTURE_TEST_CASE(ClImportEndToEnd, ClContextControlFixture)
{
// Create runtime in which test will run
IRuntime::CreationOptions options;
IRuntimePtr runtime(armnn::IRuntime::Create(options));
// build up the structure of the network
INetworkPtr net(INetwork::Create());
IConnectableLayer* input = net->AddInputLayer(0, "Input");
ActivationDescriptor descriptor;
descriptor.m_Function = ActivationFunction::ReLu;
IConnectableLayer* activation = net->AddActivationLayer(descriptor, "Activation");
IConnectableLayer* output = net->AddOutputLayer(0, "Output");
input->GetOutputSlot(0).Connect(activation->GetInputSlot(0));
activation->GetOutputSlot(0).Connect(output->GetInputSlot(0));
TensorInfo tensorInfo = TensorInfo({ 1, 24, 16, 3 }, DataType::Float32);
unsigned int numElements = tensorInfo.GetNumElements();
size_t totalBytes = numElements * sizeof(float);
input->GetOutputSlot(0).SetTensorInfo(tensorInfo);
activation->GetOutputSlot(0).SetTensorInfo(tensorInfo);
// Optimize the network
OptimizerOptions optOptions;
optOptions.m_ImportEnabled = true;
std::vector<armnn::BackendId> backends = {armnn::Compute::GpuAcc};
IOptimizedNetworkPtr optNet = Optimize(*net, backends, runtime->GetDeviceSpec(), optOptions);
BOOST_CHECK(optNet);
// Loads it into the runtime.
NetworkId netId;
std::string ignoredErrorMessage;
// Enable Importing
INetworkProperties networkProperties(false, MemorySource::Malloc, MemorySource::Malloc);
runtime->LoadNetwork(netId, std::move(optNet), ignoredErrorMessage, networkProperties);
// Creates structures for input & output
const size_t alignment =
arm_compute::CLKernelLibrary::get().get_device().getInfo<CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE>();
size_t space = totalBytes + alignment + alignment;
auto inputData = std::make_unique<uint8_t[]>(space);
void* alignedInputPtr = inputData.get();
BOOST_CHECK(std::align(alignment, totalBytes, alignedInputPtr, space));
// Input with negative values
auto* intputPtr = reinterpret_cast<float*>(alignedInputPtr);
std::fill_n(intputPtr, numElements, -5.0f);
auto outputData = std::make_unique<uint8_t[]>(space);
void* alignedOutputPtr = outputData.get();
BOOST_CHECK(std::align(alignment, totalBytes, alignedOutputPtr, space));
auto* outputPtr = reinterpret_cast<float*>(alignedOutputPtr);
std::fill_n(outputPtr, numElements, -10.0f);
InputTensors inputTensors
{
{0,armnn::ConstTensor(runtime->GetInputTensorInfo(netId, 0), alignedInputPtr)},
};
OutputTensors outputTensors
{
{0,armnn::Tensor(runtime->GetOutputTensorInfo(netId, 0), alignedOutputPtr)}
};
runtime->GetProfiler(netId)->EnableProfiling(true);
// Do the inference
runtime->EnqueueWorkload(netId, inputTensors, outputTensors);
// Retrieve the Profiler.Print() output to get the workload execution
ProfilerManager& profilerManager = armnn::ProfilerManager::GetInstance();
std::stringstream ss;
profilerManager.GetProfiler()->Print(ss);;
std::string dump = ss.str();
// Contains ActivationWorkload
std::size_t found = dump.find("ActivationWorkload");
BOOST_TEST(found != std::string::npos);
// Contains SyncMemGeneric
found = dump.find("SyncMemGeneric");
BOOST_TEST(found != std::string::npos);
// Does not contain CopyMemGeneric
found = dump.find("CopyMemGeneric");
BOOST_TEST(found == std::string::npos);
runtime->UnloadNetwork(netId);
// Check output is as expected
// Validate result by checking that the output has no negative values
auto* outputResult = reinterpret_cast<float*>(alignedOutputPtr);
BOOST_TEST(outputResult);
for(unsigned int i = 0; i < numElements; ++i)
{
BOOST_TEST(outputResult[i] >= 0);
}
}
BOOST_AUTO_TEST_SUITE_END()
| 37.284404 | 112 | 0.717028 | [
"vector"
] |
3c8c32951c9676fae4b54f0470d3aa4fa857685a | 1,140 | cpp | C++ | src/collisionsystem.cpp | Kuxe/swordbow-magic | 22c4bde7fe70728f631bfa77765dbe8ea121df33 | [
"MIT"
] | 1 | 2020-03-29T16:20:02.000Z | 2020-03-29T16:20:02.000Z | src/collisionsystem.cpp | Kuxe/swordbow-magic | 22c4bde7fe70728f631bfa77765dbe8ea121df33 | [
"MIT"
] | 47 | 2015-01-02T16:54:57.000Z | 2015-10-08T21:09:06.000Z | src/collisionsystem.cpp | Kuxe/swordbow-magic | 22c4bde7fe70728f631bfa77765dbe8ea121df33 | [
"MIT"
] | 2 | 2015-01-02T17:23:18.000Z | 2020-03-29T16:20:04.000Z | #include "collisionsystem.hpp"
#include "componentmanager.hpp"
#include "spatialindexer.hpp"
#include "movecomponent.hpp"
CollisionSystem::CollisionSystem(SpatialIndexer* spatialIndexer) :
spatialIndexer(spatialIndexer) {}
void CollisionSystem::add(ID id) {
ids.insert(id);
activeIds.push(id);
}
void CollisionSystem::remove(ID id) {
ids.erase(id);
}
void CollisionSystem::update() {
while(!activeIds.empty()) {
auto id = activeIds.front(); activeIds.pop();
//TODO: Convert from 2D to 3D
/*for(auto overlap : spatialIndexer->overlaps(id)) {
auto& outerMc = componentManager->moveComponents.at(id);
outerMc.pos.x = outerMc.oldPos.x;
outerMc.pos.y = outerMc.oldPos.y;
auto& innerMc = componentManager->moveComponents.at(overlap);
innerMc.pos.x = innerMc.oldPos.x;
innerMc.pos.y = innerMc.oldPos.y;
} */
}
}
unsigned int CollisionSystem::count() const {
return ids.size();
}
const System::Identifier CollisionSystem::getIdentifier() const {
return System::COLLISION;
}
bool CollisionSystem::activateId(ID id) {
if(ids.find(id) != ids.end()) {
activeIds.push(id);
return true;
}
return false;
}
| 23.265306 | 66 | 0.714912 | [
"3d"
] |
3c9a7c6d5a442e8a59e42cf5796da9cadd439c57 | 1,477 | cpp | C++ | solutions/summary-ranges/solution.cpp | locker/leetcode | bf34a697de47aaf32823224d054f9a45613ce180 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | solutions/summary-ranges/solution.cpp | locker/leetcode | bf34a697de47aaf32823224d054f9a45613ce180 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | solutions/summary-ranges/solution.cpp | locker/leetcode | bf34a697de47aaf32823224d054f9a45613ce180 | [
"BSD-2-Clause-FreeBSD"
] | 1 | 2019-08-30T06:53:23.000Z | 2019-08-30T06:53:23.000Z | #include <iostream>
#include <string>
#include <vector>
#include <utility>
using namespace std;
template<typename T>
ostream& operator<<(ostream& out, const vector<T>& v)
{
out << '[';
bool first = true;
for (const auto& x : v) {
if (!first)
out << ',';
out << x;
first = false;
}
out << ']';
return out;
}
class Solution {
string makeRange(int first, int last) {
if (first == last)
return to_string(first);
return to_string(first) + "->" + to_string(last);
}
public:
vector<string> summaryRanges(const vector<int>& nums) {
vector<string> ranges;
int prev = 0;
int first = 0;
bool started = false;
for (int x : nums) {
if (started && x == prev + 1) {
prev = x;
continue;
}
if (started)
ranges.push_back(makeRange(first, prev));
first = prev = x;
started = true;
}
if (started)
ranges.push_back(makeRange(first, prev));
return ranges;
}
};
int main()
{
pair<vector<int>, vector<string>> test_data[] = {
{{}, {}},
{{1}, {"1"}},
{{1, 2}, {"1->2"}},
{{1, 2, 3}, {"1->3"}},
{{0, 1, 2, 4, 5, 7}, {"0->2", "4->5", "7"}},
{{0, 2, 3, 4, 6, 8, 9}, {"0", "2->4", "6", "8->9"}},
};
bool success = true;
Solution solution;
for (const auto& [nums, expected] : test_data) {
auto result = solution.summaryRanges(nums);
cout << nums << " => " << result << endl;
if (result != expected) {
cout << " ERROR: expected " << expected << endl;
success = false;
}
}
return success ? 0 : 1;
}
| 20.232877 | 56 | 0.555856 | [
"vector"
] |
3c9d20a77d3ba0f1baa34ec367d17c458c89f44b | 1,806 | cpp | C++ | test/message/native_types.cpp | mine260309/sdbusplus | 353c8f79992853777bdec7e3bd1e0cc70490f981 | [
"Apache-2.0"
] | null | null | null | test/message/native_types.cpp | mine260309/sdbusplus | 353c8f79992853777bdec7e3bd1e0cc70490f981 | [
"Apache-2.0"
] | null | null | null | test/message/native_types.cpp | mine260309/sdbusplus | 353c8f79992853777bdec7e3bd1e0cc70490f981 | [
"Apache-2.0"
] | 1 | 2020-06-01T00:47:23.000Z | 2020-06-01T00:47:23.000Z | #include <map>
#include <sdbusplus/message.hpp>
#include <string>
#include <unordered_map>
#include <vector>
#include <gtest/gtest.h>
using namespace std::string_literals;
/* Suite tests that object_path and signature can be cleanly converted to
* and from strings and used as container parameters.
*/
TEST(MessageNativeTypeConversions, ObjectPath)
{
std::string s1 = sdbusplus::message::object_path("/asdf/");
sdbusplus::message::object_path p = std::move(s1);
ASSERT_EQ("/asdf/", p);
ASSERT_EQ(p, "/asdf/");
}
TEST(MessageNativeTypeConversions, Signature)
{
std::string s2 = sdbusplus::message::signature("iii");
sdbusplus::message::signature sig = s2;
ASSERT_EQ(sig, s2);
ASSERT_EQ(s2, sig);
}
TEST(MessageNativeTypeConversions, SignatureInVector)
{
std::vector<sdbusplus::message::signature> v = {
sdbusplus::message::signature("iii")};
ASSERT_EQ(v.front(), "iii");
}
TEST(MessageNativeTypeConversions, SignatureInMap)
{
std::map<sdbusplus::message::signature, int> m = {
{sdbusplus::message::signature("iii"), 1}};
ASSERT_EQ(m[sdbusplus::message::signature("iii")], 1);
}
TEST(MessageNativeTypeConversions, SignatureInUnorderedMap)
{
std::unordered_map<sdbusplus::message::signature, int> u = {
{sdbusplus::message::signature("iii"), 2}};
ASSERT_EQ(u[sdbusplus::message::signature("iii")], 2);
}
TEST(MessageNativeTypeConversions, WrapperReference)
{
auto orig = "str"s;
sdbusplus::message::object_path obj = orig;
auto out = static_cast<std::string>(obj);
EXPECT_EQ(orig, out);
}
TEST(MessageNativeTypeConversions, WrapperMove)
{
auto orig = "str"s;
sdbusplus::message::object_path obj = orig;
auto out = static_cast<std::string>(std::move(obj));
EXPECT_EQ(orig, out);
}
| 25.083333 | 73 | 0.692137 | [
"vector"
] |
3c9ef51b108fe25c95377787cb0644514dbbf165 | 1,332 | cpp | C++ | generated_reference/bridge/python/model.cpp | calebbergman/scapix-example1 | 668bb5148d7fa014e8ec94d86806b68368f6834d | [
"MIT"
] | 1 | 2021-03-02T09:21:29.000Z | 2021-03-02T09:21:29.000Z | generated_reference/bridge/python/model.cpp | calebbergman/scapix-example1 | 668bb5148d7fa014e8ec94d86806b68368f6834d | [
"MIT"
] | null | null | null | generated_reference/bridge/python/model.cpp | calebbergman/scapix-example1 | 668bb5148d7fa014e8ec94d86806b68368f6834d | [
"MIT"
] | null | null | null | // Generated by Scapix Language Bridge
// https://www.scapix.com
#include <scapix/bridge/python/init.h>
#include <chat/model.h>
void scapix_python_export_model(pybind11::module& m)
{
pybind11::class_<chat::model, std::shared_ptr<chat::model>>(m, "Model")
.def(pybind11::init<>())
.def<void(chat::model::*)(std::basic_string<char>, std::basic_string<char>)>("connect", &chat::model::connect)
.def<void(chat::model::*)()>("disconnect", &chat::model::disconnect)
.def<const std::vector<std::shared_ptr<chat::contact>, std::allocator<std::shared_ptr<chat::contact> > > &(chat::model::*)()>("friends", &chat::model::friends)
.def<std::vector<std::shared_ptr<chat::contact>, std::allocator<std::shared_ptr<chat::contact> > >(chat::model::*)(std::basic_string<char>)>("friends", &chat::model::friends)
.def<void(chat::model::*)(std::shared_ptr<chat::contact>)>("add_friend", &chat::model::add_friend)
.def<void(chat::model::*)(std::shared_ptr<chat::contact>)>("remove_friend", &chat::model::remove_friend)
.def<const std::vector<std::shared_ptr<chat::session>, std::allocator<std::shared_ptr<chat::session> > > &(chat::model::*)()>("sessions", &chat::model::sessions)
.def<std::shared_ptr<chat::session>(chat::model::*)(std::shared_ptr<chat::contact>)>("session_with_contact", &chat::model::session_with_contact)
;
}
| 63.428571 | 176 | 0.693694 | [
"vector",
"model"
] |
3ca42e4c826a32212f4708ff29e499e35e42fd48 | 47,836 | cxx | C++ | main/cui/source/customize/cfgutil.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/cui/source/customize/cfgutil.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/cui/source/customize/cfgutil.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_cui.hxx"
#include "cfgutil.hxx"
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/frame/XDispatchInformationProvider.hpp>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/script/provider/XScriptProviderSupplier.hpp>
#include <com/sun/star/script/provider/XScriptProvider.hpp>
#include <com/sun/star/script/browse/XBrowseNode.hpp>
#include <com/sun/star/script/browse/BrowseNodeTypes.hpp>
#include <com/sun/star/script/browse/XBrowseNodeFactory.hpp>
#include <com/sun/star/script/browse/BrowseNodeFactoryViewTypes.hpp>
#include <com/sun/star/frame/XModuleManager.hpp>
#include <com/sun/star/frame/XDesktop.hpp>
#include <com/sun/star/container/XEnumerationAccess.hpp>
#include <com/sun/star/container/XEnumeration.hpp>
#include <com/sun/star/document/XDocumentInfoSupplier.hpp>
#include <com/sun/star/document/XScriptInvocationContext.hpp>
#include <com/sun/star/style/XStyleFamiliesSupplier.hpp>
#include "acccfg.hrc"
#include "helpid.hrc"
#include <basic/sbx.hxx>
#include <basic/basicmanagerrepository.hxx>
#include <basic/sbstar.hxx>
#include <basic/sbxmeth.hxx>
#include <basic/sbmod.hxx>
#include <basic/basmgr.hxx>
#include <tools/urlobj.hxx>
#include "cuires.hrc"
#include <sfx2/app.hxx>
#include <sfx2/minfitem.hxx>
#include <unotools/processfactory.hxx>
#include <comphelper/documentinfo.hxx>
#include <svtools/imagemgr.hxx>
#include <rtl/ustrbuf.hxx>
#include <comphelper/sequenceashashmap.hxx>
#include <unotools/configmgr.hxx>
#include "dialmgr.hxx"
#include <svl/stritem.hxx>
#define _SVSTDARR_STRINGSDTOR
#include <svl/svstdarr.hxx>
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::script;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::document;
namespace css = ::com::sun::star;
static ::rtl::OUString SERVICE_UICATEGORYDESCRIPTION = ::rtl::OUString::createFromAscii("com.sun.star.ui.UICategoryDescription" );
static ::rtl::OUString SERVICE_UICMDDESCRIPTION = ::rtl::OUString::createFromAscii("com.sun.star.frame.UICommandDescription");
SfxStylesInfo_Impl::SfxStylesInfo_Impl()
{}
void SfxStylesInfo_Impl::setModel(const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& xModel)
{
m_xDoc = xModel;
}
static ::rtl::OUString FAMILY_CHARACTERSTYLE = ::rtl::OUString::createFromAscii("CharacterStyles");
static ::rtl::OUString FAMILY_PARAGRAPHSTYLE = ::rtl::OUString::createFromAscii("ParagraphStyles");
static ::rtl::OUString FAMILY_FRAMESTYLE = ::rtl::OUString::createFromAscii("FrameStyles" );
static ::rtl::OUString FAMILY_PAGESTYLE = ::rtl::OUString::createFromAscii("PageStyles" );
static ::rtl::OUString FAMILY_NUMBERINGSTYLE = ::rtl::OUString::createFromAscii("NumberingStyles");
static ::rtl::OUString CMDURL_SPART = ::rtl::OUString::createFromAscii(".uno:StyleApply?Style:string=");
static ::rtl::OUString CMDURL_FPART2 = ::rtl::OUString::createFromAscii("&FamilyName:string=");
static ::rtl::OUString CMDURL_STYLEPROT_ONLY = ::rtl::OUString::createFromAscii(".uno:StyleApply?");
static ::rtl::OUString CMDURL_SPART_ONLY = ::rtl::OUString::createFromAscii("Style:string=");
static ::rtl::OUString CMDURL_FPART_ONLY = ::rtl::OUString::createFromAscii("FamilyName:string=");
static ::rtl::OUString STYLEPROP_UINAME = ::rtl::OUString::createFromAscii("DisplayName");
::rtl::OUString SfxStylesInfo_Impl::generateCommand(const ::rtl::OUString& sFamily, const ::rtl::OUString& sStyle)
{
::rtl::OUStringBuffer sCommand(1024);
sCommand.append(CMDURL_SPART );
sCommand.append(sStyle );
sCommand.append(CMDURL_FPART2);
sCommand.append(sFamily );
return sCommand.makeStringAndClear();
}
sal_Bool SfxStylesInfo_Impl::parseStyleCommand(SfxStyleInfo_Impl& aStyle)
{
static sal_Int32 LEN_STYLEPROT = CMDURL_STYLEPROT_ONLY.getLength();
static sal_Int32 LEN_SPART = CMDURL_SPART_ONLY.getLength();
static sal_Int32 LEN_FPART = CMDURL_FPART_ONLY.getLength();
if (aStyle.sCommand.indexOf(CMDURL_STYLEPROT_ONLY, 0) != 0)
return sal_False;
aStyle.sFamily = ::rtl::OUString();
aStyle.sStyle = ::rtl::OUString();
sal_Int32 nCmdLen = aStyle.sCommand.getLength();
::rtl::OUString sCmdArgs = aStyle.sCommand.copy(LEN_STYLEPROT, nCmdLen-LEN_STYLEPROT);
sal_Int32 i = sCmdArgs.indexOf('&');
if (i<0)
return sal_False;
::rtl::OUString sArg = sCmdArgs.copy(0, i);
if (sArg.indexOf(CMDURL_SPART_ONLY) == 0)
aStyle.sStyle = sArg.copy(LEN_SPART, sArg.getLength()-LEN_SPART);
else
if (sArg.indexOf(CMDURL_FPART_ONLY) == 0)
aStyle.sFamily = sArg.copy(LEN_FPART, sArg.getLength()-LEN_FPART);
sArg = sCmdArgs.copy(i+1, sCmdArgs.getLength()-i-1);
if (sArg.indexOf(CMDURL_SPART_ONLY) == 0)
aStyle.sStyle = sArg.copy(LEN_SPART, sArg.getLength()-LEN_SPART);
else
if (sArg.indexOf(CMDURL_FPART_ONLY) == 0)
aStyle.sFamily = sArg.copy(LEN_FPART, sArg.getLength()-LEN_FPART);
if (aStyle.sFamily.getLength() && aStyle.sStyle.getLength())
return sal_True;
return sal_False;
}
void SfxStylesInfo_Impl::getLabel4Style(SfxStyleInfo_Impl& aStyle)
{
try
{
css::uno::Reference< css::style::XStyleFamiliesSupplier > xModel(m_xDoc, css::uno::UNO_QUERY);
css::uno::Reference< css::container::XNameAccess > xFamilies;
if (xModel.is())
xFamilies = xModel->getStyleFamilies();
css::uno::Reference< css::container::XNameAccess > xStyleSet;
if (xFamilies.is())
xFamilies->getByName(aStyle.sFamily) >>= xStyleSet;
css::uno::Reference< css::beans::XPropertySet > xStyle;
if (xStyleSet.is())
xStyleSet->getByName(aStyle.sStyle) >>= xStyle;
aStyle.sLabel = ::rtl::OUString();
if (xStyle.is())
xStyle->getPropertyValue(STYLEPROP_UINAME) >>= aStyle.sLabel;
}
catch(const css::uno::RuntimeException& exRun)
{ throw exRun; }
catch(const css::uno::Exception&)
{ aStyle.sLabel = ::rtl::OUString(); }
if (!aStyle.sLabel.getLength())
{
aStyle.sLabel = aStyle.sCommand;
/*
#if OSL_DEBUG_LEVEL > 1
::rtl::OUStringBuffer sMsg(256);
sMsg.appendAscii("There is no UIName for the style command \"");
sMsg.append (aStyle.sCommand );
sMsg.appendAscii("\". The UI will be invalid then ..." );
OSL_ENSURE(sal_False, ::rtl::OUStringToOString(sMsg.makeStringAndClear(), RTL_TEXTENCODING_UTF8).getStr());
#endif
*/
}
}
::std::vector< SfxStyleInfo_Impl > SfxStylesInfo_Impl::getStyleFamilies()
{
// Its an optional interface!
css::uno::Reference< css::style::XStyleFamiliesSupplier > xModel(m_xDoc, css::uno::UNO_QUERY);
if (!xModel.is())
return ::std::vector< SfxStyleInfo_Impl >();
css::uno::Reference< css::container::XNameAccess > xCont = xModel->getStyleFamilies();
css::uno::Sequence< ::rtl::OUString > lFamilyNames = xCont->getElementNames();
::std::vector< SfxStyleInfo_Impl > lFamilies;
sal_Int32 c = lFamilyNames.getLength();
sal_Int32 i = 0;
for(i=0; i<c; ++i)
{
SfxStyleInfo_Impl aFamilyInfo;
aFamilyInfo.sFamily = lFamilyNames[i];
try
{
css::uno::Reference< css::beans::XPropertySet > xFamilyInfo;
xCont->getByName(aFamilyInfo.sFamily) >>= xFamilyInfo;
if (!xFamilyInfo.is())
{
// TODO_AS currently there is no support for an UIName property .. use internal family name instead
aFamilyInfo.sLabel = aFamilyInfo.sFamily;
}
else
xFamilyInfo->getPropertyValue(STYLEPROP_UINAME) >>= aFamilyInfo.sLabel;
}
catch(const css::uno::RuntimeException& exRun)
{ throw exRun; }
catch(const css::uno::Exception&)
{ return ::std::vector< SfxStyleInfo_Impl >(); }
lFamilies.push_back(aFamilyInfo);
}
return lFamilies;
}
::std::vector< SfxStyleInfo_Impl > SfxStylesInfo_Impl::getStyles(const ::rtl::OUString& sFamily)
{
static ::rtl::OUString PROP_UINAME = ::rtl::OUString::createFromAscii("DisplayName");
css::uno::Sequence< ::rtl::OUString > lStyleNames;
css::uno::Reference< css::style::XStyleFamiliesSupplier > xModel(m_xDoc, css::uno::UNO_QUERY_THROW);
css::uno::Reference< css::container::XNameAccess > xFamilies = xModel->getStyleFamilies();
css::uno::Reference< css::container::XNameAccess > xStyleSet;
try
{
xFamilies->getByName(sFamily) >>= xStyleSet;
lStyleNames = xStyleSet->getElementNames();
}
catch(const css::uno::RuntimeException& exRun)
{ throw exRun; }
catch(const css::uno::Exception&)
{ return ::std::vector< SfxStyleInfo_Impl >(); }
::std::vector< SfxStyleInfo_Impl > lStyles;
sal_Int32 c = lStyleNames.getLength();
sal_Int32 i = 0;
for (i=0; i<c; ++i)
{
SfxStyleInfo_Impl aStyleInfo;
aStyleInfo.sFamily = sFamily;
aStyleInfo.sStyle = lStyleNames[i];
aStyleInfo.sCommand = SfxStylesInfo_Impl::generateCommand(aStyleInfo.sFamily, aStyleInfo.sStyle);
try
{
css::uno::Reference< css::beans::XPropertySet > xStyle;
xStyleSet->getByName(aStyleInfo.sStyle) >>= xStyle;
if (!xStyle.is())
continue;
xStyle->getPropertyValue(PROP_UINAME) >>= aStyleInfo.sLabel;
}
catch(const css::uno::RuntimeException& exRun)
{ throw exRun; }
catch(const css::uno::Exception&)
{ continue; }
lStyles.push_back(aStyleInfo);
}
return lStyles;
}
SV_IMPL_PTRARR(SfxGroupInfoArr_Impl, SfxGroupInfoPtr);
SfxConfigFunctionListBox_Impl::SfxConfigFunctionListBox_Impl( Window* pParent, const ResId& rResId)
: SvTreeListBox( pParent, rResId )
, pCurEntry( 0 )
, pStylesInfo( 0 )
{
SetStyle( GetStyle() | WB_CLIPCHILDREN | WB_HSCROLL | WB_SORT );
GetModel()->SetSortMode( SortAscending );
// Timer f"ur die BallonHelp
aTimer.SetTimeout( 200 );
aTimer.SetTimeoutHdl(
LINK( this, SfxConfigFunctionListBox_Impl, TimerHdl ) );
}
SfxConfigFunctionListBox_Impl::~SfxConfigFunctionListBox_Impl()
{
ClearAll();
}
void SfxConfigFunctionListBox_Impl::MouseMove( const MouseEvent& )
{
/* --> PB 2004-12-01 #i37000# - no own help text needed any longer
Point aMousePos = rMEvt.GetPosPixel();
pCurEntry = GetCurEntry();
if ( pCurEntry && GetEntry( aMousePos ) == pCurEntry )
aTimer.Start();
else
{
Help::ShowBalloon( this, aMousePos, String() );
aTimer.Stop();
}
*/
}
IMPL_LINK( SfxConfigFunctionListBox_Impl, TimerHdl, Timer*, pTimer)
/* Beschreibung
Timer-Handler f"ur die Einblendung eines Hilfetextes. Wenn nach Ablauf des Timers
der Mauszeiger immer noch auf dem aktuell selektierten Eintrag steht, wird der
Helptext des Entries als Balloon-Help eingeblendet.
*/
{
(void)pTimer; // unused
/* --> PB 2004-12-01 #i37000# - no own help text needed any longer
aTimer.Stop();
Point aMousePos = GetPointerPosPixel();
SvLBoxEntry *pEntry = GetCurEntry();
if ( pEntry && GetEntry( aMousePos ) == pEntry && pCurEntry == pEntry )
{
String sHelpText = GetHelpText( pEntry );
Help::ShowBalloon( this, OutputToScreenPixel( aMousePos ), sHelpText );
}
*/
return 0L;
}
void SfxConfigFunctionListBox_Impl::ClearAll()
/* Beschreibung
L"oscht alle Eintr"age in der FunctionListBox, alle UserDaten und alle evtl.
vorhandenen MacroInfos.
*/
{
sal_uInt16 nCount = aArr.Count();
for ( sal_uInt16 i=0; i<nCount; i++ )
{
SfxGroupInfo_Impl *pData = aArr[i];
if ( pData->nKind == SFX_CFGFUNCTION_SCRIPT )
{
String* pScriptURI = (String*)pData->pObject;
delete pScriptURI;
}
if ( pData->nKind == SFX_CFGGROUP_SCRIPTCONTAINER
)
{
XInterface* xi = static_cast<XInterface *>(pData->pObject);
if (xi != NULL)
{
xi->release();
}
}
delete pData;
}
aArr.Remove( 0, nCount );
Clear();
}
String SfxConfigFunctionListBox_Impl::GetSelectedScriptURI()
{
SvLBoxEntry *pEntry = FirstSelected();
if ( pEntry )
{
SfxGroupInfo_Impl *pData = (SfxGroupInfo_Impl*) pEntry->GetUserData();
if ( pData && ( pData->nKind == SFX_CFGFUNCTION_SCRIPT ) )
return *(String*)pData->pObject;
}
return String();
}
String SfxConfigFunctionListBox_Impl::GetCurCommand()
{
SvLBoxEntry *pEntry = FirstSelected();
if (!pEntry)
return String();
SfxGroupInfo_Impl *pData = (SfxGroupInfo_Impl*) pEntry->GetUserData();
if (!pData)
return String();
return pData->sCommand;
}
String SfxConfigFunctionListBox_Impl::GetCurLabel()
{
SvLBoxEntry *pEntry = FirstSelected();
if (!pEntry)
return String();
SfxGroupInfo_Impl *pData = (SfxGroupInfo_Impl*) pEntry->GetUserData();
if (!pData)
return String();
if (pData->sLabel.Len())
return pData->sLabel;
return pData->sCommand;
}
void SfxConfigFunctionListBox_Impl::FunctionSelected()
/* Beschreibung
Setzt die Balloonhelp zur"uck, da diese immer den Helptext des selektierten
Entry anzeigen soll.
*/
{
/* --> PB 2004-12-01 #i37000# - no own help text needed any longer
Help::ShowBalloon( this, Point(), String() );
*/
}
void SfxConfigFunctionListBox_Impl::SetStylesInfo(SfxStylesInfo_Impl* pStyles)
{
pStylesInfo = pStyles;
}
struct SvxConfigGroupBoxResource_Impl : public Resource
{
Image m_hdImage;
Image m_hdImage_hc;
Image m_libImage;
Image m_libImage_hc;
Image m_macImage;
Image m_macImage_hc;
Image m_docImage;
Image m_docImage_hc;
::rtl::OUString m_sMyMacros;
::rtl::OUString m_sProdMacros;
String m_sMacros;
String m_sDlgMacros;
String m_aHumanAppName;
String m_aStrGroupStyles;
Image m_collapsedImage;
Image m_collapsedImage_hc;
Image m_expandedImage;
Image m_expandedImage_hc;
SvxConfigGroupBoxResource_Impl();
};
SvxConfigGroupBoxResource_Impl::SvxConfigGroupBoxResource_Impl() :
Resource(CUI_RES(RID_SVXPAGE_CONFIGGROUPBOX)),
m_hdImage(CUI_RES(IMG_HARDDISK)),
m_hdImage_hc(CUI_RES(IMG_HARDDISK_HC)),
m_libImage(CUI_RES(IMG_LIB)),
m_libImage_hc(CUI_RES(IMG_LIB_HC)),
m_macImage(CUI_RES(IMG_MACRO)),
m_macImage_hc(CUI_RES(IMG_MACRO_HC)),
m_docImage(CUI_RES(IMG_DOC)),
m_docImage_hc(CUI_RES(IMG_DOC_HC)),
m_sMyMacros(String(CUI_RES(STR_MYMACROS))),
m_sProdMacros(String(CUI_RES(STR_PRODMACROS))),
m_sMacros(String(CUI_RES(STR_BASICMACROS))),
m_sDlgMacros(String(CUI_RES(STR_DLG_MACROS))),
m_aHumanAppName(String(CUI_RES(STR_HUMAN_APPNAME))),
m_aStrGroupStyles(String(CUI_RES(STR_GROUP_STYLES))),
m_collapsedImage(CUI_RES(BMP_COLLAPSED)),
m_collapsedImage_hc(CUI_RES(BMP_COLLAPSED_HC)),
m_expandedImage(CUI_RES(BMP_EXPANDED)),
m_expandedImage_hc(CUI_RES(BMP_EXPANDED_HC))
{
FreeResource();
}
SfxConfigGroupListBox_Impl::SfxConfigGroupListBox_Impl(
Window* pParent, const ResId& rResId, sal_uLong nConfigMode )
: SvTreeListBox( pParent, rResId )
, pImp(new SvxConfigGroupBoxResource_Impl()), pFunctionListBox(0), nMode( nConfigMode ), pStylesInfo(0)
{
SetStyle( GetStyle() | WB_CLIPCHILDREN | WB_HSCROLL | WB_HASBUTTONS | WB_HASLINES | WB_HASLINESATROOT | WB_HASBUTTONSATROOT );
SetNodeBitmaps( pImp->m_collapsedImage, pImp->m_expandedImage, BMP_COLOR_NORMAL );
SetNodeBitmaps( pImp->m_collapsedImage_hc, pImp->m_expandedImage_hc, BMP_COLOR_HIGHCONTRAST );
}
SfxConfigGroupListBox_Impl::~SfxConfigGroupListBox_Impl()
{
ClearAll();
}
void SfxConfigGroupListBox_Impl::ClearAll()
{
sal_uInt16 nCount = aArr.Count();
for ( sal_uInt16 i=0; i<nCount; i++ )
{
SfxGroupInfo_Impl *pData = aArr[i];
if ( pData->nKind == SFX_CFGGROUP_SCRIPTCONTAINER
)
{
XInterface* xi = static_cast<XInterface *>(pData->pObject);
if (xi != NULL)
{
xi->release();
}
}
delete pData;
}
aArr.Remove( 0, nCount );
Clear();
}
void SfxConfigGroupListBox_Impl::SetStylesInfo(SfxStylesInfo_Impl* pStyles)
{
pStylesInfo = pStyles;
}
String SfxConfigGroupListBox_Impl::GetGroup()
/* Beschreibung
Gibt den Namen der selektierten Funktionsgruppe bzw. des selektierten
Basics zur"uck.
*/
{
SvLBoxEntry *pEntry = FirstSelected();
while ( pEntry )
{
SfxGroupInfo_Impl *pInfo = (SfxGroupInfo_Impl*) pEntry->GetUserData();
if ( pInfo->nKind == SFX_CFGGROUP_FUNCTION )
return GetEntryText( pEntry );
pEntry = GetParent( pEntry );
}
return String();
}
//-----------------------------------------------
void SfxConfigGroupListBox_Impl::InitModule()
{
try
{
css::uno::Reference< css::frame::XDispatchInformationProvider > xProvider(m_xFrame, css::uno::UNO_QUERY_THROW);
css::uno::Sequence< sal_Int16 > lGroups = xProvider->getSupportedCommandGroups();
sal_Int32 c1 = lGroups.getLength();
sal_Int32 i1 = 0;
for (i1=0; i1<c1; ++i1)
{
sal_Int16& rGroupID = lGroups[i1];
::rtl::OUString sGroupID = ::rtl::OUString::valueOf((sal_Int32)rGroupID);
::rtl::OUString sGroupName ;
try
{
m_xModuleCategoryInfo->getByName(sGroupID) >>= sGroupName;
if (!sGroupName.getLength())
continue;
}
catch(const css::container::NoSuchElementException&)
{ continue; }
SvLBoxEntry* pEntry = InsertEntry(sGroupName, NULL);
SfxGroupInfo_Impl* pInfo = new SfxGroupInfo_Impl(SFX_CFGGROUP_FUNCTION, rGroupID);
pEntry->SetUserData(pInfo);
}
}
catch(const css::uno::RuntimeException& exRun)
{ throw exRun; }
catch(const css::uno::Exception&)
{}
}
//-----------------------------------------------
void SfxConfigGroupListBox_Impl::InitBasic()
{
}
//-----------------------------------------------
void SfxConfigGroupListBox_Impl::InitStyles()
{
}
//-----------------------------------------------
namespace
{
//...........................................
/** examines a component whether it supports XEmbeddedScripts, or provides access to such a
component by implementing XScriptInvocationContext.
@return
the model which supports the embedded scripts, or <NULL/> if it cannot find such a
model
*/
static Reference< XModel > lcl_getDocumentWithScripts_throw( const Reference< XInterface >& _rxComponent )
{
Reference< XEmbeddedScripts > xScripts( _rxComponent, UNO_QUERY );
if ( !xScripts.is() )
{
Reference< XScriptInvocationContext > xContext( _rxComponent, UNO_QUERY );
if ( xContext.is() )
xScripts.set( xContext->getScriptContainer(), UNO_QUERY );
}
return Reference< XModel >( xScripts, UNO_QUERY );
}
//...........................................
static Reference< XModel > lcl_getScriptableDocument_nothrow( const Reference< XFrame >& _rxFrame )
{
Reference< XModel > xDocument;
// examine our associated frame
try
{
OSL_ENSURE( _rxFrame.is(), "lcl_getScriptableDocument_nothrow: you need to pass a frame to this dialog/tab page!" );
if ( _rxFrame.is() )
{
// first try the model in the frame
Reference< XController > xController( _rxFrame->getController(), UNO_SET_THROW );
xDocument = lcl_getDocumentWithScripts_throw( xController->getModel() );
if ( !xDocument.is() )
{
// if there is no suitable document in the frame, try the controller
xDocument = lcl_getDocumentWithScripts_throw( _rxFrame->getController() );
}
}
}
catch( const Exception& )
{
//DBG_UNHANDLED_EXCEPTION();
}
return xDocument;
}
}
//-----------------------------------------------
void SfxConfigGroupListBox_Impl::Init(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR ,
const css::uno::Reference< css::frame::XFrame >& xFrame ,
const ::rtl::OUString& sModuleLongName)
{
SetUpdateMode(sal_False);
ClearAll(); // Remove all old entries from treelist box
m_xFrame = xFrame;
if ( xSMGR.is())
{
m_xSMGR = xSMGR;
m_sModuleLongName = sModuleLongName;
m_xGlobalCategoryInfo = css::uno::Reference< css::container::XNameAccess >(m_xSMGR->createInstance(SERVICE_UICATEGORYDESCRIPTION), css::uno::UNO_QUERY_THROW);
m_xModuleCategoryInfo = css::uno::Reference< css::container::XNameAccess >(m_xGlobalCategoryInfo->getByName(m_sModuleLongName) , css::uno::UNO_QUERY_THROW);
m_xUICmdDescription = css::uno::Reference< css::container::XNameAccess >(m_xSMGR->createInstance(SERVICE_UICMDDESCRIPTION) , css::uno::UNO_QUERY_THROW);
InitModule();
InitBasic();
InitStyles();
}
OSL_TRACE("** ** About to initialise SF Scripts");
// Add Scripting Framework entries
Reference< browse::XBrowseNode > rootNode;
Reference< XComponentContext > xCtx;
try
{
Reference < beans::XPropertySet > xProps(
::comphelper::getProcessServiceFactory(), UNO_QUERY_THROW );
xCtx.set( xProps->getPropertyValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DefaultContext" ))), UNO_QUERY_THROW );
Reference< browse::XBrowseNodeFactory > xFac( xCtx->getValueByName(
::rtl::OUString::createFromAscii( "/singletons/com.sun.star.script.browse.theBrowseNodeFactory") ), UNO_QUERY_THROW );
rootNode.set( xFac->createView( browse::BrowseNodeFactoryViewTypes::MACROSELECTOR ) );
//rootNode.set( xFac->createView( browse::BrowseNodeFactoryViewTypes::MACROORGANIZER ) );
}
catch( Exception& e )
{
OSL_TRACE(" Caught some exception whilst retrieving browse nodes from factory... Exception: %s",
::rtl::OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ).pData->buffer );
// TODO exception handling
}
if ( rootNode.is() )
{
if ( nMode )
{
//We call acquire on the XBrowseNode so that it does not
//get autodestructed and become invalid when accessed later.
rootNode->acquire();
SfxGroupInfo_Impl *pInfo =
new SfxGroupInfo_Impl( SFX_CFGGROUP_SCRIPTCONTAINER, 0,
static_cast<void *>(rootNode.get()));
String aTitle(pImp->m_sDlgMacros);
SvLBoxEntry *pNewEntry = InsertEntry( aTitle, NULL );
pNewEntry->SetUserData( pInfo );
pNewEntry->EnableChildsOnDemand( sal_True );
aArr.Insert( pInfo, aArr.Count() );
}
else
{
//We are only showing scripts not slot APIs so skip
//Root node and show location nodes
try {
if ( rootNode->hasChildNodes() )
{
Sequence< Reference< browse::XBrowseNode > > children =
rootNode->getChildNodes();
sal_Bool bIsRootNode = sal_False;
::rtl::OUString user = ::rtl::OUString::createFromAscii("user");
::rtl::OUString share = ::rtl::OUString::createFromAscii("share");
if ( rootNode->getName().equals(::rtl::OUString::createFromAscii("Root") ))
{
bIsRootNode = sal_True;
}
//To mimic current starbasic behaviour we
//need to make sure that only the current document
//is displayed in the config tree. Tests below
//set the bDisplay flag to FALSE if the current
//node is a first level child of the Root and is NOT
//either the current document, user or share
::rtl::OUString currentDocTitle;
Reference< XModel > xDocument( lcl_getScriptableDocument_nothrow( m_xFrame ) );
if ( xDocument.is() )
{
currentDocTitle = ::comphelper::DocumentInfo::getDocumentTitle( xDocument );
}
for ( sal_Int32 n = 0; n < children.getLength(); n++ )
{
Reference< browse::XBrowseNode >& theChild = children[n];
sal_Bool bDisplay = sal_True;
::rtl::OUString uiName = theChild->getName();
if ( bIsRootNode )
{
if ( ! ((theChild->getName().equals( user ) || theChild->getName().equals( share ) ||
theChild->getName().equals( currentDocTitle ) ) ) )
{
bDisplay=sal_False;
}
else
{
if ( uiName.equals( user ) )
{
uiName = pImp->m_sMyMacros;
}
else if ( uiName.equals( share ) )
{
uiName = pImp->m_sProdMacros;
}
}
}
if (children[n]->getType() != browse::BrowseNodeTypes::SCRIPT && bDisplay )
{
// We call acquire on the XBrowseNode so that it does not
// get autodestructed and become invalid when accessed later.
theChild->acquire();
SfxGroupInfo_Impl* pInfo =
new SfxGroupInfo_Impl(SFX_CFGGROUP_SCRIPTCONTAINER,
0, static_cast<void *>( theChild.get()));
Image aImage = GetImage( theChild, xCtx, bIsRootNode,BMP_COLOR_NORMAL );
SvLBoxEntry* pNewEntry =
InsertEntry( uiName, NULL);
SetExpandedEntryBmp(pNewEntry, aImage, BMP_COLOR_NORMAL);
SetCollapsedEntryBmp(pNewEntry, aImage, BMP_COLOR_NORMAL);
aImage = GetImage( theChild, xCtx, bIsRootNode,BMP_COLOR_HIGHCONTRAST );
SetExpandedEntryBmp(pNewEntry, aImage, BMP_COLOR_HIGHCONTRAST);
SetCollapsedEntryBmp(pNewEntry, aImage, BMP_COLOR_HIGHCONTRAST);
pNewEntry->SetUserData( pInfo );
aArr.Insert( pInfo, aArr.Count() );
if ( children[n]->hasChildNodes() )
{
Sequence< Reference< browse::XBrowseNode > > grandchildren =
children[n]->getChildNodes();
for ( sal_Int32 m = 0; m < grandchildren.getLength(); m++ )
{
if ( grandchildren[m]->getType() == browse::BrowseNodeTypes::CONTAINER )
{
pNewEntry->EnableChildsOnDemand( sal_True );
m = grandchildren.getLength();
}
}
}
}
}
}
}
catch (RuntimeException&) {
// do nothing, the entry will not be displayed in the UI
}
}
}
// add styles
if ( m_xSMGR.is() )
{
String sStyle( pImp->m_aStrGroupStyles );
SvLBoxEntry *pEntry = InsertEntry( sStyle, 0 );
SfxGroupInfo_Impl *pInfo = new SfxGroupInfo_Impl( SFX_CFGGROUP_STYLES, 0, 0 ); // TODO last parameter should contain user data
aArr.Insert( pInfo, aArr.Count() );
pEntry->SetUserData( pInfo );
pEntry->EnableChildsOnDemand( sal_True );
}
MakeVisible( GetEntry( 0,0 ) );
SetUpdateMode( sal_True );
}
Image SfxConfigGroupListBox_Impl::GetImage( Reference< browse::XBrowseNode > node, Reference< XComponentContext > xCtx, bool bIsRootNode, bool bHighContrast )
{
Image aImage;
if ( bIsRootNode )
{
::rtl::OUString user = ::rtl::OUString::createFromAscii("user");
::rtl::OUString share = ::rtl::OUString::createFromAscii("share");
if (node->getName().equals( user ) || node->getName().equals(share ) )
{
if( bHighContrast == BMP_COLOR_NORMAL )
aImage = pImp->m_hdImage;
else
aImage = pImp->m_hdImage_hc;
}
else
{
::rtl::OUString factoryURL;
::rtl::OUString nodeName = node->getName();
Reference<XInterface> xDocumentModel = getDocumentModel(xCtx, nodeName );
if ( xDocumentModel.is() )
{
Reference< ::com::sun::star::frame::XModuleManager >
xModuleManager(
xCtx->getServiceManager()
->createInstanceWithContext(
::rtl::OUString::createFromAscii("" // xxx todo
"com.sun.star.frame.ModuleManager"),
xCtx ),
UNO_QUERY_THROW );
Reference<container::XNameAccess> xModuleConfig(
xModuleManager, UNO_QUERY_THROW );
// get the long name of the document:
::rtl::OUString appModule( xModuleManager->identify(
xDocumentModel ) );
Sequence<beans::PropertyValue> moduleDescr;
Any aAny = xModuleConfig->getByName(appModule);
if( sal_True != ( aAny >>= moduleDescr ) )
{
throw RuntimeException(::rtl::OUString::createFromAscii("SFTreeListBox::Init: failed to get PropertyValue"), Reference< XInterface >());
}
beans::PropertyValue const * pmoduleDescr =
moduleDescr.getConstArray();
for ( sal_Int32 pos = moduleDescr.getLength(); pos--; )
{
if (pmoduleDescr[ pos ].Name.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM(
"ooSetupFactoryEmptyDocumentURL") ))
{
pmoduleDescr[ pos ].Value >>= factoryURL;
OSL_TRACE("factory url for doc images is %s",
::rtl::OUStringToOString( factoryURL , RTL_TEXTENCODING_ASCII_US ).pData->buffer );
break;
}
}
}
if( factoryURL.getLength() > 0 )
{
if( bHighContrast == BMP_COLOR_NORMAL )
aImage = SvFileInformationManager::GetFileImage(
INetURLObject(factoryURL), false,
BMP_COLOR_NORMAL );
else
aImage = SvFileInformationManager::GetFileImage(
INetURLObject(factoryURL), false,
BMP_COLOR_HIGHCONTRAST );
}
else
{
if( bHighContrast == BMP_COLOR_NORMAL )
aImage = pImp->m_docImage;
else
aImage = pImp->m_docImage_hc;
}
}
}
else
{
if( node->getType() == browse::BrowseNodeTypes::SCRIPT )
{
if( bHighContrast == BMP_COLOR_NORMAL )
aImage = pImp->m_macImage;
else
aImage = pImp->m_macImage_hc;
}
else
{
if( bHighContrast == BMP_COLOR_NORMAL )
aImage = pImp->m_libImage;
else
aImage = pImp->m_libImage_hc;
}
}
return aImage;
}
Reference< XInterface >
SfxConfigGroupListBox_Impl::getDocumentModel( Reference< XComponentContext >& xCtx, ::rtl::OUString& docName )
{
Reference< XInterface > xModel;
Reference< lang::XMultiComponentFactory > mcf =
xCtx->getServiceManager();
Reference< frame::XDesktop > desktop (
mcf->createInstanceWithContext(
::rtl::OUString::createFromAscii("com.sun.star.frame.Desktop"), xCtx ),
UNO_QUERY );
Reference< container::XEnumerationAccess > componentsAccess =
desktop->getComponents();
Reference< container::XEnumeration > components =
componentsAccess->createEnumeration();
while (components->hasMoreElements())
{
Reference< frame::XModel > model(
components->nextElement(), UNO_QUERY );
if ( model.is() )
{
::rtl::OUString sTdocUrl =
::comphelper::DocumentInfo::getDocumentTitle( model );
if( sTdocUrl.equals( docName ) )
{
xModel = model;
break;
}
}
}
return xModel;
}
//-----------------------------------------------
::rtl::OUString SfxConfigGroupListBox_Impl::MapCommand2UIName(const ::rtl::OUString& sCommand)
{
::rtl::OUString sUIName;
try
{
css::uno::Reference< css::container::XNameAccess > xModuleConf;
m_xUICmdDescription->getByName(m_sModuleLongName) >>= xModuleConf;
if (xModuleConf.is())
{
::comphelper::SequenceAsHashMap lProps(xModuleConf->getByName(sCommand));
sUIName = lProps.getUnpackedValueOrDefault(::rtl::OUString::createFromAscii("Name"), ::rtl::OUString());
}
}
catch(const css::uno::RuntimeException& exRun)
{ throw exRun; }
catch(css::uno::Exception&)
{ sUIName = ::rtl::OUString(); }
// fallback for missing UINames !?
if (!sUIName.getLength())
{
sUIName = sCommand;
/*
#if OSL_DEBUG_LEVEL > 1
::rtl::OUStringBuffer sMsg(256);
sMsg.appendAscii("There is no UIName for the internal command \"");
sMsg.append (sCommand );
sMsg.appendAscii("\". The UI will be invalid then ..." );
OSL_ENSURE(sal_False, ::rtl::OUStringToOString(sMsg.makeStringAndClear(), RTL_TEXTENCODING_UTF8).getStr());
#endif
*/
}
return sUIName;
}
//-----------------------------------------------
void SfxConfigGroupListBox_Impl::GroupSelected()
/* Beschreibung
Eine Funktionsgruppe oder eine Basicmodul wurde selektiert. Alle Funktionen bzw.
Macros werden in der Functionlistbox anzeigt.
*/
{
SvLBoxEntry *pEntry = FirstSelected();
SfxGroupInfo_Impl *pInfo = (SfxGroupInfo_Impl*) pEntry->GetUserData();
pFunctionListBox->SetUpdateMode(sal_False);
pFunctionListBox->ClearAll();
if ( pInfo->nKind != SFX_CFGGROUP_FUNCTION &&
pInfo->nKind != SFX_CFGGROUP_SCRIPTCONTAINER &&
pInfo->nKind != SFX_CFGGROUP_STYLES )
{
pFunctionListBox->SetUpdateMode(sal_True);
return;
}
switch ( pInfo->nKind )
{
case SFX_CFGGROUP_FUNCTION :
{
sal_uInt16 nGroup = pInfo->nUniqueID;
css::uno::Reference< css::frame::XDispatchInformationProvider > xProvider (m_xFrame, css::uno::UNO_QUERY_THROW);
css::uno::Sequence< css::frame::DispatchInformation > lCommands = xProvider->getConfigurableDispatchInformation(nGroup);
sal_Int32 c = lCommands.getLength();
sal_Int32 i = 0;
for (i=0; i<c; ++i)
{
const css::frame::DispatchInformation& rInfo = lCommands[i];
::rtl::OUString sUIName = MapCommand2UIName(rInfo.Command);
SvLBoxEntry* pFuncEntry = pFunctionListBox->InsertEntry(sUIName, NULL);
SfxGroupInfo_Impl* pGrpInfo = new SfxGroupInfo_Impl(SFX_CFGFUNCTION_SLOT, 0);
pGrpInfo->sCommand = rInfo.Command;
pGrpInfo->sLabel = sUIName;
pFuncEntry->SetUserData(pGrpInfo);
}
break;
}
case SFX_CFGGROUP_SCRIPTCONTAINER:
{
if ( !GetChildCount( pEntry ) )
{
Reference< browse::XBrowseNode > rootNode(
reinterpret_cast< browse::XBrowseNode* >( pInfo->pObject ) ) ;
try {
if ( rootNode->hasChildNodes() )
{
Sequence< Reference< browse::XBrowseNode > > children =
rootNode->getChildNodes();
for ( sal_Int32 n = 0; n < children.getLength(); n++ )
{
if (children[n]->getType() == browse::BrowseNodeTypes::SCRIPT)
{
::rtl::OUString uri;
Reference < beans::XPropertySet >xPropSet( children[n], UNO_QUERY );
if (!xPropSet.is())
{
continue;
}
Any value =
xPropSet->getPropertyValue( String::CreateFromAscii( "URI" ) );
value >>= uri;
String* pScriptURI = new String( uri );
SfxGroupInfo_Impl* pGrpInfo = new SfxGroupInfo_Impl( SFX_CFGFUNCTION_SCRIPT, 0, pScriptURI );
Image aImage = GetImage( children[n], Reference< XComponentContext >(), sal_False, BMP_COLOR_NORMAL );
SvLBoxEntry* pNewEntry =
pFunctionListBox->InsertEntry( children[n]->getName(), NULL );
pFunctionListBox->SetExpandedEntryBmp(pNewEntry, aImage, BMP_COLOR_NORMAL);
pFunctionListBox->SetCollapsedEntryBmp(pNewEntry, aImage, BMP_COLOR_NORMAL);
aImage = GetImage( children[n], Reference< XComponentContext >(), sal_False, BMP_COLOR_HIGHCONTRAST );
pFunctionListBox->SetExpandedEntryBmp(pNewEntry, aImage, BMP_COLOR_HIGHCONTRAST);
pFunctionListBox->SetCollapsedEntryBmp(pNewEntry, aImage, BMP_COLOR_HIGHCONTRAST);
pGrpInfo->sCommand = uri;
pGrpInfo->sLabel = children[n]->getName();
pNewEntry->SetUserData( pGrpInfo );
pFunctionListBox->aArr.Insert(
pGrpInfo, pFunctionListBox->aArr.Count() );
}
}
}
}
catch (RuntimeException&) {
// do nothing, the entry will not be displayed in the UI
}
}
break;
}
case SFX_CFGGROUP_STYLES :
{
SfxStyleInfo_Impl* pFamily = (SfxStyleInfo_Impl*)(pInfo->pObject);
if (pFamily)
{
const ::std::vector< SfxStyleInfo_Impl > lStyles = pStylesInfo->getStyles(pFamily->sFamily);
::std::vector< SfxStyleInfo_Impl >::const_iterator pIt;
for ( pIt = lStyles.begin();
pIt != lStyles.end() ;
++pIt )
{
SfxStyleInfo_Impl* pStyle = new SfxStyleInfo_Impl(*pIt);
SvLBoxEntry* pFuncEntry = pFunctionListBox->InsertEntry( pStyle->sLabel, NULL );
SfxGroupInfo_Impl *pGrpInfo = new SfxGroupInfo_Impl( SFX_CFGGROUP_STYLES, 0, pStyle );
pFunctionListBox->aArr.Insert( pGrpInfo, pFunctionListBox->aArr.Count() );
pGrpInfo->sCommand = pStyle->sCommand;
pGrpInfo->sLabel = pStyle->sLabel;
pFuncEntry->SetUserData( pGrpInfo );
}
}
break;
}
default:
return;
}
if ( pFunctionListBox->GetEntryCount() )
pFunctionListBox->Select( pFunctionListBox->GetEntry( 0, 0 ) );
pFunctionListBox->SetUpdateMode(sal_True);
}
sal_Bool SfxConfigGroupListBox_Impl::Expand( SvLBoxEntry* pParent )
{
sal_Bool bRet = SvTreeListBox::Expand( pParent );
if ( bRet )
{
// Wieviele Entries k"onnen angezeigt werden ?
sal_uLong nEntries = GetOutputSizePixel().Height() / GetEntryHeight();
// Wieviele Kinder sollen angezeigt werden ?
sal_uLong nChildCount = GetVisibleChildCount( pParent );
// Passen alle Kinder und der parent gleichzeitig in die View ?
if ( nChildCount+1 > nEntries )
{
// Wenn nicht, wenigstens parent ganz nach oben schieben
MakeVisible( pParent, sal_True );
}
else
{
// An welcher relativen ViewPosition steht der aufzuklappende parent
SvLBoxEntry *pEntry = GetFirstEntryInView();
sal_uLong nParentPos = 0;
while ( pEntry && pEntry != pParent )
{
nParentPos++;
pEntry = GetNextEntryInView( pEntry );
}
// Ist unter dem parent noch genug Platz f"ur alle Kinder ?
if ( nParentPos + nChildCount + 1 > nEntries )
ScrollOutputArea( (short)( nEntries - ( nParentPos + nChildCount + 1 ) ) );
}
}
return bRet;
}
void SfxConfigGroupListBox_Impl::RequestingChilds( SvLBoxEntry *pEntry )
/* Beschreibung
Ein Basic oder eine Bibliothek werden ge"offnet
*/
{
SfxGroupInfo_Impl *pInfo = (SfxGroupInfo_Impl*) pEntry->GetUserData();
pInfo->bWasOpened = sal_True;
switch ( pInfo->nKind )
{
case SFX_CFGGROUP_SCRIPTCONTAINER:
{
if ( !GetChildCount( pEntry ) )
{
Reference< browse::XBrowseNode > rootNode(
reinterpret_cast< browse::XBrowseNode* >( pInfo->pObject ) ) ;
try {
if ( rootNode->hasChildNodes() )
{
Sequence< Reference< browse::XBrowseNode > > children =
rootNode->getChildNodes();
sal_Bool bIsRootNode = sal_False;
::rtl::OUString user = ::rtl::OUString::createFromAscii("user");
::rtl::OUString share = ::rtl::OUString::createFromAscii("share");
if ( rootNode->getName().equals(::rtl::OUString::createFromAscii("Root") ))
{
bIsRootNode = sal_True;
}
/* To mimic current starbasic behaviour we
need to make sure that only the current document
is displayed in the config tree. Tests below
set the bDisplay flag to sal_False if the current
node is a first level child of the Root and is NOT
either the current document, user or share */
::rtl::OUString currentDocTitle;
Reference< XModel > xDocument( lcl_getScriptableDocument_nothrow( m_xFrame ) );
if ( xDocument.is() )
{
currentDocTitle = ::comphelper::DocumentInfo::getDocumentTitle( xDocument );
}
sal_Int32 nLen = children.getLength();
for ( sal_Int32 n = 0; n < nLen; n++ )
{
Reference< browse::XBrowseNode >& theChild = children[n];
::rtl::OUString aName( theChild->getName() );
sal_Bool bDisplay = sal_True;
if ( bIsRootNode )
{
if ( !( (aName.equals(user) || aName.equals(share) || aName.equals(currentDocTitle) ) ) )
bDisplay=sal_False;
}
if ( children[n].is() && children[n]->getType() != browse::BrowseNodeTypes::SCRIPT && bDisplay )
{
/*
We call acquire on the XBrowseNode so that it does not
get autodestructed and become invalid when accessed later.
*/
theChild->acquire();
SfxGroupInfo_Impl* pGrpInfo =
new SfxGroupInfo_Impl(SFX_CFGGROUP_SCRIPTCONTAINER,
0, static_cast<void *>( theChild.get()));
Image aImage = GetImage( theChild, Reference< XComponentContext >(), sal_False, BMP_COLOR_NORMAL );
SvLBoxEntry* pNewEntry =
InsertEntry( theChild->getName(), pEntry );
SetExpandedEntryBmp(pNewEntry, aImage, BMP_COLOR_NORMAL);
SetCollapsedEntryBmp(pNewEntry, aImage, BMP_COLOR_NORMAL);
aImage = GetImage( theChild, Reference< XComponentContext >(), sal_False, BMP_COLOR_HIGHCONTRAST );
SetExpandedEntryBmp(pNewEntry, aImage, BMP_COLOR_HIGHCONTRAST);
SetCollapsedEntryBmp(pNewEntry, aImage, BMP_COLOR_HIGHCONTRAST);
pNewEntry->SetUserData( pGrpInfo );
aArr.Insert( pGrpInfo, aArr.Count() );
if ( children[n]->hasChildNodes() )
{
Sequence< Reference< browse::XBrowseNode > > grandchildren =
children[n]->getChildNodes();
for ( sal_Int32 m = 0; m < grandchildren.getLength(); m++ )
{
if ( grandchildren[m]->getType() == browse::BrowseNodeTypes::CONTAINER )
{
pNewEntry->EnableChildsOnDemand( sal_True );
m = grandchildren.getLength();
}
}
}
}
}
}
}
catch (RuntimeException&) {
// do nothing, the entry will not be displayed in the UI
}
}
break;
}
case SFX_CFGGROUP_STYLES:
{
if ( !GetChildCount( pEntry ) )
{
const ::std::vector< SfxStyleInfo_Impl > lStyleFamilies = pStylesInfo->getStyleFamilies();
::std::vector< SfxStyleInfo_Impl >::const_iterator pIt;
for ( pIt = lStyleFamilies.begin();
pIt != lStyleFamilies.end() ;
++pIt )
{
SfxStyleInfo_Impl* pFamily = new SfxStyleInfo_Impl(*pIt);
SvLBoxEntry* pStyleEntry = InsertEntry( pFamily->sLabel, pEntry );
SfxGroupInfo_Impl *pGrpInfo = new SfxGroupInfo_Impl( SFX_CFGGROUP_STYLES, 0, pFamily );
aArr.Insert( pGrpInfo, aArr.Count() );
pStyleEntry->SetUserData( pGrpInfo );
pStyleEntry->EnableChildsOnDemand( sal_False );
}
}
break;
}
default:
DBG_ERROR( "Falscher Gruppentyp!" );
break;
}
}
void SfxConfigGroupListBox_Impl::SelectMacro( const SfxMacroInfoItem *pItem )
{
SelectMacro( pItem->GetBasicManager()->GetName(),
pItem->GetQualifiedName() );
}
void SfxConfigGroupListBox_Impl::SelectMacro( const String& rBasic,
const String& rMacro )
{
String aBasicName( rBasic );
aBasicName += ' ';
aBasicName += pImp->m_sMacros;
String aLib, aModule, aMethod;
sal_uInt16 nCount = rMacro.GetTokenCount('.');
aMethod = rMacro.GetToken( nCount-1, '.' );
if ( nCount > 2 )
{
aLib = rMacro.GetToken( 0, '.' );
aModule = rMacro.GetToken( nCount-2, '.' );
}
SvLBoxEntry *pEntry = FirstChild(0);
while ( pEntry )
{
String aEntryBas = GetEntryText( pEntry );
if ( aEntryBas == aBasicName )
{
Expand( pEntry );
SvLBoxEntry *pLib = FirstChild( pEntry );
while ( pLib )
{
String aEntryLib = GetEntryText( pLib );
if ( aEntryLib == aLib )
{
Expand( pLib );
SvLBoxEntry *pMod = FirstChild( pLib );
while ( pMod )
{
String aEntryMod = GetEntryText( pMod );
if ( aEntryMod == aModule )
{
Expand( pMod );
MakeVisible( pMod );
Select( pMod );
SvLBoxEntry *pMethod = pFunctionListBox->First();
while ( pMethod )
{
String aEntryMethod = GetEntryText( pMethod );
if ( aEntryMethod == aMethod )
{
pFunctionListBox->Select( pMethod );
pFunctionListBox->MakeVisible( pMethod );
return;
}
pMethod = pFunctionListBox->Next( pMethod );
}
}
pMod = NextSibling( pMod );
}
}
pLib = NextSibling( pLib );
}
}
pEntry = NextSibling( pEntry );
}
}
| 35.539376 | 166 | 0.610377 | [
"vector",
"model"
] |
3ca6d404970e0fd1fe8c05e396c776e43161c565 | 2,888 | cpp | C++ | LeetCode/C++/1434. Number of Ways to Wear Different Hats to Each Other.cpp | shreejitverma/GeeksforGeeks | d7bcb166369fffa9a031a258e925b6aff8d44e6c | [
"MIT"
] | 2 | 2022-02-18T05:14:28.000Z | 2022-03-08T07:00:08.000Z | LeetCode/C++/1434. Number of Ways to Wear Different Hats to Each Other.cpp | shivaniverma1/Competitive-Programming-1 | d7bcb166369fffa9a031a258e925b6aff8d44e6c | [
"MIT"
] | 6 | 2022-01-13T04:31:04.000Z | 2022-03-12T01:06:16.000Z | LeetCode/C++/1434. Number of Ways to Wear Different Hats to Each Other.cpp | shivaniverma1/Competitive-Programming-1 | d7bcb166369fffa9a031a258e925b6aff8d44e6c | [
"MIT"
] | 2 | 2022-02-14T19:53:53.000Z | 2022-02-18T05:14:30.000Z | //TLE
//46 / 65 test cases passed.
class Solution {
public:
vector<bool> used;
vector<vector<int>> hats;
int count;
int MOD = 1e9+7;
void backtrack(int s){
if(s == hats.size()){
count = (count+1)%MOD;
// cout << endl;
return ;
}
for(int h : hats[s]){
if(used[h]) continue;
used[h] = true;
// cout << h << " ";
backtrack(s+1);
used[h] = false;
}
s++;
};
int numberWays(vector<vector<int>>& hats) {
sort(hats.begin(), hats.end(),
[](const vector<int>& a, const vector<int>& b){
return a.size() < b.size();
});
count = 0;
used = vector<bool>(41, false);
this->hats = hats;
backtrack(0);
// cout << endl;
return count;
}
};
//DP + Bitmask
//https://leetcode.com/problems/number-of-ways-to-wear-different-hats-to-each-other/discuss/608686/C%2B%2B-Bit-masks-and-Bottom-Up-DP
//Runtime: 32 ms, faster than 100.00% of C++ online submissions for Number of Ways to Wear Different Hats to Each Other.
//Memory Usage: 8 MB, less than 100.00% of C++ online submissions for Number of Ways to Wear Different Hats to Each Other.
class Solution {
public:
int numberWays(vector<vector<int>>& hats) {
int m = 40; //kinds of hats
const int n = hats.size(); //number of people
const int MOD = 1e9+7;
vector<vector<int>> people(m);
//record the counts of each state from 0 to 11...1(n 1s)
vector<int> stateCounts(1 << n);
/*
state 0 means that all people do not wear a hat,
and there could only be 1 possible combination of that state
*/
stateCounts[0] = 1;
/*
hats[i] lists the hats person i likely to wear
*/
for(int i = 0; i < n; i++){
for(int h : hats[i]){
//the hat "h" can be worn by person i
people[h-1].emplace_back(i);
}
}
for(int h = 0; h < m; h++){
// for(int j = 0; j < 1 << n; j++){
for(int j = (1 << n)-1; j >= 0; j--){
//hat 'h' can be distributed to person 'p'
for(int p : people[h]){
//skip the state in which person 'p' already has a hat
/*
the result of (j & (1 << p)) will be 1<<p,
so we can not check with ((j & (1 << p)) == 1)
*/
if((j & (1 << p)) != 0) continue;
stateCounts[j | (1 << p)] += stateCounts[j];
stateCounts[j | (1 << p)] %= MOD;
}
}
}
return stateCounts[(1<<n)-1];
}
};
| 31.053763 | 133 | 0.456025 | [
"vector"
] |
3cad6d37234ac6cf6282f1b1bd4769b89b9b20f5 | 25,831 | cpp | C++ | src/Providers/ManagedSystem/IP/ANHProvider.cpp | natronkeltner/openpegasus | e64f383c1ed37826041fc63e83b4e65fc1c679ae | [
"ICU",
"Unlicense",
"OpenSSL",
"MIT"
] | 1 | 2021-11-12T21:28:50.000Z | 2021-11-12T21:28:50.000Z | src/Providers/ManagedSystem/IP/ANHProvider.cpp | natronkeltner/openpegasus | e64f383c1ed37826041fc63e83b4e65fc1c679ae | [
"ICU",
"Unlicense",
"OpenSSL",
"MIT"
] | 39 | 2021-01-18T19:28:41.000Z | 2022-03-27T20:55:36.000Z | src/Providers/ManagedSystem/IP/ANHProvider.cpp | natronkeltner/openpegasus | e64f383c1ed37826041fc63e83b4e65fc1c679ae | [
"ICU",
"Unlicense",
"OpenSSL",
"MIT"
] | 4 | 2021-07-09T12:52:33.000Z | 2021-12-21T15:05:59.000Z | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////////
//
// This is an association provider. It implements the association methods for
// the following classes:
//
// CIM_RemoteServiceAccessPoint
// CIM_NextHopRoute
// PG_AssociatedNextHop (association class)
//
// Association methods supported are: associators, associatorNames,
// references, referenceNames
//
#include "ANHProvider.h"
PEGASUS_USING_STD;
PEGASUS_USING_PEGASUS;
//********************************************************
// Constants
//********************************************************
// Namespace name
static const CIMNamespaceName NAMESPACE = CIMNamespaceName("root/cimv2");
// Class names
static const CIMName CLASS_CIM_REMOTE_SERVICE_ACCESS_POINT = CIMName(
"CIM_RemoteServiceAccessPoint");
static const CIMName CLASS_CIM_NEXT_HOP_ROUTE = CIMName("CIM_NextHopRoute");
static const CIMName CLASS_PG_ASSOCIATED_NEXT_HOP = CIMName(
"PG_AssociatedNextHop");
// Property names.
static const CIMName PROPERTY_INSTANCE_ID = CIMName("InstanceID");
static const CIMName PROPERTY_ADDRESS_TYPE = CIMName("AddressType");
static const CIMName PROPERTY_DESTINATION_ADDRESS = CIMName(
"DestinationAddress");
static const CIMName PROPERTY_DESTINATION_MASK = CIMName("DestinationMask");
static const CIMName PROPERTY_PREFIX_LENGTH = CIMName("PrefixLength");
static const CIMName PROPERTY_ACCESS_INFO = CIMName("AccessInfo");
static const CIMName PROPERTY_INFO_FORMAT = CIMName("InfoFormat");
ANHProvider::ANHProvider()
{
}
ANHProvider::~ANHProvider()
{
}
void ANHProvider::initialize(CIMOMHandle &ch)
{
_cimomHandle = ch;
_createAssociationInstances(
_NextHopRouteInstances(),
_RSApInstances());
return;
}
void ANHProvider::terminate()
{
delete this;
}
void ANHProvider::associators(
const OperationContext& context,
const CIMObjectPath& objectName,
const CIMName& associationClass,
const CIMName& resultClass,
const String& role,
const String& resultRole,
const Boolean includeQualifiers,
const Boolean includeClassOrigin,
const CIMPropertyList& propertyList,
ObjectResponseHandler& handler)
{
// validate namespace
const CIMNamespaceName& nameSpace = objectName.getNameSpace();
if (!nameSpace.equal(NAMESPACE))
{
throw CIMNotSupportedException(
nameSpace.getString() + " not supported.");
}
// Build a host and namespace independent object path
CIMObjectPath localObjectPath = CIMObjectPath(
String(),
CIMNamespaceName(),
objectName.getClassName(),
objectName.getKeyBindings());
// begin processing the request
handler.processing();
if (associationClass == CLASS_PG_ASSOCIATED_NEXT_HOP)
{
_associators(
_AssociationInstances,
localObjectPath,
role,
resultClass,
resultRole,
handler);
}
else
{
throw CIMNotSupportedException(
associationClass.getString() + " is not supported");
}
// complete processing the request
handler.complete();
}
void ANHProvider::associatorNames(
const OperationContext& context,
const CIMObjectPath& objectName,
const CIMName& associationClass,
const CIMName& resultClass,
const String& role,
const String& resultRole,
ObjectPathResponseHandler& handler)
{
// validate namespace
const CIMNamespaceName& nameSpace = objectName.getNameSpace();
if (!nameSpace.equal(NAMESPACE))
{
throw CIMNotSupportedException(
nameSpace.getString() + " not supported.");
}
// Build a host and namespace independent object path
CIMObjectPath localObjectPath = CIMObjectPath(
String(),
CIMNamespaceName(),
objectName.getClassName(),
objectName.getKeyBindings());
// begin processing the request
handler.processing();
if (associationClass == CLASS_PG_ASSOCIATED_NEXT_HOP)
{
_associatorNames(
_AssociationInstances,
localObjectPath,
role,
resultClass,
resultRole,
handler);
}
else
{
throw CIMNotSupportedException(
associationClass.getString() + " is not supported");
}
// complete processing the request
handler.complete();
}
void ANHProvider::references(
const OperationContext& context,
const CIMObjectPath& objectName,
const CIMName& resultClass,
const String& role,
const Boolean includeQualifiers,
const Boolean includeClassOrigin,
const CIMPropertyList& propertyList,
ObjectResponseHandler& handler)
{
// validate namespace
const CIMNamespaceName& nameSpace = objectName.getNameSpace();
if (!nameSpace.equal(NAMESPACE))
{
throw CIMNotSupportedException(
nameSpace.getString() + " not supported.");
}
// Build a host and namespace independent object path
CIMObjectPath localObjectPath = CIMObjectPath(
String(),
CIMNamespaceName(),
objectName.getClassName(),
objectName.getKeyBindings());
// begin processing the request
handler.processing();
// Filter the instances from the list of association instances against
// the specified role filter
//
Array<CIMInstance> resultInstances;
if (resultClass == CLASS_PG_ASSOCIATED_NEXT_HOP)
{
resultInstances =
_filterAssociationInstancesByRole(
_AssociationInstances,
localObjectPath,
role);
}
else
{
throw CIMNotSupportedException(
resultClass.getString() + " is not supported");
}
// return the instances
for (Uint32 i = 0, n = resultInstances.size(); i < n; i++)
{
handler.deliver(resultInstances[i]);
}
// complete processing the request
handler.complete();
}
void ANHProvider::referenceNames(
const OperationContext& context,
const CIMObjectPath& objectName,
const CIMName& resultClass,
const String& role,
ObjectPathResponseHandler& handler)
{
// validate namespace
const CIMNamespaceName& nameSpace = objectName.getNameSpace();
if (!nameSpace.equal(NAMESPACE))
{
throw CIMNotSupportedException(
nameSpace.getString() + " not supported.");
}
// Build a host and namespace independent object path
CIMObjectPath localObjectPath = CIMObjectPath(
String(),
CIMNamespaceName(),
objectName.getClassName(),
objectName.getKeyBindings());
// begin processing the request
handler.processing();
// Filter the instances from the list of association instances against
// the specified role filter
//
Array<CIMInstance> resultInstances;
if (resultClass == CLASS_PG_ASSOCIATED_NEXT_HOP)
{
resultInstances =
_filterAssociationInstancesByRole(
_AssociationInstances,
localObjectPath,
role);
}
else
{
throw CIMNotSupportedException(
resultClass.getString() + " is not supported");
}
// return the instance names
for (Uint32 i = 0, n = resultInstances.size(); i < n; i++)
{
CIMObjectPath objectPath = resultInstances[i].getPath();
handler.deliver(objectPath);
}
// complete processing the request
handler.complete();
}
///////////////////////////////////////////////////////////////////////////////
// Private methods
///////////////////////////////////////////////////////////////////////////////
void ANHProvider::_associators(
const Array<CIMInstance>& associationInstances,
const CIMObjectPath& localReference,
const String& role,
const CIMName& resultClass,
const String& resultRole,
ObjectResponseHandler& handler)
{
// Filter the instances from the list of association instances against
// the specified role filter
//
Array<CIMInstance> assocInstances = _filterAssociationInstancesByRole(
associationInstances,
localReference,
role);
// Now filter the result association instances against the specified
// resultClass and resultRole filters
//
for (Uint32 i = 0, m = assocInstances.size(); i < m; i++)
{
Array<CIMObjectPath> resultPaths = _filterAssociationInstances(
assocInstances[i],
localReference,
resultClass,
resultRole);
for (Uint32 j = 0, n = resultPaths.size(); j < n; j++)
{
CIMName className = resultPaths[j].getClassName();
if (className == CLASS_CIM_NEXT_HOP_ROUTE)
{
// find instance that corresponds to the reference
for (Uint32 k = 0, s = _nhrInstances.size(); k < s; k++)
{
CIMObjectPath path = _nhrInstances[k].getPath();
// Build a host and namespace independent object path
CIMObjectPath localPath = CIMObjectPath(
String(),
CIMNamespaceName(),
path.getClassName(),
path.getKeyBindings());
if (resultPaths[j].identical(localPath))
{
// deliver the instance
handler.deliver(_nhrInstances[k]);
}
}
}
else if (className == CLASS_CIM_REMOTE_SERVICE_ACCESS_POINT)
{
// find instance that corresponds to the reference
for (Uint32 k = 0, s = _rsapInstances.size(); k < s; k++)
{
CIMObjectPath path = _rsapInstances[k].getPath();
// Build a host and namespace independent object path
CIMObjectPath localPath = CIMObjectPath(
String(),
CIMNamespaceName(),
path.getClassName(),
path.getKeyBindings());
if (resultPaths[j].identical(localPath))
{
// deliver instance
handler.deliver(_rsapInstances[k]);
}
}
}
}
}
}
void ANHProvider::_associatorNames(
const Array<CIMInstance>& associationInstances,
const CIMObjectPath& localReference,
const String& role,
const CIMName& resultClass,
const String& resultRole,
ObjectPathResponseHandler& handler)
{
// Filter the instances from the list of association instances against
// the specified role filter
//
Array<CIMInstance> assocInstances;
assocInstances= _filterAssociationInstancesByRole(associationInstances,
localReference, role);
// Now filter the result association instances against the specified
// resultClass and resultRole filters
//
for (Uint32 i = 0, n = assocInstances.size(); i < n; i++)
{
Array<CIMObjectPath> resultPaths;
resultPaths = _filterAssociationInstances(assocInstances[i],
localReference, resultClass, resultRole);
for (Uint32 j = 0, m = resultPaths.size(); j < m; j++)
{
handler.deliver(resultPaths[j]);
}
}
}
/**
***************************************************************************
_filterAssociationInstancesByRole is used to filter the list of association
instances against the specified role filter. It returns a list of
association instances that pass the filter test.
@param associationInstance - The target association instances
@param targetObjectPath - The target ObjectPath
@param role - The role filter. If there is no role, this
is String::EMPTY
@return the set of association instances that pass the filter test.
***************************************************************************
*/
Array<CIMInstance> ANHProvider::_filterAssociationInstancesByRole(
const Array<CIMInstance>& associationInstances,
const CIMObjectPath& targetObjectPath,
const String& role)
{
Array<CIMInstance> returnInstances;
// Filter the instances from the list of association instances against
// the specified role filter
//
for (Uint32 i = 0, n = associationInstances.size(); i < n; i++)
{
CIMInstance instance = associationInstances[i];
// Search the association instance for all reference properties
for (Uint32 j = 0, m = instance.getPropertyCount(); j < m; j++)
{
const CIMProperty p = instance.getProperty(j);
if (p.getType() == CIMTYPE_REFERENCE)
{
CIMValue v = p.getValue();
CIMObjectPath path;
v.get(path);
if ((role == String::EMPTY) ||
(p.getName() == CIMName(role)))
{
if (targetObjectPath.identical(path))
{
returnInstances.append(instance);
}
}
}
}
}
return returnInstances;
}
/**
***************************************************************************
_filterAssociationInstances is used to filter the set of possible return
instances against the filters (resultClass and resultRole) provided with
the associators and associatorNames operations. It returns the ObjectPaths
of the set of objects that pass the filter tests.
@param assocInstance - The target association class instance
@param sourceObjectPath - The source ObjectPath
@param resultClass - The result class. If there is no resultClass,
this is String::EMPTY.
@param resultRole - The result role. If there is no role, this is
String::EMPTY
@return the ObjectPaths of the set of association instances that pass
the filter tests.
***************************************************************************
*/
Array<CIMObjectPath> ANHProvider::_filterAssociationInstances(
CIMInstance& assocInstance,
const CIMObjectPath& sourceObjectPath,
CIMName resultClass,
String resultRole)
{
Array<CIMObjectPath> returnPaths;
// get all Reference properties
for (Uint32 i = 0, n = assocInstance.getPropertyCount(); i < n; i++)
{
CIMProperty p = assocInstance.getProperty(i);
if (p.getType() == CIMTYPE_REFERENCE)
{
CIMValue v = p.getValue();
CIMObjectPath path;
v.get(path);
if (!sourceObjectPath.identical(path))
{
if (resultClass.isNull() || resultClass == path.getClassName())
{
if (resultRole == String::EMPTY ||
(p.getName() == CIMName(resultRole)))
{
returnPaths.append(path);
}
}
}
}
}
return returnPaths;
}
void ANHProvider::_createAssociationInstances(
Array<CIMInstance> nhrInst,
Array<CIMInstance> rsapInst)
{
PEG_METHOD_ENTER(TRC_PROVIDERAGENT,
"ANHProvider::_createAssociationInstances()");
for (Uint16 i = 0; i<nhrInst.size(); i++) // Routes loop.
{
CIMInstance _nhrInst = nhrInst[i];
for (Uint16 j = 0; j<rsapInst.size(); j++) // Remote Services loop.
{
CIMInstance _rsapInst = rsapInst[j];
String _accessInfo,
_address,
_destAddress;
CIMProperty _rsapAccessInfo = _rsapInst.getProperty(
_rsapInst.findProperty(PROPERTY_ACCESS_INFO));
_rsapAccessInfo.getValue().get(_accessInfo);
Uint32 index = _accessInfo.find('/');
if (index == PEG_NOT_FOUND)
{
PEG_METHOD_EXIT();
throw CIMOperationFailedException(
String("Property AccessInfo is not in the expected ") +
String("\"Address/DestinationAddress\" format."));
}
else
{
_address = _accessInfo.subString(0,index-1);
_destAddress = _accessInfo.subString(
index+1,
_accessInfo.size()-1);
}
CIMProperty _nhrDestinationAddress = _nhrInst.getProperty(
_nhrInst.findProperty(PROPERTY_DESTINATION_ADDRESS));
if (!_nhrDestinationAddress.getValue().equal(
CIMValue(_destAddress)))
{
continue;
}
// Build the CIMObjectPath from the instances matching
CIMObjectPath _rsapObj = _rsapInst.getPath();
CIMObjectPath _nhrObj = _nhrInst.getPath();
CIMInstance assocInst(CLASS_PG_ASSOCIATED_NEXT_HOP);
assocInst.addProperty(
CIMProperty(
CIMName("Antecedent"),
_rsapObj,
0,
CLASS_CIM_REMOTE_SERVICE_ACCESS_POINT));
assocInst.addProperty(
CIMProperty(
CIMName("Dependent"),
_nhrObj,
0,
CLASS_CIM_NEXT_HOP_ROUTE));
// Build CIMObjectPath from keybindings
Array<CIMKeyBinding> keyBindings;
CIMKeyBinding _rsapBinding(
CIMName("Antecedent"),
_rsapObj.toString(),
CIMKeyBinding::REFERENCE);
CIMKeyBinding _nhrBinding(
CIMName("Dependent"),
_nhrObj.toString(),
CIMKeyBinding::REFERENCE);
keyBindings.append (_rsapBinding);
keyBindings.append (_nhrBinding);
CIMObjectPath path(
String::EMPTY,
CIMNamespaceName(),
CLASS_PG_ASSOCIATED_NEXT_HOP,
keyBindings);
assocInst.setPath(path);
_AssociationInstances.append(assocInst);
break;
} // Remote Services loop end.
} // Routes loop end.
PEG_METHOD_EXIT();
}
Array<CIMInstance> ANHProvider::_NextHopRouteInstances()
{
PEG_METHOD_ENTER(TRC_PROVIDERAGENT,
"ANHProvider::_NextHopRouteInstances()");
Array<CIMInstance> _retInstances;
NextHopRouteList _nhrl;
for (Uint16 i = 0; i<_nhrl.size(); i++)
{
NextHopIPRoute _nhipr = _nhrl.getRoute(i);
if (!_nhipr.isRouteLocal())
{
CIMInstance instance(CLASS_CIM_NEXT_HOP_ROUTE);
String _destAddr, _destMask, _instanceID;
Uint16 _addrType;
Uint8 _prefLength;
if (!_nhipr.getInstanceID(_instanceID))
{
PEG_METHOD_EXIT();
throw CIMOperationFailedException(
"Can't determine InstanceID in: " +
String("ANHProvider::_NextHopRouteInstances()"));
}
instance.addProperty(CIMProperty(PROPERTY_INSTANCE_ID, _destAddr));
if (!_nhipr.getDestinationAddress(_destAddr))
{
PEG_METHOD_EXIT();
throw CIMOperationFailedException(
"Can't determine destination address in: " +
String("ANHProvider::_NextHopRouteInstances()"));
}
instance.addProperty(CIMProperty(
PROPERTY_DESTINATION_ADDRESS,
_destAddr));
if (_nhipr.getAddressType(_addrType))
{
instance.addProperty(CIMProperty(
PROPERTY_ADDRESS_TYPE,
_addrType));
if (_addrType == 1) // IPv4 address.
{
if (!_nhipr.getDestinationMask(_destMask))
{
PEG_METHOD_EXIT();
throw CIMOperationFailedException(
"Can't determine destination mask in: " +
String("ANHProvider::_NextHopRouteInstances()"));
}
instance.addProperty(CIMProperty(
PROPERTY_DESTINATION_MASK,
_destMask));
}
else
{
if (_addrType == 2) // IPv6 address.
{
if (!_nhipr.getPrefixLength(_prefLength))
{
PEG_METHOD_EXIT();
throw CIMOperationFailedException(
"Can't determine prefix length for route in: " +
String("ANHProvider::_NextHopRouteInstances()"));
}
instance.addProperty(CIMProperty(
PROPERTY_PREFIX_LENGTH,
_prefLength));
}
}
}
else
{
PEG_METHOD_EXIT();
throw CIMOperationFailedException(
"Can't determine address type in: " +
String("ANHProvider::_NextHopRouteInstances()"));
}
// Build CIMObjectPath from keybindings
Array<CIMKeyBinding> keyBindings;
keyBindings.append(
CIMKeyBinding(
PROPERTY_INSTANCE_ID,
_destAddr,
CIMKeyBinding::STRING));
CIMObjectPath path(
String::EMPTY,
CIMNamespaceName(),
CLASS_CIM_NEXT_HOP_ROUTE,
keyBindings);
instance.setPath(path);
_nhrInstances.append(instance);
_retInstances.append(instance);
}
} // Loop over next hop routes.
PEG_METHOD_EXIT();
return _retInstances;
}
Array<CIMInstance> ANHProvider::_RSApInstances()
{
PEG_METHOD_ENTER(TRC_PROVIDERAGENT,
"ANHProvider::_RSApInstances()");
Array<CIMInstance> _retInstances;
RSApList _rsapl;
for (Uint16 i = 0; i<_rsapl.size(); i++)
{
CIMInstance instance(CLASS_CIM_REMOTE_SERVICE_ACCESS_POINT);
RSAp _rsap = _rsapl.getService(i);
String _accessInfo;
Uint16 _infoFormat;
if (_rsap.getAccessInfo(_accessInfo))
{
instance.addProperty(CIMProperty(
PROPERTY_ACCESS_INFO,
_accessInfo));
}
else
{
PEG_METHOD_EXIT();
throw CIMOperationFailedException(
"Can't determine property AccessInfo in: " +
String("ANHProvider::_RSApInstances()"));
}
if (_rsap.getInfoFormat(_infoFormat))
{
instance.addProperty(CIMProperty(
PROPERTY_INFO_FORMAT,
_infoFormat));
}
else
{
PEG_METHOD_EXIT();
throw CIMOperationFailedException(
"Can't determine property InfoFormat in: " +
String("ANHProvider::_RSApInstances()"));
}
// Build CIMObjectPath from keybindings
Array<CIMKeyBinding> keyBindings;
keyBindings.append(
CIMKeyBinding(
PROPERTY_ACCESS_INFO,
_accessInfo,
CIMKeyBinding::STRING));
CIMObjectPath path(
String::EMPTY,
CIMNamespaceName(),
CLASS_CIM_REMOTE_SERVICE_ACCESS_POINT,
keyBindings);
instance.setPath(path);
_rsapInstances.append(instance);
_retInstances.append(instance);
}
PEG_METHOD_EXIT();
return _retInstances;
}
| 32.451005 | 80 | 0.570748 | [
"object"
] |
3cb7ad8ee7aca09f620fb2ce6d98c191006d6d60 | 14,503 | cpp | C++ | common/ieee1588clock.cpp | PADL/gptp | 965674140d5ff59d3ff9d3d16cee64749ed313e0 | [
"BSD-3-Clause"
] | 28 | 2020-03-13T12:42:29.000Z | 2022-02-27T06:48:02.000Z | common/ieee1588clock.cpp | PADL/gptp | 965674140d5ff59d3ff9d3d16cee64749ed313e0 | [
"BSD-3-Clause"
] | 55 | 2020-04-28T08:47:31.000Z | 2022-03-22T14:47:26.000Z | common/ieee1588clock.cpp | PADL/gptp | 965674140d5ff59d3ff9d3d16cee64749ed313e0 | [
"BSD-3-Clause"
] | 22 | 2020-03-30T12:55:13.000Z | 2022-02-17T18:38:28.000Z | /******************************************************************************
Copyright (c) 2009-2012, Intel Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the Intel Corporation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
#include <ieee1588.hpp>
#include <avbts_clock.hpp>
#include <avbts_oslock.hpp>
#include <avbts_ostimerq.hpp>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
std::string ClockIdentity::getIdentityString()
{
uint8_t cid[PTP_CLOCK_IDENTITY_LENGTH];
getIdentityString(cid);
char scid[PTP_CLOCK_IDENTITY_LENGTH * 3 + 1];
char* pscid = scid;
for (unsigned i = 0; i < PTP_CLOCK_IDENTITY_LENGTH; ++i) {
unsigned byte = cid[i];
PLAT_snprintf(pscid, 4, "%2.2X:", byte);
pscid += 3;
}
scid[PTP_CLOCK_IDENTITY_LENGTH * 3 - 1] = '\0';
return std::string(scid);
}
void ClockIdentity::set(LinkLayerAddress * addr)
{
uint64_t tmp1 = 0;
uint32_t tmp2;
addr->toOctetArray((uint8_t *) & tmp1);
tmp2 = tmp1 & 0xFFFFFF;
tmp1 >>= 24;
tmp1 <<= 16;
tmp1 |= 0xFEFF;
tmp1 <<= 24;
tmp1 |= tmp2;
memcpy(id, &tmp1, PTP_CLOCK_IDENTITY_LENGTH);
}
IEEE1588Clock::IEEE1588Clock
( bool forceOrdinarySlave, bool syntonize, uint8_t priority1,
OSTimerQueueFactory *timerq_factory, OS_IPC *ipc,
OSLockFactory *lock_factory )
{
this->priority1 = priority1;
priority2 = 248;
number_ports = 0;
this->forceOrdinarySlave = forceOrdinarySlave;
/*TODO: Make the values below configurable*/
clock_quality.clockAccuracy = 0x22;
clock_quality.cq_class = 248;
clock_quality.offsetScaledLogVariance = 0x436A;
time_source = 160;
domain_number = 0;
_syntonize = syntonize;
_new_syntonization_set_point = false;
_ppm = 0;
_phase_error_violation = 0;
_master_local_freq_offset_init = false;
_local_system_freq_offset_init = false;
this->ipc = ipc;
memset( &LastEBestIdentity, 0xFF, sizeof( LastEBestIdentity ));
timerq_lock = lock_factory->createLock( oslock_recursive );
// This should be done LAST!! to pass fully initialized clock object
timerq = timerq_factory->createOSTimerQueue( this );
fup_info = new FollowUpTLV();
fup_status = new FollowUpTLV();
return;
}
bool IEEE1588Clock::serializeState( void *buf, off_t *count ) {
bool ret = true;
if( buf == NULL ) {
*count = sizeof( _master_local_freq_offset ) + sizeof( _local_system_freq_offset ) + sizeof( LastEBestIdentity );
return true;
}
// Master-Local Frequency Offset
if( ret && *count >= (off_t) sizeof( _master_local_freq_offset )) {
memcpy
( buf, &_master_local_freq_offset,
sizeof( _master_local_freq_offset ));
*count -= sizeof( _master_local_freq_offset );
buf = ((char *)buf) + sizeof( _master_local_freq_offset );
} else if( ret == false ) {
*count += sizeof( _master_local_freq_offset );
} else {
*count = sizeof( _master_local_freq_offset )-*count;
ret = false;
}
// Local-System Frequency Offset
if( ret && *count >= (off_t) sizeof( _local_system_freq_offset )) {
memcpy
( buf, &_local_system_freq_offset,(off_t)
sizeof( _local_system_freq_offset ));
*count -= sizeof( _local_system_freq_offset );
buf = ((char *)buf) + sizeof( _local_system_freq_offset );
} else if( ret == false ) {
*count += sizeof( _local_system_freq_offset );
} else {
*count = sizeof( _local_system_freq_offset )-*count;
ret = false;
}
// LastEBestIdentity
if( ret && *count >= (off_t) sizeof( LastEBestIdentity )) {
memcpy( buf, &LastEBestIdentity, (off_t) sizeof( LastEBestIdentity ));
*count -= sizeof( LastEBestIdentity );
buf = ((char *)buf) + sizeof( LastEBestIdentity );
} else if( ret == false ) {
*count += sizeof( LastEBestIdentity );
} else {
*count = sizeof( LastEBestIdentity )-*count;
ret = false;
}
return ret;
}
bool IEEE1588Clock::restoreSerializedState( void *buf, off_t *count ) {
bool ret = true;
/* Master-Local Frequency Offset */
if( ret && *count >= (off_t) sizeof( _master_local_freq_offset )) {
memcpy
( &_master_local_freq_offset, buf,
sizeof( _master_local_freq_offset ));
*count -= sizeof( _master_local_freq_offset );
buf = ((char *)buf) + sizeof( _master_local_freq_offset );
} else if( ret == false ) {
*count += sizeof( _master_local_freq_offset );
} else {
*count = sizeof( _master_local_freq_offset )-*count;
ret = false;
}
/* Local-System Frequency Offset */
if( ret && *count >= (off_t) sizeof( _local_system_freq_offset )) {
memcpy
( &_local_system_freq_offset, buf,
sizeof( _local_system_freq_offset ));
*count -= sizeof( _local_system_freq_offset );
buf = ((char *)buf) + sizeof( _local_system_freq_offset );
} else if( ret == false ) {
*count += sizeof( _local_system_freq_offset );
} else {
*count = sizeof( _local_system_freq_offset )-*count;
ret = false;
}
/* LastEBestIdentity */
if( ret && *count >= (off_t) sizeof( LastEBestIdentity )) {
memcpy( &LastEBestIdentity, buf, sizeof( LastEBestIdentity ));
*count -= sizeof( LastEBestIdentity );
buf = ((char *)buf) + sizeof( LastEBestIdentity );
} else if( ret == false ) {
*count += sizeof( LastEBestIdentity );
} else {
*count = sizeof( LastEBestIdentity )-*count;
ret = false;
}
return ret;
}
Timestamp IEEE1588Clock::getSystemTime(void)
{
return (Timestamp(0, 0, 0));
}
void timerq_handler(void *arg)
{
event_descriptor_t *event_descriptor = (event_descriptor_t *) arg;
event_descriptor->port->processEvent(event_descriptor->event);
}
void IEEE1588Clock::addEventTimer
( CommonPort *target, Event e, unsigned long long time_ns )
{
event_descriptor_t *event_descriptor = new event_descriptor_t();
event_descriptor->event = e;
event_descriptor->port = target;
timerq->addEvent
((unsigned)(time_ns / 1000), (int)e, timerq_handler, event_descriptor,
true, NULL);
}
void IEEE1588Clock::addEventTimerLocked
( CommonPort *target, Event e, unsigned long long time_ns )
{
if( getTimerQLock() == oslock_fail ) return;
addEventTimer( target, e, time_ns );
if( putTimerQLock() == oslock_fail ) return;
}
void IEEE1588Clock::deleteEventTimer
( CommonPort *target, Event event )
{
timerq->cancelEvent((int)event, NULL);
}
void IEEE1588Clock::deleteEventTimerLocked
( CommonPort *target, Event event )
{
if( getTimerQLock() == oslock_fail ) return;
timerq->cancelEvent((int)event, NULL);
if( putTimerQLock() == oslock_fail ) return;
}
FrequencyRatio IEEE1588Clock::calcLocalSystemClockRateDifference( Timestamp local_time, Timestamp system_time ) {
unsigned long long inter_system_time;
unsigned long long inter_local_time;
FrequencyRatio ppt_offset;
GPTP_LOG_DEBUG( "Calculated local to system clock rate difference" );
if( !_local_system_freq_offset_init ) {
_prev_system_time = system_time;
_prev_local_time = local_time;
_local_system_freq_offset_init = true;
return 1.0;
}
inter_system_time =
TIMESTAMP_TO_NS(system_time) - TIMESTAMP_TO_NS(_prev_system_time);
inter_local_time =
TIMESTAMP_TO_NS(local_time) - TIMESTAMP_TO_NS(_prev_local_time);
if( inter_system_time != 0 ) {
ppt_offset = ((FrequencyRatio)inter_local_time)/inter_system_time;
} else {
ppt_offset = 1.0;
}
_prev_system_time = system_time;
_prev_local_time = local_time;
return ppt_offset;
}
FrequencyRatio IEEE1588Clock::calcMasterLocalClockRateDifference( Timestamp master_time, Timestamp sync_time ) {
unsigned long long inter_sync_time;
unsigned long long inter_master_time;
FrequencyRatio ppt_offset;
GPTP_LOG_DEBUG( "Calculated master to local clock rate difference" );
if( !_master_local_freq_offset_init ) {
_prev_sync_time = sync_time;
_prev_master_time = master_time;
_master_local_freq_offset_init = true;
return 1.0;
}
inter_sync_time =
TIMESTAMP_TO_NS(sync_time) - TIMESTAMP_TO_NS(_prev_sync_time);
uint64_t master_time_ns = TIMESTAMP_TO_NS(master_time);
uint64_t prev_master_time_ns = TIMESTAMP_TO_NS(_prev_master_time);
inter_master_time = master_time_ns - prev_master_time_ns;
if( inter_sync_time != 0 ) {
ppt_offset = ((FrequencyRatio)inter_master_time)/inter_sync_time;
} else {
ppt_offset = 1.0;
}
if( master_time_ns < prev_master_time_ns ) {
GPTP_LOG_ERROR("Negative time jump detected - inter_master_time: %lld, inter_sync_time: %lld, incorrect ppt_offset: %Lf",
inter_master_time, inter_sync_time, ppt_offset);
_master_local_freq_offset_init = false;
return NEGATIVE_TIME_JUMP;
}
_prev_sync_time = sync_time;
_prev_master_time = master_time;
return ppt_offset;
}
void IEEE1588Clock::setMasterOffset
( CommonPort *port, int64_t master_local_offset,
Timestamp local_time, FrequencyRatio master_local_freq_offset,
int64_t local_system_offset, Timestamp system_time,
FrequencyRatio local_system_freq_offset, unsigned sync_count,
unsigned pdelay_count, PortState port_state, bool asCapable )
{
_master_local_freq_offset = master_local_freq_offset;
_local_system_freq_offset = local_system_freq_offset;
if (port->getTestMode()) {
GPTP_LOG_STATUS("Clock offset:%lld Clock rate ratio:%Lf Sync Count:%u PDelay Count:%u",
master_local_offset, master_local_freq_offset, sync_count, pdelay_count);
}
if( ipc != NULL ) {
uint8_t grandmaster_id[PTP_CLOCK_IDENTITY_LENGTH];
uint8_t clock_id[PTP_CLOCK_IDENTITY_LENGTH];
PortIdentity port_identity;
uint16_t port_number;
grandmaster_clock_identity.getIdentityString(grandmaster_id);
clock_identity.getIdentityString(clock_id);
port->getPortIdentity(port_identity);
port_identity.getPortNumber(&port_number);
ipc->update(
master_local_offset, local_system_offset, master_local_freq_offset,
local_system_freq_offset, TIMESTAMP_TO_NS(local_time),
sync_count, pdelay_count, port_state, asCapable);
ipc->update_grandmaster(
grandmaster_id, domain_number);
ipc->update_network_interface(
clock_id, priority1,
clock_quality.cq_class, clock_quality.offsetScaledLogVariance,
clock_quality.clockAccuracy,
priority2, domain_number,
port->getSyncInterval(),
port->getAnnounceInterval(),
0, // TODO: Was port->getPDelayInterval() before refactoring. What do we do now?
port_number);
}
if( master_local_offset == 0 && master_local_freq_offset == 1.0 ) {
return;
}
if( _syntonize ) {
if( _new_syntonization_set_point || _phase_error_violation > PHASE_ERROR_MAX_COUNT ) {
_new_syntonization_set_point = false;
_phase_error_violation = 0;
/* Make sure that there are no transmit operations
in progress */
getTxLockAll();
if (port->getTestMode()) {
GPTP_LOG_STATUS("Adjust clock phase offset:%lld", -master_local_offset);
}
port->adjustClockPhase( -master_local_offset );
_master_local_freq_offset_init = false;
restartPDelayAll();
putTxLockAll();
master_local_offset = 0;
}
// Adjust for frequency offset
long double phase_error = (long double) -master_local_offset;
if( fabsl(phase_error) > PHASE_ERROR_THRESHOLD ) {
++_phase_error_violation;
} else {
_phase_error_violation = 0;
float syncPerSec = (float)(1.0 / pow((float)2, port->getSyncInterval()));
_ppm += (float) ((INTEGRAL * syncPerSec * phase_error) + PROPORTIONAL*((master_local_freq_offset-1.0)*1000000));
GPTP_LOG_DEBUG("phase_error = %Lf, ppm = %f", phase_error, _ppm );
}
if( _ppm < LOWER_FREQ_LIMIT ) _ppm = LOWER_FREQ_LIMIT;
if( _ppm > UPPER_FREQ_LIMIT ) _ppm = UPPER_FREQ_LIMIT;
if ( port->getTestMode() ) {
GPTP_LOG_STATUS("Adjust clock rate ppm:%f", _ppm);
}
if( !port->adjustClockRate( _ppm ) ) {
GPTP_LOG_ERROR( "Failed to adjust clock rate" );
}
}
return;
}
/* Get current time from system clock */
Timestamp IEEE1588Clock::getTime(void)
{
return getSystemTime();
}
/* Get timestamp from hardware */
Timestamp IEEE1588Clock::getPreciseTime(void)
{
return getSystemTime();
}
bool IEEE1588Clock::isBetterThan(PTPMessageAnnounce * msg)
{
unsigned char this1[14];
unsigned char that1[14];
uint16_t tmp;
if (msg == NULL)
return true;
this1[0] = priority1;
that1[0] = msg->getGrandmasterPriority1();
this1[1] = clock_quality.cq_class;
that1[1] = msg->getGrandmasterClockQuality()->cq_class;
this1[2] = clock_quality.clockAccuracy;
that1[2] = msg->getGrandmasterClockQuality()->clockAccuracy;
tmp = clock_quality.offsetScaledLogVariance;
tmp = PLAT_htons(tmp);
memcpy(this1 + 3, &tmp, sizeof(tmp));
tmp = msg->getGrandmasterClockQuality()->offsetScaledLogVariance;
tmp = PLAT_htons(tmp);
memcpy(that1 + 3, &tmp, sizeof(tmp));
this1[5] = priority2;
that1[5] = msg->getGrandmasterPriority2();
clock_identity.getIdentityString(this1 + 6);
msg->getGrandmasterIdentity((char *)that1 + 6);
#if 0
GPTP_LOG_DEBUG("(Clk)Us: ");
for (int i = 0; i < 14; ++i)
GPTP_LOG_DEBUG("%hhx ", this1[i]);
GPTP_LOG_DEBUG("(Clk)Them: ");
for (int i = 0; i < 14; ++i)
GPTP_LOG_DEBUG("%hhx ", that1[i]);
#endif
return (memcmp(this1, that1, 14) < 0) ? true : false;
}
IEEE1588Clock::~IEEE1588Clock(void)
{
// Do nothing
}
| 28.948104 | 123 | 0.721575 | [
"object"
] |
3cb7ba834217d5c59d1cdbf9857598cbd2964ae5 | 1,215 | cpp | C++ | src/objects/button/button.cpp | SamyHasRoot/dork | e027dea5a85c8efb7807afa83f552333494e1484 | [
"MIT"
] | 1 | 2021-02-23T14:56:02.000Z | 2021-02-23T14:56:02.000Z | src/objects/button/button.cpp | SamyHasRoot/dork | e027dea5a85c8efb7807afa83f552333494e1484 | [
"MIT"
] | 2 | 2021-02-14T13:57:58.000Z | 2021-02-23T14:53:38.000Z | src/objects/button/button.cpp | SamyHasRoot/dork | e027dea5a85c8efb7807afa83f552333494e1484 | [
"MIT"
] | null | null | null | #include <locale>
#include <memory>
#include <string>
#include "button_export.h"
#include "../../objects.h"
#include "../../objects.cpp"
#include "../util.h"
#include <iostream>
#include <vector>
class BUTTON_EXPORT Button : public BaseObject {
public:
using BaseObject::BaseObject;
virtual void PushAction() override;
std::vector<std::shared_ptr<BaseObject>> connections;
virtual bool AddProperty(std::string& key, std::string& value, std::vector<std::shared_ptr<BaseObject>> objs, Room::name_index_type& name_index) override;
std::unique_ptr<BaseObject> Clone() override;
};
ADD_CLONE(Button);
void Button::PushAction() {
reply_handler.Reply(PushReply { /*can_push: */ true });
for (auto obj : connections)
obj->ButtonPushedAction();
}
bool Button::AddProperty(std::string& key, std::string& value, std::vector<std::shared_ptr<BaseObject>> objs, Room::name_index_type& name_index) {
ADD_STD;
if (key == "connections") {
connections.push_back(objs[name_index[value]]);
return true;
}
return false;
}
extern "C" {
BUTTON_EXPORT BaseObject* create_object(ReplyHandler& rp) {
return new Button(rp);
}
BUTTON_EXPORT void destroy_object(BaseObject* object) {
delete object;
}
}
| 24.3 | 156 | 0.720988 | [
"object",
"vector"
] |
3cb985da1c0932c88a591a8296e860afe1864f57 | 9,674 | cpp | C++ | Src/spislave.cpp | suikan4github/murasaki | 84f391b99617027151565349012e5fc367da857e | [
"MIT"
] | 12 | 2019-02-24T05:22:37.000Z | 2021-10-01T05:56:59.000Z | Src/spislave.cpp | suikan4github/murasaki | 84f391b99617027151565349012e5fc367da857e | [
"MIT"
] | 122 | 2019-02-23T13:51:42.000Z | 2021-11-13T01:24:34.000Z | Src/spislave.cpp | suikan4github/murasaki | 84f391b99617027151565349012e5fc367da857e | [
"MIT"
] | 3 | 2019-02-24T16:38:25.000Z | 2022-03-22T15:25:09.000Z | /*
* spislave.cpp
*
* Created on: 2018/02/14
* Author: Seiichi "Suikan" Horie
*/
#include <spislave.hpp>
#include "murasaki_assert.hpp"
#include "murasaki_syslog.hpp"
#include "callbackrepositorysingleton.hpp"
// Macro for easy-to-read
#define SPIM_SYSLOG(fmt, ...) MURASAKI_SYSLOG(this, kfaSpiSlave, kseDebug, fmt, ##__VA_ARGS__)
// Check if CubeIDE generated SPI Module
#ifdef HAL_SPI_MODULE_ENABLED
namespace murasaki {
SpiSlave::SpiSlave(SPI_HandleTypeDef *spi_handle)
:
peripheral_(spi_handle),
sync_(new murasaki::Synchronizer),
critical_section_(new murasaki::CriticalSection),
interrupt_status_(kspisUnknown)
{
// Setup internal variable with given uart structure.
MURASAKI_ASSERT(nullptr != peripheral_)
MURASAKI_ASSERT(nullptr != sync_)
MURASAKI_ASSERT(nullptr != critical_section_)
// We need DMA
MURASAKI_ASSERT(peripheral_->hdmatx != nullptr)
MURASAKI_ASSERT(peripheral_->hdmarx != nullptr)
// For all SPI transfer, the data size have to be byte
MURASAKI_ASSERT(peripheral_->hdmatx->Init.PeriphDataAlignment == DMA_PDATAALIGN_BYTE)
MURASAKI_ASSERT(peripheral_->hdmarx->Init.PeriphDataAlignment == DMA_PDATAALIGN_BYTE)
MURASAKI_ASSERT(peripheral_->hdmatx->Init.MemDataAlignment == DMA_MDATAALIGN_BYTE)
MURASAKI_ASSERT(peripheral_->hdmarx->Init.MemDataAlignment == DMA_MDATAALIGN_BYTE)
// The DMA mode have to be normal
MURASAKI_ASSERT(peripheral_->hdmatx->Init.Mode == DMA_NORMAL)
MURASAKI_ASSERT(peripheral_->hdmarx->Init.Mode == DMA_NORMAL)
// Register this object to the list of the interrupt handler class.
CallbackRepositorySingleton::GetInstance()->AddPeripheralObject(this);
}
SpiSlave::~SpiSlave()
{
// Deleting resouces
if (nullptr != sync_)
delete sync_;
if (nullptr != critical_section_)
delete critical_section_;
}
SpiStatus SpiSlave::TransmitAndReceive(
const uint8_t *tx_data,
uint8_t *rx_data,
unsigned int size,
unsigned int *transfered_count,
unsigned int timeout_ms)
{
SPIM_SYSLOG("Enter");
MURASAKI_ASSERT(nullptr != tx_data);
MURASAKI_ASSERT(nullptr != rx_data);
MURASAKI_ASSERT(65536 >= size);
// exclusive operation
critical_section_->Enter();
{
// This value will be updated by TransmitAndReceiveCompleteCallback
interrupt_status_ = murasaki::kspisTimeOut;
// Assert the chip select for slave
SPIM_SYSLOG("Start SPI slave transferring");
// Keep coherence between the L2 and cache before DMA
// No Need to invalidate for TX
murasaki::CleanDataCacheByAddress(
const_cast<uint8_t*>(tx_data),
size);
// Need to invalidate for RX
murasaki::CleanAndInvalidateDataCacheByAddress(rx_data, size);
// Transmit over SPI
HAL_StatusTypeDef status = HAL_SPI_TransmitReceive_DMA(
peripheral_,
const_cast<uint8_t*>(tx_data),
rx_data,
size);
MURASAKI_ASSERT(HAL_OK == status);
// wait for the completion
sync_->Wait(timeout_ms); // return false if timeout
SPIM_SYSLOG("Sync released.")
// So far it returns always 0.
if (transfered_count != nullptr)
*transfered_count = 0;
// check the status from interrupt
switch (interrupt_status_)
{
case murasaki::kspisOK:
SPIM_SYSLOG("Receive complete successfully")
break;
case murasaki::kspisModeCRC:
MURASAKI_SYSLOG(this, kfaSpiSlave, kseWarning, "CRC error")
break;
case murasaki::kspisOverflow:
MURASAKI_SYSLOG(this, kfaSpiSlave, kseWarning, "DMA overflow / underflow")
break;
case murasaki::kspisFrameError:
MURASAKI_SYSLOG(this, kfaSpiSlave, kseWarning, "Frame error")
break;
case murasaki::kspisDMA:
MURASAKI_SYSLOG(this, kfaSpiSlave, kseError, "DMA error")
// Desable SPI to try to clear the current error status. Then, re-enable.
HAL_SPI_DeInit(peripheral_);
HAL_SPI_Init(peripheral_);
break;
case murasaki::kspisErrorFlag:
MURASAKI_SYSLOG(this, kfaSpiSlave, kseError, "Unknown error flag, Peripheral re-initialized")
// Desable SPI to try to clear the current error status. Then, re-enable.
HAL_SPI_DeInit(peripheral_);
HAL_SPI_Init(peripheral_);
break;
case murasaki::ki2csTimeOut:
MURASAKI_SYSLOG(this, kfaSpiSlave, kseWarning, "Receive timeout. DMA stopped")
// Abort on-going and not terminated transfer.
HAL_SPI_DMAStop(peripheral_);
break;
default:
MURASAKI_SYSLOG(this, kfaI2cSlave, kseEmergency, "Error is not handled. Peripheral re-initialized")
// Desable SPI to try to clear the current error status. Then, re-enable.
HAL_SPI_DeInit(peripheral_);
HAL_SPI_Init(peripheral_);
break;
}
SPIM_SYSLOG("End SPI slave transferring");
}
critical_section_->Leave();
SPIM_SYSLOG("Leave");
return interrupt_status_;
}
bool SpiSlave::TransmitAndReceiveCompleteCallback(void *ptr)
{
SPIM_SYSLOG("Enter");
MURASAKI_ASSERT(nullptr != ptr)
// if matches, release task
if (peripheral_ == ptr) {
SPIM_SYSLOG("Release sync");
// report normal completion
interrupt_status_ = murasaki::kspisOK;
// release waiting task
sync_->Release();
SPIM_SYSLOG("Return with match");
// This interrupt is for this device.
return true;
}
else {
SPIM_SYSLOG("Return without match");
// This interrupt is not for this device.
return false;
}
}
bool SpiSlave::HandleError(void *ptr)
{
SPIM_SYSLOG("Enter");
MURASAKI_ASSERT(nullptr != ptr)
if (this->Match(ptr)) {
// Check error and halde it.
if (peripheral_->ErrorCode & HAL_SPI_ERROR_CRC) {
MURASAKI_SYSLOG(this, kfaSpiSlave, kseWarning, "HAL_SPI_ERROR_CRC");
// This happens only in the CRC mode
interrupt_status_ = murasaki::kspisModeCRC;
// abort the processing
sync_->Release();
}
else if (peripheral_->ErrorCode & HAL_SPI_ERROR_OVR) {
MURASAKI_SYSLOG(this, kfaSpiSlave, kseWarning, "HAL_SPI_ERROR_OVR");
// This interrupt happen when the DMA is too slow to handle the received data.
interrupt_status_ = murasaki::kspisOverflow;
// abort the processing
sync_->Release();
}
else if (peripheral_->ErrorCode & HAL_SPI_ERROR_FRE) {
MURASAKI_SYSLOG(this, kfaSpiSlave, kseWarning, "HAL_SPI_ERROR_FRE");
// This interrupt is the frame error of the the TI frame mode
interrupt_status_ = murasaki::kspisFrameError;
// abort the processing
sync_->Release();
}
else if (peripheral_->ErrorCode & HAL_SPI_ERROR_DMA) {
MURASAKI_SYSLOG(this, kfaSpiSlave, kseWarning, "HAL_SPI_ERROR_DMA");
// This interrupt emans something happen in DMA unit
interrupt_status_ = murasaki::kspisDMA;
// abort the processing
sync_->Release();
}
else if (peripheral_->ErrorCode & HAL_SPI_ERROR_FLAG) {
MURASAKI_SYSLOG(this, kfaSpiSlave, kseWarning, "HAL_SPI_ERROR_FLAG");
// This interrupt emans something is recorded as error flag.
interrupt_status_ = murasaki::kspisErrorFlag;
// abort the processing
sync_->Release();
}
#ifdef HAL_SPI_ERROR_ABORT
else if (peripheral_->ErrorCode & HAL_SPI_ERROR_ABORT) {
MURASAKI_SYSLOG(this, kfaSpiSlave, kseWarning, "HAL_SPI_ERROR_ABORT");
// This interrupt happen when program causes problem during abort process
// No way to recover.
interrupt_status_ = murasaki::kspisAbort;
// abort the processing
sync_->Release();
}
#endif
else
{
MURASAKI_SYSLOG(this, kfaSpiSlave, kseWarning, "Unknown error interrupt")
// Unknown error. This program must be updated by the newest specificaiton.
interrupt_status_ = murasaki::kspisUnknown;
// abort the processing
sync_->Release();
}
SPIM_SYSLOG("Return with match");
return true; // report the ptr matched
}
else {
SPIM_SYSLOG("Return without match");
return false; // report the ptr doesn't match
}
}
void* SpiSlave::GetPeripheralHandle() {
SPIM_SYSLOG("Enter");
SPIM_SYSLOG("Leave");
return peripheral_;
}
} /* namespace murasaki */
#endif // HAL_SPI_MODULE_ENABLED
| 36.23221 | 116 | 0.593756 | [
"object"
] |
3cbc938dc9b5d6d02170571a5cd6d7373c2cfdd2 | 9,536 | cpp | C++ | COACH/samiul vai/03 - 109395/A.cpp | dipta007/Competitive-Programming | 998d47f08984703c5b415b98365ddbc84ad289c4 | [
"MIT"
] | 6 | 2018-10-15T18:45:05.000Z | 2022-03-29T04:30:10.000Z | UVA/10070.cpp | dipta007/Competitive-Programming | 998d47f08984703c5b415b98365ddbc84ad289c4 | [
"MIT"
] | null | null | null | UVA/10070.cpp | dipta007/Competitive-Programming | 998d47f08984703c5b415b98365ddbc84ad289c4 | [
"MIT"
] | 4 | 2018-01-07T06:20:07.000Z | 2019-08-21T15:45:59.000Z | #include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <iterator>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
using namespace std;
const double EPS = 1e-9;
const int INF = 0x7f7f7f7f;
const double PI=acos(-1.0);
#define READ(f) freopen(f, "r", stdin)
#define WRITE(f) freopen(f, "w", stdout)
#define MP(x, y) make_pair(x, y)
#define SZ(c) (int)c.size()
#define PB(x) push_back(x)
#define F(i,L,R) for (int i = L; i < R; i++)
#define FF(i,L,R) for (int i = L; i <= R; i++)
#define FR(i,L,R) for (int i = L; i > R; i--)
#define FRF(i,L,R) for (int i = L; i >= R; i--)
#define FOREACH(i,t) for (typeof(t.begin()) i=t.begin(); i!=t.end(); i++)
#define ALL(p) p.begin(),p.end()
#define ALLR(p) p.rbegin(),p.rend()
#define SET(p) memset(p, -1, sizeof(p))
#define CLR(p) memset(p, 0, sizeof(p))
#define MEM(p, v) memset(p, v, sizeof(p))
#define CPY(d, s) memcpy(d, s, sizeof(s))
#define getI(a) scanf("%d", &a)
#define getII(a,b) scanf("%d %d", &a, &b)
#define getIII(a,b,c) scanf("%d %d %d", &a, &b, &c)
#define getL(a) scanf("%I64d",&a)
#define getLL(a,b) scanf("%I64d %I64d",&a,&b)
#define getLLL(a,b,c) scanf("%I64d %I64d %I64d",&a,&b,&c)
#define getC(n) scanf("%c",&n)
#define getF(n) scanf("%lf",&n)
#define getS(n) scanf("%s",n)
#define vi vector < int >
#define vii vector < vector < int > >
#define pii pair< int, int >
#define psi pair< string, int >
#define ff first
#define ss second
#define ll long long
#define ull unsigned long long
#define ui unsigned int
#define us unsigned short
#define ld long double
template< class T > inline T _abs(T n) { return ( (n) < 0 ? -(n) : (n) ); }
template< class T > inline T _max(T a, T b) { return ( ! ( (a) < (b) ) ? (a) : (b) ) ; }
template< class T > inline T _min(T a, T b) { return ( ( (a) < (b) ) ? (a) : (b) ) ; }
template< class T > inline T _swap(T &a, T &b) { T temp=a;a=b;b=temp;}
template< class T > inline T gcd(T a, T b) { return (b) == 0 ? (a) : gcd( (b), ( (a) % (b) ) ) ; }
template< class T > inline T lcm(T a, T b) { return ( (a) / gcd( (a), (b) ) * (b) ); }
//******************DELETE****************
#define shubha
#ifdef shubhashis
#define debug(args...) {dbg,args; cerr<<endl;}
#else
#define debug(args...) // Just strip off all debug tokens
#endif
struct debugger{
template<typename T> debugger& operator , (const T& v){
cerr<<v<<" ";
return *this;
}
}dbg;
/// ********* debug template bt Bidhan Roy *********
template < typename F, typename S >
ostream& operator << ( ostream& os, const pair< F, S > & p ) {
return os << "(" << p.first << ", " << p.second << ")";
}
template < typename T >
ostream &operator << ( ostream & os, const vector< T > &v ) {
os << "{";
typename vector< T > :: const_iterator it;
for( it = v.begin(); it != v.end(); it++ ) {
if( it != v.begin() ) os << ", ";
os << *it;
}
return os << "}";
}
template < typename T >
ostream &operator << ( ostream & os, const set< T > &v ) {
os << "[";
typename set< T > :: const_iterator it;
for ( it = v.begin(); it != v.end(); it++ ) {
if( it != v.begin() ) os << ", ";
os << *it;
}
return os << "]";
}
template < typename F, typename S >
ostream &operator << ( ostream & os, const map< F, S > &v ) {
os << "[";
typename map< F , S >::const_iterator it;
for( it = v.begin(); it != v.end(); it++ ) {
if( it != v.begin() ) os << ", ";
os << it -> first << " = " << it -> second ;
}
return os << "]";
}
#define deb(x) cerr << #x << " = " << x << endl;
//******************DELETE****************
template <typename T>
string NumberToString ( T Number )
{
ostringstream ss;
ss << Number;
return ss.str();
}
struct Bigint
{
string a; // to store the digits
int sign; // sign = -1 for negative numbers, sign = 1 otherwise
// constructors
Bigint() {} // default constructor
Bigint( string b )
{
(*this) = b; // constructor for string
}
// some helpful methods
int size() // returns number of digits
{
return a.size();
}
Bigint inverseSign() // changes the sign
{
sign *= -1;
return (*this);
}
Bigint normalize( int newSign ) // removes leading 0, fixes sign
{
for( int i = a.size() - 1; i > 0 && a[i] == '0'; i-- )
a.erase(a.begin() + i);
sign = ( a.size() == 1 && a[0] == '0' ) ? 1 : newSign;
return (*this);
}
// assignment operator
void operator = ( string b ) // assigns a string to Bigint
{
a = b[0] == '-' ? b.substr(1) : b;
reverse( a.begin(), a.end() );
this->normalize( b[0] == '-' ? -1 : 1 );
}
// conditional operators
bool operator < ( const Bigint &b ) const // less than operator
{
if( sign != b.sign ) return sign < b.sign;
if( a.size() != b.a.size() )
return sign == 1 ? a.size() < b.a.size() : a.size() > b.a.size();
for( int i = a.size() - 1; i >= 0; i-- ) if( a[i] != b.a[i] )
return sign == 1 ? a[i] < b.a[i] : a[i] > b.a[i];
return false;
}
bool operator == ( const Bigint &b ) const // operator for equality
{
return a == b.a && sign == b.sign;
}
// mathematical operators
Bigint operator + ( Bigint b ) // addition operator overloading
{
if( sign != b.sign ) return (*this) - b.inverseSign();
Bigint c;
for(int i = 0, carry = 0; i<a.size() || i<b.size() || carry; i++ )
{
carry+=(i<a.size() ? a[i]-48 : 0)+(i<b.a.size() ? b.a[i]-48 : 0);
c.a += (carry % 10 + 48);
carry /= 10;
}
return c.normalize(sign);
}
Bigint operator - ( Bigint b ) // subtraction operator overloading
{
if( sign != b.sign ) return (*this) + b.inverseSign();
int s = sign;
sign = b.sign = 1;
if( (*this) < b ) return ((b - (*this)).inverseSign()).normalize(-s);
Bigint c;
for( int i = 0, borrow = 0; i < a.size(); i++ )
{
borrow = a[i] - borrow - (i < b.size() ? b.a[i] : 48);
c.a += borrow >= 0 ? borrow + 48 : borrow + 58;
borrow = borrow >= 0 ? 0 : 1;
}
return c.normalize(s);
}
Bigint operator * ( Bigint b ) // multiplication operator overloading
{
Bigint c("0");
for( int i = 0, k = a[i] - 48; i < a.size(); i++, k = a[i] - 48 )
{
while(k--) c = c + b; // ith digit is k, so, we add k times
b.a.insert(b.a.begin(), '0'); // multiplied by 10
}
return c.normalize(sign * b.sign);
}
Bigint operator / ( Bigint b ) // division operator overloading
{
if( b.size() == 1 && b.a[0] == '0' ) b.a[0] /= ( b.a[0] - 48 );
Bigint c("0"), d;
for( int j = 0; j < a.size(); j++ ) d.a += "0";
int dSign = sign * b.sign;
b.sign = 1;
for( int i = a.size() - 1; i >= 0; i-- )
{
c.a.insert( c.a.begin(), '0');
c = c + a.substr( i, 1 );
while( !( c < b ) ) c = c - b, d.a[i]++;
}
return d.normalize(dSign);
}
int operator % ( int bb ) // modulo operator overloading
{
string st=NumberToString(bb);
// stringstream ss(bb);
// ss >> st;
debug(st)
Bigint b(st);
if( b.size() == 1 && b.a[0] == '0' ) b.a[0] /= ( b.a[0] - 48 );
Bigint c("0");
b.sign = 1;
for( int i = a.size() - 1; i >= 0; i-- )
{
c.a.insert( c.a.begin(), '0');
c = c + a.substr( i, 1 );
while( !( c < b ) ) c = c - b;
}
c.normalize(sign);
stringstream ss(c.a);
int x;
ss >> x;
return x;
// return c.normalize(sign);
}
// output method
void print()
{
if( sign == -1 ) putchar('-');
for( int i = a.size() - 1; i >= 0; i-- ) putchar(a[i]);
}
};
int main() {
//READ("in.txt");
//WRITE("out.txt");
int n,ci=0;;
string st;
while(getline(cin,st))
{
Bigint y;
y=st;
if(ci) printf("\n");
ci++;
int flg=0,leap=0;
if(y%4==0 && y%100!=0)
{
leap=1;
flg=1;
printf("This is leap year.\n");
}
else if(y%400==0)
{
leap=1;
flg=1;
printf("This is leap year.\n");
}
if(y%15==0)
{
flg=1;
printf("This is huluculu festival year.\n");
}
if(y%55==0 && leap)
{
flg=1;
printf("This is bulukulu festival year.\n");
}
if(flg==0)
{
printf("This is an ordinary year.\n");
}
}
return 0;
}
| 27.72093 | 98 | 0.46078 | [
"vector"
] |
3cc1c3d4ea4fdf999a5820e146dcdb4fe6ef3424 | 12,565 | cpp | C++ | Last_Resort/ModulePowerUp.cpp | RedPillStudios/RedPill-Project1 | 1a5737e1e1690275b12442d3edd7894d6658eaaa | [
"MIT"
] | 1 | 2021-03-07T10:35:16.000Z | 2021-03-07T10:35:16.000Z | Last_Resort/ModulePowerUp.cpp | RedPillStudios/RedPill-Project1 | 1a5737e1e1690275b12442d3edd7894d6658eaaa | [
"MIT"
] | 1 | 2018-05-25T23:12:31.000Z | 2018-05-25T23:12:31.000Z | Last_Resort/ModulePowerUp.cpp | RedPillStudios/RedPill-Project1 | 1a5737e1e1690275b12442d3edd7894d6658eaaa | [
"MIT"
] | 2 | 2018-02-22T19:05:37.000Z | 2020-06-14T16:22:36.000Z | #include "Application.h"
#include "ModulePowerUp.h"
#include "ModuleTextures.h"
#include "ModuleRender.h"
#include "ModuleCollision.h"
#include "ModulePlayer.h"
#include "ModulePlayer2.h"
#include "ModuleEnemies.h"
#include "ModuleParticles.h"
#include "ModuleInput.h"
#include "Module_Hou_Player1.h"
#include "Module_Hou_Player2.h"
#include <math.h>
#define SPAWN_MARGIN 50
powerUp_Misiles::powerUp_Misiles(int x, int y) : powerUp(x, y) {
powerUp::sprite = App->textures->Load("Images/General/PowerUps_Sprite.png");
Blue.PushBack({ 49,64,31,16 });
Red.PushBack({ 18,64,31,16 });
collider = App->collision->AddCollider({ 500,120,31,16 }, COLLIDER_TYPE::COLLIDER_POWER_UP, (Module*)App->powerup);
animation = &Red;
type = POWERUP_TYPES::MISILES;
};
void powerUp_Misiles::Update() {
timing++;
if (timing >= 20) {
if (animation == &Red) {
ColorRed = false;
ColorBlue = true;
animation = &Blue;
}
else {
ColorRed = true;
ColorBlue = false;
animation = &Red;
}
timing = 0;
}
};
powerUp_Laser::powerUp_Laser(int x, int y) : powerUp(x, y) {
powerUp::sprite = App->textures->Load("Images/General/PowerUps_Sprite.png");
Blue.PushBack({ 49,80,31,16 });
Red.PushBack({ 18,80,31,16 });
collider = App->collision->AddCollider({ 500,120,31,16 }, COLLIDER_TYPE::COLLIDER_POWER_UP, (Module*)App->powerup);
animation = &Red;
type = POWERUP_TYPES::LASER;
};
void powerUp_Laser::Update() {
timing++;
if (timing >= 20) {
if (animation == &Red) {
ColorRed = false;
ColorBlue = true;
animation = &Blue;
}
else {
ColorRed = true;
ColorBlue = false;
animation = &Red;
}
timing = 0;
}
};
powerUp_Bomb::powerUp_Bomb(int x, int y) : powerUp(x, y) {
powerUp::sprite = App->textures->Load("Images/General/PowerUps_Sprite.png");
Blue.PushBack({ 49,96,31,17 });
Red.PushBack({ 18,96,31,17 });
collider = App->collision->AddCollider({ 500,120,31,16 }, COLLIDER_TYPE::COLLIDER_POWER_UP, (Module*)App->powerup);
animation = &Red;
type = POWERUP_TYPES::BOMB;
};
powerUp_Speed::powerUp_Speed(int x, int y) : powerUp(x, y) {
powerUp::sprite = App->textures->Load("Images/General/PowerUps_Sprite.png");
Speed.PushBack({0,64,18,21 });
collider = App->collision->AddCollider({ 500,120,19,21 }, COLLIDER_TYPE::COLLIDER_POWER_UP, (Module*)App->powerup);
animation = &Speed;
type = POWERUP_TYPES::SPEED;
};
void powerUp_Bomb::Update() {
timing++;
if (timing >= 20) {
if (animation == &Red) {
ColorRed = false;
ColorBlue = true;
animation = &Blue;
}
else {
ColorRed = true;
ColorBlue = false;
animation = &Red;
}
timing = 0;
}
};
ModulePowerUp::ModulePowerUp() {
for (uint i = 0; i < MAX_POWERUP; ++i)
PowerUps[i] = nullptr;
}
ModulePowerUp::~ModulePowerUp() {}
bool ModulePowerUp::Start() {
LOG("Loading PowerUps");
if (App->player->IsEnabled() == true && App->powerup->IsEnabled() == false)
App->powerup->Enable();
//PickUpSpeed = App->sound->LoadChunk("Audio/General/005_PowerUpSpeed.wav");
PickUpWeapon = App->sound->LoadChunk("Audio/General/006_PowerUpWeapon.wav");
return true;
}
bool ModulePowerUp::CleanUp() {
LOG("Cleaning Up Power Ups");
for (uint i = 0; i < MAX_POWERUP; ++i) {
if (PowerUps[i] != nullptr) {
App->textures->Unload(PowerUps[i]->sprite);
PowerUps[i]->collider->to_delete = true;
PowerUps[i]->animation = nullptr;
delete PowerUps[i];
PowerUps[i] = nullptr;
}
queue[i].type = NON;
}
//App->sound->UnloadChunks(PickUpSpeed);
App->sound->UnloadChunks(PickUpWeapon);
return true;
}
update_status ModulePowerUp::PreUpdate() {
for (uint i = 0; i < MAX_POWERUP; ++i) {
if (queue[i].type != POWERUP_TYPES::NON) {
if (queue[i].x * SCREEN_SIZE < App->render->camera.x + (App->render->camera.w * SCREEN_SIZE) + SPAWN_MARGIN) {
spawnPowerUp(queue[i]);
queue[i].type = POWERUP_TYPES::NON;
LOG("Spawning powerUp at %d", queue[i].x * SCREEN_SIZE);
}
}
}
return UPDATE_CONTINUE;
}
update_status ModulePowerUp::Update() {
for (uint i = 0; i < MAX_POWERUP; ++i)
if (PowerUps[i] != nullptr) PowerUps[i]->Update();
for (uint i = 0; i < MAX_POWERUP; ++i)
if (PowerUps[i] != nullptr)PowerUps[i]->Draw(PowerUps[i]->sprite);
return UPDATE_CONTINUE;
}
void ModulePowerUp::OnCollision(Collider *c1, Collider *c2) {
for (uint i = 0; i < MAX_POWERUP; ++i) {
if (c2->type == COLLIDER_PLAYER || c2->type == COLLIDER_PLAYER2) {
Mix_PlayChannel(-1, PickUpWeapon, 0);
if (PowerUps[i] != nullptr && PowerUps[i]->GetCollider() == c1) {
PowerUps[i]->OnCollision(c2);
if (PowerUps[i]->type != SPEED) {
if (c2->type == COLLIDER_PLAYER) {
//LVL 0 (HAVING NOTHING) --> HOU ACTIVATED
if (App->player->Lvl0) {
App->HOU_Player1->HOU_activated = true;
if (PowerUps[i]->ColorBlue == true) {
App->HOU_Player1->Blue = true;
App->HOU_Player1->Red = false;
}
else if (PowerUps[i]->ColorRed == true) {
App->HOU_Player1->Blue = false;
App->HOU_Player1->Red = true;
}
App->player->Lvl0 = false;
App->player->Lvl1 = true;
}
//LVL 1 (HAVING HOU) --> LVL2 Missiles OR LVL2 Bomb OR LVL2 Laser ACTIVATED
else if (App->player->Lvl1) {
if (PowerUps[i]->ColorBlue == true) {
App->HOU_Player1->Blue = true;
App->HOU_Player1->Red = false;
}
else if (PowerUps[i]->ColorRed == true) {
App->HOU_Player1->Blue = false;
App->HOU_Player1->Red = true;
}
if (PowerUps[i]->type == POWERUP_TYPES::MISILES) {
App->player->WeaponType = 3;
App->player->Lvl2 = true;
App->player->Lvl1 = false;
}
else if (PowerUps[i]->type == POWERUP_TYPES::LASER) {
App->player->WeaponType = 2;
App->player->Lvl2 = true;
App->player->Lvl1 = false;
}
else if (PowerUps[i]->type == POWERUP_TYPES::BOMB) {
App->player->WeaponType = 6;
App->player->Lvl2 = true;
App->player->Lvl1 = false;
}
}
//LVL2 --> LVL3 Laser OR LVL3 Missiles ACTIVATED
else if (App->player->Lvl2) {
if (PowerUps[i]->ColorBlue == true) {
App->HOU_Player1->Blue = true;
App->HOU_Player1->Red = false;
}
else if (PowerUps[i]->ColorRed == true) {
App->HOU_Player1->Blue = false;
App->HOU_Player1->Red = true;
}
if (PowerUps[i]->type == POWERUP_TYPES::LASER) {
App->player->WeaponType = 5;
App->player->Lvl3 = true;
App->player->Lvl2 = false;
}
else if (PowerUps[i]->type == POWERUP_TYPES::MISILES) {
App->player->WeaponType = 4;
App->player->Lvl3 = true;
App->player->Lvl2 = false;
}
else if (PowerUps[i]->type == POWERUP_TYPES::BOMB) {
App->player->WeaponType = 6;
/*App->player->Lvl2 == true;
App->player->Lvl3 = false;*/
}
}
//LVL3 --> LVL3 Missile or LVL3 Laser ACTIVATED
else if (App->player->Lvl3) {
if (PowerUps[i]->ColorBlue == true) {
App->HOU_Player1->Blue = true;
App->HOU_Player1->Red = false;
}
else if (PowerUps[i]->ColorRed == true) {
App->HOU_Player1->Blue = false;
App->HOU_Player1->Red = true;
}
if (PowerUps[i]->type == POWERUP_TYPES::MISILES)
App->player->WeaponType = 4;
else if (PowerUps[i]->type == POWERUP_TYPES::LASER)
App->player->WeaponType = 5;
else if (PowerUps[i]->type == POWERUP_TYPES::BOMB) {
App->player->WeaponType = 6;
App->player->Lvl2 == true;
App->player->Lvl3 = false;
}
}
/* if (PowerUps[i]->type == POWERUP_TYPES::SPEED) {
App->player->speed += 0.3;
App->enemies->AddEnemy(ENEMY_TYPES::PSPEEDP1, App->player->position.x, App->player->position.y);
}*/
}
//PLAYER 2
if (c2->type == COLLIDER_PLAYER2) {
Mix_PlayChannel(-1, PickUpWeapon, 0);
//LVL 0 (HAVING NOTHING) --> HOU ACTIVATED
if (App->player2->Lvl0) {
App->HOU_Player2->HOU_activated = true;
if (PowerUps[i]->ColorBlue == true) {
App->HOU_Player2->Blue = true;
App->HOU_Player2->Red = false;
}
else if (PowerUps[i]->ColorRed == true) {
App->HOU_Player2->Blue = false;
App->HOU_Player2->Red = true;
}
App->player2->Lvl0 = false;
App->player2->Lvl1 = true;
}
//LVL 1 (HAVING HOU) --> LVL2 Missiles OR LVL2 Bomb OR LVL2 Laser ACTIVATED
else if (App->player2->Lvl1) {
if (PowerUps[i]->ColorBlue == true) {
App->HOU_Player2->Blue = true;
App->HOU_Player2->Red = false;
}
else if (PowerUps[i]->ColorRed == true) {
App->HOU_Player2->Blue = false;
App->HOU_Player2->Red = true;
}
if (PowerUps[i]->type == POWERUP_TYPES::MISILES) {
App->player2->WeaponTypeP2 = 3;
App->player2->Lvl2 = true;
App->player2->Lvl1 = false;
}
else if (PowerUps[i]->type == POWERUP_TYPES::LASER) {
App->player2->WeaponTypeP2 = 2;
App->player2->Lvl2 = true;
App->player2->Lvl1 = false;
}
else if (PowerUps[i]->type == POWERUP_TYPES::BOMB) {
App->player2->WeaponTypeP2 = 6;
App->player2->Lvl2 = true;
App->player2->Lvl1 = false;
}
}
//LVL2 --> LVL3 Laser OR LVL3 Missiles ACTIVATED
else if (App->player2->Lvl2) {
if (PowerUps[i]->ColorBlue == true) {
App->HOU_Player2->Blue = true;
App->HOU_Player2->Red = false;
}
else if (PowerUps[i]->ColorRed == true) {
App->HOU_Player2->Blue = false;
App->HOU_Player2->Red = true;
}
if (PowerUps[i]->type == POWERUP_TYPES::LASER) {
App->player2->WeaponTypeP2 = 5;
App->player2->Lvl3 = true;
App->player2->Lvl2 = false;
}
else if (PowerUps[i]->type == POWERUP_TYPES::MISILES) {
App->player2->WeaponTypeP2 = 4;
App->player2->Lvl3 = true;
App->player2->Lvl2 = false;
}
else if (PowerUps[i]->type == POWERUP_TYPES::BOMB) {
App->player2->WeaponTypeP2 = 6;
}
}
//LVL3 LASER --> LVL2 Missile ACTIVATED
else if (App->player2->Lvl3) {
if (PowerUps[i]->ColorBlue == true) {
App->HOU_Player2->Blue = true;
App->HOU_Player2->Red = false;
}
else if (PowerUps[i]->ColorRed == true) {
App->HOU_Player2->Blue = false;
App->HOU_Player2->Red = true;
}
if (PowerUps[i]->type == POWERUP_TYPES::MISILES)
App->player2->WeaponTypeP2 = 4;
else if (PowerUps[i]->type == POWERUP_TYPES::LASER)
App->player2->WeaponTypeP2 = 5;
else if (PowerUps[i]->type == POWERUP_TYPES::BOMB)
App->player2->WeaponTypeP2 = 6;
}
/* if (PowerUps[i]->type == POWERUP_TYPES::SPEED) {
App->player2->speed += 0.3;
App->enemies->AddEnemy(ENEMY_TYPES::PSPEEDP2, App->player2->positionp2.x, App->player2->positionp2.y);
}*/
}
}
else if (PowerUps[i]->type == POWERUP_TYPES::SPEED) {
if (c2->type == COLLIDER_PLAYER) {
App->player2->speed += 0.3;
App->enemies->AddEnemy(ENEMY_TYPES::PSPEEDP1, App->player->position.x, App->player->position.y);
}
if (c2->type == COLLIDER_PLAYER2) {
App->player2->speed += 0.3;
App->enemies->AddEnemy(ENEMY_TYPES::PSPEEDP2, App->player2->positionp2.x, App->player2->positionp2.y);
}
}
delete PowerUps[i];
PowerUps[i] = nullptr;
break;
}
}
}
}
bool ModulePowerUp::AddPowerUp(POWERUP_TYPES type, int x, int y) {
bool ret = false;
for (uint i = 0; i < MAX_POWERUP; ++i) {
if (queue[i].type == POWERUP_TYPES::NON) {
queue[i].type = type;
queue[i].x = x;
queue[i].y = y;
ret = true;
break;
}
}
return ret;
}
void ModulePowerUp::spawnPowerUp(const PowerUpInfo &info)
{
// find room for the new enemy
uint i = 0;
for (; PowerUps[i] != nullptr && i < MAX_POWERUP; ++i);
if (i != MAX_POWERUP)
{
switch (info.type) {
case POWERUP_TYPES::MISILES:
PowerUps[i] = new powerUp_Misiles(info.x, info.y);
break;
case POWERUP_TYPES::LASER:
PowerUps[i] = new powerUp_Laser(info.x, info.y);
break;
case POWERUP_TYPES::BOMB:
PowerUps[i] = new powerUp_Bomb(info.x, info.y);
break;
case POWERUP_TYPES::SPEED:
PowerUps[i] = new powerUp_Speed(info.x, info.y);
break;
}
}
}
| 24.685658 | 116 | 0.587744 | [
"render"
] |
3cc1efbb641bf936f17d677a0eb0c853e49442db | 31,259 | inl | C++ | modules/SofaGeneralEngine/MeshROI.inl | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | modules/SofaGeneralEngine/MeshROI.inl | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | modules/SofaGeneralEngine/MeshROI.inl | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | /******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *
* *
* This program 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.1 of the License, or (at *
* your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#ifndef SOFA_COMPONENT_ENGINE_MESHROI_INL
#define SOFA_COMPONENT_ENGINE_MESHROI_INL
#if !defined(__GNUC__) || (__GNUC__ > 3 || (_GNUC__ == 3 && __GNUC_MINOR__ > 3))
#pragma once
#endif
#include <SofaGeneralEngine/MeshROI.h>
#include <sofa/helper/gl/template.h>
#include <sofa/helper/gl/BasicShapes.h>
#include <sofa/core/visual/VisualParams.h>
#include <sofa/helper/logging/Messaging.h>
namespace sofa
{
namespace component
{
namespace engine
{
using sofa::core::objectmodel::BaseData;
using sofa::core::objectmodel::BaseContext;
using sofa::core::topology::BaseMeshTopology;
using sofa::core::behavior::BaseMechanicalState;
using core::loader::MeshLoader;
using sofa::helper::ReadAccessor;
using sofa::helper::WriteOnlyAccessor;
using sofa::helper::vector;
using core::visual::VisualParams;
template <class DataTypes>
MeshROI<DataTypes>::MeshROI()
: d_X0( initData (&d_X0, "position", "Rest position coordinates of the degrees of freedom") )
, d_edges(initData (&d_edges, "edges", "Edge Topology") )
, d_triangles(initData (&d_triangles, "triangles", "Triangle Topology") )
, d_tetrahedra(initData (&d_tetrahedra, "tetrahedra", "Tetrahedron Topology") )
, d_X0_i( initData (&d_X0_i, "ROIposition", "ROI position coordinates of the degrees of freedom") )
, d_edges_i(initData (&d_edges_i, "ROIedges", "ROI Edge Topology") )
, d_triangles_i(initData (&d_triangles_i, "ROItriangles", "ROI Triangle Topology") )
, d_computeEdges( initData(&d_computeEdges, true,"computeEdges","If true, will compute edge list and index list inside the ROI.") )
, d_computeTriangles( initData(&d_computeTriangles, true,"computeTriangles","If true, will compute triangle list and index list inside the ROI.") )
, d_computeTetrahedra( initData(&d_computeTetrahedra, true,"computeTetrahedra","If true, will compute tetrahedra list and index list inside the ROI.") )
, d_computeTemplateTriangles( initData(&d_computeTemplateTriangles,true,"computeMeshROI","Compute with the mesh (not only bounding box)") )
, d_box( initData(&d_box, "box", "Bounding box defined by xmin,ymin,zmin, xmax,ymax,zmax") )
, d_indices( initData(&d_indices,"indices","Indices of the points contained in the ROI") )
, d_edgeIndices( initData(&d_edgeIndices,"edgeIndices","Indices of the edges contained in the ROI") )
, d_triangleIndices( initData(&d_triangleIndices,"triangleIndices","Indices of the triangles contained in the ROI") )
, d_tetrahedronIndices( initData(&d_tetrahedronIndices,"tetrahedronIndices","Indices of the tetrahedra contained in the ROI") )
, d_pointsInROI( initData(&d_pointsInROI,"pointsInROI","Points contained in the ROI") )
, d_edgesInROI( initData(&d_edgesInROI,"edgesInROI","Edges contained in the ROI") )
, d_trianglesInROI( initData(&d_trianglesInROI,"trianglesInROI","Triangles contained in the ROI") )
, d_tetrahedraInROI( initData(&d_tetrahedraInROI,"tetrahedraInROI","Tetrahedra contained in the ROI") )
, d_pointsOutROI( initData(&d_pointsOutROI,"pointsOutROI","Points not contained in the ROI") )
, d_edgesOutROI( initData(&d_edgesOutROI,"edgesOutROI","Edges not contained in the ROI") )
, d_trianglesOutROI( initData(&d_trianglesOutROI,"trianglesOutROI","Triangles not contained in the ROI") )
, d_tetrahedraOutROI( initData(&d_tetrahedraOutROI,"tetrahedraOutROI","Tetrahedra not contained in the ROI") )
, d_indicesOut( initData(&d_indicesOut,"indicesOut","Indices of the points not contained in the ROI") )
, d_edgeOutIndices( initData(&d_edgeOutIndices,"edgeOutIndices","Indices of the edges not contained in the ROI") )
, d_triangleOutIndices( initData(&d_triangleOutIndices,"triangleOutIndices","Indices of the triangles not contained in the ROI") )
, d_tetrahedronOutIndices( initData(&d_tetrahedronOutIndices,"tetrahedronOutIndices","Indices of the tetrahedra not contained in the ROI") )
, d_drawOut( initData(&d_drawOut,false,"drawOut","Draw the data not contained in the ROI") )
, d_drawMesh( initData(&d_drawMesh,false,"drawMesh","Draw Mesh used for the ROI") )
, d_drawBox( initData(&d_drawBox,false,"drawBox","Draw the Bounding box around the mesh used for the ROI") )
, d_drawPoints( initData(&d_drawPoints,false,"drawPoints","Draw Points") )
, d_drawEdges( initData(&d_drawEdges,false,"drawEdges","Draw Edges") )
, d_drawTriangles( initData(&d_drawTriangles,false,"drawTriangles","Draw Triangles") )
, d_drawTetrahedra( initData(&d_drawTetrahedra,false,"drawTetrahedra","Draw Tetrahedra") )
, d_drawSize( initData(&d_drawSize,0.0,"drawSize","rendering size for mesh and topological elements") )
, d_doUpdate( initData(&d_doUpdate,false,"doUpdate","Update the computation (not only at the init)") )
{
d_indices.beginEdit()->push_back(0);
d_indices.endEdit();
}
template <class DataTypes>
void MeshROI<DataTypes>::init()
{
addInput(&d_X0);
addInput(&d_edges);
addInput(&d_triangles);
addInput(&d_tetrahedra);
addInput(&d_X0_i);
addInput(&d_edges_i);
addInput(&d_triangles_i);
addOutput(&d_box);
addOutput(&d_indices);
addOutput(&d_edgeIndices);
addOutput(&d_triangleIndices);
addOutput(&d_tetrahedronIndices);
addOutput(&d_pointsInROI);
addOutput(&d_edgesInROI);
addOutput(&d_trianglesInROI);
addOutput(&d_tetrahedraInROI);
addOutput(&d_pointsOutROI);
addOutput(&d_edgesOutROI);
addOutput(&d_trianglesOutROI);
addOutput(&d_tetrahedraOutROI);
addOutput(&d_indicesOut);
addOutput(&d_edgeOutIndices);
addOutput(&d_triangleOutIndices);
addOutput(&d_tetrahedronOutIndices);
setDirtyValue();
checkInputData();
computeBoundingBox();
compute();
}
template <class DataTypes>
void MeshROI<DataTypes>::checkInputData()
{
if (!d_X0.isSet())
{
msg_warning(this) << "Data 'position' is not set. Get rest position of local mechanical state "
<< "or mesh loader (if no mechanical)";
BaseMechanicalState* mstate;
this->getContext()->get(mstate,BaseContext::Local);
if (mstate)
{
BaseData* parent = mstate->findData("rest_position");
if (parent)
{
d_X0.setParent(parent);
d_X0.setReadOnly(true);
}
}
else
{
MeshLoader* loader = NULL;
this->getContext()->get(loader,BaseContext::Local); // perso
if (loader)
{
BaseData* parent = loader->findData("position");
if (parent)
{
d_X0.setParent(parent);
d_X0.setReadOnly(true);
}
}
}
}
if (!d_edges.isSet() || !d_triangles.isSet() || !d_tetrahedra.isSet())
{
BaseMeshTopology* topology;
this->getContext()->get(topology,BaseContext::Local); // perso
if (topology)
{
if (!d_edges.isSet() && d_computeEdges.getValue())
{
BaseData* eparent = topology->findData("edges");
if (eparent)
{
d_edges.setParent(eparent);
d_edges.setReadOnly(true);
}
}
if (!d_triangles.isSet() && d_computeTriangles.getValue())
{
BaseData* tparent = topology->findData("triangles");
if (tparent)
{
d_triangles.setParent(tparent);
d_triangles.setReadOnly(true);
}
}
if (!d_tetrahedra.isSet() && d_computeTetrahedra.getValue())
{
BaseData* tparent = topology->findData("tetrahedra");
if (tparent)
{
d_tetrahedra.setParent(tparent);
d_tetrahedra.setReadOnly(true);
}
}
}
}
// ROI Mesh init
if (!d_X0_i.isSet())
{
msg_warning(this) << "Data 'ROIposition' is not set. Get rest position of local mechanical state "
<< "or mesh loader (if no mechanical)";
BaseMechanicalState* mstate;
this->getContext()->get(mstate,BaseContext::Local);
if (mstate)
{
BaseData* parent = mstate->findData("rest_position");
if (parent)
{
d_X0_i.setParent(parent);
d_X0_i.setReadOnly(true);
}
}
else
{
MeshLoader* loader = NULL;
this->getContext()->get(loader,BaseContext::Local); // perso
if (loader)
{
BaseData* parent = loader->findData("position");
if (parent)
{
d_X0_i.setParent(parent);
d_X0_i.setReadOnly(true);
}
}
}
}
if (!d_edges_i.isSet() || !d_triangles_i.isSet() )
{
BaseMeshTopology* topology;
this->getContext()->get(topology,BaseContext::Local); // perso
if (topology)
{
if (!d_edges_i.isSet() && d_computeEdges.getValue())
{
BaseData* eparent = topology->findData("edges");
if (eparent)
{
d_edges_i.setParent(eparent);
d_edges_i.setReadOnly(true);
}
}
if (!d_triangles_i.isSet() && d_computeTriangles.getValue())
{
BaseData* tparent = topology->findData("triangles");
if (tparent)
{
d_triangles_i.setParent(tparent);
d_triangles_i.setReadOnly(true);
}
}
}
}
}
template <class DataTypes>
void MeshROI<DataTypes>::computeBoundingBox()
{
// Bounding Box computation
Vec6 b=d_box.getValue();
ReadAccessor<Data<VecCoord>> points_i = d_X0_i;
if(points_i.size()>0)
{
CPos p = DataTypes::getCPos(points_i[0]);
b[0] = p[0]; b[1] = p[1]; b[2] = p[2];
b[3] = p[0]; b[4] = p[1]; b[5] = p[2];
for (unsigned int i=1; i<points_i.size() ; ++i)
{
p = DataTypes::getCPos(points_i[i]);
if (b[0] < p[0]) b[0] = p[0];
if (b[1] < p[1]) b[1] = p[1];
if (b[2] < p[2]) b[2] = p[2];
if (b[3] > p[0]) b[3] = p[0];
if (b[4] > p[1]) b[4] = p[1];
if (b[5] > p[2]) b[5] = p[2];
}
}
if (b[0] > b[3]) std::swap(b[0],b[3]);
if (b[1] > b[4]) std::swap(b[1],b[4]);
if (b[2] > b[5]) std::swap(b[2],b[5]);
d_box.setValue(b);
msg_info(this) << "Bounding Box " << b;
}
template <class DataTypes>
void MeshROI<DataTypes>::reinit()
{
this->requestUpdate();
}
template <class DataTypes>
bool MeshROI<DataTypes>::checkSameOrder(const typename DataTypes::CPos& A, const typename DataTypes::CPos& B, const typename DataTypes::CPos& pt, const typename DataTypes::CPos& N)
{
typename DataTypes::CPos vectorial;
vectorial[0] = (((B[1] - A[1])*(pt[2] - A[2])) - ((pt[1] - A[1])*(B[2] - A[2])));
vectorial[1] = (((B[2] - A[2])*(pt[0] - A[0])) - ((pt[2] - A[2])*(B[0] - A[0])));
vectorial[2] = (((B[0] - A[0])*(pt[1] - A[1])) - ((pt[0] - A[0])*(B[1] - A[1])));
if( (vectorial[0]*N[0] + vectorial[1]*N[1] + vectorial[2]*N[2]) < 0) return false;
else return true;
}
template <class DataTypes>
bool MeshROI<DataTypes>::isPointInMesh(const typename DataTypes::CPos& p)
{
if(!d_computeTemplateTriangles.getValue()) return true;
if(isPointInBoundingBox(p))
{
// Compute the reference point outside the bounding box
const Vec6 b = d_box.getValue();
typename DataTypes::CPos Vec;
if (( (b[0]-p[0])*(b[0]-p[0]) + (b[1]-p[1])*(b[1]-p[1]) + (b[2]-p[2])*(b[2]-p[2]) ) < ( (b[3]-p[0])*(b[3]-p[0]) + (b[4]-p[1])*(b[4]-p[1]) + (b[5]-p[2])*(b[5]-p[2]) ) )
{
Vec[0]= (b[0]-100.0f)-p[0] ;
Vec[1]= (b[1]-100.0f)-p[1];
Vec[2]= (b[2]-100.0f)-p[2];
}
else
{
Vec[0]= (b[3]+100.0f)-p[0] ;
Vec[1]= (b[4]+100.0f)-p[1];
Vec[2]= (b[5]+100.0f)-p[2];
}
ReadAccessor< Data<vector<Triangle> > > triangles_i = d_triangles_i;
const VecCoord* x0 = &d_X0_i.getValue();
int Through=0;
double d=0.0;
for (unsigned int i=0; i<triangles_i.size() ; ++i)
{
Triangle t = triangles_i[i];
CPos p0 = DataTypes::getCPos((*x0)[t[0]]);
CPos p1 = DataTypes::getCPos((*x0)[t[1]]);
CPos p2 = DataTypes::getCPos((*x0)[t[2]]);
// Normal N compuation of the ROI mesh triangle
typename DataTypes::CPos N;
N[0] = (p1[1]-p0[1])*(p2[2]-p1[2]) - (p1[2]-p0[2])*(p2[1]-p1[1]);
N[1] = (p1[2]-p0[2])*(p2[0]-p1[0]) - (p1[0]-p0[0])*(p2[2]-p1[2]);
N[2] = (p1[0]-p0[0])*(p2[1]-p1[1]) - (p1[1]-p0[1])*(p2[0]-p1[0]);
// DotProd computation
double DotProd = double (N[0]*Vec[0] + N[1]*Vec[1] + N[2]*Vec[2]);
if(DotProd !=0)
{
// Intersect point with triangle and distance
d = (N[0]*(p0[0]-p[0])+N[1]*(p0[1]-p[1])+N[2]*(p0[2]-p[2])) / (N[0]*Vec[0]+N[1]*Vec[1]+N[2]*Vec[2]);
// d negative means that line comes beind the triangle ...
if(d>=0)
{
typename DataTypes::CPos ptIN ;
ptIN[0] = (Real)(p[0] + d*Vec[0]);
ptIN[1] = (Real)(p[1] + d*Vec[1]);
ptIN[2] = (Real)(p[2] + d*Vec[2]);
if(checkSameOrder(p0,p1,ptIN,N)) { if(checkSameOrder(p1,p2,ptIN,N)) { if(checkSameOrder(p2,p0,ptIN,N)) { Through++; } } }
}
}
}
if(Through%2!=0)
return true;
}
return false;
}
template <class DataTypes>
bool MeshROI<DataTypes>::isPointInIndices(const unsigned int &pointId)
{
ReadAccessor<Data<SetIndex>> indices = d_indices;
for (unsigned int i=0; i<indices.size(); i++)
if(indices[i]==pointId)
return true;
return false;
}
template <class DataTypes>
bool MeshROI<DataTypes>::isPointInBoundingBox(const typename DataTypes::CPos& p)
{
const Vec6 b = d_box.getValue();
if( p[0] >= b[0] && p[0] <= b[3] && p[1] >= b[1] && p[1] <= b[4] && p[2] >= b[2] && p[2] <= b[5] )
return true;
return false;
}
template <class DataTypes>
bool MeshROI<DataTypes>::isEdgeInMesh(const Edge& e)
{
for (int i=0; i<2; i++)
if(!isPointInIndices(e[i]))
{
const VecCoord* x0 = &d_X0.getValue();
CPos p0 = DataTypes::getCPos((*x0)[e[0]]);
CPos p1 = DataTypes::getCPos((*x0)[e[1]]);
CPos c = (p1+p0)*0.5;
return (isPointInMesh(c));
}
return true;
}
template <class DataTypes>
bool MeshROI<DataTypes>::isTriangleInMesh(const Triangle& t)
{
for (int i=0; i<3; i++)
if(!isPointInIndices(t[i]))
{
const VecCoord* x0 = &d_X0.getValue();
CPos p0 = DataTypes::getCPos((*x0)[t[0]]);
CPos p1 = DataTypes::getCPos((*x0)[t[1]]);
CPos p2 = DataTypes::getCPos((*x0)[t[2]]);
CPos c = (p2+p1+p0)/3.0;
return (isPointInMesh(c));
}
return true;
}
template <class DataTypes>
bool MeshROI<DataTypes>::isTetrahedronInMesh(const Tetra &t)
{
for (int i=0; i<4; i++)
if(!isPointInIndices(t[i]))
{
const VecCoord* x0 = &d_X0.getValue();
CPos p0 = DataTypes::getCPos((*x0)[t[0]]);
CPos p1 = DataTypes::getCPos((*x0)[t[1]]);
CPos p2 = DataTypes::getCPos((*x0)[t[2]]);
CPos p3 = DataTypes::getCPos((*x0)[t[3]]);
CPos c = (p3+p2+p1+p0)/4.0;
return (isPointInMesh(c));
}
return true;
}
template <class DataTypes>
void MeshROI<DataTypes>::compute()
{
// Read accessor for input topology
ReadAccessor< Data<vector<Edge> > > edges = d_edges;
ReadAccessor< Data<vector<Triangle> > > triangles = d_triangles;
ReadAccessor< Data<vector<Tetra> > > tetrahedra = d_tetrahedra;
updateAllInputsIfDirty(); // the easy way to make sure every inputs are up-to-date
cleanDirty();
// Write accessor for topological element indices in MESH
SetIndex& indices = *d_indices.beginWriteOnly();
SetIndex& edgeIndices = *d_edgeIndices.beginWriteOnly();
SetIndex& triangleIndices = *d_triangleIndices.beginWriteOnly();
SetIndex& tetrahedronIndices = *d_tetrahedronIndices.beginWriteOnly();
SetIndex& indicesOut = *d_indicesOut.beginWriteOnly();
SetIndex& edgeOutIndices = *d_edgeOutIndices.beginWriteOnly();
SetIndex& triangleOutIndices = *d_triangleOutIndices.beginWriteOnly();
SetIndex& tetrahedronOutIndices = *d_tetrahedronOutIndices.beginWriteOnly();
// Write accessor for toplogical element in MESH
WriteOnlyAccessor< Data<VecCoord > > pointsInROI = d_pointsInROI;
WriteOnlyAccessor< Data<vector<Edge> > > edgesInROI = d_edgesInROI;
WriteOnlyAccessor< Data<vector<Triangle> > > trianglesInROI = d_trianglesInROI;
WriteOnlyAccessor< Data<vector<Tetra> > > tetrahedraInROI = d_tetrahedraInROI;
WriteOnlyAccessor< Data<VecCoord > > pointsOutROI = d_pointsOutROI;
WriteOnlyAccessor< Data<vector<Edge> > > edgesOutROI = d_edgesOutROI;
WriteOnlyAccessor< Data<vector<Triangle> > > trianglesOutROI = d_trianglesOutROI;
WriteOnlyAccessor< Data<vector<Tetra> > > tetrahedraOutROI = d_tetrahedraOutROI;
// Clear lists
indices.clear();
edgeIndices.clear();
triangleIndices.clear();
tetrahedronIndices.clear();
pointsInROI.clear();
edgesInROI.clear();
trianglesInROI.clear();
tetrahedraInROI.clear();
indicesOut.clear();
edgeOutIndices.clear();
triangleOutIndices.clear();
tetrahedronOutIndices.clear();
pointsOutROI.clear();
edgesOutROI.clear();
trianglesOutROI.clear();
tetrahedraOutROI.clear();
const VecCoord* x0 = &d_X0.getValue();
//Points
for( unsigned i=0; i<x0->size(); ++i )
{
CPos p = DataTypes::getCPos((*x0)[i]);
if (isPointInMesh(p))
{
indices.push_back(i);
pointsInROI.push_back((*x0)[i]);
}
else
{
indicesOut.push_back(i);
pointsOutROI.push_back((*x0)[i]);
}
}
//Edges
if (d_computeEdges.getValue())
{
for(unsigned int i=0 ; i<edges.size() ; i++)
{
Edge e = edges[i];
if (isEdgeInMesh(e))
{
edgeIndices.push_back(i);
edgesInROI.push_back(e);
}
else
{
edgeOutIndices.push_back(i);
edgesOutROI.push_back(e);
}
}
}
//Triangles
if (d_computeTriangles.getValue())
{
for(unsigned int i=0 ; i<triangles.size() ; i++)
{
Triangle t = triangles[i];
if (isTriangleInMesh(t))
{
triangleIndices.push_back(i);
trianglesInROI.push_back(t);
}
else
{
triangleOutIndices.push_back(i);
trianglesOutROI.push_back(t);
}
}
}
//Tetrahedra
if (d_computeTetrahedra.getValue())
{
for(unsigned int i=0 ; i<tetrahedra.size() ; i++)
{
Tetra t = tetrahedra[i];
if (isTetrahedronInMesh(t))
{
tetrahedronIndices.push_back(i);
tetrahedraInROI.push_back(t);
}
else
{
tetrahedronOutIndices.push_back(i);
tetrahedraOutROI.push_back(t);
}
}
}
d_indices.endEdit();
d_edgeIndices.endEdit();
d_triangleIndices.endEdit();
d_tetrahedronIndices.endEdit();
d_indicesOut.endEdit();
d_edgeOutIndices.endEdit();
d_triangleOutIndices.endEdit();
d_tetrahedronOutIndices.endEdit();
}
template <class DataTypes>
void MeshROI<DataTypes>::update()
{
if(d_doUpdate.getValue())
compute();
}
template <class DataTypes>
void MeshROI<DataTypes>::draw(const VisualParams* vparams)
{
#ifndef SOFA_NO_OPENGL
if (!vparams->displayFlags().getShowBehaviorModels() && !this->d_drawSize.getValue())
return;
const VecCoord* x0 = &d_X0.getValue();
glColor3f(1.0f, 0.4f, 0.4f);
// draw the ROI mesh
if( d_drawMesh.getValue())
{
glColor3f(0.4f, 0.4f, 1.0f);
const VecCoord* x0_i = &d_X0_i.getValue();
///draw ROI points
if(d_drawPoints.getValue())
{
if (d_drawSize.getValue())
glPointSize((GLfloat)d_drawSize.getValue());
glDisable(GL_LIGHTING);
glBegin(GL_POINTS);
glPointSize(5.0);
helper::ReadAccessor< Data<VecCoord > > points_i = d_X0_i;
for (unsigned int i=0; i<points_i.size() ; ++i)
{
CPos p = DataTypes::getCPos(points_i[i]);
helper::gl::glVertexT(p);
}
glEnd();
glPointSize(1);
}
// draw ROI edges
if(d_drawEdges.getValue())
{
glDisable(GL_LIGHTING);
glLineWidth((GLfloat)d_drawSize.getValue());
glBegin(GL_LINES);
helper::ReadAccessor< Data<helper::vector<Edge> > > edges_i = d_edges_i;
for (unsigned int i=0; i<edges_i.size() ; ++i)
{
Edge e = edges_i[i];
for (unsigned int j=0 ; j<2 ; j++)
{
CPos p = DataTypes::getCPos((*x0_i)[e[j]]);
helper::gl::glVertexT(p);
}
}
glEnd();
glPointSize(1);
}
// draw ROI triangles
if(d_drawTriangles.getValue())
{
glDisable(GL_LIGHTING);
glBegin(GL_TRIANGLES);
helper::ReadAccessor< Data<helper::vector<Triangle> > > triangles_i = d_triangles_i;
for (unsigned int i=0; i<triangles_i.size() ; ++i)
{
Triangle t = triangles_i[i];
for (unsigned int j=0 ; j<3 ; j++)
{
CPos p = DataTypes::getCPos((*x0_i)[t[j]]);
helper::gl::glVertexT(p);
}
}
glEnd();
}
glColor3f(1.0f, 0.4f, 0.4f);
}
// draw the bounding box
if( d_drawBox.getValue())
{
glDisable(GL_LIGHTING);
if (d_drawSize.getValue())
glLineWidth((GLfloat)d_drawSize.getValue());
glBegin(GL_LINES);
const Vec6& b=d_box.getValue();
const Real& Xmin=b[0];
const Real& Xmax=b[3];
const Real& Ymin=b[1];
const Real& Ymax=b[4];
const Real& Zmin=b[2];
const Real& Zmax=b[5];
glVertex3d(Xmin,Ymin,Zmin);
glVertex3d(Xmin,Ymin,Zmax);
glVertex3d(Xmin,Ymin,Zmin);
glVertex3d(Xmax,Ymin,Zmin);
glVertex3d(Xmin,Ymin,Zmin);
glVertex3d(Xmin,Ymax,Zmin);
glVertex3d(Xmin,Ymax,Zmin);
glVertex3d(Xmax,Ymax,Zmin);
glVertex3d(Xmin,Ymax,Zmin);
glVertex3d(Xmin,Ymax,Zmax);
glVertex3d(Xmin,Ymax,Zmax);
glVertex3d(Xmin,Ymin,Zmax);
glVertex3d(Xmin,Ymin,Zmax);
glVertex3d(Xmax,Ymin,Zmax);
glVertex3d(Xmax,Ymin,Zmax);
glVertex3d(Xmax,Ymax,Zmax);
glVertex3d(Xmax,Ymin,Zmax);
glVertex3d(Xmax,Ymin,Zmin);
glVertex3d(Xmin,Ymax,Zmax);
glVertex3d(Xmax,Ymax,Zmax);
glVertex3d(Xmax,Ymax,Zmin);
glVertex3d(Xmax,Ymin,Zmin);
glVertex3d(Xmax,Ymax,Zmin);
glVertex3d(Xmax,Ymax,Zmax);
glEnd();
glLineWidth(1);
}
// draw points in ROI
if( d_drawPoints.getValue())
{
if (d_drawSize.getValue())
glPointSize((GLfloat)d_drawSize.getValue());
glDisable(GL_LIGHTING);
glBegin(GL_POINTS);
glPointSize(5.0);
if(d_drawOut.getValue())
{
helper::ReadAccessor< Data<VecCoord > > pointsROI = d_pointsOutROI;
for (unsigned int i=0; i<pointsROI.size() ; ++i)
{
CPos p = DataTypes::getCPos(pointsROI[i]);
helper::gl::glVertexT(p);
}
}
else
{
helper::ReadAccessor< Data<VecCoord > > pointsROI = d_pointsInROI;
for (unsigned int i=0; i<pointsROI.size() ; ++i)
{
CPos p = DataTypes::getCPos(pointsROI[i]);
helper::gl::glVertexT(p);
}
}
glEnd();
glPointSize(1);
}
// draw edges in ROI
if( d_drawEdges.getValue())
{
glDisable(GL_LIGHTING);
glLineWidth((GLfloat)d_drawSize.getValue());
glBegin(GL_LINES);
if(d_drawOut.getValue())
{
helper::ReadAccessor< Data<helper::vector<Edge> > > edgesROI = d_edgesOutROI;
for (unsigned int i=0; i<edgesROI.size() ; ++i)
{
Edge e = edgesROI[i];
for (unsigned int j=0 ; j<2 ; j++)
{
CPos p = DataTypes::getCPos((*x0)[e[j]]);
helper::gl::glVertexT(p);
}
}
}
else
{
helper::ReadAccessor< Data<helper::vector<Edge> > > edgesROI = d_edgesInROI;
for (unsigned int i=0; i<edgesROI.size() ; ++i)
{
Edge e = edgesROI[i];
for (unsigned int j=0 ; j<2 ; j++)
{
CPos p = DataTypes::getCPos((*x0)[e[j]]);
helper::gl::glVertexT(p);
}
}
}
glEnd();
glLineWidth(1);
}
// draw triangles in ROI
if( d_drawTriangles.getValue())
{
glDisable(GL_LIGHTING);
glBegin(GL_TRIANGLES);
if(d_drawOut.getValue())
{
helper::ReadAccessor< Data<helper::vector<Triangle> > > trianglesROI = d_trianglesOutROI;
for (unsigned int i=0; i<trianglesROI.size() ; ++i)
{
Triangle t = trianglesROI[i];
for (unsigned int j=0 ; j<3 ; j++)
{
CPos p = DataTypes::getCPos((*x0)[t[j]]);
helper::gl::glVertexT(p);
}
}
}
else
{
helper::ReadAccessor< Data<helper::vector<Triangle> > > trianglesROI = d_trianglesInROI;
for (unsigned int i=0; i<trianglesROI.size() ; ++i)
{
Triangle t = trianglesROI[i];
for (unsigned int j=0 ; j<3 ; j++)
{
CPos p = DataTypes::getCPos((*x0)[t[j]]);
helper::gl::glVertexT(p);
}
}
}
glEnd();
}
// draw tetrahedra in ROI
if( d_drawTetrahedra.getValue())
{
glDisable(GL_LIGHTING);
glLineWidth((GLfloat)d_drawSize.getValue());
glBegin(GL_LINES);
if(d_drawOut.getValue())
{
helper::ReadAccessor< Data<helper::vector<Tetra> > > tetrahedraROI = d_tetrahedraOutROI;
for (unsigned int i=0; i<tetrahedraROI.size() ; ++i)
{
Tetra t = tetrahedraROI[i];
for (unsigned int j=0 ; j<4 ; j++)
{
CPos p = DataTypes::getCPos((*x0)[t[j]]);
helper::gl::glVertexT(p);
p = DataTypes::getCPos((*x0)[t[(j+1)%4]]);
helper::gl::glVertexT(p);
}
CPos p = DataTypes::getCPos((*x0)[t[0]]);
helper::gl::glVertexT(p);
p = DataTypes::getCPos((*x0)[t[2]]);
helper::gl::glVertexT(p);
p = DataTypes::getCPos((*x0)[t[1]]);
helper::gl::glVertexT(p);
p = DataTypes::getCPos((*x0)[t[3]]);
helper::gl::glVertexT(p);
}
}
else
{
helper::ReadAccessor< Data<helper::vector<Tetra> > > tetrahedraROI = d_tetrahedraInROI;
for (unsigned int i=0; i<tetrahedraROI.size() ; ++i)
{
Tetra t = tetrahedraROI[i];
for (unsigned int j=0 ; j<4 ; j++)
{
CPos p = DataTypes::getCPos((*x0)[t[j]]);
helper::gl::glVertexT(p);
p = DataTypes::getCPos((*x0)[t[(j+1)%4]]);
helper::gl::glVertexT(p);
}
CPos p = DataTypes::getCPos((*x0)[t[0]]);
helper::gl::glVertexT(p);
p = DataTypes::getCPos((*x0)[t[2]]);
helper::gl::glVertexT(p);
p = DataTypes::getCPos((*x0)[t[1]]);
helper::gl::glVertexT(p);
p = DataTypes::getCPos((*x0)[t[3]]);
helper::gl::glVertexT(p);
}
}
glEnd();
glLineWidth(1);
}
#endif /* SOFA_NO_OPENGL */
}
} // namespace engine
} // namespace component
} // namespace sofa
#endif
| 35.562002 | 180 | 0.537701 | [
"mesh",
"vector"
] |
3cc7dce13f739b675d9db8fee008011c4f9d1cfd | 6,959 | cpp | C++ | host/device_only_buffer/src/host.cpp | vishnuchebrolu/Vitis_Accel_Examples | 0f573c014efb0e385f4a7d9306821a111ebf2b74 | [
"BSD-3-Clause"
] | 1 | 2021-11-17T10:52:01.000Z | 2021-11-17T10:52:01.000Z | host/device_only_buffer/src/host.cpp | chipet/Vitis_Accel_Examples | f72dff9eea45a76e9ee0713774589624e2b52c9f | [
"BSD-3-Clause"
] | null | null | null | host/device_only_buffer/src/host.cpp | chipet/Vitis_Accel_Examples | f72dff9eea45a76e9ee0713774589624e2b52c9f | [
"BSD-3-Clause"
] | null | null | null | /**********
Copyright (c) 2020, Xilinx, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**********/
#include "xcl2.hpp"
#include <algorithm>
#include <cstdio>
#include <string>
#include <vector>
const int MAX_DIM = 16;
int main(int argc, char **argv) {
if (argc != 2) {
std::cout << "Usage: " << argv[0] << " <XCLBIN File>" << std::endl;
return EXIT_FAILURE;
}
std::string binaryFile = argv[1];
cl_int err;
cl::CommandQueue q;
cl::Context context;
cl::Kernel kernel_madd, kernel_mmult;
const size_t array_size = MAX_DIM * MAX_DIM;
const size_t size_in_bytes = array_size * sizeof(int);
// allocate memory on host for input and output matrices
std::vector<int, aligned_allocator<int>> A(array_size);
std::vector<int, aligned_allocator<int>> B(array_size);
std::vector<int, aligned_allocator<int>> sw_results(array_size, 0);
std::vector<int, aligned_allocator<int>> C(array_size, 1);
std::vector<int, aligned_allocator<int>> hw_results(array_size, 0);
// Create test data
for (int i = 0; i < int(array_size); i++) {
A[i] = i;
B[i] = 2 * i;
}
// generating sw_results
for (int i = 0; i < MAX_DIM; i++) {
for (int j = 0; j < MAX_DIM; j++) {
for (int k = 0; k < MAX_DIM; k++) {
sw_results[i * MAX_DIM + j] += A[i * MAX_DIM + k] * B[k * MAX_DIM + j];
}
}
}
for (int i = 0; i < MAX_DIM * MAX_DIM; i++)
sw_results[i] += C[i];
// The get_xil_devices will return std::vector of Xilinx Devices
// platforms and will return list of devices connected to Xilinx platform
auto devices = xcl::get_xil_devices();
// read_binary_file() is a utility API which will load the binaryFile
// and will return pointer to file buffer.
auto fileBuf = xcl::read_binary_file(binaryFile);
cl::Program::Binaries bins{{fileBuf.data(), fileBuf.size()}};
bool valid_device = false;
for (unsigned int i = 0; i < devices.size(); i++) {
auto device = devices[i];
// Creating Context and Command Queue for selected Device
OCL_CHECK(err, context = cl::Context(device, NULL, NULL, NULL, &err));
OCL_CHECK(err, q = cl::CommandQueue(context, device,
CL_QUEUE_PROFILING_ENABLE, &err));
std::cout << "Trying to program device[" << i
<< "]: " << device.getInfo<CL_DEVICE_NAME>() << std::endl;
cl::Program program(context, {device}, bins, NULL, &err);
if (err != CL_SUCCESS) {
std::cout << "Failed to program device[" << i << "] with xclbin file!\n";
} else {
std::cout << "Device[" << i << "]: program successful!\n";
OCL_CHECK(err, kernel_madd = cl::Kernel(program, "madd", &err));
OCL_CHECK(err, kernel_mmult = cl::Kernel(program, "mmult", &err));
valid_device = true;
break; // we break because we found a valid device
}
}
if (!valid_device) {
std::cout << "Failed to program any device found, exit!\n";
exit(EXIT_FAILURE);
}
// Allocate Buffer in Global Memory
// create normal buffers
OCL_CHECK(err,
cl::Buffer buffer_a(context, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY,
size_in_bytes, A.data(), &err));
OCL_CHECK(err,
cl::Buffer buffer_b(context, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY,
size_in_bytes, B.data(), &err));
OCL_CHECK(err,
cl::Buffer buffer_c(context, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY,
size_in_bytes, C.data(), &err));
OCL_CHECK(err, cl::Buffer buffer_d(context,
CL_MEM_USE_HOST_PTR | CL_MEM_WRITE_ONLY,
size_in_bytes, hw_results.data(), &err));
// creating device only buffer, buffer is not mapped to Host and is only
// accessed by the kernels.
// CL_MEM_HOST_NO_ACCESS flag specifies that host machine will not read/write
// the memory object.
OCL_CHECK(err, cl::Buffer dev_only_buf(context, CL_MEM_READ_WRITE |
CL_MEM_HOST_NO_ACCESS,
size_in_bytes, NULL, &err));
// set kernel arguments for 1st kernel : output to device only buffer
OCL_CHECK(err, err = kernel_mmult.setArg(0, buffer_a));
OCL_CHECK(err, err = kernel_mmult.setArg(1, buffer_b));
OCL_CHECK(err, err = kernel_mmult.setArg(2, dev_only_buf));
OCL_CHECK(err, err = kernel_mmult.setArg(3, MAX_DIM));
// set kernel arguments for 2nd kernel : input from device only buffer
OCL_CHECK(err, err = kernel_madd.setArg(0, dev_only_buf));
OCL_CHECK(err, err = kernel_madd.setArg(1, buffer_c));
OCL_CHECK(err, err = kernel_madd.setArg(2, buffer_d));
OCL_CHECK(err, err = kernel_madd.setArg(3, MAX_DIM));
// migrate data to global memory
OCL_CHECK(
err, err = q.enqueueMigrateMemObjects({buffer_a, buffer_b, buffer_c}, 0));
// execute 1st and 2nd kernels : since data is required for 2nd kernel from
// 1st , use events or use in order queue
OCL_CHECK(err, err = q.enqueueTask(kernel_mmult));
OCL_CHECK(err, err = q.enqueueTask(kernel_madd));
// take results
OCL_CHECK(err, err = q.enqueueMigrateMemObjects({buffer_d},
CL_MIGRATE_MEM_OBJECT_HOST));
OCL_CHECK(err, err = q.finish());
// verify
bool match =
std::equal(sw_results.begin(), sw_results.end(), hw_results.begin());
std::cout << std::endl
<< "TEST " << (match ? "PASSED" : "FAILED") << std::endl;
return (match ? EXIT_SUCCESS : EXIT_FAILURE);
}
| 39.539773 | 80 | 0.661733 | [
"object",
"vector"
] |
3cca361de079f09f8b2f9f409ecdb81ed0d78a6e | 1,734 | cpp | C++ | game/general/optionsmenu.cpp | agry/x-com | ff226a917a80ddc4501767d947bd49ee5ab61b0d | [
"MIT"
] | null | null | null | game/general/optionsmenu.cpp | agry/x-com | ff226a917a80ddc4501767d947bd49ee5ab61b0d | [
"MIT"
] | null | null | null | game/general/optionsmenu.cpp | agry/x-com | ff226a917a80ddc4501767d947bd49ee5ab61b0d | [
"MIT"
] | null | null | null |
#include "game/general/optionsmenu.h"
#include "game/general/basescreen.h"
#include "game/ufopaedia/ufopaedia.h"
#include "game/debugtools/debugmenu.h"
#include "framework/framework.h"
namespace OpenApoc {
OptionsMenu::OptionsMenu(Framework &fw)
: Stage(fw)
{
menuform = fw.gamecore->GetForm("FORM_OPTIONSMENU");
}
OptionsMenu::~OptionsMenu()
{
}
void OptionsMenu::Begin()
{
}
void OptionsMenu::Pause()
{
}
void OptionsMenu::Resume()
{
}
void OptionsMenu::Finish()
{
}
void OptionsMenu::EventOccurred(Event *e)
{
menuform->EventOccured( e );
fw.gamecore->MouseCursor->EventOccured( e );
if( e->Type == EVENT_KEY_DOWN )
{
if( e->Data.Keyboard.KeyCode == ALLEGRO_KEY_ESCAPE )
{
stageCmd.cmd = StageCmd::Command::POP;
return;
}
}
if( e->Type == EVENT_FORM_INTERACTION && e->Data.Forms.EventFlag == FormEventType::ButtonClick )
{
if( e->Data.Forms.RaisedBy->Name == "BUTTON_TEST_XCOMBASE" )
{
stageCmd.cmd = StageCmd::Command::PUSH;
stageCmd.nextStage = std::make_shared<BaseScreen>(fw);
return;
}
if( e->Data.Forms.RaisedBy->Name == "BUTTON_TEST_UFOPAEDIA" )
{
stageCmd.cmd = StageCmd::Command::PUSH;
stageCmd.nextStage = std::make_shared<Ufopaedia>(fw);
return;
}
if( e->Data.Forms.RaisedBy->Name == "BUTTON_DEBUGGING" )
{
stageCmd.cmd = StageCmd::Command::PUSH;
stageCmd.nextStage = std::make_shared<DebugMenu>(fw);
return;
}
}
}
void OptionsMenu::Update(StageCmd * const cmd)
{
menuform->Update();
*cmd = this->stageCmd;
//Reset the command to default
this->stageCmd = StageCmd();
}
void OptionsMenu::Render()
{
menuform->Render();
fw.gamecore->MouseCursor->Render();
}
bool OptionsMenu::IsTransition()
{
return false;
}
}; //namespace OpenApoc
| 18.645161 | 97 | 0.689735 | [
"render"
] |
3ccb1fcedbf6702866a4c41237d8dbe0b4353a57 | 1,291 | cc | C++ | src/rime/algo/utilities.cc | mengzhisuoliu/librime | 9eeeffcc0fa24d9dbfd6d58f936eb9fe60be3e70 | [
"BSD-3-Clause"
] | 2,326 | 2015-01-26T13:34:46.000Z | 2022-03-30T06:53:47.000Z | src/rime/algo/utilities.cc | mengzhisuoliu/librime | 9eeeffcc0fa24d9dbfd6d58f936eb9fe60be3e70 | [
"BSD-3-Clause"
] | 440 | 2015-01-26T12:29:17.000Z | 2022-03-31T13:21:59.000Z | src/rime/algo/utilities.cc | mengzhisuoliu/librime | 9eeeffcc0fa24d9dbfd6d58f936eb9fe60be3e70 | [
"BSD-3-Clause"
] | 491 | 2015-01-24T17:58:21.000Z | 2022-03-27T21:17:37.000Z | //
// Copyright RIME Developers
// Distributed under the BSD License
//
// 2013-01-30 GONG Chen <chen.sst@gmail.com>
//
#include <fstream>
#include <boost/algorithm/string.hpp>
#include <rime/algo/utilities.h>
namespace rime {
int CompareVersionString(const string& x, const string& y) {
if (x.empty() && y.empty()) return 0;
if (x.empty()) return -1;
if (y.empty()) return 1;
vector<string> xx, yy;
boost::split(xx, x, boost::is_any_of("."));
boost::split(yy, y, boost::is_any_of("."));
size_t i = 0;
for (; i < xx.size() && i < yy.size(); ++i) {
int dx = atoi(xx[i].c_str());
int dy = atoi(yy[i].c_str());
if (dx != dy) return dx - dy;
int c = xx[i].compare(yy[i]);
if (c != 0) return c;
}
if (i < xx.size()) return 1;
if (i < yy.size()) return -1;
return 0;
}
ChecksumComputer::ChecksumComputer(uint32_t initial_remainder)
: crc_(initial_remainder) {}
void ChecksumComputer::ProcessFile(const string& file_name) {
std::ifstream fin(file_name.c_str());
string file_content((std::istreambuf_iterator<char>(fin)),
std::istreambuf_iterator<char>());
crc_.process_bytes(file_content.data(), file_content.length());
}
uint32_t ChecksumComputer::Checksum() {
return crc_.checksum();
}
} // namespace rime
| 26.895833 | 65 | 0.635167 | [
"vector"
] |
3ccbe2d520145bf2c21ceeee4e31a01d237168d0 | 61,554 | cpp | C++ | drivers/storage/volsnap/vss/server/tests/writer/swriter.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | drivers/storage/volsnap/vss/server/tests/writer/swriter.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | drivers/storage/volsnap/vss/server/tests/writer/swriter.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*
**++
**
** Copyright (c) 2002 Microsoft Corporation
**
**
** Module Name:
**
** swriter.cpp
**
**
** Abstract:
**
** Test program to to register a Writer with various properties
**
** Author:
**
** Reuven Lax [reuvenl] 04-June-2002
**
**
** Revision History:
**
**--
*/
///////////////////////////////////////////////////////////////////////////////
// Includes
#include "stdafx.h"
#include "swriter.h"
#include "utility.h"
#include "writerconfig.h"
#include <string>
#include <sstream>
#include <functional>
#include <algorithm>
#include <queue>
///////////////////////////////////////////////////////////////////////////////
// Declarations and Definitions
using std::wstring;
using std::string;
using std::wstringstream;
using std::exception;
using std::vector;
using Utility::checkReturn;
using Utility::warnReturn;
using Utility::printStatus;
static const wchar_t* const BackupString = L"BACKUP";
static const wchar_t* const RestoreString = L"RESTORE";
///////////////////////////////////////////////////////////////////////////////
// Initialize the test writer
HRESULT STDMETHODCALLTYPE TestWriter::Initialize()
{
WriterConfiguration* config = WriterConfiguration::instance();
printStatus(L"Initializing Writer", Utility::high);
HRESULT hr = CVssWriter::Initialize(TestWriterId, // WriterID
TestWriterName, // wszWriterName
config->usage(), // ut
VSS_ST_OTHER); // st
checkReturn(hr, L"CVssWriter::Initialize");
hr = Subscribe();
checkReturn(hr, L"CVssWriter::Subscribe");
return S_OK;
}
// OnIdentify is called as a result of the requestor calling GatherWriterMetadata
// Here we report the writer metadata using the passed-in interface
bool STDMETHODCALLTYPE TestWriter::OnIdentify(IN IVssCreateWriterMetadata *pMetadata)
try
{
enterEvent(Utility::Identify);
WriterConfiguration* config = WriterConfiguration::instance();
// set the restore method properly
RestoreMethod method = config->restoreMethod();
HRESULT hr = pMetadata->SetRestoreMethod(method.m_method,
method.m_service.c_str(),
NULL,
method.m_writerRestore,
method.m_rebootRequired);
checkReturn(hr, L"IVssCreateWriterMetadata::SetRestoreMethod");
printStatus(L"\nSet restore method: ", Utility::high);
printStatus(method.toString(), Utility::high);
// set the alternate-location list
RestoreMethod::AlternateList::iterator currentAlt = method.m_alternateLocations.begin();
while (currentAlt != method.m_alternateLocations.end()) {
hr = pMetadata->AddAlternateLocationMapping(currentAlt->m_path. c_str(),
currentAlt->m_filespec.c_str(),
currentAlt->m_recursive,
currentAlt->m_alternatePath.substr(0, currentAlt->m_alternatePath.size()-1).c_str());
checkReturn(hr, L"IVssCreateWriterMetadata::AddAlternateLocationMapping");
printStatus(L"\nAdded Alternate Location Mapping");
printStatus(currentAlt->toString());
++currentAlt;
}
// set the exclude-file list
WriterConfiguration::ExcludeFileList::iterator currentExclude = config->excludeFiles().begin();
while (currentExclude != config->excludeFiles().end()) {
hr = pMetadata->AddExcludeFiles(currentExclude->m_path.c_str(),
currentExclude->m_filespec.c_str(),
currentExclude->m_recursive);
checkReturn(hr, L"IVssCreateWriterMetadata::AddExcludeFiles");
printStatus(L"\nAdded exclude filespec");
printStatus(currentExclude->toString());
++currentExclude;
}
// add all necessary components
WriterConfiguration::ComponentList::iterator currentComponent = config->components().begin();
while (currentComponent != config->components().end()) {
addComponent(*currentComponent, pMetadata);
++currentComponent;
}
return true;
}
catch(const exception& thrown)
{
printStatus(string("Failure in Identify event: ") + thrown.what(), Utility::low);
return false;
}
catch(HRESULT error)
{
Utility::TestWriterException e(error);
printStatus(e.what(), Utility::low);
return false;
};
// This function is called as a result of the requestor calling PrepareForBackup
// Here we do some checking to ensure that the requestor selected components properly
bool STDMETHODCALLTYPE TestWriter::OnPrepareBackup(IN IVssWriterComponents *pComponents)
try
{
enterEvent(Utility::PrepareForBackup);
WriterConfiguration* config = WriterConfiguration::instance();
// get the number of components
UINT numComponents = 0;
HRESULT hr = pComponents->GetComponentCount(&numComponents);
checkReturn(hr, L"IVssWriterComponents::GetComponentCount");
// we haven't defined CUSTOM restore method for this writer. consequently, backup apps should
// ignore it.
if ((config->restoreMethod().m_method == VSS_RME_CUSTOM) &&
numComponents > 0) {
throw Utility::TestWriterException(L"Components were selected for backup when CUSTOM restore"
L" method was used. This is incorrect");
}
m_selectedComponents.clear();
// for each component that was added
for (unsigned int x = 0; x < numComponents; x++) {
// --- get the relevant information
CComPtr<IVssComponent> pComponent;
hr = pComponents->GetComponent(x, &pComponent);
checkReturn(hr, L"IVssWriterComponents::GetComponent");
writeBackupMetadata(pComponent); // --- write private metadata
// --- find the component in the metadata document.
// --- this component may actually be a supercomponent of something
// --- listed in the metadata document, so we must handle that case.
// --- this is no longer true with the new interface changes... now, only components
// --- in the metadata doc can be added
ComponentBase identity(getPath(pComponent), getName(pComponent));
WriterConfiguration::ComponentList::iterator found =
std::find(config->components().begin(),
config->components().end(),
identity);
if (found == config->components().end()) {
wstringstream msg;
msg << L"Component with logical path: " << identity.m_logicalPath <<
L" and name: " << identity.m_name << L" was added to the document" << std::endl <<
L", but does not appear in the writer metadata";
printStatus(msg.str());
} else if (!addableComponent(*found)) {
wstringstream msg;
msg << L"Component with logical path: " << identity.m_logicalPath <<
L" and name: " << identity.m_name << L" was added to the document" << std::endl <<
L", but is not a selectable component";
printStatus(msg.str());
} else {
m_selectedComponents.push_back(*found);
}
}
// any non-selectable component with no selectable ancestor must be added. Check this.
vector<Component> mustAddComponents;
buildContainer_if(config->components().begin(),
config->components().end(),
std::back_inserter(mustAddComponents),
Utility::and1(std::not1(std::ptr_fun(isComponentSelectable)),
std::ptr_fun(addableComponent)));
vector<Component>::iterator currentMust = mustAddComponents.begin();
while (currentMust != mustAddComponents.end()) {
if (std::find(m_selectedComponents.begin(),
m_selectedComponents.end(),
*currentMust) == m_selectedComponents.end()) {
wstringstream msg;
msg << L"\nComponent with logical path: " << currentMust->m_logicalPath <<
L" and name: " << currentMust->m_name <<
L" is a non-selectable component with no selectable ancestor, and therefore " <<
L" must be added to the document. However, it was not added";
printStatus(msg.str());
}
++currentMust;
}
return true;
}
catch(const exception& thrown)
{
printStatus(string("Failure in PrepareForBackup event: ") + thrown.what(), Utility::low);
return false;
}
catch(HRESULT error)
{
Utility::TestWriterException e(error);
printStatus(e.what(), Utility::low);
return false;
};
// This function is called after a requestor calls DoSnapshotSet
// Here we ensure that the requestor has added the appropriate volumes to the
// snapshot set. If a spit directory is specified, the spit is done here as well.
bool STDMETHODCALLTYPE TestWriter::OnPrepareSnapshot()
try
{
enterEvent(Utility::PrepareForSnapshot);
// build the list of all files being backed up
vector<TargetedFile> componentFiles;
std::pointer_to_binary_function<Component, std::back_insert_iterator<vector<TargetedFile> >, void>
ptrFun(buildComponentFiles);
std::for_each(m_selectedComponents.begin(),
m_selectedComponents.end(),
std::bind2nd(ptrFun, std::back_inserter(componentFiles)));
// for every file being backed up
vector<TargetedFile>::iterator currentFile = componentFiles.begin();
while (currentFile != componentFiles.end()) {
// --- ensure the filespec has been snapshot, taking care of mount points
if (!checkPathAffected(*currentFile)) {
wstringstream msg;
msg << L"Filespec " << currentFile->m_path << currentFile->m_filespec <<
L"is selected for backup but contains files that have not been snapshot" << std::endl;
printStatus(msg.str());
}
// --- if a spit is needed, spit the file to the proper directory
if (!currentFile->m_alternatePath.empty())
spitFiles(*currentFile);
++currentFile;
}
return true;
}
catch(const exception& thrown)
{
printStatus(string("Failure in PrepareForSnapshot event: ") + thrown.what(), Utility::low);
return false;
}
catch(HRESULT error)
{
Utility::TestWriterException e(error);
printStatus(e.what(), Utility::low);
return false;
}
// This function is called after a requestor calls DoSnapshotSet
// Currently, we don't do much here that is interesting.
bool STDMETHODCALLTYPE TestWriter::OnFreeze()
try
{
enterEvent(Utility::Freeze);
return true;
}
catch(const exception& thrown)
{
printStatus(string("Failure in Freeze event: ") + thrown.what(), Utility::low);
return false;
}
catch(HRESULT error)
{
Utility::TestWriterException e(error);
printStatus(e.what(), Utility::low);
return false;
}
// This function is called after a requestor calls DoSnapshotSet
// Currently, we don't do much here that is interesting.
bool STDMETHODCALLTYPE TestWriter::OnThaw()
try
{
enterEvent(Utility::Thaw);
return true;
}
catch(const exception& thrown)
{
printStatus(string("Failure in Thaw event: ") + thrown.what(), Utility::low);
return false;
}
catch(HRESULT error)
{
Utility::TestWriterException e(error);
printStatus(e.what(), Utility::low);
return false;
}
// This function is called after a requestor calls DoSnapshotSet
// Here we cleanup the files that were spit in OnPrepareSnapshot
// and do some basic sanity checking
bool STDMETHODCALLTYPE TestWriter::OnPostSnapshot(IN IVssWriterComponents *pComponents)
try
{
enterEvent(Utility::PostSnapshot);
cleanupFiles();
// get the number of components
UINT numComponents = 0;
HRESULT hr = pComponents->GetComponentCount(&numComponents);
checkReturn(hr, L"IVssWriterComponents::GetComponentCount");
// for each component that was added
for (unsigned int x = 0; x < numComponents; x++) {
// --- get the relevant information
CComPtr<IVssComponent> pComponent;
hr = pComponents->GetComponent(x, &pComponent);
checkReturn(hr, L"IVssWriterComponents::GetComponent");
// --- ensure that the component was backed up
ComponentBase identity(getPath(pComponent), getName(pComponent));
vector<Component>::iterator found = std::find(m_selectedComponents.begin(),
m_selectedComponents.end(),
identity);
if (found == m_selectedComponents.end()) {
wstringstream msg;
msg << L"Component with logical path: " << identity.m_logicalPath <<
L"and name: " << identity.m_name <<
L"was selected in PostSnapshot, but was not selected in PrepareForSnapshot";
printStatus(msg.str(), Utility::low);
continue;
}
if (!verifyBackupMetadata(pComponent)) {
wstringstream msg;
msg << L"Component with logical path: " << identity.m_logicalPath <<
L"and name: " << identity.m_name <<
L" has been corrupted in PostSnapshot";
printStatus(msg.str(), Utility::low);
}
}
m_selectedComponents.clear();
return true;
}
catch(const exception& thrown)
{
printStatus(string("Failure in PostSnapshot event: ") + thrown.what(), Utility::low);
return false;
}
catch(HRESULT error)
{
Utility::TestWriterException e(error);
printStatus(e.what(), Utility::low);
return false;
}
// This function is called to abort the writer's backup sequence.
// If the writer has a spit component, spit files are cleaned up here.
bool STDMETHODCALLTYPE TestWriter::OnAbort()
try
{
enterEvent(Utility::Abort);
m_selectedComponents.clear();
cleanupFiles();
return true;
}
catch(const exception& thrown)
{
printStatus(string("Failure in Abort event: ") + thrown.what(), Utility::low);
return false;
}
catch(HRESULT error)
{
Utility::TestWriterException e(error);
printStatus(e.what(), Utility::low);
return false;
}
// This function is called as a result of the requestor calling BackupComplete
// Once again we do sanity checking, and we also verify that the metadata we
// wrote in PrepareForBackup has remained the same
bool STDMETHODCALLTYPE TestWriter::OnBackupComplete(IN IVssWriterComponents *pComponents)
try
{
enterEvent(Utility::BackupComplete);
WriterConfiguration* config = WriterConfiguration::instance();
// get the number of components
UINT numComponents = 0;
HRESULT hr = pComponents->GetComponentCount(&numComponents);
checkReturn(hr, L"IVssWriterComponents::GetComponentCount");
// for each component that was added
for (unsigned int x = 0; x < numComponents; x++) {
// --- get the relevant information
CComPtr<IVssComponent> pComponent;
hr = pComponents->GetComponent(x, &pComponent);
checkReturn(hr, L"IVssWriterComponents::GetComponent");
// --- ensure that the component is valid
ComponentBase identity(getPath(pComponent), getName(pComponent));
WriterConfiguration::ComponentList::iterator found =
std::find(config->components().begin(),
config->components().end(),
identity);
if (found == config->components().end()) {
wstringstream msg;
msg << L"Component with logical path: " << identity.m_logicalPath <<
L"and name: " << identity.m_name <<
L" is selected in BackupComplete, but does not appear in the writer metadata";
printStatus(msg.str(), Utility::low);
continue;
}
if (!verifyBackupMetadata(pComponent)) {
wstringstream msg;
msg << L"Component with logical path: " << identity.m_logicalPath <<
L"and name: " << identity.m_name <<
L" has been corrupted in BackupComplete";
printStatus(msg.str(), Utility::low);
}
// check that the backup succeeded
bool backupSucceeded = false;
hr = pComponent->GetBackupSucceeded(&backupSucceeded);
if (!backupSucceeded) {
wstringstream msg;
msg << L"Component with logical path: " << identity.m_logicalPath <<
L"and name: " << identity.m_name <<
L" was not marked as successfully backed up.";
}
}
return true;
}
catch(const exception& thrown)
{
printStatus(string("Failure in BackupComplete event: ") + thrown.what(), Utility::low);
return false;
}
catch(HRESULT error)
{
Utility::TestWriterException e(error);
printStatus(e.what(), Utility::low);
return false;
}
// This function is called at the end of the backup process. This may happen as a result
// of the requestor shutting down, or it may happen as a result of abnormal termination
// of the requestor.
bool STDMETHODCALLTYPE TestWriter::OnBackupShutdown(IN VSS_ID SnapshotSetId)
try
{
UNREFERENCED_PARAMETER(SnapshotSetId);
enterEvent(Utility::BackupShutdown);
return true;
}
catch(const exception& thrown)
{
printStatus(string("Failure in BackupShutdown event: ") + thrown.what(), Utility::low);
return false;
}
// This function is called as a result of the requestor calling PreRestore
// We check that component selection has been done properly, verify the
// backup metadata, and set targets appropriately.
bool STDMETHODCALLTYPE TestWriter::OnPreRestore(IN IVssWriterComponents *pComponents)
try
{
enterEvent(Utility::PreRestore);
WriterConfiguration* config = WriterConfiguration::instance();
// get the number of components
UINT numComponents = 0;
HRESULT hr = pComponents->GetComponentCount(&numComponents);
checkReturn(hr, L"IVssWriterComponents::GetComponentCount");
m_selectedRestoreComponents.clear();
// for each component that was added
for (unsigned int x = 0; x < numComponents; x++) {
// --- get the relevant information
CComPtr<IVssComponent> pComponent;
hr = pComponents->GetComponent(x, &pComponent);
checkReturn(hr, L"IVssWriterComponents::GetComponent");
// --- ensure that the component is valid
ComponentBase identity(getPath(pComponent), getName(pComponent));
WriterConfiguration::ComponentList::iterator found =
std::find(config->components().begin(),
config->components().end(),
identity);
if (found == config->components().end()) {
wstringstream msg;
msg << L"Component with logical path: " << identity.m_logicalPath <<
L"and name: " << identity.m_name <<
L" is selected in PreRestore, but does not appear in the writer metadata";
pComponent->SetPreRestoreFailureMsg(msg.str().c_str());
printStatus(msg.str(), Utility::low);
continue;
}
// only process those component that are selected for restore
bool selectedForRestore = false;
hr = pComponent->IsSelectedForRestore(&selectedForRestore);
checkReturn(hr, L"IVssComponent::IsSelectedForRestore");
if (!selectedForRestore)
continue;
m_selectedRestoreComponents.push_back(*found);
if (!verifyBackupMetadata(pComponent)) { // --- verify the backup metadata
wstringstream msg;
msg << L"Component with logical path: " << identity.m_logicalPath <<
L"and name: " << identity.m_name <<
L" has been corrupted in PreRestore";
pComponent->SetPreRestoreFailureMsg(msg.str().c_str());
printStatus(msg.str(), Utility::low);
}
writeRestoreMetadata(pComponent); // --- write restore metadata
// --- set the target appropriately
if (found->m_restoreTarget != VSS_RT_UNDEFINED) {
HRESULT hr =pComponent->SetRestoreTarget(found->m_restoreTarget);
checkReturn(hr, L"IVssComponent::SetRestoreTarget");
printStatus(wstring(L"Set Restore Target: ") +
Utility::toString(found->m_restoreTarget), Utility::high);
}
}
return true;
}
catch(const exception& thrown)
{
printStatus(string("Failure in PreRestore event: ") + thrown.what(), Utility::low);
return false;
}
catch(HRESULT error)
{
Utility::TestWriterException e(error);
printStatus(e.what(), Utility::low);
return false;
}
// This function is called as a result of the requestor calling PreRestore
// We do some sanity checking, and then check to see if files have indeed
// been restored
bool STDMETHODCALLTYPE TestWriter::OnPostRestore(IN IVssWriterComponents *pComponents)
try
{
enterEvent(Utility::PostRestore);
// get the number of components
UINT numComponents = 0;
HRESULT hr = pComponents->GetComponentCount(&numComponents);
checkReturn(hr, L"IVssWriterComponents::GetComponentCount");
// for each component
for (unsigned int x = 0; x < numComponents; x++) {
// --- get the relevant information
CComPtr<IVssComponent> pComponent;
hr = pComponents->GetComponent(x, &pComponent);
checkReturn(hr, L"I VssWriterComponents::GetComponent");
// --- ensure that the component is valid
ComponentBase identity(getPath(pComponent), getName(pComponent));
vector<Component>::iterator found = std::find(m_selectedRestoreComponents.begin(),
m_selectedRestoreComponents.end(),
identity);
if (found == m_selectedRestoreComponents.end()) {
wstringstream msg;
msg << L"Component with logical path: " << identity.m_logicalPath <<
L"and name: " << identity.m_name <<
L" is selected in PostRestore, but was not selected in PreRestore";
pComponent->SetPostRestoreFailureMsg(msg.str().c_str());
printStatus(msg.str(), Utility::low);
continue;
}
// only process those component that are selected for restore
bool selectedForRestore = false;
hr = pComponent->IsSelectedForRestore(&selectedForRestore);
checkReturn(hr, L"IVssComponent::IsSelectedForRestore");
if (!selectedForRestore)
continue;
if (!verifyRestoreMetadata(pComponent)) {
wstringstream msg;
msg << L"Component with logical path: " << identity.m_logicalPath <<
L"and name: " << identity.m_name <<
L" has been corrupted in PostRestore";
pComponent->SetPostRestoreFailureMsg(msg.str().c_str());
printStatus(msg.str(), Utility::low);
continue;
}
VSS_FILE_RESTORE_STATUS rStatus;
hr = pComponent->GetFileRestoreStatus(&rStatus);
checkReturn(hr, L"IVssComponent::GetFileRestoreStatus");
if (rStatus != VSS_RS_ALL) {
wstringstream msg;
msg << L"Component with logical path: " << identity.m_logicalPath <<
L"and name: " << identity.m_name <<
L" was not marked as having been successfully restored";
printStatus(msg.str(), Utility::low);
continue;
}
updateNewTargets(pComponent, *found);
verifyFilesRestored(pComponent, *found);
}
return true;
}
catch(const exception& thrown)
{
printStatus(string("Failure in PostRestore event: ") + thrown.what(), Utility::low);
return false;
}
catch(HRESULT error)
{
Utility::TestWriterException e(error);
printStatus(e.what(), Utility::low);
return false;
}
// This function is called at the entry to all writer events.
// A status message is printed to the console, and the event is failed if necessary.
void TestWriter::enterEvent(Utility::Events event)
{
static HRESULT errors[] = { VSS_E_WRITERERROR_INCONSISTENTSNAPSHOT,
VSS_E_WRITERERROR_OUTOFRESOURCES,
VSS_E_WRITERERROR_TIMEOUT,
VSS_E_WRITERERROR_RETRYABLE
};
printStatus(wstring(L"\nReceived event: ") + Utility::toString(event));
WriterConfiguration* config = WriterConfiguration::instance();
// figure out whether we should fail this event
WriterEvent writerEvent(event);
WriterConfiguration::FailEventList::iterator found = std::find(config->failEvents().begin(),
config->failEvents().end(),
writerEvent);
// if so, then fail it unless failures have run out
if (found != config->failEvents().end()) {
bool failEvent = !found->m_retryable || (m_failures[event] < found->m_numFailures);
bool setFailure = inSequence(event);
if (!found->m_retryable && setFailure)
SetWriterFailure(VSS_E_WRITERERROR_NONRETRYABLE);
else if (failEvent && setFailure)
SetWriterFailure(errors[rand() % (sizeof(errors) / sizeof(errors[0]))]);
if (failEvent) {
++m_failures[event];
wstringstream msg;
msg << L"Failure Requested in Event: " << Utility::toString(event) <<
L" Failing for the " << m_failures[event] << L" time";
throw Utility::TestWriterException(msg.str());
}
}
}
// This helper function adds a component to the writer-metadata document
void TestWriter::addComponent(const Component& component, IVssCreateWriterMetadata* pMetadata)
{
const wchar_t* logicalPath = component.m_logicalPath.empty() ? NULL : component.m_logicalPath.c_str();
// add the component to the document
HRESULT hr = pMetadata->AddComponent(component.m_componentType, // ct
logicalPath, // logicalwszLogicalPath
component.m_name.c_str(), // wszComponentName
NULL, // wszCaption
NULL, // pbIcon
0, // cbIcon
true, // bRestoreMetadata
true, // bNotifyOnBackupComplete
component.m_selectable, // bSelectable
component.m_selectableForRestore // bSelectableForRestore
);
checkReturn(hr, L"IVssCreateWriterMetadata::AddComponent");
printStatus(L"\nAdded component: ", Utility::high);
printStatus(component.toString(), Utility::high);
// add all of the files to the component. NOTE: we don't allow distinctions between database files
// and database log files in the VSS_CT_DATABASE case.
// we sometimes put a '\' on the end and sometimes not to keep requestors honest.
Component::ComponentFileList::iterator current = component.m_files.begin();
while (current != component.m_files.end()) {
if (component.m_componentType == VSS_CT_FILEGROUP) {
const wchar_t* alternate = current->m_alternatePath.empty() ? NULL :
current->m_alternatePath.c_str();
hr = pMetadata->AddFilesToFileGroup(logicalPath,
component.m_name.c_str(),
current->m_path.substr(0, current->m_path.size()-1).c_str(),
current->m_filespec.c_str(),
current->m_recursive,
alternate);
checkReturn(hr, L"IVssCreateWriterMetadata::AddFilesToFileGroup");
} else if (component.m_componentType == VSS_CT_DATABASE) {
hr = pMetadata->AddDatabaseFiles(logicalPath,
component.m_name.c_str(),
current->m_path.c_str(),
current->m_filespec.c_str());
checkReturn(hr, L"IVssCreateWriterMetadata::AddDatabaseFiles");
} else {
assert(false);
}
printStatus(L"\nAdded Component Filespec: ");
printStatus(current->toString());
++current;
}
// add all dependencies to the dependency list for the writer
Component::DependencyList::iterator currentDependency = component.m_dependencies.begin();
while (currentDependency != component.m_dependencies.end()) {
hr = pMetadata->AddComponentDependency(logicalPath,
component.m_name.c_str(), // wszForLogicalPath
currentDependency->m_writerId, // wszForComponentName
currentDependency->m_logicalPath.c_str(), // wszOnLogicalPath
currentDependency->m_componentName.c_str() // wszOnComponentName
);
checkReturn(hr, L"IVssCreateWriterMetadata::AddComponentDependency");
printStatus(L"\nAdded Component Dependency: ");
printStatus(currentDependency->toString());
++currentDependency;
}
}
// This helper function spits all files in a file specification to an alternate location
void TestWriter::spitFiles(const TargetedFile& file)
{
assert(!file.m_path.empty());
assert(file.m_path[file.m_path.size() - 1] == L'\\');
assert(!file.m_alternatePath.empty());
assert(file.m_alternatePath[file.m_alternatePath.size() - 1] == L'\\');
// ensure that both the source and target directories exist
DWORD attributes = ::GetFileAttributes(file.m_path.c_str());
if ((attributes == INVALID_FILE_ATTRIBUTES) ||
!(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
wstringstream msg;
msg << L"The source path " << file.m_path << L" does not exist";
throw Utility::TestWriterException(msg.str());
}
attributes = ::GetFileAttributes(file.m_alternatePath.c_str());
if ((attributes == INVALID_FILE_ATTRIBUTES) ||
!(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
wstringstream msg;
msg << L"The target path " << file.m_alternatePath << L" does not exist";
throw Utility::TestWriterException(msg.str());
}
// start by copying files from the specified root directory
std::queue<wstring> paths;
paths.push(file.m_path);
// walk through in breadth-first order. It's less resource intensive than depth-first, and
// potentially more performant
while (!paths.empty()) {
// --- grab the next path off the queue
wstring currentPath = paths.front();
paths.pop();
// --- start walking all files in the directory
WIN32_FIND_DATA findData;
Utility::AutoFindFileHandle findHandle = ::FindFirstFile((currentPath + L'*').c_str(), &findData);
if (findHandle == INVALID_HANDLE_VALUE)
continue;
do {
wstring currentName = findData.cFileName;
if (currentName == L"." ||
currentName == L"..")
continue;
std::transform(currentName.begin(), currentName.end(), currentName.begin(), towupper);
// --- if we've hit a direcctory and we care to do a recursive spit
if ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
file.m_recursive) {
assert(!currentName.empty());
if (currentName[currentName.size() - 1] != L'\\')
currentName += L"\\";
// figure out where the target for this new directory is
assert(currentPath.find(file.m_path) == 0);
wstring extraDirectory = currentPath.substr(file.m_path.size());
wstring alternateLocation = file.m_alternatePath + extraDirectory + currentName;
// create a target directory to hold the copied files.
if (!::CreateDirectory(alternateLocation.c_str(), NULL) &&
::GetLastError() != ERROR_ALREADY_EXISTS)
checkReturn(HRESULT_FROM_WIN32(::GetLastError()), L"CreateDirectory");
m_directoriesToRemove.push(alternateLocation.c_str());
// push the directory on the queue so it gets processed as well
paths.push(currentPath + currentName);
continue;
}
// --- if we've hit a regular file with a matching filespec
if (!(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
wildcardMatches(currentName, file.m_filespec)) {
// figure out where the new target location is
assert(currentPath.find(file.m_path) == 0);
wstring extraDirectory = currentPath.substr(file.m_path.size());
wstring alternateLocation = file.m_alternatePath + extraDirectory + currentName;
wstringstream msg;
msg << L"Spitting File: " << currentPath + currentName <<
L" To location: " << alternateLocation;
printStatus(msg.str() , Utility::high);
// copy the file over
if (!::CopyFile((currentPath + currentName).c_str(), alternateLocation.c_str(), FALSE))
checkReturn(HRESULT_FROM_WIN32(::GetLastError()), L"CopyFile");
else
m_toDelete.push_back(alternateLocation);
}
} while (::FindNextFile(findHandle, &findData));
}
}
// extract the component name from an interface pointer
wstring TestWriter::getName(IVssComponent* pComponent)
{
CComBSTR name;
HRESULT hr = pComponent->GetComponentName(&name);
checkReturn(hr, L"IVssComponent::GetComponentName");
assert(name != NULL); // this should never happen
return (BSTR)name;
}
// extract the component logical path from an interface pointer
wstring TestWriter::getPath(IVssComponent* pComponent)
{
CComBSTR path;
HRESULT hr = pComponent->GetLogicalPath(&path);
checkReturn(hr, L"IVssComponent::GetLogicalPath");
// GetLogicalPath can indeed return NULL so be careful
return (path.Length() > 0) ? (BSTR)path : L"";
}
// write a backup metadata stamp to the component
void TestWriter::writeBackupMetadata(IVssComponent* pComponent)
{
HRESULT hr = pComponent->SetBackupMetadata(metadata(pComponent, BackupString).c_str());
checkReturn(hr, L"IVssComponent::SetBackupMetadata");
printStatus(wstring(L"Writing backup metadata: ") + metadata(pComponent, BackupString),
Utility::high);
}
// verify that a backup metadata stamp is intact
bool TestWriter::verifyBackupMetadata(IVssComponent* pComponent)
{
CComBSTR data;
HRESULT hr = pComponent->GetBackupMetadata(&data);
checkReturn(hr, L"IVssComponent::GetBackupMetadata");
printStatus(wstring(L"\nComparing metadata: ") + (data.Length() ? (BSTR)data : L"") +
wstring(L" Against expected string: ") + metadata(pComponent, BackupString),
Utility::high);
if (data.Length() == 0 || metadata(pComponent, BackupString) != (BSTR)data)
return false;
return true;
}
// write a restore metadata stamp to the component
void TestWriter::writeRestoreMetadata(IVssComponent* pComponent)
{
HRESULT hr = pComponent->SetRestoreMetadata(metadata(pComponent, RestoreString).c_str());
checkReturn(hr, L"IVssComponent::SetRestoreMetadata");
printStatus(wstring(L"Writing restore metadata: ") + metadata(pComponent, RestoreString),
Utility::high);
}
// verify that a restore metadata stamp is intact
bool TestWriter::verifyRestoreMetadata(IVssComponent* pComponent)
{
CComBSTR data;
HRESULT hr = pComponent->GetRestoreMetadata(&data);
checkReturn(hr, L"IVssComponent::GetRestoreMetadata");
printStatus(wstring(L"Comparing metadata: ") + (data.Length() ? (BSTR)data : L"") +
wstring(L" Against expected string: ") + metadata(pComponent, RestoreString),
Utility::high);
if (data.Length() == 0 || metadata(pComponent, RestoreString) != (BSTR)data)
return false;
return true;
}
// check to see if the specified file (or files) are all in the current snapshot set
// doesn't check directory junctions... this will not be changed anytime soon.
// recursive mount points are also not handled very well
bool TestWriter::checkPathAffected(const TargetedFile& file)
{
wstring backupPath = file.m_alternatePath.empty() ? file.m_path : file.m_alternatePath;
// if the path in question isn't snapshot, then return false
if (!IsPathAffected(backupPath.c_str()))
return false;
// if the filespec isn't recursive, then we're done
if (!file.m_recursive)
return true;
// get the name of the volume we live on
wchar_t volumeMount[MAX_PATH];
if(!::GetVolumePathName(backupPath.c_str(), volumeMount, MAX_PATH))
checkReturn(HRESULT_FROM_WIN32(::GetLastError()), L"GetVolumePathName");
assert(backupPath.find(volumeMount) == 0);
wchar_t volumeName[MAX_PATH];
if (!::GetVolumeNameForVolumeMountPoint(volumeMount, volumeName, MAX_PATH))
checkReturn(HRESULT_FROM_WIN32(::GetLastError()), L"GetVolumeNameForVolumeMountPoint");
// start off with the volume name and starting directory on a worklist.
std::queue<std::pair<wstring, wstring> > worklist;
worklist.push(std::make_pair(wstring(volumeName), backupPath.substr(wcslen(volumeMount))));
while (!worklist.empty()) {
// get the current volume and directory off the worklist
wstring currentVolume = worklist.front().first;
wstring currentPath = worklist.front().second;
worklist.pop();
// now, enumerate all mount points on the volume
Utility::AutoFindMountHandle findHandle = ::FindFirstVolumeMountPoint(currentVolume.c_str(), volumeMount, MAX_PATH);
if (findHandle == INVALID_HANDLE_VALUE)
continue;
do {
std::transform(volumeMount, volumeMount + wcslen(volumeMount), volumeMount, towupper);
wstring mountPoint = currentVolume + volumeMount;
// if this mount point is included in the file specification, the volume better be included in the snapshot set
if ((mountPoint.find(currentVolume + currentPath) == 0) &&
!IsPathAffected(mountPoint.c_str()))
return false;
if (!::GetVolumeNameForVolumeMountPoint(volumeMount, volumeName, MAX_PATH))
checkReturn(HRESULT_FROM_WIN32(::GetLastError()), L"GetVolumeNameForVolumeMountPoint");
// put this volume on the worklist so it gets processed as well
// Mount points always point to the root of a volume, so pass in
// an empty second argument. When junctions are supported, we
// will pass in the target directory as the second argument.
worklist.push(std::make_pair(wstring(volumeName), wstring())); // this line will change when we support junctions
} while (::FindNextVolumeMountPoint(findHandle, volumeMount, MAX_PATH) == TRUE);
}
return true;
}
// delete all files and directories created in PrepareForSnapshot
void TestWriter::cleanupFiles()
{
// delete all created files
vector<wstring>::iterator currentFile = m_toDelete.begin();
while (currentFile != m_toDelete.end()) {
if (!::DeleteFile(currentFile->c_str()))
warnReturn(HRESULT_FROM_WIN32(::GetLastError()), L"DeleteFile");
++currentFile;
}
m_toDelete.clear();
// remove all created directories in the proper order
while (!m_directoriesToRemove.empty()) {
wstring dir = m_directoriesToRemove.top();
if (!::RemoveDirectory(dir.c_str()))
warnReturn(HRESULT_FROM_WIN32(::GetLastError()), L"RemoveDirectory");
m_directoriesToRemove.pop();
}
}
// check to see if the requestor has added any new targets, and add them to the
// Component structure
void TestWriter::updateNewTargets(IVssComponent* pComponent, Component& writerComponent)
{
HRESULT hr = S_OK;
UINT newTargetCount = 0;
hr = pComponent->GetNewTargetCount(&newTargetCount);
checkReturn(hr, L"IVssComponent::GetNewTargetCount");
writerComponent.m_newTargets.clear();
for (UINT x = 0; x < newTargetCount; x++) {
// get information about the new target
CComPtr<IVssWMFiledesc> newTarget;
hr = pComponent->GetNewTarget(x, &newTarget);
checkReturn(hr, L"IVssComponent::GetNewTarget");
CComBSTR path, filespec, alternateLocation;
bool recursive = false;
hr = newTarget->GetPath(&path);
checkReturn(hr, L"IVssComponent:GetPath");
hr = newTarget->GetFilespec(&filespec);
checkReturn(hr, L"IVssComponent:GetFilespec");
hr = newTarget->GetRecursive(&recursive);
checkReturn(hr, L"IVssComponent:GetRecursive");
hr = newTarget->GetAlternateLocation(&alternateLocation);
checkReturn(hr, L"IVssComponent:GetAlternateLocation");
// add it to the new-target list
writerComponent.m_newTargets.push_back(TargetedFile(wstring(path),
wstring(filespec),
recursive,
wstring(alternateLocation)));
}
}
// verify that files in the component were restored properly.
// assumption is that the directory being restored to is empty if the checkExcluded parameter is true.
// currently, we have a very simple-minded approach to handle the wildcard case
// a more general solution will involve hashing files, and will be implemented if time is found
void TestWriter::verifyFilesRestored(IVssComponent* pComponent, const Component& writerComponent)
{
WriterConfiguration* config = WriterConfiguration::instance();
// no checking is being done. Don't do anything
if (!config->checkIncludes() && !config->checkExcludes())
return;
// for each file in the component
VSS_RESTORE_TARGET target = writerComponent.m_restoreTarget;
VSS_RESTOREMETHOD_ENUM method = config->restoreMethod().m_method;
// build the list of all filespecs that need restoring
vector<TargetedFile> componentFiles;
buildComponentFiles(writerComponent, std::back_inserter(componentFiles));
for (vector<TargetedFile>::iterator currentFile = componentFiles.begin();
currentFile != componentFiles.end();
++currentFile) {
// --- figure out if there are any matching exclude files
vector<File> excludeFiles;
if (config->checkExcludes()) {
buildContainer_if(config->excludeFiles().begin(),
config->excludeFiles().end(),
std::back_inserter(excludeFiles),
std::bind2nd(std::ptr_fun(targetMatches), *currentFile));
}
// if there's no checking to be done for this filespec, continue
if (excludeFiles.empty() && !config->checkIncludes())
continue;
// --- if there are new targets, look for one that references our file
// --- if we find such a target, ensure that the file was restored there
// --- NOTE: after the interface changes, there should be at most one matching
// --- target.
vector<TargetedFile> targets;
buildContainer_if(writerComponent.m_newTargets.begin(),
writerComponent.m_newTargets.end(),
std::back_inserter(targets),
std::bind2nd(std::equal_to<File>(), *currentFile));
if (targets.size() > 1) {
wstringstream msg;
msg << L"More than one new target matched filespec " <<
currentFile->toString() << std::endl << L"This is an illegal configuration";
printStatus(msg.str());
}
if (!targets.empty()) {
// create a function object to use for verification
VerifyFileAtLocation locationChecker(excludeFiles, pComponent, false);
locationChecker(targets[0], *currentFile); // TODO: no longer need this fancy functor, since we're not doing a for_each
}
vector<TargetedFile> alternateLocations;
buildContainer_if(config->restoreMethod().m_alternateLocations.begin(),
config->restoreMethod().m_alternateLocations.end(),
std::back_inserter(alternateLocations),
std::bind2nd(std::equal_to<File>(), *currentFile));
// --- NOTE: once again, interface changes mean we expect at most one
assert(alternateLocations.size() <= 1);
bool alternateRestore = !alternateLocations.empty() &&
((target == VSS_RT_ALTERNATE) || (method == VSS_RME_RESTORE_TO_ALTERNATE_LOCATION));
if ((method == VSS_RME_RESTORE_IF_CAN_REPLACE) ||
(method == VSS_RME_RESTORE_IF_NOT_THERE) ||
alternateRestore) {
// --- in all of these cases, the backup application may restore to an alternate location.
// if we're not in either of the following two states, then the alternate location should only be used if there's
// a matching element in the backup document. Check to see if this is true
// create a function object to use for verification
// TODO: we no longer need this fancy functor object since we're not doing a for_each
if (!alternateLocations.empty()) {
VerifyFileAtLocation locationChecker(excludeFiles, pComponent,
(target != VSS_RT_ALTERNATE) && (method != VSS_RME_RESTORE_TO_ALTERNATE_LOCATION));
// check to ensure that the file has been restored to each matching alternate location
// once again, this isn't quite correct, but good enough for now. More complicated
// test scenarios will eventually break this.
locationChecker(alternateLocations[0], *currentFile);
}
}
// none of the above cases are true. We need to check to see that the file is restored to its original location
if ((method != VSS_RME_RESTORE_AT_REBOOT) && (method != VSS_RME_RESTORE_AT_REBOOT_IF_CANNOT_REPLACE) &&
!alternateRestore) {
// create a function object to use for verification
VerifyFileAtLocation locationChecker(excludeFiles, pComponent, false);
locationChecker(TargetedFile(currentFile->m_path,
currentFile->m_filespec,
currentFile->m_recursive,
currentFile->m_path),
*currentFile);
}
}
}
bool __cdecl TestWriter::isSubcomponent(ComponentBase sub, ComponentBase super)
{
// if the components are the same, then return true
if (super == sub)
return true;
wstring path = super.m_logicalPath;
if (!path.empty() && path[path.size() - 1] != L'\\')
path+= L"\\";
path += super.m_name;
// if the supercomponent full path is the same as the subcomponent logical path, then true
if (path == sub.m_logicalPath)
return true;
// otherwise, check for partial match
return sub.m_logicalPath.find(path + L"\\") == 0;
}
bool __cdecl TestWriter::targetMatches (File target, File file)
{
assert(!file.m_filespec.empty());
assert(!target.m_filespec.empty());
// the filespec must match first of all
if (!wildcardMatches(file.m_filespec, target.m_filespec))
return false;
// check the path
if (file.m_recursive) {
if (!target.m_recursive)
return target.m_path.find(file.m_path) == 0;
else
return (target.m_path.find(file.m_path) == 0) ||(file.m_path.find(target.m_path) == 0);
} else {
if (!target.m_recursive)
return file.m_path == target.m_path;
else
return file.m_path.find(target.m_path) == 0;
}
}
// This helper function tests whether a component can be legally added to the backup document
bool __cdecl TestWriter::addableComponent(Component toAdd)
{
WriterConfiguration* config = WriterConfiguration::instance();
if (toAdd.m_selectable)
return true;
// see if there are any selectable ancestors
vector<Component> ancestors;
buildContainer_if(config->components().begin(),
config->components().end(),
std::back_inserter(ancestors),
Utility::and1(std::bind2nd(std::ptr_fun(isSupercomponent), toAdd),
std::ptr_fun(isComponentSelectable)));
return ancestors.empty();
}
// check to see if two wildcards match.
// specifically, check to see whether the set of expansions of the first wildcard has a
// non-empty intersection with the set of expansions of the second wildcard.
// This function is not terribly efficient, but wildcards tend to be fairly short.
bool TestWriter::wildcardMatches(const wstring& first, const wstring& second)
{
// if both string are empty, then they surely match
if (first.empty() && second.empty())
return true;
// if we're done with the component, the wildcard better be terminated with '*' characters
if (first.empty())
return (second[0] == L'*') && wildcardMatches(first, second.substr(1));
if (second.empty())
return (first[0] == L'*') && wildcardMatches(first.substr(1), second);
switch(first[0]) {
case L'?':
if (second[0] == L'*') {
return wildcardMatches(first.substr(1), second) || // '*' matches character
wildcardMatches(first, second.substr(1)); // '*' matches nothing
}
// otherwise, the rest of the strings must match
return wildcardMatches(first.substr(1), second.substr(1));
case L'*':
return wildcardMatches(first, second.substr(1)) || // '*' matches character
wildcardMatches(first.substr(1), second); // '*' matches nothing
default:
switch(second[0]) {
case L'?':
return wildcardMatches(first.substr(1), second.substr(1));
case L'*':
return wildcardMatches(first.substr(1), second) || // '*' matches character
wildcardMatches(first, second.substr(1)); // '*' matches nothing
default:
return (first[0] == second[0]) &&
wildcardMatches(first.substr(1), second.substr(1));
}
}
}
wstring TestWriter::VerifyFileAtLocation::verifyFileAtLocation(const File& file, const TargetedFile& location) const
{
WriterConfiguration* config = WriterConfiguration::instance();
// complicated set of assertions.
assert(!(file.m_recursive && !location.m_recursive) ||
(location.m_path.find(file.m_path) == 0));
assert(!(location.m_recursive && !file.m_recursive) ||
(file.m_path.find(location.m_path) == 0));
assert(!(file.m_recursive && location.m_recursive) ||
((file.m_path.find(location.m_path) == 0) || (location.m_path.find(file.m_path) == 0)));
assert(!m_excluded.empty() || config->checkIncludes());
assert(m_excluded.empty() || config->checkExcludes());
// performant case where we don't have to walk any directory trees
if (!file.m_recursive && !location.m_recursive && isExact(file.m_filespec)) {
assert(m_excluded.size() <= 1); // if not, the config file isn't set up right
// --- if this is an alternate location mapping, only process it if there's a matching alternate location
// --- in the backup document
if (m_verifyAlternateLocation &&
!verifyAlternateLocation(TargetedFile(file.m_path, file.m_filespec, false, location.m_alternatePath))) {
return L"";
}
// --- ensure that the file has been restored, unless the file is excluded
printStatus(wstring(L"\nChecking file ") +
location.m_alternatePath + file.m_filespec,
Utility::high);
// check for error cases
if (m_excluded.empty()) {
if (::GetFileAttributes((location.m_alternatePath + file.m_filespec).c_str()) == INVALID_FILE_ATTRIBUTES) {
wstringstream msg;
msg << L"\nThe file: " << std::endl << file.toString() << std::endl <<
L"was not restored to location " << location.m_alternatePath;
printStatus(msg.str(), Utility::low);
return msg.str();
}
} else if (::GetFileAttributes((location.m_alternatePath + file.m_filespec).c_str()) != INVALID_FILE_ATTRIBUTES) {
wstringstream msg;
msg << L"\nThe file: " << file.m_path << file.m_filespec <<
L" should have been excluded, but appears in location " << location.m_alternatePath;
printStatus(msg.str(), Utility::low);
return msg.str();
}
return L"";
}
std::queue<wstring> paths;
// figure out what directory to start looking from
wstring startPath = location.m_alternatePath;
if (location.m_recursive && (file.m_path.find(location.m_path) == 0))
startPath += file.m_path.substr(location.m_path.size());
paths.push(startPath);
// in the recursive case, files will hopefully be backed up high in the directory tree
// consequently, we're going to walk the tree breadth-first
printStatus(L"\nChecking that filespec was restored:", Utility::high);
while (!paths.empty()) {
wstring currentPath = paths.front();
paths.pop();
printStatus(wstring(L" Checking directory: ") + currentPath,
Utility::high);
// for every file in the current directory (can't pass in filespec since we want to match all directories)
WIN32_FIND_DATA findData;
Utility::AutoFindFileHandle findHandle = ::FindFirstFile((currentPath + L"*").c_str(), &findData);
if (findHandle == INVALID_HANDLE_VALUE)
continue;
do {
wstring currentName = findData.cFileName;
std::transform(currentName.begin(), currentName.end(), currentName.begin(), towupper);
if (currentName == L"." ||
currentName == L"..")
continue;
// --- if the file is a directory
if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
assert(!currentName.empty());
if (currentName[currentName.size() - 1] != L'\\')
currentName += L"\\";
// add it if necessary
if (file.m_recursive)
paths.push(currentPath + currentName);
continue; // skip to next file
}
printStatus(wstring(L" Checking file: ") + currentName);
// --- translate the path to what it would have been in the original tree
assert(currentPath.find(location.m_alternatePath) == 0);
wstring originalPath = file.m_path;
if (file.m_recursive && (location.m_path.find(file.m_path) == 0))
originalPath += location.m_path.substr(file.m_path.size());
originalPath += currentPath.substr(location.m_alternatePath.size());
// --- if this is an alternate location mapping, only process it if there's a matching
// --- alternate location mapping in the backup document
if (m_verifyAlternateLocation &&
!verifyAlternateLocation(TargetedFile(originalPath, currentName, false, currentPath))) {
continue;
}
// --- find an exclude item that matches
// --- if !config->checkExcluded(), m_excluded will be an empty container, and
// --- std::find_if will return the end iterator
vector<File>::const_iterator found =
std::find_if(m_excluded.begin(),
m_excluded.end(),
std::bind2nd(std::ptr_fun(targetMatches), File(originalPath, currentName, false)));
// --- return if this is either an excluded file, or if we've found at least one matching include file
if (found != m_excluded.end()) {
wstringstream msg;
msg << L"The file " << originalPath << currentName <<
L" should have been excluded, but appears in location " << currentPath;
printStatus(msg.str(), Utility::low);
return msg.str();
} else if (config->checkIncludes() &&
wildcardMatches(currentName, file.m_filespec)) {
return L""; // declare success in cheesy case
}
} while (::FindNextFile(findHandle, &findData));
}
if (config->checkIncludes()) {
wstringstream msg;
msg << L"None of the files specified by " << std::endl << file.toString() << std::endl <<
L" were restored to location " << location.m_alternatePath;
printStatus(msg.str(), Utility::low);
return msg.str();
}
// we're only checking excludes, and we didn't find any violations
return L"";
}
// verify that an alternate location mapping appears in the backup document
bool TestWriter::VerifyFileAtLocation::verifyAlternateLocation(const TargetedFile& writerAlt) const
{
assert (isExact(writerAlt.m_filespec));
assert(!writerAlt.m_recursive);
unsigned int mappings = 0;
HRESULT hr = m_pComponent->GetAlternateLocationMappingCount(&mappings);
checkReturn(hr, L"IVssComponent::GetAlternateLocationMappingCount");
for (unsigned int x = 0; x < mappings; x++) {
// get the current alternate location mapping
CComPtr<IVssWMFiledesc> filedesc;
hr = m_pComponent->GetAlternateLocationMapping(x, &filedesc);
checkReturn(hr, L"IVssComponent::GetAlternateLocationMapping");
// grab all relevant fields
CComBSTR bstrPath, bstrFilespec, bstrAlternateLocation;
hr = filedesc->GetPath(&bstrPath);
checkReturn(hr, L"IVssComponent::GetPath");
if (bstrPath.Length() == 0) {
printStatus(L"An Alternate Location Mapping with an empty path was added to the backup document",
Utility::low);
continue;
}
hr = filedesc->GetFilespec(&bstrFilespec);
checkReturn(hr, L"IVssComponent::GetFilespec");
if (bstrFilespec.Length() == 0) {
printStatus(L"An Alternate Location Mapping with an empty filespec was added to the backup document",
Utility::low);
continue;
}
hr = filedesc->GetAlternateLocation(&bstrAlternateLocation);
checkReturn(hr, L"IVssComponent::GetAlternateLocation");
if (bstrAlternateLocation.Length() == 0) {
printStatus(L"An Alternate Location Mapping with an empty alternateLocation was added to the backup document",
Utility::low);
continue;
}
bool recursive;
hr = filedesc->GetRecursive(&recursive);
checkReturn(hr, L"IVssComponent::GetRecursive");
// convert the fields to uppercase and ensure paths are '\' terminated
wstring path = bstrPath;
std::transform(path.begin(), path.end(), path.begin(), towupper);
if (path[path.size() - 1] != L'\\')
path += L'\\';
wstring filespec = bstrFilespec;
std::transform(filespec.begin(), filespec.end(), filespec.begin(), towupper);
wstring alternatePath = bstrAlternateLocation;
std::transform(alternatePath.begin(), alternatePath.end(), alternatePath.begin(), towupper);
if (alternatePath[alternatePath.size() - 1] != L'\\')
alternatePath += L'\\';
// check to see if that passed-in mapping is encompassed by the one in the backup document
if (targetMatches(File(path, filespec, recursive), writerAlt)) {
if (recursive) {
if (writerAlt.m_alternatePath.find(alternatePath) != 0)
return false;
assert(writerAlt.m_path.find(path) == 0);
alternatePath += writerAlt.m_path.substr(path.size());
}
return alternatePath == writerAlt.m_alternatePath;
}
}
return false;
}
// add the current error message to the PostRestoreFailureMsg
void TestWriter::VerifyFileAtLocation::saveErrorMessage(const wstring& message) const
{
if (!message.empty()) {
CComBSTR old;
m_pComponent->GetPostRestoreFailureMsg(&old);
wstring oldMessage = (old.Length() > 0) ? (BSTR)old : L"";
m_pComponent->SetPostRestoreFailureMsg((oldMessage + wstring(L"\n") + message).c_str());
}
}
| 39.815006 | 156 | 0.623371 | [
"object",
"vector",
"transform"
] |
3cce2d7d1f9a290bc4274150eee4eb70d3fc865d | 2,673 | cc | C++ | src/tiles/tiles_state.cc | eaburns/pbnf | 36e291c89fd95fd2578cdf61201ff983c2e21a68 | [
"MIT"
] | 4 | 2017-12-06T14:09:20.000Z | 2021-11-06T03:42:54.000Z | src/tiles/tiles_state.cc | eaburns/pbnf | 36e291c89fd95fd2578cdf61201ff983c2e21a68 | [
"MIT"
] | null | null | null | src/tiles/tiles_state.cc | eaburns/pbnf | 36e291c89fd95fd2578cdf61201ff983c2e21a68 | [
"MIT"
] | null | null | null | // © 2014 the PBNF Authors under the MIT license. See AUTHORS for the list of authors.
/**
* \file tiles_state.cc
*
*
*
* \author Ethan Burns
* \date 2008-11-03
*/
#include <assert.h>
#include <math.h>
#include <vector>
#include <iostream>
#include "tiles.h"
#include "tiles_state.h"
using namespace std;
//
// This technique is from Korf, R.E. and Schultze P, "Large-Scale
// Parallel Breadth-First Search, AAAI-05.
//
void TilesState::compute_hash(void)
{
unsigned int bits = 0;
const Tiles *t = static_cast<const Tiles *>(domain);
const vector<uint64_t> *ones = t->get_ones();
const vector<uint64_t> *fact_ary = t->get_fact_ary();
hash_val = 0;
for (int i = tiles.size() - 1; i >= 0; i -= 1) {
uint64_t k = tiles[i];
uint64_t mask = ~((~0) << k);
uint64_t v = mask & bits;
uint64_t d = k - ones->at(v);
hash_val += d * fact_ary->at(i);
bits |= 1 << k;
}
}
TilesState::TilesState(SearchDomain *d, State *parent, fp_type c, fp_type g,
fp_type h_val, vector<unsigned int> tiles,
unsigned int blank)
: State(d, parent, c, g),
tiles(tiles),
blank(blank)
{
this->h = h_val;
compute_hash();
}
TilesState::TilesState(SearchDomain *d, State *parent, fp_type c, fp_type g,
vector<unsigned int> t, unsigned int b)
: State(d, parent, c, g),
tiles(t),
blank(b)
{
assert(t[b] == 0);
if (domain->get_heuristic())
this->h = domain->get_heuristic()->compute(this);
else
this->h = 0;
assert(this->h == 0 ? is_goal() : 1);
compute_hash();
}
/**
* Test if the tiles are in order.
*/
bool TilesState::is_goal(void)
{
Tiles * t= static_cast<Tiles*>(domain);
return t->is_goal(this);
}
uint64_t TilesState::hash(void) const
{
return hash_val;
}
State *TilesState::clone(void) const
{
return new TilesState(domain, parent, c, g, tiles, blank);
}
void TilesState::print(ostream &o) const
{
Tiles *t = static_cast<Tiles*>(domain);
unsigned int i = 0;
o << "Hash: " << hash_val << endl;
for (unsigned int y = 0; y < t->get_height(); y += 1) {
for (unsigned int x = 0; x < t->get_width(); x += 1) {
o << tiles[i];
if (x < t->get_width() - 1)
o << "\t";
i += 1;
}
o << endl;
}
}
/**
* Test if two states are the same configuration.
*/
bool TilesState::equals(State *s) const
{
TilesState *other = static_cast<TilesState *>(s);
for (unsigned int i = 0; i < tiles.size(); i += 1)
if (tiles[i] != other->tiles[i])
return false;
return true;
}
/**
* Get the tile vector.
*/
const vector<unsigned int> *TilesState::get_tiles(void) const
{
return &tiles;
}
/**
* Get the blank position.
*/
unsigned int TilesState::get_blank(void) const
{
return blank;
}
| 18.692308 | 86 | 0.623644 | [
"vector"
] |
3cce5d412164766eb2530259b5d86a70cec6a07e | 9,089 | cpp | C++ | src/software/ai/navigator/placeholder_navigator/placeholder_navigator_test.cpp | scveloso/Software | ac882d3df0aa0d108e5157c076c82c030d023e12 | [
"MIT"
] | null | null | null | src/software/ai/navigator/placeholder_navigator/placeholder_navigator_test.cpp | scveloso/Software | ac882d3df0aa0d108e5157c076c82c030d023e12 | [
"MIT"
] | null | null | null | src/software/ai/navigator/placeholder_navigator/placeholder_navigator_test.cpp | scveloso/Software | ac882d3df0aa0d108e5157c076c82c030d023e12 | [
"MIT"
] | null | null | null | #include "software/ai/navigator/placeholder_navigator/placeholder_navigator.h"
#include <gtest/gtest.h>
#include "software/ai/intent/all_intents.h"
#include "software/ai/primitive/all_primitives.h"
#include "software/test_util/test_util.h"
TEST(PlaceholderNavigatorTest, convert_catch_intent_to_catch_primitive)
{
World world = ::Test::TestUtil::createBlankTestingWorld();
PlaceholderNavigator placeholderNavigator;
std::vector<std::unique_ptr<Intent>> intents;
intents.emplace_back(std::make_unique<CatchIntent>(1, 0, 10, 0.3, 0));
auto primitive_ptrs = placeholderNavigator.getAssignedPrimitives(world, intents);
// Make sure we got exactly 1 primitive back
EXPECT_EQ(primitive_ptrs.size(), 1);
auto expected_primitive = CatchPrimitive(1, 0, 10, 0.3);
auto primitive = dynamic_cast<CatchPrimitive &>(*(primitive_ptrs.at(0)));
EXPECT_EQ(expected_primitive, primitive);
}
TEST(PlaceholderNavigatorTest, convert_chip_intent_to_chip_primitive)
{
World world = ::Test::TestUtil::createBlankTestingWorld();
PlaceholderNavigator placeholderNavigator;
std::vector<std::unique_ptr<Intent>> intents;
intents.emplace_back(
std::make_unique<ChipIntent>(0, Point(), Angle::quarter(), 0, 1));
auto primitive_ptrs = placeholderNavigator.getAssignedPrimitives(world, intents);
// Make sure we got exactly 1 primitive back
EXPECT_EQ(primitive_ptrs.size(), 1);
auto expected_primitive = ChipPrimitive(0, Point(), Angle::quarter(), 0);
auto primitive = dynamic_cast<ChipPrimitive &>(*(primitive_ptrs.at(0)));
EXPECT_EQ(expected_primitive, primitive);
}
TEST(PlaceholderNavigatorTest,
convert_direct_velocity_intent_to_direct_velocity_primitive)
{
World world = ::Test::TestUtil::createBlankTestingWorld();
PlaceholderNavigator placeholderNavigator;
std::vector<std::unique_ptr<Intent>> intents;
intents.emplace_back(std::make_unique<DirectVelocityIntent>(3, 1, -2, 0.4, 1000, 4));
auto primitive_ptrs = placeholderNavigator.getAssignedPrimitives(world, intents);
// Make sure we got exactly 1 primitive back
EXPECT_EQ(primitive_ptrs.size(), 1);
auto expected_primitive = DirectVelocityPrimitive(3, 1, -2, 0.4, 1000);
auto primitive = dynamic_cast<DirectVelocityPrimitive &>(*(primitive_ptrs.at(0)));
EXPECT_EQ(expected_primitive, primitive);
}
TEST(PlaceholderNavigatorTest, convert_direct_wheels_intent_to_direct_wheels_primitive)
{
World world = ::Test::TestUtil::createBlankTestingWorld();
PlaceholderNavigator placeholderNavigator;
std::vector<std::unique_ptr<Intent>> intents;
intents.emplace_back(
std::make_unique<DirectWheelsIntent>(2, 80, 22, 55, 201, 5000, 60));
auto primitive_ptrs = placeholderNavigator.getAssignedPrimitives(world, intents);
// Make sure we got exactly 1 primitive back
EXPECT_EQ(primitive_ptrs.size(), 1);
auto expected_primitive = DirectWheelsPrimitive(2, 80, 22, 55, 201, 5000);
auto primitive = dynamic_cast<DirectWheelsPrimitive &>(*(primitive_ptrs.at(0)));
EXPECT_EQ(expected_primitive, primitive);
}
TEST(PlaceholderNavigatorTest, convert_dribble_intent_to_dribble_primitive)
{
World world = ::Test::TestUtil::createBlankTestingWorld();
PlaceholderNavigator placeholderNavigator;
std::vector<std::unique_ptr<Intent>> intents;
intents.emplace_back(
std::make_unique<DribbleIntent>(0, Point(), Angle::quarter(), 8888, true, 50));
auto primitive_ptrs = placeholderNavigator.getAssignedPrimitives(world, intents);
// Make sure we got exactly 1 primitive back
EXPECT_EQ(primitive_ptrs.size(), 1);
auto expected_primitive = DribblePrimitive(0, Point(), Angle::quarter(), 8888, true);
auto primitive = dynamic_cast<DribblePrimitive &>(*(primitive_ptrs.at(0)));
EXPECT_EQ(expected_primitive, primitive);
}
TEST(PlaceholderNavigatorTest, convert_kick_intent_to_kick_primitive)
{
World world = ::Test::TestUtil::createBlankTestingWorld();
PlaceholderNavigator placeholderNavigator;
std::vector<std::unique_ptr<Intent>> intents;
intents.emplace_back(
std::make_unique<KickIntent>(0, Point(), Angle::quarter(), 0, 1));
auto primitive_ptrs = placeholderNavigator.getAssignedPrimitives(world, intents);
// Make sure we got exactly 1 primitive back
EXPECT_EQ(primitive_ptrs.size(), 1);
auto expected_primitive = KickPrimitive(0, Point(), Angle::quarter(), 0);
auto primitive = dynamic_cast<KickPrimitive &>(*(primitive_ptrs.at(0)));
EXPECT_EQ(expected_primitive, primitive);
}
TEST(PlaceholderNavigatorTest, convert_move_intent_to_move_primitive)
{
World world = ::Test::TestUtil::createBlankTestingWorld();
PlaceholderNavigator placeholderNavigator;
std::vector<std::unique_ptr<Intent>> intents;
intents.emplace_back(
std::make_unique<MoveIntent>(0, Point(), Angle::quarter(), 0, 1));
auto primitive_ptrs = placeholderNavigator.getAssignedPrimitives(world, intents);
// Make sure we got exactly 1 primitive back
EXPECT_EQ(primitive_ptrs.size(), 1);
auto expected_primitive = MovePrimitive(0, Point(), Angle::quarter(), 0);
auto primitive = dynamic_cast<MovePrimitive &>(*(primitive_ptrs.at(0)));
EXPECT_EQ(expected_primitive, primitive);
}
TEST(PlaceholderNavigatorTest, convert_movespin_intent_to_movespin_primitive)
{
World world = ::Test::TestUtil::createBlankTestingWorld();
PlaceholderNavigator placeholderNavigator;
std::vector<std::unique_ptr<Intent>> intents;
intents.emplace_back(
std::make_unique<MoveSpinIntent>(0, Point(), AngularVelocity::full(), 1.0, 1));
auto primitive_ptrs = placeholderNavigator.getAssignedPrimitives(world, intents);
// Make sure we got exactly 1 primitive back
EXPECT_EQ(primitive_ptrs.size(), 1);
auto expected_primitive = MoveSpinPrimitive(0, Point(), AngularVelocity::full(), 1.0);
auto primitive = dynamic_cast<MoveSpinPrimitive &>(*(primitive_ptrs.at(0)));
EXPECT_EQ(expected_primitive, primitive);
}
TEST(PlaceholderNavigatorTest, convert_pivot_intent_to_pivot_primitive)
{
World world = ::Test::TestUtil::createBlankTestingWorld();
PlaceholderNavigator placeholderNavigator;
std::vector<std::unique_ptr<Intent>> intents;
intents.emplace_back(std::make_unique<PivotIntent>(0, Point(1, 0.4), Angle::half(),
Angle::ofRadians(1.25), true, 1));
auto primitive_ptrs = placeholderNavigator.getAssignedPrimitives(world, intents);
// Make sure we got exactly 1 primitive back
EXPECT_EQ(primitive_ptrs.size(), 1);
auto expected_primitive =
PivotPrimitive(0, Point(1, 0.4), Angle::half(), Angle::ofRadians(1.25), true);
auto primitive = dynamic_cast<PivotPrimitive &>(*(primitive_ptrs.at(0)));
EXPECT_EQ(expected_primitive, primitive);
}
TEST(PlaceholderNavigatorTest, convert_stop_intent_to_stop_primitive)
{
World world = ::Test::TestUtil::createBlankTestingWorld();
PlaceholderNavigator placeholderNavigator;
std::vector<std::unique_ptr<Intent>> intents;
intents.emplace_back(std::make_unique<StopIntent>(0, false, 1));
auto primitive_ptrs = placeholderNavigator.getAssignedPrimitives(world, intents);
// Make sure we got exactly 1 primitive back
EXPECT_EQ(primitive_ptrs.size(), 1);
auto expected_primitive = StopPrimitive(0, false);
auto primitive = dynamic_cast<StopPrimitive &>(*(primitive_ptrs.at(0)));
EXPECT_EQ(expected_primitive, primitive);
}
TEST(PlaceholderNavigatorTest, convert_multiple_intents_to_primitives)
{
World world = ::Test::TestUtil::createBlankTestingWorld();
PlaceholderNavigator placeholderNavigator;
std::vector<std::unique_ptr<Intent>> intents;
intents.emplace_back(std::make_unique<StopIntent>(0, false, 1));
intents.emplace_back(std::make_unique<PivotIntent>(0, Point(1, 0.4), Angle::half(),
Angle::ofRadians(3.2), true, 1));
intents.emplace_back(
std::make_unique<MoveIntent>(0, Point(), Angle::quarter(), 0, 1));
auto primitive_ptrs = placeholderNavigator.getAssignedPrimitives(world, intents);
// Make sure we got exactly 3 primitives back
EXPECT_EQ(primitive_ptrs.size(), 3);
auto expected_stop_primitive = StopPrimitive(0, false);
auto stop_primitive = dynamic_cast<StopPrimitive &>(*(primitive_ptrs.at(0)));
EXPECT_EQ(expected_stop_primitive, stop_primitive);
auto expected_pivot_primitive =
PivotPrimitive(0, Point(1, 0.4), Angle::half(), Angle::ofRadians(3.2), true);
auto pivot_primitive = dynamic_cast<PivotPrimitive &>(*(primitive_ptrs.at(1)));
EXPECT_EQ(expected_pivot_primitive, pivot_primitive);
auto expected_move_primitive = MovePrimitive(0, Point(), Angle::quarter(), 0);
auto move_primitive = dynamic_cast<MovePrimitive &>(*(primitive_ptrs.at(2)));
EXPECT_EQ(expected_move_primitive, move_primitive);
}
| 40.216814 | 90 | 0.727143 | [
"vector"
] |
3cce9909f1734d4f5c0f87cc9fc4b33562389dc0 | 8,928 | cpp | C++ | compiler/CodeGen/CTypeCodeGenerator.cpp | mattmassicotte/three | 3986c656724d1317bdb46d4777f8f952103d7ce7 | [
"MIT"
] | 8 | 2015-01-02T21:40:55.000Z | 2016-05-12T10:48:09.000Z | compiler/CodeGen/CTypeCodeGenerator.cpp | mattmassicotte/three | 3986c656724d1317bdb46d4777f8f952103d7ce7 | [
"MIT"
] | null | null | null | compiler/CodeGen/CTypeCodeGenerator.cpp | mattmassicotte/three | 3986c656724d1317bdb46d4777f8f952103d7ce7 | [
"MIT"
] | null | null | null | #include "CTypeCodeGenerator.h"
#include <sstream>
namespace Three {
std::string CTypeCodeGenerator::codeGen(const DataType& type, const std::string& varName) {
DataType usedType(type);
std::string innerStr;
// The check for a name catches aliased pointer types. Without doing this, we'll loose the
// alias, and render the underlying type. That's not incorrect, but its much less readable,
// and often surprising when inspecting the C code.
while (usedType.isPointer() && !usedType.hasName()) {
std::string pointerStr = "*";
if (usedType.kind() == DataType::Kind::NullablePointer) {
pointerStr += " THREE_ATTR_NULLABLE";
}
if (CTypeCodeGenerator::typeCanBeConst(usedType)) {
pointerStr += " const";
}
assert(usedType.subtypeCount() == 1 && "Error: a pointer must have exactly one subtype");
usedType = usedType.subtypeAtIndex(0);
// pre-pend the value, because we are working our way in
innerStr = pointerStr + innerStr;
}
// apply the variable name here, if we have one
if (varName.size() > 0) {
innerStr += " " + varName;
}
std::stringstream s;
switch (usedType.kind()) {
case DataType::Kind::Function:
case DataType::Kind::CFunction:
s << CTypeCodeGenerator::codeGenFunctionType(usedType, innerStr);
break;
default:
s << CTypeCodeGenerator::codeGenType(usedType);
s << innerStr;
break;
}
return s.str();
}
std::string CTypeCodeGenerator::codeGenType(const DataType& type) {
std::stringstream s;
switch (type.kind()) {
case DataType::Kind::Undefined: assert(0 && "Bug: cannot codegen an undefined type");
case DataType::Kind::Unknown: assert(0 && "Bug: cannot codegen an unknown type");
case DataType::Kind::Void:
case DataType::Kind::Integer:
case DataType::Kind::Boolean:
case DataType::Kind::Natural:
case DataType::Kind::Float:
case DataType::Kind::Real:
case DataType::Kind::Character:
case DataType::Kind::Vararg:
case DataType::Kind::Tuple:
case DataType::Kind::CInt:
case DataType::Kind::CChar:
case DataType::Kind::CUnsignedInt:
case DataType::Kind::Closure:
case DataType::Kind::Structure:
case DataType::Kind::Enumeration:
case DataType::Kind::Union:
case DataType::Kind::CStructure:
case DataType::Kind::CStructPrefixedStructure:
s << CTypeCodeGenerator::codeGenScalarType(type);
break;
case DataType::Kind::Array:
s << CTypeCodeGenerator::codeGenType(type.subtypeAtIndex(0));
s << "[";
if (type.arrayCount() > 0) {
s << type.arrayCount();
}
s << "]";
assert(type.subtypeCount() > 0);
break;
case DataType::Kind::Pointer:
case DataType::Kind::NullablePointer:
// Normally, we don't take this path. But,
// if a pointer is a named type (aliased), we want to use
// that in the C source.
assert(type.hasName());
if (CTypeCodeGenerator::typeCanBeConst(type)) {
s << "const ";
}
s << type.name();
break;
default:
std::cout << type.kind() << std::endl;
assert(0 && "Error: unhandled C type");
break;
}
return s.str();
}
std::string CTypeCodeGenerator::codeGenScalarType(const DataType& type) {
std::stringstream s;
if (CTypeCodeGenerator::typeCanBeConst(type)) {
s << "const ";
}
if (type.isCScalar()) {
s << CTypeCodeGenerator::codeGenCScalarType(type);
return s.str();
}
switch (type.kind()) {
case DataType::Kind::Void:
s << "void";
break;
case DataType::Kind::Integer:
s << "int";
break;
case DataType::Kind::Boolean:
s << "bool";
break;
case DataType::Kind::Natural:
if (type.widthSpecifier() > 16 && type.widthSpecifier() <= 32) {
s << "uint32_t";
} else {
s << "unsigned int";
}
break;
case DataType::Kind::Float:
case DataType::Kind::Real:
if (type.widthSpecifier() > 32) {
s << "double";
} else {
s << "float";
}
break;
case DataType::Kind::Character:
s << "char";
break;
case DataType::Kind::Closure:
s << "three_closure_t";
break;
case DataType::Kind::Vararg:
s << "va_list";
break;
case DataType::Kind::Tuple:
s << CTypeCodeGenerator::codeGenTupleStructName(type);
break;
case DataType::Kind::Structure:
case DataType::Kind::Enumeration:
case DataType::Kind::Union:
case DataType::Kind::CStructure:
s << type.name();
break;
case DataType::Kind::CStructPrefixedStructure:
s << std::string("struct ") + type.name();
break;
default:
assert(0 && "Bug: unhandled scalar type");
break;
}
return s.str();
}
std::string CTypeCodeGenerator::codeGenCScalarType(const DataType& type) {
assert(type.isCScalar());
if (type.hasName()) {
// This is a bit weird, but we need to preserve the type's name during codegen.
// The actual underlying type will be correct here, but its way easier to understand
// if we use any typedef'd name that was applied.
return type.name();
}
switch (type.kind()) {
case DataType::Kind::CUnsignedInt:
return "unsigned int";
case DataType::Kind::CInt:
return "int";
case DataType::Kind::CChar:
return "char";
default:
break;
}
assert(0 && "Bug: unhandled scalar C type");
return "";
}
std::string CTypeCodeGenerator::codeGenFunction(const DataType& type, const std::string& leadingString) {
std::stringstream s;
// returnType function(param1, param2)
// returnType (*varName)(param1, param2)
s << CTypeCodeGenerator::codeGen(type.returnType()) << " ";
s << leadingString;
s << "(";
if (type.parameterCount() == 0) {
s << "void";
} else {
type.eachParameterWithLast([&s] (const DataType& paramType, bool last) {
s << CTypeCodeGenerator::codeGen(paramType, paramType.label());
if (!last) {
s << ", ";
}
});
}
s << ")";
return s.str();
}
std::string CTypeCodeGenerator::codeGenFunctionType(const DataType& type, const std::string& innerString) {
std::stringstream s;
// returnType (*varName)(param1, param2)
s << "(" << innerString << ")";
return CTypeCodeGenerator::codeGenFunction(type, s.str());
}
std::string CTypeCodeGenerator::codeGenTupleStructName(const DataType& type) {
std::stringstream s;
assert(type.kind() == DataType::Kind::Tuple);
assert(type.subtypeCount() > 0);
type.eachSubtypeWithLast([&] (const DataType& subtype, bool last) {
s << CTypeCodeGenerator::codeGen(subtype);
s << "_";
});
s << "tuple_t";
std::string result = s.str();
std::replace(result.begin(), result.end(), '*', 'P'); // replace all '*' to 'P'
std::replace(result.begin(), result.end(), ' ', '_'); // replace all ' ' to '_'
return result;
}
bool CTypeCodeGenerator::typeCanBeConst(const DataType& type) {
switch (type.kind()) {
case DataType::Kind::Void:
case DataType::Kind::Vararg:
return false;
default:
break;
}
return type.access() == DataType::Access::Read;
}
}
| 32.347826 | 111 | 0.50056 | [
"render"
] |
3cd199614284c878142a613ddb01a5dce231d081 | 65,490 | cpp | C++ | src/frontend/SageIII/ompAstConstruction.cpp | haiwangcat/ROSE | 75bf4106a5febe40269ea0361a024b7811668d45 | [
"BSD-3-Clause"
] | 4 | 2015-03-17T13:52:21.000Z | 2022-01-12T05:32:47.000Z | src/frontend/SageIII/ompAstConstruction.cpp | haiwangcat/ROSE | 75bf4106a5febe40269ea0361a024b7811668d45 | [
"BSD-3-Clause"
] | null | null | null | src/frontend/SageIII/ompAstConstruction.cpp | haiwangcat/ROSE | 75bf4106a5febe40269ea0361a024b7811668d45 | [
"BSD-3-Clause"
] | 1 | 2019-12-25T10:18:01.000Z | 2019-12-25T10:18:01.000Z | // Put here code used to construct SgOmp* nodes
// Liao 10/8/2010
#include "sage3basic.h"
#include "rose_paths.h"
#include "astPostProcessing.h"
#include "sageBuilder.h"
#include "OmpAttribute.h"
#include "ompAstConstruction.h"
//void processOpenMP(SgSourceFile* sageFilePtr);
//Liao, 10/27/2008: parsing OpenMP pragma here
//Handle OpenMP pragmas. This should be called after preprocessing information is attached since macro calls may exist within pragmas, Liao, 3/31/2009
extern int omp_parse();
extern OmpSupport::OmpAttribute* getParsedDirective();
extern void omp_parser_init(SgNode* aNode, const char* str);
//Fortran OpenMP parser interface
void parse_fortran_openmp(SgSourceFile *sageFilePtr);
using namespace std;
using namespace SageInterface;
using namespace SageBuilder;
using namespace OmpSupport;
// Liao 4/23/2011, special function to copy file info of the original SgPragma or Fortran comments
static bool copyStartFileInfo (SgNode* src, SgNode* dest, OmpAttribute* oa)
{
bool result = false;
ROSE_ASSERT (src && dest);
// same src and dest, no copy is needed
if (src == dest) return true;
SgLocatedNode* lsrc = isSgLocatedNode(src);
ROSE_ASSERT (lsrc);
SgLocatedNode* ldest= isSgLocatedNode(dest);
ROSE_ASSERT (ldest);
// ROSE_ASSERT (lsrc->get_file_info()->isTransformation() == false);
// already the same, no copy is needed
if (lsrc->get_startOfConstruct()->get_filename() == ldest->get_startOfConstruct()->get_filename()
&& lsrc->get_startOfConstruct()->get_line() == ldest->get_startOfConstruct()->get_line()
&& lsrc->get_startOfConstruct()->get_col() == ldest->get_startOfConstruct()->get_col())
return true;
Sg_File_Info* copy = new Sg_File_Info (*(lsrc->get_startOfConstruct()));
ROSE_ASSERT (copy != NULL);
// delete old start of construct
Sg_File_Info *old_info = ldest->get_startOfConstruct();
if (old_info) delete (old_info);
ldest->set_startOfConstruct(copy);
copy->set_parent(ldest);
// cout<<"debug: set ldest@"<<ldest <<" with file info @"<< copy <<endl;
ROSE_ASSERT (lsrc->get_startOfConstruct()->get_filename() == ldest->get_startOfConstruct()->get_filename());
ROSE_ASSERT (lsrc->get_startOfConstruct()->get_line() == ldest->get_startOfConstruct()->get_line());
ROSE_ASSERT (lsrc->get_startOfConstruct()->get_col() == ldest->get_startOfConstruct()->get_col());
ROSE_ASSERT (lsrc->get_startOfConstruct()->get_filename() == ldest->get_file_info()->get_filename());
ROSE_ASSERT (lsrc->get_startOfConstruct()->get_line() == ldest->get_file_info()->get_line());
ROSE_ASSERT (lsrc->get_startOfConstruct()->get_col() == ldest->get_file_info()->get_col());
ROSE_ASSERT (ldest->get_file_info() == copy);
// Adjustment for Fortran, the AST node attaching the Fortran comment will not actual give out the accurate line number for the comment
if (is_Fortran_language())
{
ROSE_ASSERT (oa != NULL);
PreprocessingInfo *currentPreprocessingInfoPtr = oa->getPreprocessingInfo();
ROSE_ASSERT (currentPreprocessingInfoPtr != NULL);
int commentLine = currentPreprocessingInfoPtr->getLineNumber();
ldest->get_file_info()->set_line(commentLine);
}
return result;
}
namespace OmpSupport
{
// an internal data structure to avoid redundant AST traversal to find OpenMP pragmas
static std::list<SgPragmaDeclaration* > omp_pragma_list;
// a similar list to save encountered Fortran comments which are OpenMP directives
std::list<OmpAttribute* > omp_comment_list;
// A pragma list to store the dangling pragmas for Fortran end directives.
// There are stored to ensure correct unparsing after converting Fortran comments into pragmas
// But they should be immediately removed during the OpenMP lowering phase
// static std::list<SgPragmaDeclaration* > omp_end_pragma_list;
// find all SgPragmaDeclaration nodes within a file and parse OpenMP pragmas into OmpAttribute info.
void attachOmpAttributeInfo(SgSourceFile *sageFilePtr)
{
ROSE_ASSERT(sageFilePtr != NULL);
if (sageFilePtr->get_openmp() == false)
return;
// For Fortran, search comments for OpenMP directives
if (sageFilePtr->get_Fortran_only()||sageFilePtr->get_F77_only()||sageFilePtr->get_F90_only()||
sageFilePtr->get_F95_only() || sageFilePtr->get_F2003_only())
{
parse_fortran_openmp(sageFilePtr);
} //end if (fortran)
else
{
// For C/C++, search pragma declarations for OpenMP directives
std::vector <SgNode*> all_pragmas = NodeQuery::querySubTree (sageFilePtr, V_SgPragmaDeclaration);
std::vector<SgNode*>::iterator iter;
for(iter=all_pragmas.begin();iter!=all_pragmas.end();iter++)
{
SgPragmaDeclaration* pragmaDeclaration = isSgPragmaDeclaration(*iter);
ROSE_ASSERT(pragmaDeclaration != NULL);
#if 0 // We should not enforce this since the pragma may come from transformation-generated node
if ((pragmaDeclaration->get_file_info()->isTransformation()
&& pragmaDeclaration->get_file_info()->get_filename()==string("transformation")))
{
cout<<"Found a pragma which is transformation generated. @"<< pragmaDeclaration;
cout<<pragmaDeclaration->unparseToString()<<endl;
pragmaDeclaration->get_file_info()->display("debug transformation generated pragma declaration.");
// Liao 4/23/2011
// #pragma omp task can shown up before a single statement body of a for loop,
// In this case, the frontend will insert a basic block under the loop
// and put both the pragma and the single statement into the block.
// AstPostProcessing() will reset the transformation flag for the pragma
// since its parent(the block) is transformation generated, not in the original code
ROSE_ASSERT(pragmaDeclaration->get_file_info()->isTransformation() ==false || pragmaDeclaration->get_file_info()->get_filename()!=string("transformation"));
}
#endif
SageInterface::replaceMacroCallsWithExpandedStrings(pragmaDeclaration);
string pragmaString = pragmaDeclaration->get_pragma()->get_pragma();
istringstream istr(pragmaString);
std::string key;
istr >> key;
if (key == "omp")
{
// Liao, 3/12/2009
// Outliner may move pragma statements to a new file
// after the pragma has been attached OmpAttribute.
// We have to skip generating the attribute again in the new file
OmpAttributeList* previous = getOmpAttributeList(pragmaDeclaration);
// store them into a buffer, reused by build_OpenMP_AST()
omp_pragma_list.push_back(pragmaDeclaration);
if (previous == NULL )
{
// Call parser
#ifndef ROSE_USE_INTERNAL_FRONTEND_DEVELOPMENT
omp_parser_init(pragmaDeclaration,pragmaString.c_str());
omp_parse();
#endif
OmpAttribute* attribute = getParsedDirective();
//cout<<"sage_gen_be.C:23758 debug:\n"<<pragmaString<<endl;
//attribute->print();//debug only for now
addOmpAttribute(attribute,pragmaDeclaration);
//cout<<"debug: attachOmpAttributeInfo() for a pragma:"<<pragmaString<<"at address:"<<pragmaDeclaration<<endl;
//cout<<"file info for it is:"<<pragmaDeclaration->get_file_info()->get_filename()<<endl;
#if 1 // Liao, 2/12/2010, this could be a bad idea. It causes trouble in comparing
//user-defined and compiler-generated OmpAttribute.
// We attach the attribute redundantly on affected loops also
// for easier loop handling later on in autoTuning's outlining step (reproducing lost pragmas)
if (attribute->getOmpDirectiveType() ==e_for ||attribute->getOmpDirectiveType() ==e_parallel_for)
{
SgForStatement* forstmt = isSgForStatement(getNextStatement(pragmaDeclaration));
ROSE_ASSERT(forstmt != NULL);
//forstmt->addNewAttribute("OmpAttribute",attribute);
addOmpAttribute(attribute,forstmt);
}
#endif
}
}
}// end for
}
}
// Clause node builders
//----------------------------------------------------------
//! Build SgOmpDefaultClause from OmpAttribute, if any
SgOmpDefaultClause * buildOmpDefaultClause(OmpAttribute* att)
{
ROSE_ASSERT(att != NULL);
if (!att->hasClause(e_default))
return NULL;
//grab default option
omp_construct_enum dv = att->getDefaultValue();
SgOmpClause::omp_default_option_enum sg_dv;
switch (dv)
{
case e_default_none:
sg_dv = SgOmpClause::e_omp_default_none;
break;
case e_default_shared:
sg_dv = SgOmpClause::e_omp_default_shared;
break;
case e_default_private:
sg_dv = SgOmpClause::e_omp_default_private;
break;
case e_default_firstprivate:
sg_dv = SgOmpClause::e_omp_default_firstprivate;
break;
default:
{
cerr<<"error: buildOmpDefaultClase() Unacceptable default option from OmpAttribute:"
<<OmpSupport::toString(dv)<<endl;
ROSE_ASSERT(false) ;
}
}//end switch
SgOmpDefaultClause* result = new SgOmpDefaultClause(sg_dv);
setOneSourcePositionForTransformation(result);
ROSE_ASSERT(result);
return result;
}
// Sara Royuela ( Nov 2, 2012 ): Check for clause parameters that can be defined in macros
// This adds support for the use of macro definitions in OpenMP clauses
// We need a traversal over SgExpression to support macros in any possition of an "assignment_expr"
// F.i.: #define THREADS_1 16
// #define THREADS_2 8
// int main( int arg, char** argv ) {
// #pragma omp parallel num_threads( THREADS_1 + THREADS_2 )
// {}
// }
SgVarRefExpVisitor::SgVarRefExpVisitor()
: expressions()
{}
std::vector<SgVarRefExp*> SgVarRefExpVisitor::get_expressions()
{
return expressions;
}
void SgVarRefExpVisitor::visit(SgNode* node)
{
SgVarRefExp* expr = isSgVarRefExp(node);
if(expr != NULL)
{
expressions.push_back(expr);
}
}
SgExpression* checkOmpExpressionClause( SgExpression* clause_expression, SgGlobal* global )
{
ROSE_ASSERT(clause_expression != NULL);
SgExpression* clause_value = clause_expression;
if( isSgTypeUnknown( clause_expression->get_type( ) ) )
{
SgVarRefExpVisitor v;
v.traverse(clause_expression, preorder);
std::vector<SgVarRefExp*> expressions = v.get_expressions();
if( !expressions.empty() )
{
SgDeclarationStatementPtrList& declarations = global->get_declarations();
while( !expressions.empty() )
{
SgName clause_name = expressions.back()->get_symbol()->get_name( );
for(SgDeclarationStatementPtrList::iterator it = declarations.begin(); it != declarations.end(); ++it)
{
SgDeclarationStatement * declaration = *it;
AttachedPreprocessingInfoType * preproc_info = declaration->getAttachedPreprocessingInfo();
if( preproc_info != NULL )
{ // There is preprocessed info attached to the current node
for(AttachedPreprocessingInfoType::iterator current_preproc_info = preproc_info->begin();
current_preproc_info != preproc_info->end(); current_preproc_info++)
{
if((*current_preproc_info)->getTypeOfDirective() == PreprocessingInfo::CpreprocessorDefineDeclaration)
{
std::string define_macro = (*current_preproc_info)->getString();
// Parse the macro: we are only interested in macros with the form #define MACRO_NAME MACRO_VALUE
size_t parenthesis = define_macro.find("(");
if(parenthesis == string::npos)
{ // Non function macro
unsigned int macro_name_init_pos = (unsigned int)(define_macro.find("define")) + 6;
while(macro_name_init_pos<define_macro.size() && define_macro[macro_name_init_pos]==' ')
macro_name_init_pos++;
unsigned int macro_name_end_pos = define_macro.find(" ", macro_name_init_pos);
std::string macro_name = define_macro.substr(macro_name_init_pos, macro_name_end_pos-macro_name_init_pos);
if(macro_name==clause_name.getString())
{ // Clause is defined in a macro
size_t comma = define_macro.find(",");
if(comma == string::npos); // Macros like "#define MACRO_NAME VALUE1, VALUE2" are not accepted
{ // We create here an expression with the value of the clause defined in the macro
unsigned int macro_value_init_pos = macro_name_end_pos + 1;
while(macro_value_init_pos<define_macro.size() && define_macro[macro_value_init_pos]==' ')
macro_value_init_pos++;
unsigned int macro_value_end_pos = macro_value_init_pos;
while(macro_value_end_pos<define_macro.size() &&
define_macro[macro_value_end_pos]!=' ' && define_macro[macro_value_end_pos]!='\n')
macro_value_end_pos++;
std::string macro_value = define_macro.substr(macro_value_init_pos, macro_value_end_pos-macro_value_init_pos);
// Check whether the value is a valid integer
std::string::const_iterator it = macro_value.begin();
while (it != macro_value.end() && std::isdigit(*it))
++it;
ROSE_ASSERT(!macro_value.empty() && it == macro_value.end());
int macro_int_value = atoi(macro_value.c_str());
clause_value = buildIntVal(macro_int_value);
}
}
}
}
}
}
}
expressions.pop_back();
}
}
else
{
printf("error in buildOmpExpressionClause(): unacceptable parameter in OpenMP clause\n");
ROSE_ASSERT(false);
}
}
return clause_value;
}
SgOmpExpressionClause* buildOmpExpressionClause(OmpAttribute* att, omp_construct_enum clause_type)
{
ROSE_ASSERT(att != NULL);
if (!att->hasClause(clause_type))
return NULL;
SgOmpExpressionClause * result = NULL ;
SgGlobal* file = SageInterface::getGlobalScope( att->getNode() );
switch (clause_type)
{
case e_collapse:
{
SgExpression* collapse_param = checkOmpExpressionClause( att->getExpression(e_collapse).second, file );
result = new SgOmpCollapseClause(collapse_param);
break;
}
case e_if:
{
SgExpression* if_param = checkOmpExpressionClause( att->getExpression(e_if).second, file );
result = new SgOmpIfClause(if_param);
break;
}
case e_num_threads:
{
SgExpression* num_threads_param = checkOmpExpressionClause( att->getExpression(e_num_threads).second, file );
result = new SgOmpNumThreadsClause(num_threads_param);
break;
}
default:
{
printf("error in buildOmpExpressionClause(): unacceptable clause type:%s\n",
OmpSupport::toString(clause_type).c_str());
ROSE_ASSERT(false);
}
}
ROSE_ASSERT(result != NULL);
setOneSourcePositionForTransformation(result);
return result;
}
SgOmpNowaitClause * buildOmpNowaitClause(OmpAttribute* att)
{
ROSE_ASSERT(att != NULL);
if (!att->hasClause(e_nowait))
return NULL;
SgOmpNowaitClause* result = new SgOmpNowaitClause();
ROSE_ASSERT(result);
setOneSourcePositionForTransformation(result);
return result;
}
SgOmpOrderedClause * buildOmpOrderedClause(OmpAttribute* att)
{
ROSE_ASSERT(att != NULL);
if (!att->hasClause(e_ordered_clause))
return NULL;
SgOmpOrderedClause* result = new SgOmpOrderedClause();
ROSE_ASSERT(result);
setOneSourcePositionForTransformation(result);
return result;
}
SgOmpUntiedClause * buildOmpUntiedClause(OmpAttribute* att)
{
ROSE_ASSERT(att != NULL);
if (!att->hasClause(e_untied))
return NULL;
SgOmpUntiedClause* result = new SgOmpUntiedClause();
ROSE_ASSERT(result);
setOneSourcePositionForTransformation(result);
return result;
}
//Build SgOmpScheduleClause from OmpAttribute, if any
SgOmpScheduleClause* buildOmpScheduleClause(OmpAttribute* att)
{
ROSE_ASSERT(att != NULL);
if (!att->hasClause(e_schedule))
return NULL;
// convert OmpAttribute schedule kind to SgOmpClause schedule kind
omp_construct_enum oa_kind = att->getScheduleKind();
SgOmpClause::omp_schedule_kind_enum sg_kind;
switch (oa_kind)
{
case e_schedule_static:
sg_kind = SgOmpClause::e_omp_schedule_static;
break;
case e_schedule_dynamic:
sg_kind = SgOmpClause::e_omp_schedule_dynamic;
break;
case e_schedule_guided:
sg_kind = SgOmpClause::e_omp_schedule_guided;
break;
case e_schedule_auto:
sg_kind = SgOmpClause::e_omp_schedule_auto;
break;
case e_schedule_runtime:
sg_kind = SgOmpClause::e_omp_schedule_runtime;
break;
default:
{
cerr<<"error: buildOmpScheduleClause() Unacceptable schedule kind from OmpAttribute:"
<<OmpSupport::toString(oa_kind)<<endl;
ROSE_ASSERT(false) ;
}
}
SgExpression* chunksize_exp = att->getExpression(e_schedule).second;
// ROSE_ASSERT(chunksize_exp != NULL); // chunk size is optional
// finally build the node
SgOmpScheduleClause* result = new SgOmpScheduleClause(sg_kind, chunksize_exp);
// setOneSourcePositionForTransformation(result);
ROSE_ASSERT(result != NULL);
return result;
}
//! A helper function to convert OmpAttribute reduction operator to SgClause reduction operator
//TODO move to sageInterface?
static SgOmpClause::omp_reduction_operator_enum toSgOmpClauseReductionOperator(omp_construct_enum at_op)
{
SgOmpClause::omp_reduction_operator_enum result = SgOmpClause::e_omp_reduction_unkown;
switch (at_op)
{
case e_reduction_plus: //+
{
result = SgOmpClause::e_omp_reduction_plus;
break;
}
case e_reduction_mul: //*
{
result = SgOmpClause::e_omp_reduction_mul;
break;
}
case e_reduction_minus: // -
{
result = SgOmpClause::e_omp_reduction_minus;
break;
}
// C/C++ only
case e_reduction_bitand: // &
{
result = SgOmpClause::e_omp_reduction_bitand;
break;
}
case e_reduction_bitor: // |
{
result = SgOmpClause::e_omp_reduction_bitor;
break;
}
case e_reduction_bitxor: // ^
{
result = SgOmpClause::e_omp_reduction_bitxor;
break;
}
case e_reduction_logand: // &&
{
result = SgOmpClause::e_omp_reduction_logand;
break;
}
case e_reduction_logor: // ||
{
result = SgOmpClause::e_omp_reduction_logor;
break;
}
// fortran operator
case e_reduction_and: // .and.
{
result = SgOmpClause::e_omp_reduction_and;
break;
}
case e_reduction_or: // .or.
{
result = SgOmpClause::e_omp_reduction_or;
break;
}
case e_reduction_eqv: // fortran .eqv.
{
result = SgOmpClause::e_omp_reduction_eqv;
break;
}
case e_reduction_neqv: // fortran .neqv.
// reduction intrinsic procedure name for Fortran
{
result = SgOmpClause::e_omp_reduction_neqv;
break;
}
case e_reduction_max:
{
result = SgOmpClause::e_omp_reduction_max;
break;
}
case e_reduction_min:
{
result = SgOmpClause::e_omp_reduction_min;
break;
}
case e_reduction_iand:
{
result = SgOmpClause::e_omp_reduction_iand;
break;
}
case e_reduction_ior:
{
result = SgOmpClause::e_omp_reduction_ior;
break;
}
case e_reduction_ieor:
{
result = SgOmpClause::e_omp_reduction_ieor;
break;
}
default:
{
printf("error: unacceptable omp construct enum for reduction operator conversion:%s\n", OmpSupport::toString(at_op).c_str());
ROSE_ASSERT(false);
break;
}
}
ROSE_ASSERT(result != SgOmpClause::e_omp_reduction_unkown);
return result;
}
//A helper function to set SgVarRefExpPtrList from OmpAttribute's construct-varlist map
static void setClauseVariableList(SgOmpVariablesClause* target, OmpAttribute* att, omp_construct_enum key)
{
ROSE_ASSERT(target&&att);
// build variable list
std::vector<std::pair<std::string,SgNode* > > varlist = att->getVariableList(key);
#if 0
// Liao 6/10/2010 we relax this assertion to workaround
// shared(num_threads), a clause keyword is used as a variable
// we skip variable list of shared() for now so shared clause will have empty variable list
#endif
ROSE_ASSERT(varlist.size()!=0);
std::vector<std::pair<std::string,SgNode* > >::iterator iter;
for (iter = varlist.begin(); iter!= varlist.end(); iter ++)
{
SgInitializedName* iname = isSgInitializedName((*iter).second);
ROSE_ASSERT(iname !=NULL);
//target->get_variables().push_back(iname);
// Liao 1/27/2010, fix the empty parent pointer of the SgVarRefExp here
SgVarRefExp * var_ref = buildVarRefExp(iname);
target->get_variables().push_back(var_ref);
var_ref->set_parent(target);
}
}
//! Try to build a reduction clause with a given operation type from OmpAttribute
SgOmpReductionClause* buildOmpReductionClause(OmpAttribute* att, omp_construct_enum reduction_op)
{
ROSE_ASSERT(att !=NULL);
if (!att->hasReductionOperator(reduction_op))
return NULL;
SgOmpClause::omp_reduction_operator_enum sg_op = toSgOmpClauseReductionOperator(reduction_op);
SgOmpReductionClause* result = new SgOmpReductionClause(sg_op);
setOneSourcePositionForTransformation(result);
ROSE_ASSERT(result != NULL);
// build variable list
setClauseVariableList(result, att, reduction_op);
return result;
}
//Build one of the clauses with a variable list
SgOmpVariablesClause * buildOmpVariableClause(OmpAttribute* att, omp_construct_enum clause_type)
{
ROSE_ASSERT(att != NULL);
if (!att->hasClause(clause_type))
return NULL;
SgOmpVariablesClause* result = NULL;
switch (clause_type)
{
case e_copyin:
{
result = new SgOmpCopyinClause();
break;
}
case e_copyprivate:
{
result = new SgOmpCopyprivateClause();
break;
}
case e_firstprivate:
{
result = new SgOmpFirstprivateClause();
break;
}
case e_lastprivate:
{
result = new SgOmpLastprivateClause();
break;
}
case e_private:
{
result = new SgOmpPrivateClause();
break;
}
case e_shared:
{
result = new SgOmpSharedClause();
break;
}
case e_reduction:
{
printf("error: buildOmpVariableClause() does not handle reduction\n");
ROSE_ASSERT(false);
}
default:
{
cerr<<"error: buildOmpVariableClause() Unacceptable clause type:"
<<OmpSupport::toString(clause_type)<<endl;
ROSE_ASSERT(false) ;
}
} //end switch
//build varlist
ROSE_ASSERT(result != NULL);
setClauseVariableList(result, att, clause_type);
return result;
}
// Build a single SgOmpClause from OmpAttribute for type c_clause_type, excluding reduction clauses
SgOmpClause* buildOmpNonReductionClause(OmpAttribute* att, omp_construct_enum c_clause_type)
{
SgOmpClause* result = NULL;
ROSE_ASSERT(att != NULL);
ROSE_ASSERT(isClause(c_clause_type));
if (!att->hasClause(c_clause_type))
return NULL;
switch (c_clause_type)
{
case e_default:
{
result = buildOmpDefaultClause(att);
break;
}
case e_nowait:
{
result = buildOmpNowaitClause(att);
break;
}
case e_ordered_clause:
{
result = buildOmpOrderedClause(att);
break;
}
case e_schedule:
{
result = buildOmpScheduleClause(att);
break;
}
case e_untied:
{
result = buildOmpUntiedClause(att);
break;
}
case e_if:
case e_collapse:
case e_num_threads:
{
result = buildOmpExpressionClause(att, c_clause_type);
break;
}
case e_copyin:
case e_copyprivate:
case e_firstprivate:
case e_lastprivate:
case e_private:
case e_shared:
{
result = buildOmpVariableClause(att, c_clause_type);
break;
}
case e_reduction:
{
printf("error: buildOmpNonReductionClause() does not handle reduction. Please use buildOmpReductionClause().\n");
ROSE_ASSERT(false);
break;
}
default:
{
printf("Warning: buildOmpNoReductionClause(): unhandled clause type: %s\n", OmpSupport::toString(c_clause_type).c_str());
ROSE_ASSERT(false);
break;
}
}
ROSE_ASSERT(result != NULL);
setOneSourcePositionForTransformation(result);
return result;
}
//! Get the affected structured block from an OmpAttribute
SgStatement* getOpenMPBlockFromOmpAttribte (OmpAttribute* att)
{
SgStatement* result = NULL;
ROSE_ASSERT(att != NULL);
omp_construct_enum c_clause_type = att->getOmpDirectiveType();
// Some directives have no followed statements/blocks
if (!isDirectiveWithBody(c_clause_type))
return NULL;
SgNode* snode = att-> getNode ();
ROSE_ASSERT(snode != NULL); //? not sure for Fortran
// Liao 10/19/2010 We convert Fortran comments into SgPragmaDeclarations
// So we can reuse the same code to generate OpenMP AST from pragmas
#if 0
SgFile * file = getEnclosingFileNode (snode);
if (file->get_Fortran_only()||file->get_F77_only()||file->get_F90_only()||
file->get_F95_only() || file->get_F2003_only())
{ //Fortran check setNode()
//printf("buildOmpParallelStatement() Fortran is not handled yet\n");
//ROSE_ASSERT(false);
}
else // C/C++ must be pragma declaration statement
{
SgPragmaDeclaration* pragmadecl = att->getPragmaDeclaration();
result = getNextStatement(pragmadecl);
}
#endif
SgPragmaDeclaration* pragmadecl = att->getPragmaDeclaration();
result = getNextStatement(pragmadecl);
// ROSE_ASSERT(result!=NULL);
// Not all pragma decl has a structured body!!
return result;
}
//add clauses to target based on OmpAttribute
static void appendOmpClauses(SgOmpClauseBodyStatement* target, OmpAttribute* att)
{
ROSE_ASSERT(target && att);
// for Omp statements with clauses
// must copy those clauses here, since they will be deallocated later on
vector<omp_construct_enum> clause_vector = att->getClauses();
std::vector<omp_construct_enum>::iterator citer;
for (citer = clause_vector.begin(); citer != clause_vector.end(); citer++)
{
omp_construct_enum c_clause = *citer;
if (!isClause(c_clause))
{
// printf ("Found a construct which is not a clause:%s\n within attr:%p\n", OmpSupport::toString(c_clause).c_str(), att);
ROSE_ASSERT(isClause(c_clause));
continue;
}
else
{
// printf ("Found a clause construct:%s\n", OmpSupport::toString(c_clause).c_str());
}
// special handling for reduction
if (c_clause == e_reduction)
{
std::vector<omp_construct_enum> rops = att->getReductionOperators();
ROSE_ASSERT(rops.size()!=0);
std::vector<omp_construct_enum>::iterator iter;
for (iter=rops.begin(); iter!=rops.end();iter++)
{
omp_construct_enum rop = *iter;
SgOmpClause* sgclause = buildOmpReductionClause(att, rop);
target->get_clauses().push_back(sgclause);
}
}
else
{
SgOmpClause* sgclause = buildOmpNonReductionClause(att, c_clause);
target->get_clauses().push_back(sgclause);
sgclause->set_parent(target); // is This right?
}
}
}
// Directive statement builders
//----------------------------------------------------------
//! Build a SgOmpBodyStatement
// handle body and optional clauses for it
SgOmpBodyStatement * buildOmpBodyStatement(OmpAttribute* att)
{
SgStatement* body = getOpenMPBlockFromOmpAttribte(att);
//Must remove the body from its previous parent first before attaching it
//to the new parent statement.
// We want to keep its preprocessing information during this relocation
// so we don't auto keep preprocessing information in its original places.
removeStatement(body,false);
if (body==NULL)
{
cerr<<"error: buildOmpBodyStatement() found empty body for "<<att->toOpenMPString()<<endl;
ROSE_ASSERT(body != NULL);
}
SgOmpBodyStatement* result = NULL;
switch (att->getOmpDirectiveType())
{
case e_atomic:
result = new SgOmpAtomicStatement(NULL, body);
break;
case e_critical:
result = new SgOmpCriticalStatement(NULL, body, SgName(att->getCriticalName()));
break;
case e_master:
result = new SgOmpMasterStatement(NULL, body);
break;
case e_ordered_directive:
result = new SgOmpOrderedStatement(NULL, body);
break;
case e_section:
result = new SgOmpSectionStatement(NULL, body);
break;
case e_parallel:
result = new SgOmpParallelStatement(NULL, body);
break;
case e_for:
result = new SgOmpForStatement(NULL, body);
break;
case e_single:
result = new SgOmpSingleStatement(NULL, body);
break;
case e_sections:
result = new SgOmpSectionsStatement(NULL, body);
break;
case e_task:
result = new SgOmpTaskStatement(NULL, body);
break;
//Fortran
case e_do:
result = new SgOmpDoStatement(NULL, body);
break;
case e_workshare:
result = new SgOmpWorkshareStatement(NULL, body);
break;
default:
{
cerr<<"error: unacceptable omp construct for buildOmpBodyStatement():"<<OmpSupport::toString(att->getOmpDirectiveType())<<endl;
ROSE_ASSERT(false);
}
}
ROSE_ASSERT(result != NULL);
//setOneSourcePositionForTransformation(result);
// copyStartFileInfo (att->getNode(), result); // No need here since its caller will set file info again
//set the current parent
body->set_parent(result);
// add clauses for those SgOmpClauseBodyStatement
if (isSgOmpClauseBodyStatement(result))
appendOmpClauses(isSgOmpClauseBodyStatement(result), att);
// result->get_file_info()->display("debug after building ..");
return result;
}
SgOmpFlushStatement* buildOmpFlushStatement(OmpAttribute* att)
{
ROSE_ASSERT(att != NULL);
SgOmpFlushStatement* result = new SgOmpFlushStatement();
ROSE_ASSERT(result !=NULL);
setOneSourcePositionForTransformation(result);
// build variable list
std::vector<std::pair<std::string,SgNode* > > varlist = att->getVariableList(e_flush);
// ROSE_ASSERT(varlist.size()!=0); // can have empty variable list
std::vector<std::pair<std::string,SgNode* > >::iterator iter;
for (iter = varlist.begin(); iter!= varlist.end(); iter ++)
{
SgInitializedName* iname = isSgInitializedName((*iter).second);
ROSE_ASSERT(iname !=NULL);
result->get_variables().push_back(buildVarRefExp(iname));
}
return result;
}
SgOmpThreadprivateStatement* buildOmpThreadprivateStatement(OmpAttribute* att)
{
ROSE_ASSERT(att != NULL);
SgOmpThreadprivateStatement* result = new SgOmpThreadprivateStatement();
ROSE_ASSERT(result !=NULL);
setOneSourcePositionForTransformation(result);
// build variable list
std::vector<std::pair<std::string,SgNode* > > varlist = att->getVariableList(e_threadprivate);
ROSE_ASSERT(varlist.size()!=0);
std::vector<std::pair<std::string,SgNode* > >::iterator iter;
for (iter = varlist.begin(); iter!= varlist.end(); iter ++)
{
SgInitializedName* iname = isSgInitializedName((*iter).second);
ROSE_ASSERT(iname !=NULL);
result->get_variables().push_back(buildVarRefExp(iname));
}
result->set_definingDeclaration(result);
return result;
}
//! Build nodes for combined OpenMP directives:
// parallel for
// parallel sections
// parallel workshare //TODO fortran later on
// We don't provide dedicated Sage node for combined directives,
// so we separate them in the AST as 1st and 2nd directive statement
// the first is always parallel and we return it from the function
SgOmpParallelStatement* buildOmpParallelStatementFromCombinedDirectives(OmpAttribute* att)
{
ROSE_ASSERT(att != NULL);
SgStatement* body = getOpenMPBlockFromOmpAttribte(att);
//Must remove the body from its previous parent
removeStatement(body);
ROSE_ASSERT(body != NULL);
// build the 2nd directive node first
SgStatement * second_stmt = NULL;
switch (att->getOmpDirectiveType())
{
case e_parallel_for:
{
second_stmt = new SgOmpForStatement(NULL, body);
setOneSourcePositionForTransformation(second_stmt);
break;
}
case e_parallel_sections:
{
second_stmt = new SgOmpSectionsStatement(NULL, body);
setOneSourcePositionForTransformation(second_stmt);
break;
}
// Fortran
case e_parallel_do:
{
second_stmt = new SgOmpDoStatement(NULL, body);
setOneSourcePositionForTransformation(second_stmt);
break;
}
case e_parallel_workshare:
{
second_stmt = new SgOmpWorkshareStatement(NULL, body);
setOneSourcePositionForTransformation(second_stmt);
break;
}
default:
{
cerr<<"error: unacceptable directive type in buildOmpParallelStatementFromCombinedDirectives(): "<<OmpSupport::toString(att->getOmpDirectiveType())<<endl;
ROSE_ASSERT(false);
}
} //end switch
ROSE_ASSERT(second_stmt);
body->set_parent(second_stmt);
copyStartFileInfo (att->getNode(), second_stmt, att);
// build the 1st directive node then
SgOmpParallelStatement* first_stmt = new SgOmpParallelStatement(NULL, second_stmt);
setOneSourcePositionForTransformation(first_stmt);
copyStartFileInfo (att->getNode(), first_stmt, att);
second_stmt->set_parent(first_stmt);
// allocate clauses to them, let the 2nd one have higher priority
// if a clause can be allocated to either of them
vector<omp_construct_enum> clause_vector = att->getClauses();
std::vector<omp_construct_enum>::iterator citer;
for (citer = clause_vector.begin(); citer != clause_vector.end(); citer++)
{
omp_construct_enum c_clause = *citer;
if (!isClause(c_clause))
{
printf ("Found a construct which is not a clause:%s\n within attr:%p\n", OmpSupport::toString(c_clause).c_str(), att);
ROSE_ASSERT(isClause(c_clause));
continue;
}
else
{
// printf ("Found a clause construct:%s\n", OmpSupport::toString(c_clause).c_str());
}
switch (c_clause)
{
// clauses allocated to omp parallel
case e_if:
case e_num_threads:
case e_default:
case e_shared:
case e_copyin:
{
SgOmpClause* sgclause = buildOmpNonReductionClause(att, c_clause);
ROSE_ASSERT(sgclause != NULL);
first_stmt->get_clauses().push_back(sgclause);
break;
}
// unique clauses allocated to omp for
case e_schedule:
case e_collapse:
case e_ordered_clause:
{
if (!isSgOmpForStatement(second_stmt) && !isSgOmpDoStatement(second_stmt))
{
printf("Error: buildOmpParallelStatementFromCombinedDirectives(): unacceptable clauses for parallel for/do\n");
att->print();
ROSE_ASSERT(false);
}
}
case e_private:
case e_firstprivate:
case e_lastprivate:
// case e_nowait: // nowait should not appear with combined directives
{
SgOmpClause* sgclause = buildOmpNonReductionClause(att, c_clause);
ROSE_ASSERT(sgclause != NULL);
// TODO parallel workshare
isSgOmpClauseBodyStatement(second_stmt)->get_clauses().push_back(sgclause);
break;
}
case e_reduction: //special handling for reduction
{
std::vector<omp_construct_enum> rops = att->getReductionOperators();
ROSE_ASSERT(rops.size()!=0);
std::vector<omp_construct_enum>::iterator iter;
for (iter=rops.begin(); iter!=rops.end();iter++)
{
omp_construct_enum rop = *iter;
SgOmpClause* sgclause = buildOmpReductionClause(att, rop);
ROSE_ASSERT(sgclause != NULL);
isSgOmpClauseBodyStatement(second_stmt)->get_clauses().push_back(sgclause);
}
break;
}
default:
{
cerr<<"error: unacceptable clause for combined parallel for directive:"<<OmpSupport::toString(c_clause)<<endl;
ROSE_ASSERT(false);
}
}
} // end clause allocations
/*
handle dangling #endif attached to the loop
1. original
#ifdef _OPENMP
#pragma omp parallel for private(i,k)
#endif
for () ...
2. after splitting
#ifdef _OPENMP
#pragma omp parallel
#pragma omp for private(i,k)
#endif
for () ...
3. We need to move #endif to omp parallel statement 's after position
transOmpParallel () will take care of it later on
#ifdef _OPENMP
#pragma omp parallel
#pragma omp for private(i) reduction(+ : j)
for (i = 1; i < 1000; i++)
if ((key_array[i - 1]) > (key_array[i]))
j++;
#endif
This is no perfect solution until we handle preprocessing information as structured statements in AST
*/
movePreprocessingInfo(body, first_stmt, PreprocessingInfo::before, PreprocessingInfo::after, true);
return first_stmt;
}
//! for C/C++ replace OpenMP pragma declaration with an SgOmpxxStatement
void replaceOmpPragmaWithOmpStatement(SgPragmaDeclaration* pdecl, SgStatement* ompstmt)
{
ROSE_ASSERT(pdecl != NULL);
ROSE_ASSERT(ompstmt!= NULL);
SgScopeStatement* scope = pdecl ->get_scope();
ROSE_ASSERT(scope !=NULL);
#if 0
SgOmpBodyStatement * omp_cb_stmt = isSgOmpBodyStatement(ompstmt);
// do it within buildOmpBodyStatement()
// avoid two parents point to the same structured block
// optionally remove the immediate structured block
if (omp_cb_stmt!= NULL)
{
SgStatement* next_stmt = getNextStatement(pdecl);
// not true after splitting combined directives, the body becomes the 2nd directive
// ROSE_ASSERT(next_stmt == omp_cb_stmt->get_body()); // ompstmt's body is set already
removeStatement(next_stmt);
}
#endif
// replace the pragma
moveUpPreprocessingInfo(ompstmt, pdecl); // keep #ifdef etc attached to the pragma
replaceStatement(pdecl, ompstmt);
}
//! Convert omp_pragma_list to SgOmpxxx nodes
void convert_OpenMP_pragma_to_AST (SgSourceFile *sageFilePtr)
{
list<SgPragmaDeclaration* >::reverse_iterator iter; // bottom up handling for nested cases
ROSE_ASSERT (sageFilePtr != NULL);
#if 0
// remove the end pragmas within Fortran. They were preserved for debugging (the conversion from comments to pragmas) purpose.
list<SgPragmaDeclaration* >::reverse_iterator end_iter;
for (end_iter=omp_end_pragma_list.rbegin(); end_iter!=omp_end_pragma_list.rend(); end_iter ++)
removeStatement (*end_iter);
#endif
for (iter = omp_pragma_list.rbegin(); iter != omp_pragma_list.rend(); iter ++)
{
// Liao, 11/18/2009
// It is possible that several source files showing up in a single compilation line
// We have to check if the pragma declaration's file information matches the current file being processed
// Otherwise we will process the same pragma declaration multiple times!!
SgPragmaDeclaration* decl = *iter;
// Liao, 2/8/2010
// Some pragmas are set to "transformation generated" when we fix scopes for some pragma under single statement block
// e.g if ()
// #pragma
// do_sth()
// will be changed to
// if ()
// {
// #pragma
// do_sth()
// }
// So we process a pragma if it is either within the same file or marked as transformation
if (decl->get_file_info()->get_filename()!= sageFilePtr->get_file_info()->get_filename()
&& !(decl->get_file_info()->isTransformation()))
continue;
// Liao 10/19/2010
// We now support OpenMP AST construction for both C/C++ and Fortran
// But we allow Fortran End directives to exist after -rose:openmp:ast_only
// Otherwise the code unparsed will be illegal Fortran code (No {} blocks in Fortran)
if (isFortranEndDirective(getOmpAttribute(decl)->getOmpDirectiveType()))
continue;
//cout<<"debug: convert_OpenMP_pragma_to_AST() handling pragma at "<<decl<<endl;
//ROSE_ASSERT (decl->get_file_info()->get_filename() != string("transformation"));
OmpAttributeList* oattlist= getOmpAttributeList(decl);
ROSE_ASSERT (oattlist != NULL) ;
vector <OmpAttribute* > ompattlist = oattlist->ompAttriList;
ROSE_ASSERT (ompattlist.size() != 0) ;
ROSE_ASSERT (ompattlist.size() == 1) ; // when do we have multiple directives associated with one pragma?
vector <OmpAttribute* >::iterator i = ompattlist.begin();
for (; i!=ompattlist.end(); i++)
{
OmpAttribute* oa = *i;
omp_construct_enum omp_type = oa->getOmpDirectiveType();
ROSE_ASSERT(isDirective(omp_type));
SgStatement* omp_stmt = NULL;
switch (omp_type)
{
// simplest OMP directives
case e_barrier:
{
omp_stmt = new SgOmpBarrierStatement();
break;
}
case e_taskwait:
{
omp_stmt = new SgOmpTaskwaitStatement();
break;
}
// with variable list
case e_threadprivate:
{
omp_stmt = buildOmpThreadprivateStatement(oa);
break;
}
case e_flush:
{
omp_stmt = buildOmpFlushStatement(oa);
break;
}
// with a structured block/statement followed
case e_atomic:
case e_master:
case e_section:
case e_critical:
case e_ordered_directive:
case e_parallel:
case e_for:
case e_single:
case e_task:
case e_sections:
//fortran
case e_do:
case e_workshare:
{
omp_stmt = buildOmpBodyStatement(oa);
break;
}
case e_parallel_for:
case e_parallel_sections:
case e_parallel_workshare://fortran
case e_parallel_do:
{
omp_stmt = buildOmpParallelStatementFromCombinedDirectives(oa);
break;
}
default:
{
cerr<<"Error: convert_OpenMP_pragma_to_AST(): unhandled OpenMP directive type:"<<OmpSupport::toString(omp_type)<<endl;
assert (false);
break;
}
}
setOneSourcePositionForTransformation(omp_stmt);
copyStartFileInfo (oa->getNode(), omp_stmt, oa);
//ROSE_ASSERT (omp_stmt->get_file_info()->isTransformation() != true);
replaceOmpPragmaWithOmpStatement(decl, omp_stmt);
} // end for (OmpAttribute)
}// end for (omp_pragma_list)
}
//! A helper function to ensure a sequence statements either has only one statement
// or all are put under a single basic block.
// begin_decl is the begin directive which is immediately in front of the list of statements
// Return the single statement or the basic block.
// This function is used to wrap all statement between begin and end Fortran directives into a block,
// if necessary(more than one statement)
static SgStatement * ensureSingleStmtOrBasicBlock (SgPragmaDeclaration* begin_decl, const std::vector <SgStatement*>& stmt_vec)
{
ROSE_ASSERT (begin_decl != NULL);
SgStatement * result = NULL;
ROSE_ASSERT (stmt_vec.size() > 0);
if (stmt_vec.size() ==1)
{
result = stmt_vec[0];
ROSE_ASSERT (getNextStatement(begin_decl) == result);
}
else
{
result = buildBasicBlock();
// Have to remove them from their original scope first.
// Otherwise they will show up twice in the unparsed code: original place and under the new block
// I tried to merge this into appendStatement() but it broke other transformations I don't want debug
for (std::vector <SgStatement*>::const_iterator iter = stmt_vec.begin(); iter != stmt_vec.end(); iter++)
removeStatement(*iter);
appendStatementList (stmt_vec, isSgScopeStatement(result));
insertStatementAfter (begin_decl, result, false);
}
return result;
}
//! Merge clauses from end directives to the corresponding begin directives
// dowait clause: end do, end sections, end single, end workshare
// copyprivate clause: end single
void mergeEndClausesToBeginDirective (SgPragmaDeclaration* begin_decl, SgPragmaDeclaration* end_decl)
{
ROSE_ASSERT (begin_decl!=NULL);
ROSE_ASSERT (end_decl!=NULL);
// Make sure they match
omp_construct_enum begin_type, end_type;
begin_type = getOmpConstructEnum (begin_decl);
end_type = getOmpConstructEnum (end_decl);
ROSE_ASSERT (begin_type == getBeginOmpConstructEnum(end_type));
#if 0
// Make sure they are at the same level ??
// Fortran do loop may have wrong file info, which cause comments to be attached to another scope
// Consequently, the end pragma will be in a higher/ different scope
// A workaround for bug 495: https://outreach.scidac.gov/tracker/?func=detail&atid=185&aid=495&group_id=24
if (SageInterface::is_Fortran_language() )
{
if (begin_decl->get_parent() != end_decl->get_parent())
{
ROSE_ASSERT (isAncestor (end_decl->get_parent(), begin_decl->get_parent()));
}
}
else
#endif
ROSE_ASSERT (begin_decl->get_parent() == end_decl->get_parent());
// merge end directive's clause to the begin directive.
OmpAttribute* begin_att = getOmpAttribute (begin_decl);
OmpAttribute* end_att = getOmpAttribute (end_decl);
// Merge possible nowait clause
switch (end_type)
{
case e_end_do:
case e_end_sections:
case e_end_single:
case e_end_workshare:
{
if (end_att->hasClause(e_nowait))
{
begin_att->addClause(e_nowait);
}
break;
}
default:
break; // there should be no clause for other cases
}
// Merge possible copyrpivate (list) from end single
if ((end_type == e_end_single) && end_att ->hasClause(e_copyprivate))
{
begin_att->addClause (e_copyprivate);
std::vector<std::pair<std::string,SgNode* > > varList = end_att->getVariableList(e_copyprivate);
std::vector<std::pair<std::string,SgNode* > >::iterator iter;
for (iter = varList.begin(); iter != varList.end(); iter++)
{
std::pair<std::string,SgNode* > element = *iter;
SgInitializedName* i_name = isSgInitializedName(element.second);
ROSE_ASSERT (i_name != NULL);
begin_att->addVariable(e_copyprivate, element.first, i_name);
}
}
}
//! This function will Find a (optional) end pragma for an input pragma (decl)
// and merge clauses from the end pragma to the beginning pragma
// statements in between will be put into a basic block if there are more than one statements
void merge_Matching_Fortran_Pragma_pairs(SgPragmaDeclaration* decl, omp_construct_enum omp_type)
{
ROSE_ASSERT (getOmpConstructEnum(decl)== omp_type );
ROSE_ASSERT (isFortranBeginDirective(omp_type));
omp_construct_enum end_omp_type = getEndOmpConstructEnum(omp_type);
SgPragmaDeclaration* end_decl = NULL;
SgStatement* next_stmt = getNextStatement(decl);
// SgStatement* prev_stmt = decl;
// SgBasicBlock* func_body = getEnclosingProcedure (decl)->get_body();
// ROSE_ASSERT (func_body != NULL);
std::vector<SgStatement*> affected_stmts; // statements which are inside the begin .. end pair
// Find possible end directives attached to a pragma declaration
while (next_stmt!= NULL)
{
end_decl = isSgPragmaDeclaration (next_stmt);
if ((end_decl) && (getOmpConstructEnum(end_decl) == end_omp_type))
break;
else
end_decl = NULL; // MUST reset to NULL if not a match
affected_stmts.push_back(next_stmt);
// prev_stmt = next_stmt; // save previous statement
next_stmt = getNextStatement (next_stmt);
#if 0
// Liao 1/21/2011
// A workaround of wrong file info for Do loop body
// See bug 495 https://outreach.scidac.gov/tracker/?func=detail&atid=185&aid=495&group_id=24
// Comments will not be attached before ENDDO, but some parent located node instead.
// SageInterface::getNextStatement() will not climb out current scope and find a matching end directive attached to a parent node.
//
// For example
// do i = 1, 10
// !$omp task
// call process(item(i))
// !$omp end task
// enddo
// The !$omp end task comments will not be attached before ENDDO , but inside SgBasicBlock, which is an ancestor node
if (SageInterface::is_Fortran_language() )
{
// try to climb up one statement level, until reaching the function body
SgStatement* parent_stmt = getEnclosingStatement(prev_stmt->get_parent());
// getNextStatement() cannot take SgFortranDo's body as input (the body is not a child of its scope's declaration list)
// So we climb up to the parent do loop
if (isSgFortranDo(parent_stmt->get_parent()))
parent_stmt = isSgFortranDo(parent_stmt->get_parent());
else if (isSgWhileStmt(parent_stmt->get_parent()))
parent_stmt = isSgWhileStmt(parent_stmt->get_parent());
if (parent_stmt != func_body)
next_stmt = getNextStatement (parent_stmt);
}
#endif
} // end while
// mandatory end directives for most begin directives, except for two cases:
// !$omp end do
// !$omp end parallel do
if (end_decl == NULL)
{
if ((end_omp_type!=e_end_do) && (end_omp_type!=e_end_parallel_do))
{
cerr<<"merge_Matching_Fortran_Pragma_pairs(): cannot find required end directive for: "<< endl;
cerr<<decl->get_pragma()->get_pragma()<<endl;
ROSE_ASSERT (false);
}
else
return; // There is nothing further to do if the optional end directives do not exist
} // end if sanity check
// at this point, we have found a matching end directive/pragma
ROSE_ASSERT (end_decl);
ensureSingleStmtOrBasicBlock(decl, affected_stmts);
mergeEndClausesToBeginDirective (decl,end_decl);
// SgBasicBlock is not unparsed in Fortran
//
// To ensure the unparsed Fortran code is correct for debugging -rose:openmp:ast_only
// after converting Fortran comments to Pragmas.
// x. We should not tweak the original text for the pragmas.
// x. We should not remove the end pragma declaration since SgBasicBlock is not unparsed.
// In the end , the pragmas don't matter too much, the OmpAttributes attached to them
// are used to guide translations.
removeStatement(end_decl);
// we should save those useless end pragmas to a list
// and remove them as one of the first steps in OpenMP lowering for Fortran
// omp_end_pragma_list.push_back(end_decl);
} // end merge_Matching_Fortran_Pragma_pairs()
//! This function will
// x. Find matching OpenMP directive pairs
// an inside out order is used to handle nested regions
// x. Put statements in between into a basic block
// x. Merge clauses from the ending directive to the beginning directives
// The result is an Fortran OpenMP AST with C/C++ pragmas
// so we can simply reuse convert_OpenMP_pragma_to_AST() to generate
// OpenMP AST nodes for Fortran programs
void convert_Fortran_Pragma_Pairs (SgSourceFile *sageFilePtr)
{
ROSE_ASSERT (sageFilePtr != NULL);
list<SgPragmaDeclaration* >::reverse_iterator iter; // bottom up handling for nested cases
for (iter = omp_pragma_list.rbegin(); iter != omp_pragma_list.rend(); iter ++)
{
// It is possible that several source files showing up in a single compilation line
// We have to check if the pragma declaration's file information matches the current file being processed
// Otherwise we will process the same pragma declaration multiple times!!
SgPragmaDeclaration* decl = *iter;
// Some pragmas are set to "transformation generated" when we fix scopes for some pragma under single statement block
// e.g if ()
// #pragma
// do_sth()
// will be changed to
// if ()
// {
// #pragma
// do_sth()
// }
// So we process a pragma if it is either within the same file or marked as transformation
if (decl->get_file_info()->get_filename()!= sageFilePtr->get_file_info()->get_filename()
&& !(decl->get_file_info()->isTransformation()))
continue;
omp_construct_enum omp_type = getOmpConstructEnum(decl);
#if 0
// skip if the construct is Fortran end directive of any kinds
// since we always start the conversion from a begin directive
if (isFortranEndDirective(omp_type))
continue;
#endif
// Now we
if (isFortranBeginDirective(omp_type))
merge_Matching_Fortran_Pragma_pairs (decl, omp_type);
} // end for omp_pragma_list
} // end convert_Fortran_Pragma_Pairs()
//! Convert OpenMP Fortran comments to pragmas
// main purpose is to
// x. Generate pragmas from OmpAttributes and insert them into the right places
// since the floating comments are very difficult to work with
// we move them to the fake pragmas to ease later translations.
// The backend has been extended to unparse the pragma in order to debug this step.
// x. Enclose affected Fortran statement into a basic block
// x. Merge clauses from END directives to the begin directive
// This will temporarily introduce C/C++-like AST with pragmas attaching OmpAttributes.
// This should be fine since we have SgBasicBlock in Fortran AST also.
//
// The benefit is that pragma-to-AST conversion written for C/C++ can
// be reused for Fortran after this pass.
// Liao 10/18/2010
void convert_Fortran_OMP_Comments_to_Pragmas (SgSourceFile *sageFilePtr)
{
// We reuse the pragma list for C/C++ here
//ROSE_ASSERT (omp_pragma_list.size() ==0);
ROSE_ASSERT (sageFilePtr != NULL);
// step 1: Each OmpAttribute will have a dedicated SgPragmaDeclaration for it
list <OmpAttribute *>::iterator iter;
for (iter = omp_comment_list.begin(); iter != omp_comment_list.end(); iter ++)
{
OmpAttribute * att = *iter;
ROSE_ASSERT (att->getNode() !=NULL);
ROSE_ASSERT (att->getPreprocessingInfo() !=NULL);
//cout<<"debug omp attribute @"<<att<<endl;
SgStatement* stmt = isSgStatement(att->getNode());
// TODO verify this assertion is true for Fortran OpenMP comments
ROSE_ASSERT (stmt != NULL);
//cout<<"debug at ompAstConstruction.cpp:"<<stmt <<" " << stmt->getAttachedPreprocessingInfo ()->size() <<endl;
ROSE_ASSERT (stmt->getAttachedPreprocessingInfo ()->size() != 0);
// So we process the directive if it's anchor node is either within the same file or marked as transformation
if (stmt->get_file_info()->get_filename()!= sageFilePtr->get_file_info()->get_filename()
&& !(stmt->get_file_info()->isTransformation()))
continue;
SgScopeStatement * scope = stmt->get_scope();
ROSE_ASSERT (scope != NULL);
// the pragma will have string to ease debugging
string p_name = att->toOpenMPString();
SgPragmaDeclaration * p_decl = buildPragmaDeclaration("omp "+ p_name, scope);
//preserve the original source file info ,TODO complex cases , use real preprocessing info's line information !!
copyStartFileInfo (att->getNode(), p_decl, att);
omp_pragma_list.push_back(p_decl);
// move the attribute to the pragma
// remove the attribute from the original statement 's OmpAttributeList
removeOmpAttribute(att, stmt);
//cout<<"debug at after removeOmpAttribute:"<<stmt <<" " << stmt->getAttachedPreprocessingInfo ()->size() <<endl;
// remove the getPreprocessingInfo also
PreprocessingInfo* info = att->getPreprocessingInfo();
ROSE_ASSERT (info != NULL);
// We still keep the peprocessingInfo. its line number will be used later to set file info object
//att->setPreprocessingInfo(NULL);// set this as if the OmpAttribute was from a pragma, not from a comment
AttachedPreprocessingInfoType *comments = stmt ->getAttachedPreprocessingInfo ();
ROSE_ASSERT (comments != NULL);
ROSE_ASSERT (comments->size() !=0);
AttachedPreprocessingInfoType::iterator m_pos = find (comments->begin(), comments->end(), info);
if (m_pos == comments->end())
{
cerr<<"Cannot find a Fortran comment from a node: "<<endl;
cerr<<"The comment is "<<info->getString()<<endl;
cerr<<"The AST Node is "<<stmt->class_name()<<endl;
stmt->get_file_info()->display("debug here");
AttachedPreprocessingInfoType::iterator i;
for (i = comments->begin(); i!= comments->end(); i++)
{
cerr<<(*i)->getString()<<endl;
}
//cerr<<"The AST Node is at line:"<<stmt->get_file_info().get_line()<<endl;
ROSE_ASSERT (m_pos != comments->end());
}
comments->erase (m_pos);
att->setNode(p_decl);
addOmpAttribute(att, p_decl);
//cout<<"debug at after addOmpAttribute:"<<stmt <<" " << stmt->getAttachedPreprocessingInfo ()->size() <<endl;
// two cases for where to insert the pragma, depending on where the preprocessing info is attached to stmt
// 1. PreprocessingInfo::before
// insert the pragma right before the original Fortran statement
// 2. PreprocessingInfo::inside
// insert it as the last statement within stmt
PreprocessingInfo::RelativePositionType position = info->getRelativePosition ();
if (position == PreprocessingInfo::before)
{
// Don't automatically move comments here!
if (isSgBasicBlock(stmt) && isSgFortranDo (stmt->get_parent()))
{// special handling for the body of SgFortranDo. The comments will be attached before the body
// But we cannot insert the pragma before the body. So we prepend it into the body instead
prependStatement(p_decl, isSgBasicBlock(stmt));
}
else
insertStatementBefore (stmt, p_decl, false);
}
else if (position == PreprocessingInfo::inside)
{
SgScopeStatement* scope = isSgScopeStatement(stmt);
ROSE_ASSERT (scope != NULL);
appendStatement(p_decl, scope);
}
else if (position == PreprocessingInfo::after)
{
insertStatementAfter(stmt, p_decl, false);
}
else
{
cerr<<"ompAstConstruction.cpp , illegal PreprocessingInfo::RelativePositionType:"<<position<<endl;
ROSE_ASSERT (false);
}
//cout<<"debug at after appendStmt:"<<stmt <<" " << stmt->getAttachedPreprocessingInfo ()->size() <<endl;
} // end for omp_comment_list
convert_Fortran_Pragma_Pairs(sageFilePtr);
} // end convert_Fortran_OMP_Comments_to_Pragmas ()
void build_OpenMP_AST(SgSourceFile *sageFilePtr)
{
// build AST for OpenMP directives and clauses
// by converting OmpAttributeList to SgOmpxxx Nodes
if (sageFilePtr->get_Fortran_only()||sageFilePtr->get_F77_only()||sageFilePtr->get_F90_only()||
sageFilePtr->get_F95_only() || sageFilePtr->get_F2003_only())
{
convert_Fortran_OMP_Comments_to_Pragmas (sageFilePtr);
// end if (fortran)
}
else
{
// for C/C++ pragma's OmpAttributeList --> SgOmpxxx nodes
if (SgProject::get_verbose() > 1)
{
printf ("Calling convert_OpenMP_pragma_to_AST() \n");
}
}
// We can turn this off to debug the convert_Fortran_OMP_Comments_to_Pragmas()
convert_OpenMP_pragma_to_AST( sageFilePtr);
}
// Liao, 5/31/2009 an entry point for OpenMP related processing
// including parsing, AST construction, and later on translation
void processOpenMP(SgSourceFile *sageFilePtr)
{
// DQ (4/4/2010): This function processes both C/C++ and Fortran code.
// As a result of the Fortran processing some OMP pragmas will cause
// transformation (e.g. declaration of private variables will add variables
// to the local scope). So this function has side-effects for all languages.
if (SgProject::get_verbose() > 1)
{
printf ("Processing OpenMP directives \n");
}
ROSE_ASSERT(sageFilePtr != NULL);
if (sageFilePtr->get_openmp() == false)
{
if (SgProject::get_verbose() > 1)
{
printf ("Skipping calls to lower OpenMP sageFilePtr->get_openmp() = %s \n",sageFilePtr->get_openmp() ? "true" : "false");
}
return;
}
// parse OpenMP directives and attach OmpAttributeList to relevant SgNode
attachOmpAttributeInfo(sageFilePtr);
// stop here if only OpenMP parsing is requested
if (sageFilePtr->get_openmp_parse_only())
{
if (SgProject::get_verbose() > 1)
{
printf ("Skipping calls to lower OpenMP sageFilePtr->get_openmp_parse_only() = %s \n",sageFilePtr->get_openmp_parse_only() ? "true" : "false");
}
return;
}
// Build OpenMP AST nodes based on parsing results
build_OpenMP_AST(sageFilePtr);
// stop here if only OpenMP AST construction is requested
if (sageFilePtr->get_openmp_ast_only())
{
if (SgProject::get_verbose() > 1)
{
printf ("Skipping calls to lower OpenMP sageFilePtr->get_openmp_ast_only() = %s \n",sageFilePtr->get_openmp_ast_only() ? "true" : "false");
}
return;
}
lower_omp(sageFilePtr);
}
} // end of the namespace
| 39.884287 | 167 | 0.636265 | [
"object",
"vector"
] |
3cd8ce894e1410e7eb1129640fbc7a288355108c | 6,014 | cpp | C++ | GLEANKernel/GLEANLib/Architecture Classes/High_Level_processor.cpp | dekieras/GLEANKernel | fac01f025b65273be96c5ea677c0ce192c570799 | [
"MIT"
] | 1 | 2018-06-22T23:01:13.000Z | 2018-06-22T23:01:13.000Z | GLEANKernel/GLEANLib/Architecture Classes/High_Level_processor.cpp | dekieras/GLEANKernel | fac01f025b65273be96c5ea677c0ce192c570799 | [
"MIT"
] | null | null | null | GLEANKernel/GLEANLib/Architecture Classes/High_Level_processor.cpp | dekieras/GLEANKernel | fac01f025b65273be96c5ea677c0ce192c570799 | [
"MIT"
] | null | null | null | #include "High_Level_processor.h"
#include "Coordinator.h"
#include "Vocal_event_types.h"
#include "Device_event_types.h"
#include "Cognitive_event_types.h"
#include "Human_processor.h"
#include "Syllable_counter.h"
#include "Numeric_utilities.h"
#include "Output_tee.h"
#include "Output_tee_globals.h"
#include "Glean_exceptions.h"
#include <iostream>
using namespace std;
const long Get_device_delay_c = 1000; // time delay for a Get_from_device
const long Put_device_delay_c = 1000; // time delay for a Put_to_device
const long input_store_time_c = 900; // time delay to store input
const long input_delay_time_c = 100; // additional time for operation to be complete
void High_Level_processor::initialize()
{
waiting_for_object = false;
Object_Memory_Processor::initialize();
}
void High_Level_processor::display_object_info(Output_tee& ot) const
{
Object_Memory_Processor::display_object_info(ot, "High_Level Memory");
}
void High_Level_processor::accept_event(const High_Level_event * event_ptr)
{
broadcast_to_recorders(event_ptr);
event_ptr->handle_self(this);
}
void High_Level_processor::handle_event(const High_Level_Put_Command * event_ptr)
{
long completion_time = get_time() + Put_device_delay_c;
// // time less one to align with next cognitive cycle.
if ((completion_time % 50) == 0)
completion_time--;
if(Trace_out && get_trace()) {
Trace_out << processor_info() << " High-level Put_to_device at time " << completion_time << ":" << endl;
Symbol_list_t::const_iterator pit = event_ptr->props.begin();
Symbol_list_t::const_iterator vit = event_ptr->values.begin();
for(; pit != event_ptr->props.end() && vit != event_ptr->values.end(); ++pit, ++vit) {
if(pit != event_ptr->props.begin())
Trace_out << ", ";
Trace_out << *pit << " is " << *vit;
}
Trace_out << endl;
}
// send the event at the completion time to the device
Event * output_event_ptr = new Device_HLPut_event(completion_time, get_human_ptr()->get_device_ptr(),
event_ptr->props, event_ptr->values);
Coordinator::get_instance().schedule_event(output_event_ptr);
send_operation_complete(completion_time);
}
// send a request to the device to supply some input, and wait for a response.
//
// the first High_Level_Get_Input_event is taken to satisfy the request
void High_Level_processor::handle_event(const High_Level_Get_Command * event_ptr)
{
long completion_time = get_time() + Get_device_delay_c;
// time less one to align with next cognitive cycle.
if ((completion_time % 50) == 0)
completion_time--;
if(Trace_out && get_trace()) {
Trace_out << processor_info() << " High-level Get_from_device at time " << completion_time << ":" << endl;
Symbol_list_t::const_iterator pit = event_ptr->props.begin();
Symbol_list_t::const_iterator vit = event_ptr->values.begin();
for(; pit != event_ptr->props.end() && vit != event_ptr->values.end(); ++pit, ++vit) {
if(pit != event_ptr->props.begin())
Trace_out << ", ";
Trace_out << *pit << " is " << *vit;
}
Trace_out << endl;
}
// send the event at the completion time to the device
Event * output_event_ptr = new Device_HLGet_event(completion_time, get_human_ptr()->get_device_ptr(),
event_ptr->props, event_ptr->values, event_ptr->tag);
Coordinator::get_instance().schedule_event(output_event_ptr);
waiting_for_object = true;
// send_acknowledgement(completion_time);
}
// the input that arrives is used to update the object memory and the tag store, and then
// the operation is deemed complete
void High_Level_processor::handle_event(const High_Level_Input_event * event_ptr)
{
if(Trace_out && get_trace()) {
Trace_out << processor_info() << " High_Level device information arrived for " << event_ptr->object_name << ":" << endl;
Symbol_list_t::const_iterator pit = event_ptr->props.begin();
Symbol_list_t::const_iterator vit = event_ptr->values.begin();
for(;pit != event_ptr->props.end() && vit != event_ptr->values.end(); ++pit, ++vit)
Trace_out << *pit << " is " << *vit << ", ";
Trace_out << "and_store_under " << event_ptr->tag << endl;
}
if(!waiting_for_object)
throw Glean_exception(this, "Unexpected High_Level_Input_event arrived");
// store the info
store(event_ptr->object_name, event_ptr->props, event_ptr->values);
// all objects are in focus
store(event_ptr->object_name, Status_c, In_focus_c);
// // assume a constant store time per property
// long total_time = get_time() + input_property_store_time_c * long(event_ptr->values.size());
// ensure that stores arrive before the operation is considered complete
long total_time = get_time() + input_store_time_c;
// time less one to align with next cognitive cycle.
if ((total_time % 50) == 0)
total_time--;
store_WM_object(event_ptr->object_name, total_time);
store_WM_object_under_tag(event_ptr->object_name, event_ptr->tag,total_time);
// operation required its total time plus some extra to make sure WM objects have been updated
send_operation_complete(total_time + input_delay_time_c);
// display_contents(Normal_out);
}
// the input that arrives is used to update the object memory and the tag store, and then
// the operation is deemed complete
void High_Level_processor::handle_event(const High_Level_Erase_event * event_ptr)
{
if(Trace_out && get_trace())
Trace_out << processor_info() << " High_Level Erase from device of " << event_ptr->object_name << endl;
// erase the object
erase(event_ptr->object_name);
erase_WM_object(event_ptr->object_name, get_time());
long total_time = get_time() + input_store_time_c;
// operation required its total time to make sure WM objects have been updated
send_operation_complete(total_time + input_delay_time_c);
// display_contents(Normal_out);
}
void High_Level_processor::send_operation_complete(int completion_time)
{
Event * event_ptr = new Cognitive_High_Level_Operation_Complete_event (completion_time, get_human_ptr()->get_cognitive_ptr());
Coordinator::get_instance().schedule_event(event_ptr);
}
| 37.123457 | 127 | 0.742933 | [
"object"
] |
3cdcb9c3a5d3beb7b730189bda4cc1296221eeb4 | 10,652 | cpp | C++ | interface/src/raypick/StylusPointer.cpp | parkerchard/hifi | ae348babe4624bbce4151c9d84fa9cbeedf2c0eb | [
"Apache-2.0"
] | 1 | 2019-07-08T06:54:01.000Z | 2019-07-08T06:54:01.000Z | interface/src/raypick/StylusPointer.cpp | parkerchard/hifi | ae348babe4624bbce4151c9d84fa9cbeedf2c0eb | [
"Apache-2.0"
] | null | null | null | interface/src/raypick/StylusPointer.cpp | parkerchard/hifi | ae348babe4624bbce4151c9d84fa9cbeedf2c0eb | [
"Apache-2.0"
] | 2 | 2019-06-13T22:25:13.000Z | 2022-01-31T15:17:55.000Z | //
// Created by Bradley Austin Davis on 2017/10/24
// Copyright 2013-2017 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 "StylusPointer.h"
#include "RayPick.h"
#include "Application.h"
#include "avatar/AvatarManager.h"
#include "avatar/MyAvatar.h"
#include <DependencyManager.h>
#include "PickScriptingInterface.h"
#include <PickManager.h>
static const float TABLET_MIN_HOVER_DISTANCE = -0.1f;
static const float TABLET_MAX_HOVER_DISTANCE = 0.1f;
static const float TABLET_MIN_TOUCH_DISTANCE = -0.1f;
static const float TABLET_MAX_TOUCH_DISTANCE = 0.005f;
static const float HOVER_HYSTERESIS = 0.01f;
static const float TOUCH_HYSTERESIS = 0.001f;
static const QString DEFAULT_STYLUS_MODEL_URL = PathUtils::resourcesUrl() + "/meshes/tablet-stylus-fat.fbx";
StylusPointer::StylusPointer(const QVariant& props, const QUuid& stylus, bool hover, bool enabled,
const glm::vec3& modelPositionOffset, const glm::quat& modelRotationOffset, const glm::vec3& modelDimensions) :
Pointer(DependencyManager::get<PickScriptingInterface>()->createStylusPick(props), enabled, hover),
_stylus(stylus),
_modelPositionOffset(modelPositionOffset),
_modelDimensions(modelDimensions),
_modelRotationOffset(modelRotationOffset)
{
}
StylusPointer::~StylusPointer() {
if (!_stylus.isNull()) {
DependencyManager::get<EntityScriptingInterface>()->deleteEntity(_stylus);
}
}
QUuid StylusPointer::buildStylus(const QVariantMap& properties) {
// FIXME: we have to keep using the Overlays interface here, because existing scripts use overlay properties to define pointers
QVariantMap propertiesMap;
QString modelUrl = DEFAULT_STYLUS_MODEL_URL;
if (properties["model"].isValid()) {
QVariantMap modelData = properties["model"].toMap();
if (modelData["url"].isValid()) {
modelUrl = modelData["url"].toString();
}
}
// TODO: make these configurable per pointer
propertiesMap["name"] = "stylus";
propertiesMap["url"] = modelUrl;
propertiesMap["loadPriority"] = 10.0f;
propertiesMap["solid"] = true;
propertiesMap["visible"] = false;
propertiesMap["ignorePickIntersection"] = true;
propertiesMap["drawInFront"] = false;
return qApp->getOverlays().addOverlay("model", propertiesMap);
}
void StylusPointer::updateVisuals(const PickResultPointer& pickResult) {
auto stylusPickResult = std::static_pointer_cast<const StylusPickResult>(pickResult);
if (_enabled && !qApp->getPreferAvatarFingerOverStylus() && _renderState != DISABLED && stylusPickResult) {
StylusTip tip(stylusPickResult->pickVariant);
if (tip.side != bilateral::Side::Invalid) {
show(tip);
return;
}
}
if (_showing) {
hide();
}
}
void StylusPointer::show(const StylusTip& tip) {
if (!_stylus.isNull()) {
auto modelOrientation = tip.orientation * _modelRotationOffset;
auto sensorToWorldScale = DependencyManager::get<AvatarManager>()->getMyAvatar()->getSensorToWorldScale();
auto modelPositionOffset = modelOrientation * (_modelPositionOffset * sensorToWorldScale);
EntityItemProperties properties;
properties.setPosition(tip.position + modelPositionOffset);
properties.setRotation(modelOrientation);
properties.setDimensions(sensorToWorldScale * _modelDimensions);
properties.setVisible(true);
DependencyManager::get<EntityScriptingInterface>()->editEntity(_stylus, properties);
}
_showing = true;
}
void StylusPointer::hide() {
if (!_stylus.isNull()) {
EntityItemProperties properties;
properties.setVisible(false);
DependencyManager::get<EntityScriptingInterface>()->editEntity(_stylus, properties);
}
_showing = false;
}
bool StylusPointer::shouldHover(const PickResultPointer& pickResult) {
auto stylusPickResult = std::static_pointer_cast<const StylusPickResult>(pickResult);
if (_renderState == EVENTS_ON && stylusPickResult && stylusPickResult->intersects) {
auto sensorScaleFactor = DependencyManager::get<AvatarManager>()->getMyAvatar()->getSensorToWorldScale();
float hysteresis = _state.hovering ? HOVER_HYSTERESIS * sensorScaleFactor : 0.0f;
bool hovering = isWithinBounds(stylusPickResult->distance, TABLET_MIN_HOVER_DISTANCE * sensorScaleFactor,
TABLET_MAX_HOVER_DISTANCE * sensorScaleFactor, hysteresis);
_state.hovering = hovering;
return hovering;
}
_state.hovering = false;
return false;
}
bool StylusPointer::shouldTrigger(const PickResultPointer& pickResult) {
auto stylusPickResult = std::static_pointer_cast<const StylusPickResult>(pickResult);
bool wasTriggering = false;
if (_renderState == EVENTS_ON && stylusPickResult) {
auto sensorScaleFactor = DependencyManager::get<AvatarManager>()->getMyAvatar()->getSensorToWorldScale();
float distance = stylusPickResult->distance;
// If we're triggering on an object, recalculate the distance instead of using the pickResult
glm::vec3 origin = vec3FromVariant(stylusPickResult->pickVariant["position"]);
glm::vec3 direction = _state.triggering ? -_state.surfaceNormal : -stylusPickResult->surfaceNormal;
if ((_state.triggering || _state.wasTriggering) && stylusPickResult->objectID != _state.triggeredObject.objectID) {
distance = glm::dot(findIntersection(_state.triggeredObject, origin, direction) - origin, direction);
}
float hysteresis = _state.triggering ? TOUCH_HYSTERESIS * sensorScaleFactor : 0.0f;
if (isWithinBounds(distance, TABLET_MIN_TOUCH_DISTANCE * sensorScaleFactor,
TABLET_MAX_TOUCH_DISTANCE * sensorScaleFactor, hysteresis)) {
_state.wasTriggering = _state.triggering;
if (!_state.triggering) {
_state.triggeredObject = PickedObject(stylusPickResult->objectID, stylusPickResult->type);
_state.intersection = stylusPickResult->intersection;
_state.triggerPos2D = findPos2D(_state.triggeredObject, origin);
_state.triggerStartTime = usecTimestampNow();
_state.surfaceNormal = stylusPickResult->surfaceNormal;
_state.deadspotExpired = false;
_state.triggering = true;
}
return true;
}
wasTriggering = _state.triggering;
}
_state.wasTriggering = wasTriggering;
_state.triggering = false;
return false;
}
PickResultPointer StylusPointer::getPickResultCopy(const PickResultPointer& pickResult) const {
auto stylusPickResult = std::dynamic_pointer_cast<StylusPickResult>(pickResult);
if (!stylusPickResult) {
return std::make_shared<StylusPickResult>();
}
return std::make_shared<StylusPickResult>(*stylusPickResult.get());
}
Pointer::PickedObject StylusPointer::getHoveredObject(const PickResultPointer& pickResult) {
auto stylusPickResult = std::static_pointer_cast<const StylusPickResult>(pickResult);
if (!stylusPickResult) {
return PickedObject();
}
return PickedObject(stylusPickResult->objectID, stylusPickResult->type);
}
Pointer::Buttons StylusPointer::getPressedButtons(const PickResultPointer& pickResult) {
// TODO: custom buttons for styluses
Pointer::Buttons toReturn({ "Primary", "Focus" });
return toReturn;
}
PointerEvent StylusPointer::buildPointerEvent(const PickedObject& target, const PickResultPointer& pickResult, const std::string& button, bool hover) {
QUuid pickedID;
glm::vec2 pos2D;
glm::vec3 intersection, surfaceNormal, direction, origin;
auto stylusPickResult = std::static_pointer_cast<StylusPickResult>(pickResult);
if (stylusPickResult) {
intersection = stylusPickResult->intersection;
surfaceNormal = hover ? stylusPickResult->surfaceNormal : _state.surfaceNormal;
const QVariantMap& stylusTip = stylusPickResult->pickVariant;
origin = vec3FromVariant(stylusTip["position"]);
direction = -surfaceNormal;
pos2D = findPos2D(target, origin);
pickedID = stylusPickResult->objectID;
}
// If we just started triggering and we haven't moved too much, don't update intersection and pos2D
float sensorToWorldScale = DependencyManager::get<AvatarManager>()->getMyAvatar()->getSensorToWorldScale();
float deadspotSquared = TOUCH_PRESS_TO_MOVE_DEADSPOT_SQUARED * sensorToWorldScale * sensorToWorldScale;
bool withinDeadspot = usecTimestampNow() - _state.triggerStartTime < POINTER_MOVE_DELAY && glm::distance2(pos2D, _state.triggerPos2D) < deadspotSquared;
if ((_state.triggering || _state.wasTriggering) && !_state.deadspotExpired && withinDeadspot) {
pos2D = _state.triggerPos2D;
intersection = _state.intersection;
} else if (pickedID != target.objectID) {
intersection = findIntersection(target, origin, direction);
}
if (!withinDeadspot) {
_state.deadspotExpired = true;
}
return PointerEvent(pos2D, intersection, surfaceNormal, direction);
}
bool StylusPointer::isWithinBounds(float distance, float min, float max, float hysteresis) {
return (distance == glm::clamp(distance, min - hysteresis, max + hysteresis));
}
void StylusPointer::setRenderState(const std::string& state) {
if (state == "events on") {
_renderState = EVENTS_ON;
} else if (state == "events off") {
_renderState = EVENTS_OFF;
} else if (state == "disabled") {
_renderState = DISABLED;
}
}
QVariantMap StylusPointer::toVariantMap() const {
return QVariantMap();
}
glm::vec3 StylusPointer::findIntersection(const PickedObject& pickedObject, const glm::vec3& origin, const glm::vec3& direction) {
switch (pickedObject.type) {
case ENTITY:
case LOCAL_ENTITY:
return RayPick::intersectRayWithEntityXYPlane(pickedObject.objectID, origin, direction);
default:
return glm::vec3(NAN);
}
}
glm::vec2 StylusPointer::findPos2D(const PickedObject& pickedObject, const glm::vec3& origin) {
switch (pickedObject.type) {
case ENTITY:
case LOCAL_ENTITY:
return RayPick::projectOntoEntityXYPlane(pickedObject.objectID, origin);
case HUD:
return DependencyManager::get<PickManager>()->calculatePos2DFromHUD(origin);
default:
return glm::vec2(NAN);
}
}
| 41.609375 | 156 | 0.707191 | [
"object",
"model",
"solid"
] |
c9e3e2b2b4bf772194167157f55c6dcbc584741e | 5,216 | cpp | C++ | Classes/AppDelegate.cpp | funkyzooink/fresh-engine | de15fa6ebe1b686819b28cd92ee8a6771c4ff878 | [
"MIT"
] | 3 | 2019-10-09T09:17:49.000Z | 2022-03-02T17:57:05.000Z | Classes/AppDelegate.cpp | funkyzooink/fresh-engine | de15fa6ebe1b686819b28cd92ee8a6771c4ff878 | [
"MIT"
] | 33 | 2019-10-08T18:45:48.000Z | 2022-01-05T21:53:02.000Z | Classes/AppDelegate.cpp | funkyzooink/fresh-engine | de15fa6ebe1b686819b28cd92ee8a6771c4ff878 | [
"MIT"
] | 7 | 2019-10-10T11:31:58.000Z | 2021-02-08T14:24:30.000Z | #include "AppDelegate.h"
#include "GameData/Constants.h"
#include "GameData/GameConfig.h"
#include "Helpers/AudioPlayer.h"
#include "Helpers/Localization.h"
#include "Scenes/BootScene.h"
#include "Scenes/GameScene.h"
USING_NS_CC;
AppDelegate::AppDelegate()
{
}
AppDelegate::~AppDelegate()
{
#if USE_AUDIO_ENGINE
AudioEngine::end();
#elif USE_SIMPLE_AUDIO_ENGINE
SimpleAudioEngine::end();
#endif
}
// if you want a different context, modify the value of glContextAttrs
// it will affect all platforms
void AppDelegate::initGLContextAttrs()
{
// set OpenGL context attributes:
// red,green,blue,alpha,depth,stencil,multisamplesCount
GLContextAttrs glContextAttrs = { 8, 8, 8, 8, 24, 8, 0 };
GLView::setGLContextAttrs(glContextAttrs);
}
bool AppDelegate::applicationDidFinishLaunching()
{
// initialize director
auto director = Director::getInstance();
auto title = Localization::getLocalizedString(GAMECONFIG.getMainSceneConfig()->title);
auto glview = director->getOpenGLView();
if (!glview)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || \
(CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
glview = GLViewImpl::createWithFullScreen(title); //, cocos2d::Rect(0, 0, designResolution.width,
// designResolution.height));
#else
glview = GLViewImpl::create(title);
#endif
director->setOpenGLView(glview);
}
auto resolutions = GAMECONFIG.getSpriteResolutions();
cocos2d::Size designResolution;
std::string tileSizeIdentifier = "";
auto orientation = GAMECONFIG.getDeviceOrientation();
ResolutionPolicy policy = ResolutionPolicy::FIXED_HEIGHT;
auto visibleSize = Director::getInstance()->getVisibleSize().width;
if (orientation == "portrait")
{
visibleSize = Director::getInstance()->getVisibleSize().height;
policy = ResolutionPolicy::FIXED_WIDTH;
}
for (auto const& resolution : resolutions)
{
// set to current resolution
designResolution = resolution.size;
tileSizeIdentifier = resolution.tileMapIdentifier;
auto resolutionCompareSize = resolution.size.width;
if (orientation == "portrait")
{
resolutionCompareSize = resolution.size.height;
}
if (visibleSize > resolutionCompareSize * 1.2) // if bigger than
// current resolution then
// continue loop to use next
{
continue;
}
else // otherwise abort loop
{
break;
}
}
// turn on display FPS
// director->setDisplayStats(true);
// set FPS. the default value is 1.0/60 if you don't call this
director->setAnimationInterval(1.0F / 60);
glview->setDesignResolutionSize(designResolution.width * 0.9, designResolution.height * 0.9, policy);
FileUtils::getInstance()->addSearchResolutionsOrder("img/" + tileSizeIdentifier);
CONSTANTS.setTileSizeIdentifier(tileSizeIdentifier);
// create a scene. it's an autorelease object
auto scene = BootScene::createScene();
// run
director->runWithScene(scene);
return true;
}
// This function will be called when the app is inactive. Note, when receiving a
// phone call it is invoked.
void AppDelegate::applicationDidEnterBackground()
{
Director::getInstance()->stopAnimation();
Scene* scene = Director::getInstance()->getRunningScene();
if (dynamic_cast<GameScene*>(scene->getChildByTag(998)) != nullptr)
{
GameScene* gameScene = dynamic_cast<GameScene*>(scene->getChildByTag(998));
gameScene->applicationDidEnterBackground();
}
AudioPlayer::pauseMusic();
}
// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground()
{
Director::getInstance()->startAnimation();
AudioPlayer::resumeMusic();
}
void AppDelegate::applicationScreenSizeChanged(int newWidth, int newHeight)
{
// TODO do we want apps that have both, landscape and portrait?
// auto director = Director::getInstance();
// auto glview = director->getOpenGLView();
// if (glview)
// {
// auto size = glview->getFrameSize();
// if (size.equals(Size(newWidth, newHeight)))
// return;
//
// glview->setFrameSize(newWidth, newHeight);
//
// ResolutionPolicy resolutionPolicy = glview->getResolutionPolicy();
// if (size.width < newWidth)
// { // switch to landscape
// resolutionPolicy = ResolutionPolicy::FIXED_HEIGHT;
// }
// else
// { // switch to portrait
// resolutionPolicy = ResolutionPolicy::FIXED_WIDTH;
// }
//
// glview->setDesignResolutionSize(newWidth, newHeight, resolutionPolicy);
// }
}
| 32.397516 | 121 | 0.619057 | [
"object"
] |
c9ebb52f13ae6055c88e8fedecaec365684cdf2d | 2,408 | cc | C++ | src/0349_intersection_of_two_arrays/intersection_of_two_arrays.cc | youngqqcn/LeetCodeNodes | 62bbd30fbdf1640526d7fc4437cde1b05d67fc8f | [
"MIT"
] | 1 | 2021-05-23T02:15:03.000Z | 2021-05-23T02:15:03.000Z | src/0349_intersection_of_two_arrays/intersection_of_two_arrays.cc | youngqqcn/LeetCodeNotes | 62bbd30fbdf1640526d7fc4437cde1b05d67fc8f | [
"MIT"
] | null | null | null | src/0349_intersection_of_two_arrays/intersection_of_two_arrays.cc | youngqqcn/LeetCodeNotes | 62bbd30fbdf1640526d7fc4437cde1b05d67fc8f | [
"MIT"
] | null | null | null | // author: yqq
// date: 2021-07-30 14:11:28
// descriptions: https://leetcode-cn.com/problems/intersection-of-two-arrays
#include <bits/stdc++.h>
#include <iostream>
#include <numeric>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <queue>
#include <stack>
#include <unordered_set>
#include <unordered_map>
#include <string.h>
#include <stdlib.h>
using namespace std;
/*
给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2]
示例 2:
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[9,4]
说明:
输出结果中的每个元素一定是唯一的。
我们可以不考虑输出结果的顺序。
*/
class Solution {
public:
vector<int> intersection_v1(vector<int>& nums1, vector<int>& nums2)
{
set<int> s1(nums1.begin(), nums1.end());
set<int> s2(nums2.begin(), nums2.end());
vector<int> result;
auto last = set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(),
std::inserter(result, result.begin())); // 插入迭代器
return result;
}
vector<int> intersection(vector<int>& nums1, vector<int>& nums2)
{
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end());
vector<int> result;
for(int p1 = 0, p2 = 0; p1 < nums1.size() && p2 < nums2.size(); )
{
if(nums1[p1] == nums2[p2])
{
int value = nums1[p1];
result.push_back(value);
while(p1 < nums1.size() && nums1[p1] == value) { p1++; }
while(p2 < nums2.size() && nums2[p2] == value) { p2++; }
}
else
{
if(nums1[p1] < nums2[p2]) {
p1++;
} else {
p2++;
}
}
}
return result;
}
};
void test(vector<int> nums1, vector<int> nums2, set<int> expected)
{
Solution sol;
auto result = sol.intersection(nums1, nums2);
if(result.size() != expected.size())
{
cout << "FAILED" << endl;
return;
}
for(auto item : result)
{
auto it = expected.find(item);
if(it == expected.end()) {
cout << "FAILED" << endl;
return;
}
expected.erase(it);
}
cout << "PASSED" << endl;
}
int main()
{
test({1,2,2,1}, {2,2}, {2});
test({4,9,5}, {9,4,9,8,4}, {9, 4});
return 0;
}
| 21.5 | 80 | 0.509136 | [
"vector"
] |
c9eeb98e6c3cd47af9c461c5ed19f45b27d36bc7 | 9,250 | cpp | C++ | modules/variants/assemble_test.cpp | spiralgenetics/biograph | 33c78278ce673e885f38435384f9578bfbf9cdb8 | [
"BSD-2-Clause"
] | 16 | 2021-07-14T23:32:31.000Z | 2022-03-24T16:25:15.000Z | modules/variants/assemble_test.cpp | spiralgenetics/biograph | 33c78278ce673e885f38435384f9578bfbf9cdb8 | [
"BSD-2-Clause"
] | 9 | 2021-07-20T20:39:47.000Z | 2021-09-16T20:57:59.000Z | modules/variants/assemble_test.cpp | spiralgenetics/biograph | 33c78278ce673e885f38435384f9578bfbf9cdb8 | [
"BSD-2-Clause"
] | 9 | 2021-07-15T19:38:35.000Z | 2022-01-31T19:24:56.000Z | #include "modules/variants/assemble.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "modules/bio_base/dna_testutil.h"
#include "modules/variants/assemble_testutil.h"
using namespace testing;
using namespace variants;
using namespace dna_testutil;
class merge_test : public Test {
public:
aligned_var av(aoffset_t left_offset, aoffset_t right_offset, dna_sequence seq) {
aligned_var result;
result.left_offset = left_offset;
result.right_offset = right_offset;
result.seq = seq;
return result;
}
assembly_ptr make_assembly(aoffset_t left_offset, aoffset_t right_offset, dna_sequence seq,
std::vector<aligned_var> aligned_vars = {}) {
assembly_ptr a = make_unique<assembly>();
a->left_offset = left_offset;
a->right_offset = right_offset;
a->seq = seq;
a->aligned_variants = aligned_vars;
if (aligned_vars.empty()) {
a->matches_reference = true;
}
return a;
}
void do_merge() { m_result = merge_assemblies(*m_in1, *m_in2); }
protected:
assembly_ptr m_in1;
assembly_ptr m_in2;
assembly_ptr m_result;
};
TEST_F(merge_test, disjoint) {
m_in1 = make_assembly(10, 40, tseq("ABC"));
m_in2 = make_assembly(41, 71, tseq("ABC"));
do_merge();
EXPECT_FALSE(m_result) << *m_result;
}
TEST_F(merge_test, touching) {
m_in1 = make_assembly(10, 40, tseq("ABC"));
m_in2 = make_assembly(40, 70, tseq("DEF"));
do_merge();
ASSERT_TRUE(m_result);
EXPECT_THAT(*m_result, RefAssemblyIs(10, 70));
EXPECT_EQ(m_result->seq, tseq("ABCDEF"));
}
TEST_F(merge_test, bad_overlap) {
// This normally wouldn't happen since they'd both be matching the same reference
m_in1 = make_assembly(10, 40, tseq("ABC"));
m_in2 = make_assembly(30, 60, tseq("DEF"));
do_merge();
EXPECT_FALSE(m_result) << *m_result;
}
TEST_F(merge_test, good_overlap) {
m_in1 = make_assembly(10, 40, tseq("ABC"));
m_in2 = make_assembly(30, 60, tseq("CDE"));
do_merge();
ASSERT_TRUE(m_result);
EXPECT_THAT(*m_result, RefAssemblyIs(10, 60));
EXPECT_EQ(m_result->seq, tseq("ABCDE"));
}
TEST_F(merge_test, whole_overlap) {
m_in1 = make_assembly(10, 40, tseq("ABC"));
m_in2 = make_assembly(10, 40, tseq("ABC"));
do_merge();
ASSERT_TRUE(m_result);
EXPECT_THAT(*m_result, RefAssemblyIs(10, 40));
EXPECT_EQ(m_result->seq, tseq("ABC"));
}
TEST_F(merge_test, whole_overlap_bad) {
m_in1 = make_assembly(10, 40, tseq("ABC"));
m_in2 = make_assembly(10, 40, tseq("AbbC"), {av(20, 30, tseq("bb"))});
do_merge();
EXPECT_FALSE(m_result);
}
TEST_F(merge_test, subsumed_bad) {
m_in1 = make_assembly(10, 40, tseq("ABC"));
m_in2 = make_assembly(20, 30, tseq("D"));
do_merge();
EXPECT_FALSE(m_result) << *m_result;
}
TEST_F(merge_test, subsumed_good) {
m_in1 = make_assembly(10, 40, tseq("ABC"));
m_in2 = make_assembly(20, 30, tseq("B"));
do_merge();
ASSERT_TRUE(m_result);
EXPECT_THAT(*m_result, RefAssemblyIs(10, 40));
EXPECT_EQ(m_result->seq, tseq("ABC"));
}
TEST_F(merge_test, disjoint_vars_good) {
m_in1 = make_assembly(10, 40, tseq("AbbC"), {av(20, 30, tseq("bb"))});
m_in2 = make_assembly(40, 70, tseq("DeeF"), {av(50, 60, tseq("ee"))});
do_merge();
ASSERT_TRUE(m_result);
EXPECT_THAT(*m_result, AssemblyIs(10, tseq("AbbCDeeF"), 70));
EXPECT_THAT(m_result->aligned_variants,
ElementsAre(av(20, 30, tseq("bb")), av(50, 60, tseq("ee"))));
}
TEST_F(merge_test, overlapping_vars_good) {
m_in1 = make_assembly(10, 50, tseq("ABccD"), {av(30, 40, tseq("cc"))});
m_in2 = make_assembly(20, 60, tseq("BccDE"), {av(30, 40, tseq("cc"))});
do_merge();
ASSERT_TRUE(m_result);
EXPECT_THAT(*m_result, AssemblyIs(10, tseq("ABccDE"), 60));
EXPECT_THAT(m_result->aligned_variants, ElementsAre(av(30, 40, tseq("cc"))));
}
TEST_F(merge_test, overlapping_vars_bad) {
m_in1 = make_assembly(10, 50, tseq("ABccD"), {av(30, 40, tseq("cc"))});
m_in2 = make_assembly(20, 60, tseq("BxxDE"), {av(30, 40, tseq("xx"))});
do_merge();
EXPECT_FALSE(m_result) << *m_result;
}
TEST_F(merge_test, subsumed_vars_good) {
m_in1 = make_assembly(10, 80, tseq("AbbCddEffG"),
{av(20, 30, tseq("bb")), av(40, 50, tseq("dd")), av(60, 70, tseq("ff"))});
m_in2 = make_assembly(30, 60, tseq("CddE"), {av(40, 50, tseq("dd"))});
do_merge();
ASSERT_TRUE(m_result);
EXPECT_THAT(*m_result, AssemblyIs(10, tseq("AbbCddEffG"), 80));
EXPECT_THAT(m_result->aligned_variants,
ElementsAre(av(20, 30, tseq("bb")), av(40, 50, tseq("dd")), av(60, 70, tseq("ff"))));
}
TEST_F(merge_test, left_ref) {
m_in1 = make_assembly(10, 40, tseq("ABC"));
m_in2 = make_assembly(30, 60, tseq("CddE"), {av(40, 50, tseq("dd"))});
do_merge();
ASSERT_TRUE(m_result);
EXPECT_THAT(*m_result, AssemblyIs(10, tseq("ABCddE"), 60));
EXPECT_THAT(m_result->aligned_variants, ElementsAre(av(40, 50, tseq("dd"))));
}
TEST_F(merge_test, right_ref) {
m_in1 = make_assembly(10, 40, tseq("AbbC"), {av(20, 30, tseq("bb"))});
m_in2 = make_assembly(30, 60, tseq("CDE"));
do_merge();
ASSERT_TRUE(m_result);
EXPECT_THAT(*m_result, AssemblyIs(10, tseq("AbbCDE"), 60));
EXPECT_THAT(m_result->aligned_variants, ElementsAre(av(20, 30, tseq("bb"))));
}
TEST_F(merge_test, delete_overlap) {
m_in1 = make_assembly(10, 70, tseq("ABF"), {av(30, 60, tseq(""))});
m_in2 = make_assembly(20, 80, tseq("BFG"), {av(30, 60, tseq(""))});
do_merge();
ASSERT_TRUE(m_result);
EXPECT_THAT(*m_result, AssemblyIs(10, tseq("ABFG"), 80));
EXPECT_THAT(m_result->aligned_variants, ElementsAre(av(30, 60, tseq(""))));
}
TEST_F(merge_test, delete_adjacent) {
m_in1 = make_assembly(10, 100, tseq("A"), {av(20, 100, tseq(""))});
m_in2 = make_assembly(100, 200, tseq("H"), {av(100, 190, tseq(""))});
do_merge();
ASSERT_TRUE(m_result);
EXPECT_THAT(*m_result, AssemblyIs(10, tseq("AH"), 200));
EXPECT_THAT(m_result->aligned_variants,
ElementsAre(av(20, 100, tseq("")), av(100, 190, tseq(""))));
}
TEST_F(merge_test, insert_right_adjacent) {
m_in1 = make_assembly(10, 100, tseq("A"), {av(20, 100, tseq(""))});
m_in2 = make_assembly(100, 110, tseq("efgH"), {av(100, 100, tseq("efg"))});
do_merge();
ASSERT_TRUE(m_result);
EXPECT_THAT(*m_result, AssemblyIs(10, tseq("AefgH"), 110));
EXPECT_THAT(m_result->aligned_variants,
ElementsAre(av(20, 100, tseq("")), av(100, 100, tseq("efg"))));
}
TEST_F(merge_test, insert_both_adjacent) {
m_in1 = make_assembly(90, 100, tseq("Abcd"), {av(100, 100, tseq("bcd"))});
m_in2 = make_assembly(100, 110, tseq("efgH"), {av(100, 100, tseq("efg"))});
do_merge();
ASSERT_TRUE(m_result);
EXPECT_THAT(*m_result, AssemblyIs(90, tseq("AbcdefgH"), 110));
EXPECT_THAT(m_result->aligned_variants,
ElementsAre(av(100, 100, tseq("bcd")), av(100, 100, tseq("efg"))));
}
TEST_F(merge_test, insert_left_adjacent) {
m_in1 = make_assembly(90, 100, tseq("Abcd"), {av(100, 100, tseq("bcd"))});
m_in2 = make_assembly(100, 200, tseq("H"), {av(100, 190, tseq(""))});
do_merge();
ASSERT_TRUE(m_result);
EXPECT_THAT(*m_result, AssemblyIs(90, tseq("AbcdH"), 200));
EXPECT_THAT(m_result->aligned_variants,
ElementsAre(av(100, 100, tseq("bcd")), av(100, 190, tseq(""))));
}
// Merges seen in the wild
TEST_F(merge_test, wild1) {
aligned_var v;
m_in1 = make_unique<assembly>();
m_in1->left_offset = 248033565;
m_in1->right_offset = 248033882;
m_in1->seq = dna_sequence(
"CATGCCCAGAAAAATTAGGATTGGTATATTCATGAGCAGTATCAGAGTCACGGCCACCCATAGAGCCTGCACCACCATGCCCAGAAGAACGA"
"GGATTAGTATATTCATGAGCAGTATCAGAGTCACGGCCACCCATAGAGCCTGCACCACCATGCCCAGAAGAACGAGGATTAGTATATTCATG"
"AGCAGTATCAGAGTCACGGCCACCCATAGAGCCTGCACCACCACACCCAGAAGAACGAGGATTAGTATATTCATGAGCAGTATCAGAGTCAC"
"GGCCACCCGTAGAGCCTGCACCACCACGCCCAGAAGAACGAGGATTAGTATATTCATGAGCAGTATCAGAGTCACGGCCACCCATAGAGCCT"
"GCACCACCACGCCCAGAAGAATGAGGATTAGTATATTCATGAGCAGTATCAGAGTCACGGCCACCCATAGAGCCTGCACCACCACACCCAGA"
"AGAACGAGGATTAGTATATTCATGAGCAGTATCAGAGTCACGGCCACCCATAGAGCCTGCACCACCACGCCCAGAAGAACGA");
v.left_offset = 248033717;
v.right_offset = 248033718;
v.seq = dna_sequence("T");
m_in1->aligned_variants.push_back(v);
v.left_offset = 248033730;
v.right_offset = 248033730;
v.seq = dna_sequence(
"GAGGATTAGTATATTCATGAGCAGTATCAGAGTCACGGCCACCCATAGAGCCTGCACCACCACACCCAGAAGAACGAGGATTAGTATATTCA"
"TGAGCAGTATCAGAGTCACGGCCACCCGTAGAGCCTGCACCACCACGCCCAGAAGAACGAGGATTAGTATATTCATGAGCAGTATCAGAGTC"
"ACGGCCACCCATAGAGCCTGCACCACCACGCCCAGAAGAAT");
m_in1->aligned_variants.push_back(v);
m_in2 = make_unique<assembly>();
m_in2->left_offset = 248033766;
m_in2->right_offset = 248034153;
m_in2->seq = dna_sequence(
"GGCCACCCATAGAGCCTGCACCACCACACCCAGAAGAACGAGGATTAGTATATTCATGAGCAGTATCAGAGTCACGGCCACCCATAGAGCCT"
"GCACCACCACGCCCAGAAGAACGAGGATTAGTATATTCATGAGCAGTATCAGAGTCACGGCCACCCGTAGAGCCTGCACCACCACGCCCAGA"
"AGAACGAGGATTAGTATATTCATGAGCAGTATCAGAGTCATGGCCACCCATAG");
v.left_offset = 248033794;
v.right_offset = 248033869;
v.seq = dna_sequence("");
m_in2->aligned_variants.push_back(v);
v.left_offset = 248033925;
v.right_offset = 248034000;
v.seq = dna_sequence("");
m_in2->aligned_variants.push_back(v);
do_merge();
EXPECT_FALSE(m_result) << *m_result;
}
| 35.305344 | 100 | 0.692757 | [
"vector"
] |
c9f2b6c1f58872614a28c73ae9ebdb1ad02635c6 | 5,787 | cpp | C++ | src/rosync.cpp | Nexure/RoSync | 1d947ae91eb36d86ec978920e74ab97bc28377d8 | [
"MIT"
] | null | null | null | src/rosync.cpp | Nexure/RoSync | 1d947ae91eb36d86ec978920e74ab97bc28377d8 | [
"MIT"
] | 3 | 2021-07-17T19:39:18.000Z | 2021-07-17T19:43:14.000Z | src/rosync.cpp | Nexure/RoSync | 1d947ae91eb36d86ec978920e74ab97bc28377d8 | [
"MIT"
] | null | null | null | #include "./rosync.h"
#include "./utils.h"
rosync::rosync() : sessions(std::make_shared<session_container>()), sync_dir_manager(std::make_shared<sync_manager>(sessions))
{
}
rosync::~rosync()
{
}
http_response rosync::get_health(shttp_request request)
{
return http_response(status_code::OK);
}
http_response rosync::get_sync_dirs(shttp_request request)
{
json response = json::array();
for (auto it : sync_dir_manager->get_sync_directories())
{
response.push_back(json
{
{"id", it->get_id()},
{"path", it->get_directory()}
}
);
}
return http_response(status_code::OK, response);
}
http_response rosync::get_sync_dirs_hashes(shttp_request request)
{
return http_response();
}
http_response rosync::sync_dir(shttp_request request)
{
auto json_body = request->get_json_body();
auto directory = json_body["directory"].get<std::string>();
std::shared_ptr<sync_directory> sync_directory;
// BROKEN rn
// replace the path dependent on the os
// directory = sanitize_path(directory);
// get the created directory
if (!sync_dir_manager->add_directory(directory, &sync_directory))
{
throw status_exception::with_error_message(status_code::InternalServerError, "Failed to create sync directory");
}
return http_response(status_code::OK, json
{
{"id", sync_directory->get_id()},
{"directory", directory},
{"dirs", ""},
{"files", ""}
});
}
void rosync::map_endpoint(uWS::App& http_server, http_method method, std::string endpoint, web_handler function)
{
auto request_call = [=](uws_response res, uws_request req, shttp_request request)
{
#define CAN_WRITE(x) if (!request->get_token().is_canceled()) x
try
{
auto response = function(request);
CAN_WRITE(response.write(res));
}
catch (status_exception& status)
{
CAN_WRITE(status.write_response(res));
}
catch (nlohmann::json::exception& e)
{
auto response = status_exception::with_error_message(status_code::InternalServerError, "Invalid json data passed");
CAN_WRITE(response.write_response(res));
}
catch (std::exception& e)
{
auto response = status_exception::with_error_message(status_code::InternalServerError, e.what());
CAN_WRITE(response.write_response(res));
}
#undef CAN_WRITE
};
auto request_proxy = [=](uws_response res, uws_request req)
{
concurrency::cancellation_token_source cts;
auto token = cts.get_token();
auto request = std::make_shared<http_request>(req, res, token);
auto task = concurrency::create_task([=]
{
request->await_body();
if (token.is_canceled())
{
return;
}
request_call(res, req, request);
}, token
);
res->onAborted([=] {
cts.cancel();
});
};
switch (method) {
case http_method::ANY:
http_server.any(endpoint, request_proxy);
break;
case http_method::GET:
http_server.get(endpoint, request_proxy);
break;
case http_method::POST:
http_server.post(endpoint, request_proxy);
break;
case http_method::PATCH:
http_server.any(endpoint, request_proxy);
break;
case http_method::PUT:
http_server.put(endpoint, request_proxy);
break;
case http_method::DEL:
http_server.del(endpoint, request_proxy);
break;
default:
throw std::runtime_error("invalid endpoint method passed");
}
}
void rosync::register_endpoints(uWS::App& http_server)
{
// generic method to make mapping endpoints less repetitive and long
#define MAP_ENDPOINT(method, endpoint, func_name) \
map_endpoint(http_server, method, endpoint, std::bind(&rosync::func_name, this, std::placeholders::_1))
// endpoint mapping to functions
MAP_ENDPOINT(http_method::GET, "/health", get_health);
// endpoint to get sync directories
MAP_ENDPOINT(http_method::GET, "/syncing", get_sync_dirs);
// endpoint to start syncing directory
MAP_ENDPOINT(http_method::PUT, "/syncing", sync_dir);
// endpoint to get sync dir hashes
MAP_ENDPOINT(http_method::GET, "/syncing/:id", get_sync_dirs_hashes);
// generic http endpoints
http_server
.get("/*", [](auto* res, auto* req)
{
http_response response(status_code::NotFound, json
{
{"code", "404"},
{"message", "Not Found"}
});
response.write(res);
});
#undef MAP_ENDPOINT
}
void rosync::start_webserver()
{
// create server instances
uWS::App server_instance;
// register the endpoints
register_endpoints(server_instance);
// start up the instance to listen
server_instance
.listen(PORT, [&](auto* token)
{
std::scoped_lock lock(webserver_mutex);
std::cout << "Thread " << std::this_thread::get_id();
if (token)
{
std::cout << " listening on port " << PORT << std::endl;
}
else
{
std::cout << " failed to listen on port" << PORT << std::endl;
}
})
.run();
}
#ifdef USE_TASK_POOL
void rosync::run()
{
// create array of server tasks at the system concurrency limit
std::vector<concurrency::task<void>> tasks;
// create web-server based on takss
for (auto i = 0; i < std::thread::hardware_concurrency(); i++)
{
auto task = concurrency::create_task(std::bind(&rosync::start_webserver, this));
tasks.push_back(task);
}
// wait for all server threads to stop before exiting the program
concurrency::when_all(tasks.begin(), tasks.end()).get();
}
#else
void rosync::run()
{
// create array of server threads at the system concurrency limit
std::vector<std::thread*> threads(std::thread::hardware_concurrency());
// create web-serverb based on threads
std::transform(threads.begin(), threads.end(), threads.begin(), [&](std::thread*) {
return new std::thread(std::bind(&rosync::start_webserver, this));
});
// wait for all server threads to stop before exiting the program
std::for_each(threads.begin(), threads.end(), [](std::thread* t) {
t->join();
delete t;
});
}
#endif
| 24.417722 | 126 | 0.69708 | [
"vector",
"transform"
] |
c9f6fd3eb57c09c35cb7e501be48e443d09aa08a | 264 | hpp | C++ | ext/src/oboe_otel_api.hpp | appoptics/opentelemetry-exporter-ruby | e81352b3a63279917da658bce43e0fc941a80f8a | [
"Apache-2.0"
] | null | null | null | ext/src/oboe_otel_api.hpp | appoptics/opentelemetry-exporter-ruby | e81352b3a63279917da658bce43e0fc941a80f8a | [
"Apache-2.0"
] | null | null | null | ext/src/oboe_otel_api.hpp | appoptics/opentelemetry-exporter-ruby | e81352b3a63279917da658bce43e0fc941a80f8a | [
"Apache-2.0"
] | null | null | null | #ifndef OBOE_API_HPP
#define OBOE_API_HPP
#include <unistd.h>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
#include <vector>
#include "oboe.h"
class Otel {
static bool sendEvent(const std::string bson_str, int len);
};
#endif | 15.529412 | 63 | 0.727273 | [
"vector"
] |
c9f7bd7febfba01fb398416b78564dde8a9c6955 | 533 | hh | C++ | src/nn/src/include/common.hh | juliia5m/knu_voice | 1f5d150ded23af4c152b8d20f1ab4ecec77b40e1 | [
"Apache-2.0"
] | 717 | 2015-01-03T15:25:46.000Z | 2022-03-30T12:45:45.000Z | src/common.hh | H2020-InFuse/fast-gmm | e88b58d0cb3c9cf1579e6e7c6523a4f10d7e904a | [
"MIT"
] | 91 | 2015-03-19T09:25:23.000Z | 2021-05-19T08:51:26.000Z | src/common.hh | H2020-InFuse/fast-gmm | e88b58d0cb3c9cf1579e6e7c6523a4f10d7e904a | [
"MIT"
] | 315 | 2015-01-21T00:06:00.000Z | 2022-03-29T08:13:36.000Z | /*
* $File: common.hh
* $Date: Sun Sep 08 08:35:24 2013 +0800
* $Author: Xinyu Zhou <zxytim[at]gmail[dot]com>
*/
#include "type.hh"
#include "dataset.hh"
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <cstring>
#include <memory>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <limits>
#define For(i, n) for (__decltype(n) i = 0; i < (n); i ++)
#define Forr(i, l, r) for (__decltype(r) i = (l); i <= (r); i ++)
/**
* vim: syntax=cpp11 foldmethod=marker
*/
| 17.766667 | 65 | 0.628518 | [
"vector"
] |
c9f8556bccb417664457f1f8824a502a15c079e5 | 5,168 | cpp | C++ | src/bm_sim/meters.cpp | edgarcosta92/behavioral-model | de9ec3ddc45c2b210681a7675c0bded6e56ec9d3 | [
"Apache-2.0"
] | 390 | 2015-10-13T05:22:51.000Z | 2022-03-30T19:18:14.000Z | src/bm_sim/meters.cpp | edgarcosta92/behavioral-model | de9ec3ddc45c2b210681a7675c0bded6e56ec9d3 | [
"Apache-2.0"
] | 919 | 2015-08-10T17:50:50.000Z | 2022-03-31T17:46:07.000Z | src/bm_sim/meters.cpp | edgarcosta92/behavioral-model | de9ec3ddc45c2b210681a7675c0bded6e56ec9d3 | [
"Apache-2.0"
] | 351 | 2015-09-18T03:32:32.000Z | 2022-03-31T03:56:38.000Z | /* Copyright 2013-present Barefoot Networks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Antonin Bas (antonin@barefootnetworks.com)
*
*/
#include <bm/bm_sim/meters.h>
#include <bm/bm_sim/logger.h>
#include <bm/bm_sim/packet.h>
#include <algorithm>
#include <vector>
#include <string>
namespace bm {
using MeterErrorCode = Meter::MeterErrorCode;
using ticks = std::chrono::microseconds; // better with nanoseconds ?
using std::chrono::duration_cast;
namespace {
Meter::clock::time_point time_init = Meter::clock::now();
} // namespace
MeterErrorCode
Meter::set_rate(size_t idx, const rate_config_t &config) {
MeterRate &rate = rates[idx];
rate.valid = true;
rate.info_rate = config.info_rate;
rate.burst_size = config.burst_size;
rate.tokens = config.burst_size;
rate.tokens_last = 0u;
rate.color = (idx + 1);
if (idx > 0) {
MeterRate &prev_rate = rates[idx - 1];
if (prev_rate.info_rate > rate.info_rate) return INVALID_INFO_RATE_VALUE;
}
return SUCCESS;
}
MeterErrorCode
Meter::reset_rates() {
auto lock = unique_lock();
for (MeterRate &rate : rates) {
rate.valid = false;
}
configured = false;
return SUCCESS;
}
Meter::color_t
Meter::execute(const Packet &pkt, color_t pre_color) {
color_t packet_color = 0;
if (!configured) return packet_color;
clock::time_point now = clock::now();
int64_t micros_since_init = duration_cast<ticks>(now - time_init).count();
auto lock = unique_lock();
/* I tried to make this as accurate as I could. Everything is computed
compared to a single time point (init). I do not use the interval since
last update, because it would require multiple consecutive
approximations. Maybe this is an overkill or I am underestimating the code
I wrote for BMv1.
The only thing that could go wrong is if tokens_since_init grew too large,
but I think it would take years even at high throughput */
for (MeterRate &rate : rates) {
uint64_t tokens_since_init =
static_cast<uint64_t>(micros_since_init * rate.info_rate);
assert(tokens_since_init >= rate.tokens_last);
size_t new_tokens = tokens_since_init - rate.tokens_last;
rate.tokens_last = tokens_since_init;
rate.tokens = std::min(rate.tokens + new_tokens, rate.burst_size);
size_t input = (type == MeterType::PACKETS) ? 1u : pkt.get_ingress_length();
if (rate.tokens < input) {
packet_color = rate.color;
break;
} else {
rate.tokens -= input;
}
}
return std::max(pre_color, packet_color);
}
void
Meter::serialize(std::ostream *out) const {
auto lock = unique_lock();
(*out) << configured << "\n";
if (configured) {
for (const auto &rate : rates)
(*out) << rate.info_rate << " " << rate.burst_size << "\n";
}
}
void
Meter::deserialize(std::istream *in) {
auto lock = unique_lock();
(*in) >> configured;
if (configured) {
for (size_t i = 0; i < rates.size(); i++) {
rate_config_t config;
(*in) >> config.info_rate;
(*in) >> config.burst_size;
set_rate(i, config);
}
}
}
void
Meter::reset_global_clock() {
time_init = Meter::clock::now();
}
std::vector<Meter::rate_config_t>
Meter::get_rates() const {
std::vector<rate_config_t> configs;
auto lock = unique_lock();
if (!configured) return configs;
// elegant but probably not the most efficient
for (const MeterRate &rate : rates)
configs.push_back(rate_config_t::make(rate.info_rate, rate.burst_size));
std::reverse(configs.begin(), configs.end());
return configs;
}
MeterArray::MeterArray(const std::string &name, p4object_id_t id,
MeterType type, size_t rate_count, size_t size)
: NamedP4Object(name, id) {
meters.reserve(size);
for (size_t i = 0; i < size; i++)
meters.emplace_back(type, rate_count);
}
MeterArray::color_t
MeterArray::execute_meter(const Packet &pkt, size_t idx, color_t pre_color) {
BMLOG_DEBUG_PKT(pkt, "Executing meter {}[{}]", get_name(), idx);
return meters[idx].execute(pkt, pre_color);
}
MeterArray::MeterErrorCode
MeterArray::set_rates(const std::vector<rate_config_t> &configs) {
return set_rates(configs.begin(), configs.end());
}
MeterArray::MeterErrorCode
MeterArray::set_rates(const std::initializer_list<rate_config_t> &configs) {
return set_rates(configs.begin(), configs.end());
}
void
MeterArray::reset_state() {
for (auto &m : meters) m.reset_rates();
}
void
MeterArray::serialize(std::ostream *out) const {
for (const auto &m : meters) m.serialize(out);
}
void
MeterArray::deserialize(std::istream *in) {
for (auto &m : meters) m.deserialize(in);
}
} // namespace bm
| 27.343915 | 80 | 0.692918 | [
"vector"
] |
c9fbec9020a1a6aa6209d40689b751e6a13b181a | 5,184 | cpp | C++ | Source/3rdParty/tinyxml2/SAXParser.cpp | Karshilov/Dorothy-SSR | cce19ed2218d76f941977370f6b3894e2f87236a | [
"MIT"
] | 43 | 2020-01-29T02:22:41.000Z | 2021-12-06T04:20:12.000Z | Source/3rdParty/tinyxml2/SAXParser.cpp | Jilliana8397/Dorothy-SSR | 5ad647909c5e20cb7ebde9a1a054cdb944969dcb | [
"MIT"
] | 1 | 2020-03-19T16:23:12.000Z | 2020-03-19T16:23:12.000Z | Source/3rdParty/tinyxml2/SAXParser.cpp | Jilliana8397/Dorothy-SSR | 5ad647909c5e20cb7ebde9a1a054cdb944969dcb | [
"MIT"
] | 8 | 2020-03-08T13:46:08.000Z | 2021-07-19T11:30:23.000Z | #include "tinyxml2/SAXParser.h"
#include "Const/Header.h"
#include "Basic/Content.h"
using namespace Dorothy;
class XmlSaxHander : public tinyxml2::XMLVisitor
{
public:
XmlSaxHander():_saxParser(nullptr) { }
virtual bool VisitEnter( const tinyxml2::XMLElement& element, const tinyxml2::XMLAttribute* firstAttribute );
virtual bool VisitExit( const tinyxml2::XMLElement& element );
virtual bool Visit( const tinyxml2::XMLText& text );
virtual bool Visit( const tinyxml2::XMLUnknown&) { return true; }
void setSAXParser(SAXParser* parser)
{
_saxParser = parser;
}
private:
SAXParser *_saxParser;
};
bool XmlSaxHander::VisitEnter( const tinyxml2::XMLElement& element, const tinyxml2::XMLAttribute* firstAttribute )
{
std::vector<const char*> attsVector;
for( const tinyxml2::XMLAttribute* attrib = firstAttribute; attrib; attrib = attrib->Next() )
{
attsVector.push_back(attrib->Name());
attsVector.push_back(attrib->Value());
}
attsVector.push_back(nullptr);
SAXParser::startElement(_saxParser, (const XML_CHAR *)element.Value(), (const XML_CHAR **)(&attsVector[0]));
return true;
}
bool XmlSaxHander::VisitExit( const tinyxml2::XMLElement& element )
{
SAXParser::endElement(_saxParser, (const XML_CHAR *)element.Value());
return true;
}
bool XmlSaxHander::Visit( const tinyxml2::XMLText& text )
{
SAXParser::textHandler(_saxParser, (const XML_CHAR *)text.Value(), (int)strlen(text.Value()));
return true;
}
SAXParser::SAXParser():
_delegator(nullptr)
{ }
SAXParser::~SAXParser()
{ }
const std::string& SAXParser::getLastError() const
{
return _lastError;
}
bool SAXParser::parseXml(const std::string& xmlData)
{
_lastError.clear();
tinyxml2::XMLError error;
if (xmlData.empty())
{
error = _tinyDoc.Parse(xmlData.c_str());
}
else
{
error = _tinyDoc.Parse(xmlData.c_str(), xmlData.size());
}
if (error != tinyxml2::XML_NO_ERROR)
{
_lastError = fmt::format("Xml document error at line {}, ", _tinyDoc.GetErrorLine());
switch (error)
{
case tinyxml2::XML_NO_ATTRIBUTE: _lastError += "no attribute."; break;
case tinyxml2::XML_WRONG_ATTRIBUTE_TYPE: _lastError += "wrong attribute type."; break;
case tinyxml2::XML_ERROR_FILE_NOT_FOUND: _lastError += "file not found."; break;
case tinyxml2::XML_ERROR_FILE_COULD_NOT_BE_OPENED: _lastError += "file could not be opened."; break;
case tinyxml2::XML_ERROR_FILE_READ_ERROR: _lastError += "file read error."; break;
case tinyxml2::XML_ERROR_ELEMENT_MISMATCH: _lastError += "element mismatch."; break;
case tinyxml2::XML_ERROR_PARSING_ELEMENT: _lastError += "parsing element error."; break;
case tinyxml2::XML_ERROR_PARSING_ATTRIBUTE: _lastError += "parsing attribute error."; break;
case tinyxml2::XML_ERROR_IDENTIFYING_TAG: _lastError += "identifying tag error."; break;
case tinyxml2::XML_ERROR_PARSING_TEXT: _lastError += "parsing text error."; break;
case tinyxml2::XML_ERROR_PARSING_CDATA: _lastError += "parsing cdata error."; break;
case tinyxml2::XML_ERROR_PARSING_COMMENT: _lastError += "parsing comment error."; break;
case tinyxml2::XML_ERROR_PARSING_DECLARATION: _lastError += "parsing declaration error."; break;
case tinyxml2::XML_ERROR_PARSING_UNKNOWN: _lastError += "parsing unknown error."; break;
case tinyxml2::XML_ERROR_EMPTY_DOCUMENT: _lastError += "empty document."; break;
case tinyxml2::XML_ERROR_MISMATCHED_ELEMENT: _lastError += "mismatch element."; break;
case tinyxml2::XML_ERROR_PARSING: _lastError += "parsing error."; break;
case tinyxml2::XML_CAN_NOT_CONVERT_TEXT: _lastError += "can not convert text."; break;
case tinyxml2::XML_NO_TEXT_NODE: _lastError += "no text node."; break;
default:
break;
}
if (_tinyDoc.GetErrorStr1())
{
_lastError += " ";
_lastError += _tinyDoc.GetErrorStr1();
}
if (_tinyDoc.GetErrorStr2())
{
_lastError += ", ";
_lastError += _tinyDoc.GetErrorStr2();
}
_lastError += "\n";
return false;
}
XmlSaxHander printer;
printer.setSAXParser(this);
return _tinyDoc.Accept(&printer);
}
bool SAXParser::parse(const std::string& filename)
{
auto data = SharedContent.load(filename);
return parseXml(Slice(r_cast<char*>(data.first.get()), data.second));
}
void SAXParser::startElement(void* ctx, const XML_CHAR* name, const XML_CHAR** atts)
{
((SAXParser*)(ctx))->_delegator->startElement((char*)name, (const char**)atts);
}
void SAXParser::endElement(void* ctx, const XML_CHAR* name)
{
((SAXParser*)(ctx))->_delegator->endElement((char*)name);
}
void SAXParser::textHandler(void* ctx, const XML_CHAR* name, int len)
{
((SAXParser*)(ctx))->_delegator->textHandler((char*)name, len);
}
void SAXParser::setDelegator(SAXDelegator* delegator)
{
_delegator = delegator;
}
void SAXParser::placeCDataHeader(const char* cdataHeader)
{
tinyxml2::XMLUtil::PlaceCDataHeader(cdataHeader);
}
void SAXParser::setHeaderHandler(void(*handler)(const char* start, const char* end))
{
tinyxml2::XMLUtil::PlaceHeaderHandler(handler);
}
int SAXParser::getLineNumber(const char* name)
{
int line = 1;
for (const char* c = _tinyDoc.GetCharBuffer(); c != name; c++)
{
if (*c == '\n')
{
line++;
}
}
return line;
}
| 30.857143 | 114 | 0.724151 | [
"vector"
] |
c9fd56c7f461be8f4f2a1ee9717f184b76563566 | 10,703 | cpp | C++ | src/common/GExpectationChecksT.cpp | denisbertini/geneva | eff76fc489001512022d1a20c5561623d73efc32 | [
"Apache-2.0",
"BSD-3-Clause"
] | 4 | 2020-05-20T07:23:19.000Z | 2021-09-12T23:12:21.000Z | src/common/GExpectationChecksT.cpp | denisbertini/geneva | eff76fc489001512022d1a20c5561623d73efc32 | [
"Apache-2.0",
"BSD-3-Clause"
] | 10 | 2020-05-05T13:24:08.000Z | 2021-07-27T13:23:17.000Z | src/common/GExpectationChecksT.cpp | denisbertini/geneva | eff76fc489001512022d1a20c5561623d73efc32 | [
"Apache-2.0",
"BSD-3-Clause"
] | 7 | 2020-04-09T10:33:11.000Z | 2021-09-08T12:24:55.000Z | /********************************************************************************
*
* This file is part of the Geneva library collection. The following license
* applies to this file:
*
* ------------------------------------------------------------------------------
* 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.
* ------------------------------------------------------------------------------
*
* Note that other files in the Geneva library collection may use a different
* license. Please see the licensing information in each file.
*
********************************************************************************
*
* Geneva was started by Dr. Rüdiger Berlich and was later maintained together
* with Dr. Ariel Garcia under the auspices of Gemfony scientific. For further
* information on Gemfony scientific, see http://www.gemfomy.eu .
*
* The majority of files in Geneva was released under the Apache license v2.0
* in February 2020.
*
* See the NOTICE file in the top-level directory of the Geneva library
* collection for a list of contributors and copyright information.
*
********************************************************************************/
#include "common/GExpectationChecksT.hpp"
namespace Gem {
namespace Common {
/******************************************************************************/
////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
// Identifies test counter and success counter
const std::size_t TESTCOUNTER = 0;
const std::size_t SUCCESSCOUNTER = 1;
/******************************************************************************/
////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/**
* The standard constructor -- initialization with class name and expectation
*/
GToken::GToken(
std::string caller
, Gem::Common::expectation e
)
: m_test_counter(std::make_tuple(std::size_t(0), std::size_t(0)))
, m_caller(std::move(caller))
, m_e(e)
{ /* nothing */ }
/******************************************************************************/
/**
* Increments the test counter
*/
void GToken::incrTestCounter() {
std::get<TESTCOUNTER>(m_test_counter) += 1;
}
/******************************************************************************/
/**
* Increments the counter of tests that met the expectation
*/
void GToken::incrSuccessCounter() {
std::get<SUCCESSCOUNTER>(m_test_counter) += 1;
}
/******************************************************************************/
/**
* Allows to retrieve the current state of the success counter
*/
std::size_t GToken::getSuccessCounter() const {
return std::get<SUCCESSCOUNTER>(m_test_counter);
}
/******************************************************************************/
/** @brief Allows to retrieve the current state of the test counter */
std::size_t GToken::getTestCounter() const {
return std::get<TESTCOUNTER>(m_test_counter);
}
/******************************************************************************/
/**
* Allows to check whether the expectation was met
*/
bool GToken::expectationMet() const {
switch (m_e) {
case Gem::Common::expectation::FP_SIMILARITY:
case Gem::Common::expectation::EQUALITY:
if (std::get<TESTCOUNTER>(m_test_counter) == std::get<SUCCESSCOUNTER>(m_test_counter)) {
return true;
}
break;
case Gem::Common::expectation::INEQUALITY:
if (std::get<SUCCESSCOUNTER>(m_test_counter) > 0) {
return true;
}
break;
}
return false;
}
/******************************************************************************/
/**
* Conversion to a boolean indicating whether the expectation was met
*/
GToken::operator bool() const {
return this->expectationMet();
}
/******************************************************************************/
/**
* Allows to retrieve the expectation token
*/
Gem::Common::expectation GToken::getExpectation() const {
return m_e;
}
/******************************************************************************/
/**
* Allows to retrieve the expectation token as a string
*/
std::string GToken::getExpectationStr() const {
switch (m_e) {
case Gem::Common::expectation::FP_SIMILARITY:
return "FP_SIMILARITY";
break;
case Gem::Common::expectation::EQUALITY:
return "EQUALITY";
break;
case Gem::Common::expectation::INEQUALITY:
return "INEQUALITY";
break;
default:
return "unknown";
break;
}
}
/******************************************************************************/
/**
* Allows to retrieve the name of the caller
*/
std::string GToken::getCallerName() const {
return m_caller;
}
/******************************************************************************/
/**
* Allows to register an error message e.g. obtained from a failed check
*/
void GToken::registerErrorMessage(std::string const &m) {
if (not m.empty()) {
m_error_messages.push_back(m);
} else {
throw gemfony_exception(
g_error_streamer(DO_LOG, time_and_place)
<< "In GToken::registerErrorMessage(): Error" << std::endl
<< "Tried to register empty error message" << std::endl
);
}
}
/******************************************************************************/
/**
* Allows to register an exception obtained from a failed check
*/
void GToken::registerErrorMessage(g_expectation_violation const & g) {
m_error_messages.emplace_back(g.what());
}
/******************************************************************************/
/**
* Allows to retrieve the currently registered error messages
*/
std::string GToken::getErrorMessages() const {
std::string result;
result = "Registered errors:\n";
for(auto const& error: m_error_messages) {
result += error;
}
return result;
}
/******************************************************************************/
/**
* Conversion to a string indicating success or failure
*/
std::string GToken::toString() const {
std::string result = "Expectation of ";
switch (m_e) {
case Gem::Common::expectation::FP_SIMILARITY: {
result += std::string("FP_SIMILARITY was ");
}
break;
case Gem::Common::expectation::EQUALITY: {
result += std::string("EQUALITY was ");
}
break;
case Gem::Common::expectation::INEQUALITY: {
result += std::string("INEQUALITY was ");
}
break;
}
if (this->expectationMet()) {
result += std::string("met in ") + m_caller + std::string("\n");
} else {
result += std::string("not met in ") + m_caller + std::string("\n");
// We only add specific information about failed checks for the expectation
// "inequality", so we do not swamp the user with useless information.
// For the inequality information, just one out of many checks for data-
// inequality must be met, so the "equal" comparisons are of no concern.
// Only the information "everything is equal while inequality was expected"
// is important. If equality or similarity were expected, every single
// deviation from equality is of interest.
if (Gem::Common::expectation::INEQUALITY != m_e) {
for(auto const& error: m_error_messages) {
result += error;
}
}
}
return result;
}
/******************************************************************************/
/**
* Evaluates the information in this object
*/
void GToken::evaluate() const {
if (not this->expectationMet()) {
throw(g_expectation_violation(this->toString()));
}
}
/******************************************************************************/
/**
* Easy output of GToken objects
*/
std::ostream &operator<<(std::ostream &s, GToken const & g) {
s
<< "GToken for caller " << g.getCallerName() << " with expectation " << g.getExpectationStr() << ":" << std::endl
<< "Test counter: " << g.getTestCounter() << std::endl
<< "Success counter: " << g.getSuccessCounter() << std::endl
<< g.getErrorMessages() << std::endl;
return s;
}
/******************************************************************************/
////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/**
* This function checks whether two objects of type boost::logic::tribool meet a given expectation.
*
* @param x The first vector to be compared
* @param y The second vector to be compared
* @param x_name The name of the first parameter
* @param y_name The name of the second parameter
* @param e The expectation both parameters need to fulfill
* @param limit The maximum allowed deviation of two floating point values
*/
void compare(
boost::logic::tribool const & x
, boost::logic::tribool const & y
, std::string const & x_name
, std::string const & y_name
, Gem::Common::expectation e
, double
) {
bool expectationMet = false;
std::string expectation_str;
switch (e) {
case Gem::Common::expectation::FP_SIMILARITY:
case Gem::Common::expectation::EQUALITY:
expectation_str = "FP_SIMILARITY / EQUALITY";
if ((x == true && y == true) ||
(x == false && y == false) ||
(boost::logic::indeterminate(x) && boost::logic::indeterminate(y))) {
expectationMet = true;
}
break;
case Gem::Common::expectation::INEQUALITY:
expectation_str = "INEQUALITY";
if (not (x == true && y == true) &&
not (x == false && y == false) &&
not (boost::logic::indeterminate(x) && boost::logic::indeterminate(y))) {
expectationMet = true;
}
break;
};
if (not expectationMet) {
std::ostringstream error;
error
<< "Expectation of " << expectation_str << " was violated for parameters " << std::endl
<< "[" << std::endl
<< x_name << " = " << x << std::endl
<< y_name << " = " << y << std::endl
<< "]" << std::endl;
throw g_expectation_violation(error.str());
}
}
/******************************************************************************/
////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
} /* namespace Common */
} /* namespace Gem */
| 32.237952 | 116 | 0.519013 | [
"object",
"vector"
] |
c9fee29f9ae7888443636b8f0774883387b1fb8e | 2,065 | cc | C++ | chrome/browser/ui/search/search_delegate_unittest.cc | nagineni/chromium-crosswalk | 5725642f1c67d0f97e8613ec1c3e8107ab53fdf8 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 9 | 2018-09-21T05:36:12.000Z | 2021-11-15T15:14:36.000Z | chrome/browser/ui/search/search_delegate_unittest.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 | chrome/browser/ui/search/search_delegate_unittest.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 "chrome/browser/search/search.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/search/search_model.h"
#include "chrome/browser/ui/search/search_tab_helper.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/test/base/browser_with_test_window_test.h"
typedef BrowserWithTestWindowTest SearchDelegateTest;
// Test the propagation of search "mode" changes from the tab's search model to
// the browser's search model.
TEST_F(SearchDelegateTest, SearchModel) {
chrome::EnableInstantExtendedAPIForTesting();
// Initial state.
EXPECT_TRUE(browser()->search_model()->mode().is_default());
// Propagate change from tab's search model to browser's search model.
AddTab(browser(), GURL("http://foo/0"));
content::WebContents* web_contents =
browser()->tab_strip_model()->GetWebContentsAt(0);
SearchTabHelper::FromWebContents(web_contents)->model()->
SetMode(SearchMode(SearchMode::MODE_NTP, SearchMode::ORIGIN_NTP));
EXPECT_TRUE(browser()->search_model()->mode().is_ntp());
// Add second tab, make it active, and make sure its mode changes
// propagate to the browser's search model.
AddTab(browser(), GURL("http://foo/1"));
browser()->tab_strip_model()->ActivateTabAt(1, true);
web_contents = browser()->tab_strip_model()->GetWebContentsAt(1);
SearchTabHelper::FromWebContents(web_contents)->model()->
SetMode(SearchMode(SearchMode::MODE_SEARCH_RESULTS,
SearchMode::ORIGIN_DEFAULT));
EXPECT_TRUE(browser()->search_model()->mode().is_search());
// The first tab is not active so changes should not propagate.
web_contents = browser()->tab_strip_model()->GetWebContentsAt(0);
SearchTabHelper::FromWebContents(web_contents)->model()->
SetMode(SearchMode(SearchMode::MODE_NTP, SearchMode::ORIGIN_NTP));
EXPECT_TRUE(browser()->search_model()->mode().is_search());
}
| 44.891304 | 79 | 0.739467 | [
"model"
] |
c9ffb9cb07ddb0e2ac2df0c6198cc0fc1f7307b3 | 10,085 | hpp | C++ | include/netp/event_loop.hpp | netplus/netplus | e3b621e65742f38733d3dcaa1873443da8bbd611 | [
"MIT"
] | 48 | 2021-02-22T03:10:40.000Z | 2022-03-29T03:26:33.000Z | include/netp/event_loop.hpp | netplus/netplus | e3b621e65742f38733d3dcaa1873443da8bbd611 | [
"MIT"
] | 7 | 2021-03-20T09:25:11.000Z | 2022-03-07T03:26:56.000Z | include/netp/event_loop.hpp | netplus/netplus | e3b621e65742f38733d3dcaa1873443da8bbd611 | [
"MIT"
] | 13 | 2021-02-25T01:49:58.000Z | 2022-03-21T00:30:34.000Z | #ifndef _NETP_IO_EVENT_LOOP_HPP
#define _NETP_IO_EVENT_LOOP_HPP
#include <vector>
#include <set>
#include <netp/core.hpp>
#include <netp/string.hpp>
#include <netp/smart_ptr.hpp>
#include <netp/mutex.hpp>
#include <netp/promise.hpp>
#include <netp/packet.hpp>
#include <netp/poller_abstract.hpp>
#include <netp/timer.hpp>
#include <netp/dns_resolver.hpp>
#if defined(NETP_HAS_POLLER_EPOLL)
#define NETP_DEFAULT_POLLER_TYPE netp::io_poller_type::T_EPOLL
#elif defined(NETP_HAS_POLLER_SELECT)
#define NETP_DEFAULT_POLLER_TYPE netp::io_poller_type::T_SELECT
#elif defined(NETP_HAS_POLLER_KQUEUE)
#define NETP_DEFAULT_POLLER_TYPE netp::io_poller_type::T_KQUEUE
#elif defined(NETP_HAS_POLLER_IOCP)
#define NETP_DEFAULT_POLLER_TYPE netp::io_poller_type::T_IOCP
#define NETP_DEFAULT_POLLER_TYPE_IOCP
#else
#error "unknown poller type"
#endif
namespace netp {
typedef std::function<void()> fn_task_t;
typedef std::vector<fn_task_t, netp::allocator<fn_task_t>> io_task_q_t;
enum event_loop_flag {
f_th_thread_affinity =1<<0,
f_th_priority_above_normal =1<<1,
f_th_priority_time_critical = 1 << 2,
f_enable_dns_resolver =1<<3
};
struct event_loop_cfg {
explicit event_loop_cfg(u8_t type_, u8_t flag_, u32_t read_buf_) :
type(type_),
flag(flag_),
thread_affinity(0),
no_wait_us(1),
channel_read_buf_size(read_buf_)
{}
//u16_t no_wait_us wide used construct
explicit event_loop_cfg(u8_t type_, u8_t flag_, u32_t read_buf_, u8_t no_wait_us_) :
type(type_),
flag(flag_),
thread_affinity(0),
no_wait_us(u8_t(no_wait_us_)),
channel_read_buf_size(read_buf_)
{}
u8_t type;
u8_t flag;
u8_t thread_affinity;
u8_t no_wait_us;
u32_t channel_read_buf_size;
std::vector<netp::string_t, netp::allocator<netp::string_t>> dns_hosts;
};
class event_loop;
typedef std::function<NRP<event_loop>(event_loop_cfg const& cfg) > fn_event_loop_maker_t;
extern NRP<event_loop> default_event_loop_maker(event_loop_cfg const& cfg);
enum class loop_state {
S_IDLE,
S_LAUNCHING,
S_RUNNING,
S_TERMINATING, //no more watch evt
S_TERMINATED, //no more new timer, we need this state to make sure all channel have a chance to check terminating flag
S_EXIT //exit..
};
class dns_resolver;
class timer_broker;
class thread;
class event_loop :
public ref_base
{
enum LOOP_WAIT_FLAG {
F_LOOP_WAIT_NONE_ZERO_TIME_WAIT =1,
F_LOOP_WAIT_ENTER_WAITING = 1<<1
};
friend class event_loop_group;
protected:
std::thread::id m_tid;
std::atomic<bool> m_waiting;
std::atomic<u8_t> m_state;
event_loop_cfg m_cfg;
const NRP<poller_abstract> m_poller;
NRP<timer_broker> m_tb;
NRP<dns_resolver> m_dns_resolver;
int m_io_ctx_count;
int m_io_ctx_count_before_running;
spin_mutex m_tq_mutex;
io_task_q_t m_tq_standby;
io_task_q_t m_tq;
NRP<netp::packet> m_channel_rcv_buf;
NRP<netp::thread> m_th;
//timer_timepoint_t m_wait_until;
std::atomic<long> m_internal_ref_count;
std::vector<netp::string_t, netp::allocator<netp::string_t>> m_dns_hosts;
protected:
inline long internal_ref_count() { return m_internal_ref_count.load(std::memory_order_relaxed); }
inline void store_internal_ref_count( long count ) { m_internal_ref_count.store( count, std::memory_order_relaxed); }
inline void inc_internal_ref_count() { m_internal_ref_count.fetch_add(1, std::memory_order_relaxed); }
//inline void __internal_ref_count_inc() { netp::atomic_incre(&m_internal_ref_count); }
//0, NO WAIT
//~0, INFINITE WAIT
//>0, WAIT nanosecond
i64_t _calc_wait_dur_in_nano() {
NETP_ASSERT( m_waiting.load(std::memory_order_relaxed) == false, "_calc_wait_dur_in_nano waiting check failed" );
static_assert(TIMER_TIME_INFINITE == i64_t(-1), "timer infinite check");
netp::timer_duration_t ndelay;
m_tb->expire(ndelay);
i64_t ndelayns = i64_t(ndelay.count());
//@note: opt for select, epoll_wait
//@note: select, epoll_wait cost too much time to return (ms level)
if ( (ndelayns != TIMER_TIME_INFINITE) && (ndelayns <= (i64_t(m_cfg.no_wait_us)*1000LL)) ) {
//less than 1us
return 0;
}
{
lock_guard<spin_mutex> lg(m_tq_mutex);
if (m_tq_standby.size() != 0) {
return 0;
}
NETP_POLLER_WAIT_ENTER(m_waiting);
}
return ndelayns;
}
virtual void init();
virtual void deinit();
void __run();
void __do_notify_terminating();
void __notify_terminating();
void __do_enter_terminated();
int __launch();
void __terminate();
public:
event_loop(event_loop_cfg const& cfg, NRP<poller_abstract> const& poller);
~event_loop();
inline void schedule(fn_task_t&& f) {
//NOTE: upate on 2021/04/03
//lock_guard of m_tq_mutex also works as a memory barrier for memory accesses across loops in between task caller and task callee
//NOTE: update on 2021/03/28
//lock_guard of m_tq_mutex would pose a load/store memory barrier at least
//these kinds of barrier could make sure that the compiler would not reorder the instruction around the barrier, so interrupt_poller would always have a false initial value
//as a per thread variable, the reorder brought by CPU should not be a issue for _interrupt_poller
bool _interrupt_poller = false;
{
lock_guard<spin_mutex> lg(m_tq_mutex);
m_tq_standby.push_back(std::move(f));
_interrupt_poller=( m_tq_standby.size() == 1 && !in_event_loop() && m_waiting.load(std::memory_order_relaxed));
}
if (_interrupt_poller) {
m_poller->interrupt_wait();
}
}
inline void schedule(fn_task_t const& f) {
bool _interrupt_poller = false;
{
lock_guard<spin_mutex> lg(m_tq_mutex);
m_tq_standby.push_back(f);
_interrupt_poller=( m_tq_standby.size() == 1 && !in_event_loop() && m_waiting.load(std::memory_order_relaxed));
}
if (NETP_UNLIKELY(_interrupt_poller)) {
m_poller->interrupt_wait();
}
}
inline void execute(fn_task_t&& f) {
if (in_event_loop()) {
f();
return;
}
schedule(std::move(f));
}
inline void execute(fn_task_t const& f) {
if (in_event_loop()) {
f();
return;
}
schedule(f);
}
__NETP_FORCE_INLINE
bool in_event_loop() const {
return std::this_thread::get_id() == m_tid;
}
void launch(NRP<netp::timer> const& t , NRP<netp::promise<int>> const& lf = nullptr ) {
if(!in_event_loop()) {
netp::timer_clock_t::time_point outer_loop_tp = netp::timer_clock_t::now();
schedule([L = NRP<event_loop>(this), t, lf, outer_loop_tp]() {
netp::timer_clock_t::time_point inner_loop_tp = netp::timer_clock_t::now();
timer_duration_t tdur = t->get_delay();
tdur = tdur - (inner_loop_tp - outer_loop_tp);
if (tdur <= timer_duration_t(0)) { tdur = timer_duration_t(1); }
t->set_delay(tdur);
L->launch(t, lf);
});
return;
}
if (NETP_LIKELY(m_state.load(std::memory_order_acquire) < u8_t(loop_state::S_TERMINATED))) {
m_tb->launch(t);
(lf != nullptr)? lf->set(netp::OK):(void)0;
} else {
(lf != nullptr) ? lf->set(netp::E_IO_EVENT_LOOP_TERMINATED):NETP_THROW("DO NOT LAUNCH AFTER TERMINATED, OR PASS A PROMISE TO OVERRIDE THIS ERRO");
}
}
void launch(NRP<netp::timer>&& t, NRP<netp::promise<int>> const& lf = nullptr) {
if (!in_event_loop()) {
schedule([L = NRP<event_loop>(this), t=std::move(t) , lf]() {
L->launch(std::move(t), lf);
});
return;
}
if (NETP_LIKELY(m_state.load(std::memory_order_acquire) < u8_t(loop_state::S_TERMINATED))) {
m_tb->launch(std::move(t));
(lf != nullptr) ? lf->set(netp::OK) : (void)0;
} else {
(lf != nullptr) ? lf->set(netp::E_IO_EVENT_LOOP_TERMINATED) : NETP_THROW("DO NOT LAUNCH AFTER TERMINATED, OR PASS A PROMISE TO OVERRIDE THIS ERRO");
}
}
__NETP_FORCE_INLINE
NRP<dns_query_promise> resolve(string_t const& domain) {
NETP_ASSERT(m_cfg.flag& f_enable_dns_resolver);
return m_dns_resolver->resolve(domain);
}
__NETP_FORCE_INLINE
u8_t poller_type() const { return m_cfg.type; }
__NETP_FORCE_INLINE
NRP<netp::packet> const& channel_rcv_buf() const {
return m_channel_rcv_buf;
}
inline int io_do(io_action act, io_ctx* ctx) {
NETP_ASSERT(in_event_loop());
if (((u8_t(act) & u8_t(io_action::READ_WRITE)) == 0) || m_state.load(std::memory_order_acquire) < u8_t(loop_state::S_TERMINATING)) {
return m_poller->io_do(act, ctx);
} else {
return netp::E_IO_EVENT_LOOP_TERMINATED;
}
}
inline io_ctx* io_begin(SOCKET fd, NRP<io_monitor> const& iom) {
NETP_ASSERT(in_event_loop());
if (m_state.load(std::memory_order_acquire) < u8_t(loop_state::S_TERMINATING)) {
io_ctx* _ctx= m_poller->io_begin(fd, iom);
if (NETP_LIKELY(_ctx != nullptr)) {
++m_io_ctx_count;
}
return _ctx;
}
return 0;
}
inline void io_end(io_ctx* ctx) {
NETP_ASSERT(in_event_loop());
m_poller->io_end(ctx);
if ( (--m_io_ctx_count == m_io_ctx_count_before_running) && m_state.load(std::memory_order_acquire) == u8_t(loop_state::S_TERMINATING)) {
__do_enter_terminated();
}
}
};
class app;
typedef std::vector<NRP<event_loop>> event_loop_vector_t;
class event_loop_group:
public non_atomic_ref_base
{
friend class netp::app;
enum class bye_event_loop_state {
S_IDLE,
S_PREPARING,
S_RUNNING,
S_EXIT
};
private:
netp::shared_mutex m_loop_mtx;
std::atomic<u32_t> m_curr_loop_idx;
event_loop_vector_t m_loop;
std::atomic<bye_event_loop_state> m_bye_state;
NRP<event_loop> m_bye_event_loop;
long m_bye_ref_count;
event_loop_cfg m_cfg;
fn_event_loop_maker_t m_fn_loop_maker;
void _wait_loop();
public:
event_loop_group(event_loop_cfg const& cfg, fn_event_loop_maker_t const& fn_maker);
~event_loop_group();
void wait();
void notify_terminating();
void start(u32_t count);
void stop();
netp::size_t size();
NRP<event_loop> next(std::set<NRP<event_loop>> const& exclude_this_set_if_have_more);
NRP<event_loop> next();
void execute(fn_task_t&& f);
void schedule(fn_task_t&& f);
void launch(NRP<netp::timer> const& t, NRP<netp::promise<int>> const& lf = nullptr);
};
}
#endif
| 29.31686 | 175 | 0.713733 | [
"vector"
] |
a0057cb84cb42d4137a88ccaab2da008bda6e7eb | 7,536 | cpp | C++ | component/oai-udr/src/api_server/api/SubsToNotifyCollectionApi.cpp | kukkalli/oai-cn5g-fed | 15634fac935ac8671b61654bdf75bf8af07d3c3a | [
"Apache-2.0"
] | null | null | null | component/oai-udr/src/api_server/api/SubsToNotifyCollectionApi.cpp | kukkalli/oai-cn5g-fed | 15634fac935ac8671b61654bdf75bf8af07d3c3a | [
"Apache-2.0"
] | null | null | null | component/oai-udr/src/api_server/api/SubsToNotifyCollectionApi.cpp | kukkalli/oai-cn5g-fed | 15634fac935ac8671b61654bdf75bf8af07d3c3a | [
"Apache-2.0"
] | null | null | null | /*
* Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenAirInterface Software Alliance licenses this file to You under
* the OAI Public License, Version 1.1 (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.openairinterface.org/?page_id=698
*
* 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.
*-------------------------------------------------------------------------------
* For more information about the OpenAirInterface (OAI) Software Alliance:
* contact@openairinterface.org
*/
/**
* Nudr_DataRepository API OpenAPI file
* Unified Data Repository Service. © 2020, 3GPP Organizational Partners (ARIB,
* ATIS, CCSA, ETSI, TSDSI, TTA, TTC). All rights reserved.
*
* The version of the OpenAPI document: 2.1.2
*
*
* NOTE: This class is auto generated by OpenAPI Generator
* (https://openapi-generator.tech). https://openapi-generator.tech Do not edit
* the class manually.
*/
#include "SubsToNotifyCollectionApi.h"
#include "Helpers.h"
#include "udr_config.hpp"
extern oai::udr::config::udr_config udr_cfg;
namespace oai::udr::api {
using namespace oai::udr::helpers;
using namespace oai::udr::model;
SubsToNotifyCollectionApi::SubsToNotifyCollectionApi(
std::shared_ptr<Pistache::Rest::Router> rtr) {
router = rtr;
}
void SubsToNotifyCollectionApi::init() { setupRoutes(); }
void SubsToNotifyCollectionApi::setupRoutes() {
using namespace Pistache::Rest;
Routes::Get(
*router,
base + udr_cfg.nudr.api_version + "/subscription-data/subs-to-notify",
Routes::bind(&SubsToNotifyCollectionApi::query_subs_to_notify_handler,
this));
Routes::Delete(
*router,
base + udr_cfg.nudr.api_version + "/subscription-data/subs-to-notify",
Routes::bind(&SubsToNotifyCollectionApi::
remove_multiple_subscription_data_subscriptions_handler,
this));
Routes::Post(
*router,
base + udr_cfg.nudr.api_version + "/subscription-data/subs-to-notify",
Routes::bind(
&SubsToNotifyCollectionApi::subscription_data_subscriptions_handler,
this));
// Default handler, called when a route is not found
router->addCustomHandler(Routes::bind(
&SubsToNotifyCollectionApi::subs_to_notify_collection_api_default_handler,
this));
}
void SubsToNotifyCollectionApi::query_subs_to_notify_handler(
const Pistache::Rest::Request &request,
Pistache::Http::ResponseWriter response) {
// Getting the query params
auto ueIdQuery = request.query().get("ue-id");
Pistache::Optional<std::string> ueId;
if (!ueIdQuery.isEmpty()) {
std::string valueQuery_instance;
if (fromStringValue(ueIdQuery.get(), valueQuery_instance)) {
ueId = Pistache::Some(valueQuery_instance);
}
}
auto supportedFeaturesQuery = request.query().get("supported-features");
Pistache::Optional<std::string> supportedFeatures;
if (!supportedFeaturesQuery.isEmpty()) {
std::string valueQuery_instance;
if (fromStringValue(supportedFeaturesQuery.get(), valueQuery_instance)) {
supportedFeatures = Pistache::Some(valueQuery_instance);
}
}
try {
this->query_subs_to_notify(ueId, supportedFeatures, response);
} catch (nlohmann::detail::exception &e) {
// send a 400 error
response.send(Pistache::Http::Code::Bad_Request, e.what());
return;
} catch (Pistache::Http::HttpError &e) {
response.send(static_cast<Pistache::Http::Code>(e.code()), e.what());
return;
} catch (std::exception &e) {
// send a 500 error
response.send(Pistache::Http::Code::Internal_Server_Error, e.what());
return;
}
}
void SubsToNotifyCollectionApi::
remove_multiple_subscription_data_subscriptions_handler(
const Pistache::Rest::Request &request,
Pistache::Http::ResponseWriter response) {
// Getting the query params
auto ueIdQuery = request.query().get("ue-id");
Pistache::Optional<std::string> ueId;
if (!ueIdQuery.isEmpty()) {
std::string valueQuery_instance;
if (fromStringValue(ueIdQuery.get(), valueQuery_instance)) {
ueId = Pistache::Some(valueQuery_instance);
}
}
auto nfInstanceIdQuery = request.query().get("nf-instance-id");
Pistache::Optional<std::string> nfInstanceId;
if (!nfInstanceIdQuery.isEmpty()) {
std::string valueQuery_instance;
if (fromStringValue(nfInstanceIdQuery.get(), valueQuery_instance)) {
nfInstanceId = Pistache::Some(valueQuery_instance);
}
}
auto deleteAllNfsQuery = request.query().get("delete-all-nfs");
Pistache::Optional<bool> deleteAllNfs;
if (!deleteAllNfsQuery.isEmpty()) {
bool valueQuery_instance;
if (fromStringValue(deleteAllNfsQuery.get(), valueQuery_instance)) {
deleteAllNfs = Pistache::Some(valueQuery_instance);
}
}
auto implicitUnsubscribeIndicationQuery =
request.query().get("implicit-unsubscribe-indication");
Pistache::Optional<bool> implicitUnsubscribeIndication;
if (!implicitUnsubscribeIndicationQuery.isEmpty()) {
bool valueQuery_instance;
if (fromStringValue(implicitUnsubscribeIndicationQuery.get(),
valueQuery_instance)) {
implicitUnsubscribeIndication = Pistache::Some(valueQuery_instance);
}
}
try {
this->remove_multiple_subscription_data_subscriptions(
ueId, nfInstanceId, deleteAllNfs, implicitUnsubscribeIndication,
response);
} catch (nlohmann::detail::exception &e) {
// send a 400 error
response.send(Pistache::Http::Code::Bad_Request, e.what());
return;
} catch (Pistache::Http::HttpError &e) {
response.send(static_cast<Pistache::Http::Code>(e.code()), e.what());
return;
} catch (std::exception &e) {
// send a 500 error
response.send(Pistache::Http::Code::Internal_Server_Error, e.what());
return;
}
}
void SubsToNotifyCollectionApi::subscription_data_subscriptions_handler(
const Pistache::Rest::Request &request,
Pistache::Http::ResponseWriter response) {
// Getting the body param
SubscriptionDataSubscriptions subscriptionDataSubscriptions;
try {
nlohmann::json::parse(request.body()).get_to(subscriptionDataSubscriptions);
this->subscription_data_subscriptions(subscriptionDataSubscriptions,
response);
} catch (nlohmann::detail::exception &e) {
// send a 400 error
response.send(Pistache::Http::Code::Bad_Request, e.what());
return;
} catch (Pistache::Http::HttpError &e) {
response.send(static_cast<Pistache::Http::Code>(e.code()), e.what());
return;
} catch (std::exception &e) {
// send a 500 error
response.send(Pistache::Http::Code::Internal_Server_Error, e.what());
return;
}
}
void SubsToNotifyCollectionApi::subs_to_notify_collection_api_default_handler(
const Pistache::Rest::Request &, Pistache::Http::ResponseWriter response) {
response.send(Pistache::Http::Code::Not_Found,
"The requested method does not exist");
}
} // namespace oai::udr::api
| 36.760976 | 81 | 0.701964 | [
"model"
] |
a009fed034471656c2aa87a9a652a2a1b5e72e86 | 30,654 | cpp | C++ | src/mechanics_model.cpp | StopkaKris/ExaConstit | fecf8b5d0d97946e29244360c3bc538c3efb433a | [
"BSD-3-Clause"
] | 16 | 2019-10-11T17:03:20.000Z | 2021-11-17T14:09:47.000Z | src/mechanics_model.cpp | Leonidas-Z/ExaConstit | 0ab293cb6543b97eabde99e3ab43c1e921258ae4 | [
"BSD-3-Clause"
] | 41 | 2020-01-29T04:40:16.000Z | 2022-03-11T16:59:31.000Z | src/mechanics_model.cpp | Leonidas-Z/ExaConstit | 0ab293cb6543b97eabde99e3ab43c1e921258ae4 | [
"BSD-3-Clause"
] | 7 | 2019-10-12T02:00:58.000Z | 2022-03-10T04:09:35.000Z | #include "mfem.hpp"
#include "mfem/general/forall.hpp"
#include "mechanics_model.hpp"
#include "mechanics_log.hpp"
#include "BCManager.hpp"
#include <math.h> // log
#include <algorithm>
#include <iostream> // cerr
#include "RAJA/RAJA.hpp"
using namespace mfem;
using namespace std;
void computeDefGrad(QuadratureFunction *qf, ParFiniteElementSpace *fes,
Vector &x0)
{
const FiniteElement *fe;
const IntegrationRule *ir;
double* qf_data = qf->ReadWrite();
int qf_offset = qf->GetVDim(); // offset at each integration point
QuadratureSpace* qspace = qf->GetSpace();
ParGridFunction x_gf;
double* vals = x0.ReadWrite();
const int NE = fes->GetNE();
x_gf.MakeTRef(fes, vals);
x_gf.SetFromTrueVector();
// loop over elements
for (int i = 0; i < NE; ++i) {
// get element transformation for the ith element
ElementTransformation* Ttr = fes->GetElementTransformation(i);
fe = fes->GetFE(i);
// declare data to store shape function gradients
// and element Jacobians
DenseMatrix Jrt, DSh, DS, PMatI, Jpt, F0, F1;
int dof = fe->GetDof(), dim = fe->GetDim();
if (qf_offset != (dim * dim)) {
mfem_error("computeDefGrd0 stride input arg not dim*dim");
}
DSh.SetSize(dof, dim);
DS.SetSize(dof, dim);
Jrt.SetSize(dim);
Jpt.SetSize(dim);
F0.SetSize(dim);
F1.SetSize(dim);
PMatI.SetSize(dof, dim);
// get element physical coordinates
// Array<int> vdofs;
// Vector el_x;
// fes->GetElementVDofs(i, vdofs);
// x0.GetSubVector(vdofs, el_x);
// PMatI.UseExternalData(el_x.ReadWrite(), dof, dim);
// get element physical coordinates
Array<int> vdofs(dof * dim);
Vector el_x(PMatI.Data(), dof * dim);
fes->GetElementVDofs(i, vdofs);
x_gf.GetSubVector(vdofs, el_x);
ir = &(qspace->GetElementIntRule(i));
int elem_offset = qf_offset * ir->GetNPoints();
// loop over integration points where the quadrature function is
// stored
for (int j = 0; j < ir->GetNPoints(); ++j) {
const IntegrationPoint &ip = ir->IntPoint(j);
Ttr->SetIntPoint(&ip);
CalcInverse(Ttr->Jacobian(), Jrt);
fe->CalcDShape(ip, DSh);
Mult(DSh, Jrt, DS);
MultAtB(PMatI, DS, Jpt);
// store local beginning step deformation gradient for a given
// element and integration point from the quadrature function
// input argument. We want to set the new updated beginning
// step deformation gradient (prior to next time step) to the current
// end step deformation gradient associated with the converged
// incremental solution. The converged _incremental_ def grad is Jpt
// that we just computed above. We compute the updated beginning
// step def grad as F1 = Jpt*F0; F0 = F1; We do this because we
// are not storing F1.
int k = 0;
for (int n = 0; n < dim; ++n) {
for (int m = 0; m < dim; ++m) {
F0(m, n) = qf_data[i * elem_offset + j * qf_offset + k];
++k;
}
}
// compute F1 = Jpt*F0;
Mult(Jpt, F0, F1);
// set new F0 = F1
F0 = F1;
// loop over element Jacobian data and populate
// quadrature function with the new F0 in preparation for the next
// time step. Note: offset0 should be the
// number of true state variables.
k = 0;
for (int m = 0; m < dim; ++m) {
for (int n = 0; n < dim; ++n) {
qf_data[i * elem_offset + j * qf_offset + k] =
F0(n, m);
++k;
}
}
}
Ttr = NULL;
}
fe = NULL;
ir = NULL;
qf_data = NULL;
qspace = NULL;
return;
}
// This method sets the end time step stress to the beginning step
// and then returns the internal data pointer of the end time step
// array.
double* ExaModel::StressSetup()
{
const double *stress_beg = stress0->Read();
double *stress_end = stress1->ReadWrite();
const int N = stress0->Size();
MFEM_FORALL(i, N, stress_end[i] = stress_beg[i]; );
return stress_end;
}
// This methods set the end time step state variable array to the
// beginning time step values and then returns the internal data pointer
// of the end time step array.
double* ExaModel::StateVarsSetup()
{
const double *state_vars_beg = matVars0->Read();
double *state_vars_end = matVars1->ReadWrite();
const int N = matVars0->Size();
MFEM_FORALL(i, N, state_vars_end[i] = state_vars_beg[i]; );
return state_vars_end;
}
// the getter simply returns the beginning step stress
void ExaModel::GetElementStress(const int elID, const int ipNum,
bool beginStep, double* stress, int numComps)
{
const IntegrationRule *ir = NULL;
double* qf_data = NULL;
int qf_offset = 0;
QuadratureFunction* qf = NULL;
QuadratureSpace* qspace = NULL;
if (beginStep) {
qf = stress0;
}
else {
qf = stress1;
}
qf_data = qf->HostReadWrite();
qf_offset = qf->GetVDim();
qspace = qf->GetSpace();
// check offset to input number of components
if (qf_offset != numComps) {
cerr << "\nGetElementStress: number of components does not match quad func offset"
<< endl;
}
ir = &(qspace->GetElementIntRule(elID));
int elem_offset = qf_offset * ir->GetNPoints();
for (int i = 0; i<numComps; ++i) {
stress[i] = qf_data[elID * elem_offset + ipNum * qf_offset + i];
}
ir = NULL;
qf_data = NULL;
qf = NULL;
qspace = NULL;
return;
}
void ExaModel::SetElementStress(const int elID, const int ipNum,
bool beginStep, double* stress, int numComps)
{
// printf("inside ExaModel::SetElementStress, elID, ipNum %d %d \n", elID, ipNum);
const IntegrationRule *ir;
double* qf_data;
int qf_offset;
QuadratureFunction* qf;
QuadratureSpace* qspace;
if (beginStep) {
qf = stress0;
}
else {
qf = stress1;
}
qf_data = qf->HostReadWrite();
qf_offset = qf->GetVDim();
qspace = qf->GetSpace();
// check offset to input number of components
if (qf_offset != numComps) {
cerr << "\nSetElementStress: number of components does not match quad func offset"
<< endl;
}
ir = &(qspace->GetElementIntRule(elID));
int elem_offset = qf_offset * ir->GetNPoints();
for (int i = 0; i<qf_offset; ++i) {
int k = elID * elem_offset + ipNum * qf_offset + i;
qf_data[k] = stress[i];
}
return;
}
void ExaModel::GetElementStateVars(const int elID, const int ipNum,
bool beginStep, double* stateVars,
int numComps)
{
const IntegrationRule *ir;
double* qf_data;
int qf_offset;
QuadratureFunction* qf;
QuadratureSpace* qspace;
if (beginStep) {
qf = matVars0;
}
else {
qf = matVars1;
}
qf_data = qf->ReadWrite();
qf_offset = qf->GetVDim();
qspace = qf->GetSpace();
// check offset to input number of components
if (qf_offset != numComps) {
cerr << "\nGetElementStateVars: num. components does not match quad func offset"
<< endl;
}
ir = &(qspace->GetElementIntRule(elID));
int elem_offset = qf_offset * ir->GetNPoints();
for (int i = 0; i<numComps; ++i) {
stateVars[i] = qf_data[elID * elem_offset + ipNum * qf_offset + i];
}
ir = NULL;
qf_data = NULL;
qf = NULL;
qspace = NULL;
return;
}
void ExaModel::SetElementStateVars(const int elID, const int ipNum,
bool beginStep, double* stateVars,
int numComps)
{
const IntegrationRule *ir;
double* qf_data;
int qf_offset;
QuadratureFunction* qf;
QuadratureSpace* qspace;
if (beginStep) {
qf = matVars0;
}
else {
qf = matVars1;
}
qf_data = qf->ReadWrite();
qf_offset = qf->GetVDim();
qspace = qf->GetSpace();
// check offset to input number of components
if (qf_offset != numComps) {
cerr << "\nSetElementStateVars: num. components does not match quad func offset"
<< endl;
}
ir = &(qspace->GetElementIntRule(elID));
int elem_offset = qf_offset * ir->GetNPoints();
for (int i = 0; i<qf_offset; ++i) {
qf_data[elID * elem_offset + ipNum * qf_offset + i] = stateVars[i];
}
ir = NULL;
qf_data = NULL;
qf = NULL;
qspace = NULL;
return;
}
void ExaModel::GetElementMatGrad(const int elID, const int ipNum, double* grad,
int numComps)
{
const IntegrationRule *ir;
double* qf_data;
int qf_offset;
QuadratureFunction* qf;
QuadratureSpace* qspace;
qf = matGrad;
qf_data = qf->HostReadWrite();
qf_offset = qf->GetVDim();
qspace = qf->GetSpace();
// check offset to input number of components
if (qf_offset != numComps) {
cerr << "\nGetElementMatGrad: num. components does not match quad func offset"
<< endl;
}
ir = &(qspace->GetElementIntRule(elID));
int elem_offset = qf_offset * ir->GetNPoints();
for (int i = 0; i<numComps; ++i) {
grad[i] = qf_data[elID * elem_offset + ipNum * qf_offset + i];
}
ir = NULL;
qf_data = NULL;
qf = NULL;
qspace = NULL;
return;
}
void ExaModel::SetElementMatGrad(const int elID, const int ipNum,
double* grad, int numComps)
{
const IntegrationRule *ir;
double* qf_data;
int qf_offset;
QuadratureFunction* qf;
QuadratureSpace* qspace;
qf = matGrad;
qf_data = qf->ReadWrite();
qf_offset = qf->GetVDim();
qspace = qf->GetSpace();
// check offset to input number of components
if (qf_offset != numComps) {
cerr << "\nSetElementMatGrad: num. components does not match quad func offset"
<< endl;
}
ir = &(qspace->GetElementIntRule(elID));
int elem_offset = qf_offset * ir->GetNPoints();
for (int i = 0; i<qf_offset; ++i) {
int k = elID * elem_offset + ipNum * qf_offset + i;
qf_data[k] = grad[i];
}
ir = NULL;
qf_data = NULL;
qf = NULL;
qspace = NULL;
return;
}
void ExaModel::GetMatProps(double* props)
{
double* mpdata = matProps->ReadWrite();
for (int i = 0; i < matProps->Size(); i++) {
props[i] = mpdata[i];
}
return;
}
void ExaModel::SetMatProps(double* props, int size)
{
matProps->NewDataAndSize(props, size);
return;
}
void ExaModel::UpdateStress()
{
stress0->Swap(*stress1);
}
void ExaModel::UpdateStateVars()
{
matVars0->Swap(*matVars1);
}
void ExaModel::UpdateEndCoords(const Vector& vels)
{
int size;
size = vels.Size();
Vector end_crds(size);
end_crds = 0.0;
// tdofs sounds like it should hold the data points of interest, since the GetTrueDofs()
// points to the underlying data in the GridFunction if all the TDofs lie on a processor
Vector bcrds;
bcrds.SetSize(size);
// beg_coords is the beginning time step coordinates
beg_coords->GetTrueDofs(bcrds);
int size2 = bcrds.Size();
if (size != size2) {
mfem_error("TrueDofs and Vel Solution vector sizes are different");
}
const double* bcrd = bcrds.Read();
const double* vel = vels.Read();
double* end_crd = end_crds.ReadWrite();
// Perform a simple time integration to get our new end time step coordinates
MFEM_FORALL(i, size, {
end_crd[i] = vel[i] * dt + bcrd[i];
});
// Now make sure the update gets sent to all the other processors that have ghost copies
// of our data.
end_coords->Distribute(end_crds);
return;
}
// A helper function that takes in a 3x3 rotation matrix and converts it over
// to a unit quaternion.
// rmat should be constant here...
void ExaModel::RMat2Quat(const DenseMatrix& rmat, Vector& quat)
{
double inv2 = 1.0 / 2.0;
double phi = 0.0;
static const double eps = numeric_limits<double>::epsilon();
double tr_r = 0.0;
double inv_sin = 0.0;
double s = 0.0;
quat = 0.0;
tr_r = rmat(0, 0) + rmat(1, 1) + rmat(2, 2);
phi = inv2 * (tr_r - 1.0);
phi = min(phi, 1.0);
phi = max(phi, -1.0);
phi = acos(phi);
if (abs(phi) < eps) {
quat[3] = 1.0;
}
else {
inv_sin = 1.0 / sin(phi);
quat[0] = phi;
quat[1] = inv_sin * inv2 * (rmat(2, 1) - rmat(1, 2));
quat[2] = inv_sin * inv2 * (rmat(0, 2) - rmat(2, 0));
quat[3] = inv_sin * inv2 * (rmat(1, 0) - rmat(0, 1));
}
s = sin(inv2 * quat[0]);
quat[0] = cos(quat[0] * inv2);
quat[1] = s * quat[1];
quat[2] = s * quat[2];
quat[3] = s * quat[3];
return;
}
// A helper function that takes in a unit quaternion and and returns a 3x3 rotation
// matrix.
void ExaModel::Quat2RMat(const Vector& quat, DenseMatrix& rmat)
{
double qbar = 0.0;
qbar = quat[0] * quat[0] - (quat[1] * quat[1] + quat[2] * quat[2] + quat[3] * quat[3]);
rmat(0, 0) = qbar + 2.0 * quat[1] * quat[1];
rmat(1, 0) = 2.0 * (quat[1] * quat[2] + quat[0] * quat[3]);
rmat(2, 0) = 2.0 * (quat[1] * quat[3] - quat[0] * quat[2]);
rmat(0, 1) = 2.0 * (quat[1] * quat[2] - quat[0] * quat[3]);
rmat(1, 1) = qbar + 2.0 * quat[2] * quat[2];
rmat(2, 1) = 2.0 * (quat[2] * quat[3] + quat[0] * quat[1]);
rmat(0, 2) = 2.0 * (quat[1] * quat[3] + quat[0] * quat[2]);
rmat(1, 2) = 2.0 * (quat[2] * quat[3] - quat[0] * quat[1]);
rmat(2, 2) = qbar + 2.0 * quat[3] * quat[3];
return;
}
// The below method computes the polar decomposition of a 3x3 matrix using a method
// proposed in: https://animation.rwth-aachen.de/media/papers/2016-MIG-StableRotation.pdf
// The paper listed provides a fast and robust way to obtain the rotation portion
// of a positive definite 3x3 matrix which then allows for the easy computation
// of U and V.
void ExaModel::CalcPolarDecompDefGrad(DenseMatrix& R, DenseMatrix& U,
DenseMatrix& V, double err)
{
DenseMatrix omega_mat, temp;
DenseMatrix def_grad(R, 3);
int dim = 3;
Vector quat;
int max_iter = 500;
double norm, inv_norm;
double ac1[3], ac2[3], ac3[3];
double w_top[3], w[3];
double w_bot, w_norm, w_norm_inv2, w_norm_inv;
double cth, sth;
double r1da1, r2da2, r3da3;
quat.SetSize(4);
omega_mat.SetSize(dim);
temp.SetSize(dim);
quat = 0.0;
RMat2Quat(def_grad, quat);
norm = quat.Norml2();
inv_norm = 1.0 / norm;
quat *= inv_norm;
Quat2RMat(quat, R);
ac1[0] = def_grad(0, 0); ac1[1] = def_grad(1, 0); ac1[2] = def_grad(2, 0);
ac2[0] = def_grad(0, 1); ac2[1] = def_grad(1, 1); ac2[2] = def_grad(2, 1);
ac3[0] = def_grad(0, 2); ac3[1] = def_grad(1, 2); ac3[2] = def_grad(2, 2);
for (int i = 0; i < max_iter; i++) {
// The dot products that show up in the paper
r1da1 = R(0, 0) * ac1[0] + R(1, 0) * ac1[1] + R(2, 0) * ac1[2];
r2da2 = R(0, 1) * ac2[0] + R(1, 1) * ac2[1] + R(2, 1) * ac2[2];
r3da3 = R(0, 2) * ac3[0] + R(1, 2) * ac3[1] + R(2, 2) * ac3[2];
// The summed cross products that show up in the paper
w_top[0] = (-R(2, 0) * ac1[1] + R(1, 0) * ac1[2]) +
(-R(2, 1) * ac2[1] + R(1, 1) * ac2[2]) +
(-R(2, 2) * ac3[1] + R(1, 2) * ac3[2]);
w_top[1] = (R(2, 0) * ac1[0] - R(0, 0) * ac1[2]) +
(R(2, 1) * ac2[0] - R(0, 1) * ac2[2]) +
(R(2, 2) * ac3[0] - R(0, 2) * ac3[2]);
w_top[2] = (-R(1, 0) * ac1[0] + R(0, 0) * ac1[1]) +
(-R(1, 1) * ac2[0] + R(0, 1) * ac2[1]) +
(-R(1, 2) * ac3[0] + R(0, 2) * ac3[1]);
w_bot = (1.0 / (abs(r1da1 + r2da2 + r3da3) + err));
// The axial vector that shows up in the paper
w[0] = w_top[0] * w_bot; w[1] = w_top[1] * w_bot; w[2] = w_top[2] * w_bot;
// The norm of the axial vector
w_norm = sqrt(w[0] * w[0] + w[1] * w[1] + w[2] * w[2]);
// If the norm is below our desired error we've gotten our solution
// So we can break out of the loop
if (w_norm < err) {
break;
}
// The exponential mapping for an axial vector
// The 3x3 case has been explicitly unrolled here
w_norm_inv2 = 1.0 / (w_norm * w_norm);
w_norm_inv = 1.0 / w_norm;
sth = sin(w_norm) * w_norm_inv;
cth = (1.0 - cos(w_norm)) * w_norm_inv2;
omega_mat(0, 0) = 1.0 - cth * (w[2] * w[2] + w[1] * w[1]);
omega_mat(1, 1) = 1.0 - cth * (w[2] * w[2] + w[0] * w[0]);
omega_mat(2, 2) = 1.0 - cth * (w[1] * w[1] + w[0] * w[0]);
omega_mat(0, 1) = -sth * w[2] + cth * w[1] * w[0];
omega_mat(0, 2) = sth * w[1] + cth * w[2] * w[0];
omega_mat(1, 0) = sth * w[2] + cth * w[0] * w[1];
omega_mat(1, 2) = -sth * w[0] + cth * w[2] * w[1];
omega_mat(2, 0) = -sth * w[1] + cth * w[0] * w[2];
omega_mat(2, 1) = sth * w[0] + cth * w[2] * w[1];
Mult(omega_mat, R, temp);
R = temp;
}
// Now that we have the rotation portion of our deformation gradient
// the left and right stretch tensors are easy to find.
MultAtB(R, def_grad, U);
MultABt(def_grad, R, V);
return;
}
// This method calculates the Eulerian strain which is given as:
// e = 1/2 (I - B^(-1)) = 1/2 (I - F(^-T)F^(-1))
void ExaModel::CalcEulerianStrain(DenseMatrix& E, const DenseMatrix &F)
{
int dim = 3;
DenseMatrix Finv(dim), Binv(dim);
double half = 1.0 / 2.0;
CalcInverse(F, Finv);
MultAtB(Finv, Finv, Binv);
E = 0.0;
for (int j = 0; j < dim; j++) {
for (int i = 0; i < dim; i++) {
E(i, j) -= half * Binv(i, j);
}
E(j, j) += half;
}
return;
}
// This method calculates the Lagrangian strain which is given as:
// E = 1/2 (C - I) = 1/2 (F^(T)F - I)
void ExaModel::CalcLagrangianStrain(DenseMatrix& E, const DenseMatrix &F)
{
int dim = 3;
// DenseMatrix F(Jpt, dim);
DenseMatrix C(dim);
double half = 1.0 / 2.0;
MultAtB(F, F, C);
E = 0.0;
for (int j = 0; j < dim; j++) {
for (int i = 0; i < dim; i++) {
E(i, j) += half * C(i, j);
}
E(j, j) -= half;
}
return;
}
// This method calculates the Biot strain which is given as:
// E = (U - I) or sometimes seen as E = (V - I) if R = I
void ExaModel::CalcBiotStrain(DenseMatrix& E, const DenseMatrix &F)
{
int dim = 3;
DenseMatrix rmat(F, dim);
DenseMatrix umat, vmat;
umat.SetSize(dim);
vmat.SetSize(dim);
CalcPolarDecompDefGrad(rmat, umat, vmat);
E = umat;
E(0, 0) -= 1.0;
E(1, 1) -= 1.0;
E(2, 2) -= 1.0;
return;
}
void ExaModel::CalcLogStrain(DenseMatrix& E, const DenseMatrix &F)
{
// calculate current end step logorithmic strain (Hencky Strain)
// which is taken to be E = ln(U) = 1/2 ln(C), where C = (F_T)F.
// We have incremental F from MFEM, and store F0 (Jpt0) so
// F = F_hat*F0. With F, use a spectral decomposition on C to obtain a
// form where we only have to take the natural log of the
// eigenvalues
// UMAT uses the E = ln(V) approach instead
DenseMatrix B;
int dim = 3;
B.SetSize(dim);
// F.SetSize(dim);
// F = Jpt;
MultABt(F, F, B);
// compute eigenvalue decomposition of B
double lambda[dim];
double vec[dim * dim];
// fix_me: was failing
B.CalcEigenvalues(&lambda[0], &vec[0]);
// compute ln(V) using spectral representation
E = 0.0;
for (int i = 0; i<dim; ++i) { // outer loop for every eigenvalue/vector
for (int j = 0; j<dim; ++j) { // inner loops for diadic product of eigenvectors
for (int k = 0; k<dim; ++k) {
// Dense matrices are col. maj. representation, so the indices were
// reversed for it to be more cache friendly.
E(k, j) += 0.5 * log(lambda[i]) * vec[i * dim + j] * vec[i * dim + k];
}
}
}
return;
}
// This function is used in generating the B matrix commonly seen in the formation of
// the material tangent stiffness matrix in mechanics [B^t][Cstiff][B]
// Although we're goint to return really B^t here since it better matches up
// with how DS is set up memory wise
// The B matrix should have dimensions equal to (dof*dim, 6).
// We assume it hasn't been initialized ahead of time or it's already
// been written in, so we rewrite over everything in the below.
void ExaModel::GenerateGradMatrix(const DenseMatrix& DS, DenseMatrix& B)
{
int dof = DS.Height();
// The B matrix generally has the following structure that is
// repeated for the number of dofs if we're dealing with something
// that results in a symmetric Cstiff. If we aren't then it's a different
// structure
// [DS(i,0) 0 0]
// [0 DS(i, 1) 0]
// [0 0 DS(i, 2)]
// [0 DS(i,2) DS(i,1)]
// [DS(i,2) 0 DS(i,0)]
// [DS(i,1) DS(i,0) 0]
// Just going to go ahead and make the assumption that
// this is for a 3D space. Should put either an assert
// or an error here if it isn't
// We should also put an assert if B doesn't have dimensions of
// (dim*dof, 6)
// fix_me
// We've rolled out the above B matrix in the comments
// This is definitely not the most efficient way of doing this memory wise.
// However, it might be fine for our needs.
// The ordering has now changed such that B matches up with mfem's internal
// ordering of vectors such that it's [x0...xn, y0...yn, z0...zn] ordering
// The previous single loop has been split into 3 so the B matrix
// is constructed in chunks now instead of performing multiple striding
// operations in a single loop.
// x dofs
for (int i = 0; i < dof; i++) {
B(i, 0) = DS(i, 0);
B(i, 1) = 0.0;
B(i, 2) = 0.0;
B(i, 3) = 0.0;
B(i, 4) = DS(i, 2);
B(i, 5) = DS(i, 1);
}
// y dofs
for (int i = 0; i < dof; i++) {
B(i + dof, 0) = 0.0;
B(i + dof, 1) = DS(i, 1);
B(i + dof, 2) = 0.0;
B(i + dof, 3) = DS(i, 2);
B(i + dof, 4) = 0.0;
B(i + dof, 5) = DS(i, 0);
}
// z dofs
for (int i = 0; i < dof; i++) {
B(i + 2 * dof, 0) = 0.0;
B(i + 2 * dof, 1) = 0.0;
B(i + 2 * dof, 2) = DS(i, 2);
B(i + 2 * dof, 3) = DS(i, 1);
B(i + 2 * dof, 4) = DS(i, 0);
B(i + 2 * dof, 5) = 0.0;
}
return;
}
void ExaModel::GenerateGradBarMatrix(const mfem::DenseMatrix& DS, const mfem::DenseMatrix& eDS, mfem::DenseMatrix& B)
{
int dof = DS.Height();
for (int i = 0; i < dof; i++) {
const double B1 = (eDS(i, 0) - DS(i, 0)) / 3.0;
B(i, 0) = B1 + DS(i, 0);
B(i, 1) = B1;
B(i, 2) = B1;
B(i, 3) = 0.0;
B(i, 4) = DS(i, 2);
B(i, 5) = DS(i, 1);
}
// y dofs
for (int i = 0; i < dof; i++) {
const double B2 = (eDS(i, 1) - DS(i, 1)) / 3.0;
B(i + dof, 0) = B2;
B(i + dof, 1) = B2 + DS(i, 1);
B(i + dof, 2) = B2;
B(i + dof, 3) = DS(i, 2);
B(i + dof, 4) = 0.0;
B(i + dof, 5) = DS(i, 0);
}
// z dofs
for (int i = 0; i < dof; i++) {
const double B3 = (eDS(i, 2) - DS(i, 2)) / 3.0;
B(i + 2 * dof, 0) = B3;
B(i + 2 * dof, 1) = B3;
B(i + 2 * dof, 2) = B3 + DS(i, 2);
B(i + 2 * dof, 3) = DS(i, 1);
B(i + 2 * dof, 4) = DS(i, 0);
B(i + 2 * dof, 5) = 0.0;
}
return;
}
void ExaModel::GenerateGradGeomMatrix(const DenseMatrix& DS, DenseMatrix& Bgeom)
{
int dof = DS.Height();
// For a 3D mesh Bgeom has the following shape:
// [DS(i, 0), 0, 0]
// [DS(i, 0), 0, 0]
// [DS(i, 0), 0, 0]
// [0, DS(i, 1), 0]
// [0, DS(i, 1), 0]
// [0, DS(i, 1), 0]
// [0, 0, DS(i, 2)]
// [0, 0, DS(i, 2)]
// [0, 0, DS(i, 2)]
// We'll be returning the transpose of this.
// It turns out the Bilinear operator can't have this created using
// the dense gradient matrix, DS.
// It can be used in the following: Bgeom^T Sigma_bar Bgeom
// where Sigma_bar is a block diagonal version of sigma repeated 3 times in 3D.
// I'm assumming we're in 3D and have just unrolled the loop
// The ordering has now changed such that Bgeom matches up with mfem's internal
// ordering of vectors such that it's [x0...xn, y0...yn, z0...zn] ordering
// The previous single loop has been split into 3 so the B matrix
// is constructed in chunks now instead of performing multiple striding
// operations in a single loop.
// x dofs
for (int i = 0; i < dof; i++) {
Bgeom(i, 0) = DS(i, 0);
Bgeom(i, 1) = DS(i, 1);
Bgeom(i, 2) = DS(i, 2);
Bgeom(i, 3) = 0.0;
Bgeom(i, 4) = 0.0;
Bgeom(i, 5) = 0.0;
Bgeom(i, 6) = 0.0;
Bgeom(i, 7) = 0.0;
Bgeom(i, 8) = 0.0;
}
// y dofs
for (int i = 0; i < dof; i++) {
Bgeom(i + dof, 0) = 0.0;
Bgeom(i + dof, 1) = 0.0;
Bgeom(i + dof, 2) = 0.0;
Bgeom(i + dof, 3) = DS(i, 0);
Bgeom(i + dof, 4) = DS(i, 1);
Bgeom(i + dof, 5) = DS(i, 2);
Bgeom(i + dof, 6) = 0.0;
Bgeom(i + dof, 7) = 0.0;
Bgeom(i + dof, 8) = 0.0;
}
// z dofs
for (int i = 0; i < dof; i++) {
Bgeom(i + 2 * dof, 0) = 0.0;
Bgeom(i + 2 * dof, 1) = 0.0;
Bgeom(i + 2 * dof, 2) = 0.0;
Bgeom(i + 2 * dof, 3) = 0.0;
Bgeom(i + 2 * dof, 4) = 0.0;
Bgeom(i + 2 * dof, 5) = 0.0;
Bgeom(i + 2 * dof, 6) = DS(i, 0);
Bgeom(i + 2 * dof, 7) = DS(i, 1);
Bgeom(i + 2 * dof, 8) = DS(i, 2);
}
}
// This takes in the material gradient matrix that's being used in most models as the 2D
// version and saves off the 4D space version
void ExaModel::TransformMatGradTo4D()
{
const int npts = matGrad->Size() / matGrad->GetVDim();
const int dim = 3;
const int dim2 = 6;
const int DIM5 = 5;
const int DIM3 = 3;
std::array<RAJA::idx_t, DIM5> perm5 {{ 4, 3, 2, 1, 0 } };
std::array<RAJA::idx_t, DIM3> perm3 {{ 2, 1, 0 } };
// bunch of helper RAJA views to make dealing with data easier down below in our kernel.
RAJA::Layout<DIM5> layout_4Dtensor = RAJA::make_permuted_layout({{ dim, dim, dim, dim, npts } }, perm5);
RAJA::View<double, RAJA::Layout<DIM5, RAJA::Index_type, 0> > cmat_4d(matGradPA.ReadWrite(), layout_4Dtensor);
// bunch of helper RAJA views to make dealing with data easier down below in our kernel.
RAJA::Layout<DIM3> layout_2Dtensor = RAJA::make_permuted_layout({{ dim2, dim2, npts } }, perm3);
RAJA::View<const double, RAJA::Layout<DIM3, RAJA::Index_type, 0> > cmat(matGrad->Read(), layout_2Dtensor);
// This sets up our 4D tensor to be the same as the 2D tensor which takes advantage of symmetry operations
MFEM_FORALL(i, npts, {
cmat_4d(0, 0, 0, 0, i) = cmat(0, 0, i);
cmat_4d(1, 1, 0, 0, i) = cmat(1, 0, i);
cmat_4d(2, 2, 0, 0, i) = cmat(2, 0, i);
cmat_4d(1, 2, 0, 0, i) = cmat(3, 0, i);
cmat_4d(2, 1, 0, 0, i) = cmat_4d(1, 2, 0, 0, i);
cmat_4d(2, 0, 0, 0, i) = cmat(4, 0, i);
cmat_4d(0, 2, 0, 0, i) = cmat_4d(2, 0, 0, 0, i);
cmat_4d(0, 1, 0, 0, i) = cmat(5, 0, i);
cmat_4d(1, 0, 0, 0, i) = cmat_4d(0, 1, 0, 0, i);
cmat_4d(0, 0, 1, 1, i) = cmat(0, 1, i);
cmat_4d(1, 1, 1, 1, i) = cmat(1, 1, i);
cmat_4d(2, 2, 1, 1, i) = cmat(2, 1, i);
cmat_4d(1, 2, 1, 1, i) = cmat(3, 1, i);
cmat_4d(2, 1, 1, 1, i) = cmat_4d(1, 2, 1, 1, i);
cmat_4d(2, 0, 1, 1, i) = cmat(4, 1, i);
cmat_4d(0, 2, 1, 1, i) = cmat_4d(2, 0, 1, 1, i);
cmat_4d(0, 1, 1, 1, i) = cmat(5, 1, i);
cmat_4d(1, 0, 1, 1, i) = cmat_4d(0, 1, 1, 1, i);
cmat_4d(0, 0, 2, 2, i) = cmat(0, 2, i);
cmat_4d(1, 1, 2, 2, i) = cmat(1, 2, i);
cmat_4d(2, 2, 2, 2, i) = cmat(2, 2, i);
cmat_4d(1, 2, 2, 2, i) = cmat(3, 2, i);
cmat_4d(2, 1, 2, 2, i) = cmat_4d(1, 2, 2, 2, i);
cmat_4d(2, 0, 2, 2, i) = cmat(4, 2, i);
cmat_4d(0, 2, 2, 2, i) = cmat_4d(2, 0, 2, 2, i);
cmat_4d(0, 1, 2, 2, i) = cmat(5, 2, i);
cmat_4d(1, 0, 2, 2, i) = cmat_4d(0, 1, 2, 2, i);
cmat_4d(0, 0, 1, 2, i) = cmat(0, 3, i);
cmat_4d(1, 1, 1, 2, i) = cmat(1, 3, i);
cmat_4d(2, 2, 1, 2, i) = cmat(2, 3, i);
cmat_4d(1, 2, 1, 2, i) = cmat(3, 3, i);
cmat_4d(2, 1, 1, 2, i) = cmat_4d(1, 2, 1, 2, i);
cmat_4d(2, 0, 1, 2, i) = cmat(4, 3, i);
cmat_4d(0, 2, 1, 2, i) = cmat_4d(2, 0, 1, 2, i);
cmat_4d(0, 1, 1, 2, i) = cmat(5, 3, i);
cmat_4d(1, 0, 1, 2, i) = cmat_4d(0, 1, 1, 2, i);
cmat_4d(0, 0, 2, 1, i) = cmat(0, 3, i);
cmat_4d(1, 1, 2, 1, i) = cmat(1, 3, i);
cmat_4d(2, 2, 2, 1, i) = cmat(2, 3, i);
cmat_4d(1, 2, 2, 1, i) = cmat(3, 3, i);
cmat_4d(2, 1, 2, 1, i) = cmat_4d(1, 2, 1, 2, i);
cmat_4d(2, 0, 2, 1, i) = cmat(4, 3, i);
cmat_4d(0, 2, 2, 1, i) = cmat_4d(2, 0, 1, 2, i);
cmat_4d(0, 1, 2, 1, i) = cmat(5, 3, i);
cmat_4d(1, 0, 2, 1, i) = cmat_4d(0, 1, 1, 2, i);
cmat_4d(0, 0, 2, 0, i) = cmat(0, 4, i);
cmat_4d(1, 1, 2, 0, i) = cmat(1, 4, i);
cmat_4d(2, 2, 2, 0, i) = cmat(2, 4, i);
cmat_4d(1, 2, 2, 0, i) = cmat(3, 4, i);
cmat_4d(2, 1, 2, 0, i) = cmat_4d(1, 2, 2, 0, i);
cmat_4d(2, 0, 2, 0, i) = cmat(4, 4, i);
cmat_4d(0, 2, 2, 0, i) = cmat_4d(2, 0, 2, 0, i);
cmat_4d(0, 1, 2, 0, i) = cmat(5, 4, i);
cmat_4d(1, 0, 2, 0, i) = cmat_4d(0, 1, 2, 0, i);
cmat_4d(0, 0, 0, 2, i) = cmat(0, 4, i);
cmat_4d(1, 1, 0, 2, i) = cmat(1, 4, i);
cmat_4d(2, 2, 0, 2, i) = cmat(2, 4, i);
cmat_4d(1, 2, 0, 2, i) = cmat(3, 4, i);
cmat_4d(2, 1, 0, 2, i) = cmat_4d(1, 2, 2, 0, i);
cmat_4d(2, 0, 0, 2, i) = cmat(4, 4, i);
cmat_4d(0, 2, 0, 2, i) = cmat_4d(2, 0, 2, 0, i);
cmat_4d(0, 1, 0, 2, i) = cmat(5, 4, i);
cmat_4d(1, 0, 0, 2, i) = cmat_4d(0, 1, 2, 0, i);
cmat_4d(0, 0, 0, 1, i) = cmat(0, 5, i);
cmat_4d(1, 1, 0, 1, i) = cmat(1, 5, i);
cmat_4d(2, 2, 0, 1, i) = cmat(2, 5, i);
cmat_4d(1, 2, 0, 1, i) = cmat(3, 5, i);
cmat_4d(2, 1, 0, 1, i) = cmat_4d(1, 2, 0, 1, i);
cmat_4d(2, 0, 0, 1, i) = cmat(4, 5, i);
cmat_4d(0, 2, 0, 1, i) = cmat_4d(2, 0, 0, 1, i);
cmat_4d(0, 1, 0, 1, i) = cmat(5, 5, i);
cmat_4d(1, 0, 0, 1, i) = cmat_4d(0, 1, 0, 1, i);
cmat_4d(0, 0, 1, 0, i) = cmat(0, 5, i);
cmat_4d(1, 1, 1, 0, i) = cmat(1, 5, i);
cmat_4d(2, 2, 1, 0, i) = cmat(2, 5, i);
cmat_4d(1, 2, 1, 0, i) = cmat(3, 5, i);
cmat_4d(2, 1, 1, 0, i) = cmat_4d(1, 2, 0, 1, i);
cmat_4d(2, 0, 1, 0, i) = cmat(4, 5, i);
cmat_4d(0, 2, 1, 0, i) = cmat_4d(2, 0, 0, 1, i);
cmat_4d(0, 1, 1, 0, i) = cmat(5, 5, i);
cmat_4d(1, 0, 1, 0, i) = cmat_4d(0, 1, 0, 1, i);
});
} | 29.531792 | 117 | 0.548542 | [
"mesh",
"shape",
"vector",
"3d"
] |
a016f5a968282c26570440ca8c1cc36d5682a72f | 10,744 | cpp | C++ | examples/cpp/builtin_objects/builtin_objects.cpp | LightEngineProject/light-engine | 5a343dd0b4c58ff77e29c1c31ff8e7d7d16dce66 | [
"MIT"
] | null | null | null | examples/cpp/builtin_objects/builtin_objects.cpp | LightEngineProject/light-engine | 5a343dd0b4c58ff77e29c1c31ff8e7d7d16dce66 | [
"MIT"
] | 2 | 2019-02-24T16:52:34.000Z | 2019-02-28T10:41:22.000Z | examples/cpp/builtin_objects/builtin_objects.cpp | LightEngineProjects/light-engine | 5a343dd0b4c58ff77e29c1c31ff8e7d7d16dce66 | [
"MIT"
] | null | null | null | #include <light_engine.hpp>
#include <gui_common.hpp>
using namespace LE;
void generate_points(glm::vec3 const & min_pt, glm::vec3 const& max_pt) {
shader_prog_ptr_t shader_prog = shader_prog_t::create_default();
for (size_t i = 0; i < 10; ++i) {
point_t point(min_pt + (max_pt - min_pt) * glm::vec3((float)rand() / RAND_MAX, (float)rand() / RAND_MAX, (float)rand() / RAND_MAX));
point.set_shader_prog(shader_prog);
point.set_color(glm::vec3(0, 1, 0));
object_ptr_t object = point.compile();
object->set_points_size(i + 1);
scene->add_object(object);
}
}
void generate_triangles(glm::vec3 const& min_pt, glm::vec3 const& max_pt) {
shader_prog_ptr_t shader_prog = shader_prog_t::create_default();
std::array<glm::vec3, 3> triangle_vertices;
for (size_t i = 0; i < 2; ++i) {
for (auto & vertex : triangle_vertices)
vertex = glm::vec3(min_pt + (max_pt - min_pt) * glm::vec3((float)rand() / RAND_MAX, (float)rand() / RAND_MAX, (float)rand() / RAND_MAX));
triangle_t triangle(triangle_vertices);
triangle.set_shader_prog(shader_prog);
triangle.set_color(glm::vec3(0.5, 0, 0.5));
object_ptr_t object = triangle.compile();
scene->add_object(object);
}
}
void generate_spheres(glm::vec3 const& min_pt, glm::vec3 const& max_pt) {
shader_prog_ptr_t shader_prog = shader_prog_t::create_default();
sphere_t regular_sphere(min_pt + (max_pt - min_pt) * glm::vec3(0.33, 0.5, 0.33), 0.5, 1);
regular_sphere.set_shader_prog(shader_prog);
regular_sphere.set_color(glm::vec3(0, 1, 0));
scene->add_object(regular_sphere.compile());
{
sphere_t detailed_sphere(min_pt + (max_pt - min_pt) * glm::vec3(0.66, 0.5, 0.33), 0.5, 3);
detailed_sphere.set_shader_prog(shader_prog);
detailed_sphere.set_color(glm::vec3(0, 1, 0));
object_ptr_t object = detailed_sphere.compile();
object->set_polygon_mode(object_t::PM_line);
scene->add_object(object);
}
{
sphere_t lighted_sphere(min_pt + (max_pt - min_pt) * glm::vec3(0.33, 0.5, 0.66), 0.5, 3);
lighted_sphere.set_shader_prog(shader_prog_t::create_lightning());
lighted_sphere.set_color(glm::vec3(0, 1, 0));
lighted_sphere.generate_normales();
object_ptr_t object = lighted_sphere.compile();
object->set_uniforms_callback([] (shader_prog_ptr_t const& shader_prog) {
shader_prog->uniform_variable("mvp")->set(camera->model_view_projection_matrix());
shader_prog->uniform_variable("normal_matrix")->set(camera->normal_matrix());
shader_prog->uniform_variable("model_view")->set(camera->model_view_matrix());
shader_prog->uniform_variable("light_position")->set(glm::vec3(0, 1, 10));
shader_prog->uniform_variable("light_color")->set(glm::vec3(1, 1, 1));
shader_prog->uniform_variable("ambient_strength")->set(0.4f);
shader_prog->uniform_variable("diffuse_strength")->set(0.3f);
shader_prog->uniform_variable("specular_strength")->set(0.7f);
}
);
scene->add_object(object);
}
{
sphere_t detailed_sphere(min_pt + (max_pt - min_pt) * glm::vec3(0.66, 0.5, 0.66), 0.5, 5);
detailed_sphere.set_shader_prog(shader_prog_t::create_texture());
detailed_sphere.set_texture(std::make_shared<texture_t>(image_t::generate_chess(32, 32)));
detailed_sphere.generate_tex_coords();
object_ptr_t object = detailed_sphere.compile();
scene->add_object(object);
}
}
void generate_quads(glm::vec3 const& min_pt, glm::vec3 const& max_pt) {
const shader_prog_ptr_t shader_prog = shader_prog_t::create_default();
const float half_z = ((min_pt + max_pt) / 2.f).z;
const glm::vec3 offset = (max_pt - min_pt) / 6.f;
std::array<glm::vec3, 4> quad_vertices{
glm::vec3(min_pt.x + offset.x, min_pt.y + offset.y, half_z),
glm::vec3(min_pt.x + offset.x, max_pt.y - offset.y, half_z),
glm::vec3(max_pt.x - offset.x, max_pt.y - offset.y, half_z),
glm::vec3(max_pt.x - offset.x, min_pt.y + offset.y, half_z)
};
quad_t quad(quad_vertices);
quad.set_shader_prog(shader_prog_t::create_texture());
quad.set_texture(std::make_shared<texture_t>(image_t::generate_chess(6, 6)));
object_ptr_t object = quad.compile();
scene->add_object(object);
}
void generate_box(glm::vec3 const& min_pt, glm::vec3 const& max_pt) {
shader_prog_ptr_t shader_prog = shader_prog_t::create_default();
box_t box((min_pt + max_pt) / 2.f, glm::vec3(0, 0.5, 0), glm::vec3(0.5, 0, 0), glm::vec3(0, 0, 0.5));
box.set_shader_prog(shader_prog);
box.set_color(glm::vec3(1, 1, 0));
object_ptr_t object = box.compile();
scene->add_object(object);
}
void generate_lines(glm::vec3 const& min_pt, glm::vec3 const& max_pt) {
shader_prog_ptr_t shader_prog = shader_prog_t::create_default();
for (unsigned int i = 0; i < 50; ++i) {
line_t line(min_pt + (max_pt - min_pt) * glm::vec3((float)rand() / RAND_MAX, (float)rand() / RAND_MAX, (float)rand() / RAND_MAX),
min_pt + (max_pt - min_pt) * glm::vec3((float)rand() / RAND_MAX, (float)rand() / RAND_MAX, (float)rand() / RAND_MAX));
line.set_shader_prog(shader_prog);
line.set_color(glm::vec3(0.5, 0.5, 1));
object_ptr_t object = line.compile();
scene->add_object(object);
}
}
void generate_point_cloud(glm::vec3 const& min_pt, glm::vec3 const& max_pt) {
shader_prog_ptr_t shader_prog = shader_prog_t::create_default();
const size_t points_num = 10000;
std::vector<glm::vec3> points(points_num);
for (size_t i = 0; i < points_num; ++i)
points[i] = min_pt + (max_pt - min_pt) * glm::vec3((float)rand() / RAND_MAX, (float)rand() / RAND_MAX, (float)rand() / RAND_MAX);
point_cloud_t point_cloud = point_cloud_t(points);
point_cloud.set_shader_prog(shader_prog);
point_cloud.set_color(glm::vec3(1, 0.3, 0.7));
object_ptr_t object = point_cloud.compile();
object->set_points_size(3);
scene->add_object(object);
}
void generate_billboard(glm::vec3 const& min_pt, glm::vec3 const& max_pt) {
const float half_z = ((min_pt + max_pt) / 2.f).z;
const glm::vec3 offset = (max_pt - min_pt) / 6.f;
std::array<glm::vec3, 4> quad_vertices{
glm::vec3(min_pt.x + offset.x, min_pt.y + offset.y, half_z),
glm::vec3(min_pt.x + offset.x, max_pt.y - offset.y, half_z),
glm::vec3(max_pt.x - offset.x, max_pt.y - offset.y, half_z),
glm::vec3(max_pt.x - offset.x, min_pt.y + offset.y, half_z)
};
quad_t quad(quad_vertices);
quad.set_shader_prog(shader_prog_t::create_billboard());
quad.set_color(glm::vec3(1, 0, 0));
object_ptr_t object = quad.compile();
object->set_uniforms_callback([](shader_prog_ptr_t const& shader_prog) {
shader_prog->uniform_variable("billboard_matrix")->set(camera->billboard_matrix(camera->pos()));
}
);
scene->add_object(object);
}
void generate_skybox() {
box_textured_t box(glm::vec3(0, 0, 0), glm::vec3(0, 250, 0), glm::vec3(250, 0, 0), glm::vec3(0, 0, 250));
box.set_shader_prog(shader_prog_t::create_skybox());
box.set_texture(std::make_shared<texture_t>(image_t::generate_chess(128, 128, glm::uvec3(20, 40, 31), glm::uvec3(80, 46, 71))));
object_ptr_t object = box.compile();
object->set_uniforms_callback([](shader_prog_ptr_t const& shader_prog) {
shader_prog->uniform_variable("mvp")->set(camera->model_view_projection_matrix());
shader_prog->uniform_variable("camera_pos")->set(camera->pos());
}
);
object->enable_face_culling(false, false);
scene->add_object(object);
}
void draw_mesh(glm::vec3 const & min_pt, glm::vec3 const & max_pt, glm::vec3 const & cells_num) {
const glm::vec3 cell_size = (max_pt - min_pt) / cells_num;
shader_prog_ptr_t shader_prog = shader_prog_t::create_default();
for (size_t i = 0; i < cells_num.x; ++i)
for (size_t j = 0; j < cells_num.y; ++j)
for (size_t k = 0; k < cells_num.z; ++k) {
box_wireframe_t box(min_pt + cell_size * glm::vec3(i, j, k) + cell_size / 2.f,
0.5f * cell_size * glm::vec3(0, 1, 0), 0.5f * cell_size * glm::vec3(1, 0, 0), 0.5f * cell_size * glm::vec3(0, 0, 1));
box.set_shader_prog(shader_prog);
box.set_color(glm::vec3(1, 1, 1));
object_ptr_t object = box.compile();
scene->add_object(object);
}
}
int main( int argc, char ** argv ) {
examples_gui_t gui(argc, argv, "Builtin Objects Example");
frame_ptr_t frame = std::make_shared<frame_t>();
frame->set_background_color(glm::vec3(0, 0, 0));
light_engine->add_frame(frame);
scene = std::make_shared<scene_t>();
frame->add_scene(scene);
camera = scene->get_camera();
camera->z_far(500);
user_camera = std::make_unique<user_wasd_camera_t>(camera);
user_camera->set_camera_wheel_sensetivity(2);
user_camera->set_camera_keyboard_sensetivity(0.01f);
const glm::vec3 cells_num = glm::vec3(3, 1, 3);
const glm::vec3 min_pt = glm::vec3(-5.f, -10.f / 3, 5.f), max_pt = glm::vec3(5.f, 0.f, 15.f);
const glm::vec3 cell_size = (max_pt - min_pt) / cells_num;
draw_mesh(min_pt, max_pt, cells_num);
generate_skybox();
unsigned int cur_cell_x = 0, cur_cell_z = 0;
generate_points(min_pt + glm::vec3(cur_cell_x, 0, cur_cell_z) * cell_size, min_pt + glm::vec3(cur_cell_x + 1, 1, cur_cell_z + 1) * cell_size);
cur_cell_x = 1; cur_cell_z = 0;
generate_triangles(min_pt + glm::vec3(cur_cell_x, 0, cur_cell_z) * cell_size, min_pt + glm::vec3(cur_cell_x + 1, 1, cur_cell_z + 1) * cell_size);
cur_cell_x = 2; cur_cell_z = 0;
generate_spheres(min_pt + glm::vec3(cur_cell_x, 0, cur_cell_z) * cell_size, min_pt + glm::vec3(cur_cell_x + 1, 1, cur_cell_z + 1) * cell_size);
cur_cell_x = 0; cur_cell_z = 1;
generate_quads(min_pt + glm::vec3(cur_cell_x, 0, cur_cell_z) * cell_size, min_pt + glm::vec3(cur_cell_x + 1, 1, cur_cell_z + 1) * cell_size);
cur_cell_x = 1; cur_cell_z = 1;
generate_box(min_pt + glm::vec3(cur_cell_x, 0, cur_cell_z) * cell_size, min_pt + glm::vec3(cur_cell_x + 1, 1, cur_cell_z + 1) * cell_size);
cur_cell_x = 2; cur_cell_z = 1;
generate_lines(min_pt + glm::vec3(cur_cell_x, 0, cur_cell_z) * cell_size, min_pt + glm::vec3(cur_cell_x + 1, 1, cur_cell_z + 1) * cell_size);
cur_cell_x = 0; cur_cell_z = 2;
generate_point_cloud(min_pt + glm::vec3(cur_cell_x, 0, cur_cell_z) * cell_size, min_pt + glm::vec3(cur_cell_x + 1, 1, cur_cell_z + 1) * cell_size);
cur_cell_x = 1; cur_cell_z = 2;
generate_billboard(min_pt + glm::vec3(cur_cell_x, 0, cur_cell_z) * cell_size, min_pt + glm::vec3(cur_cell_x + 1, 1, cur_cell_z + 1) * cell_size);
gui.start();
return 0;
} | 45.719149 | 150 | 0.666791 | [
"object",
"vector"
] |
a01806acf16236c36054c9d39596cdaf5054a6ee | 23,531 | cpp | C++ | tile_editor/tile_set_scenes_collection_source_editor.cpp | Relintai/tile_map_backport | 598b4d8bd1420fd547a458ec2998fa481dfbbfe4 | [
"MIT"
] | null | null | null | tile_editor/tile_set_scenes_collection_source_editor.cpp | Relintai/tile_map_backport | 598b4d8bd1420fd547a458ec2998fa481dfbbfe4 | [
"MIT"
] | null | null | null | tile_editor/tile_set_scenes_collection_source_editor.cpp | Relintai/tile_map_backport | 598b4d8bd1420fd547a458ec2998fa481dfbbfe4 | [
"MIT"
] | null | null | null | /*************************************************************************/
/* tile_set_scenes_collection_source_editor.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "tile_set_scenes_collection_source_editor.h"
#include "editor/editor_resource_preview.h"
#include "editor/editor_scale.h"
#include "editor/editor_settings.h"
#include "scene/gui/item_list.h"
#include "core/core_string_names.h"
void RTileSetScenesCollectionSourceEditor::TileSetScenesCollectionProxyObject::set_id(int p_id) {
ERR_FAIL_COND(p_id < 0);
if (source_id == p_id) {
return;
}
ERR_FAIL_COND_MSG(tile_set->has_source(p_id), vformat("Cannot change RTileSet Scenes Collection source ID. Another RTileSet source exists with id %d.", p_id));
int previous_source = source_id;
source_id = p_id; // source_id must be updated before, because it's used by the source list update.
tile_set->set_source_id(previous_source, p_id);
emit_signal(("changed"), "id");
}
int RTileSetScenesCollectionSourceEditor::TileSetScenesCollectionProxyObject::get_id() {
return source_id;
}
bool RTileSetScenesCollectionSourceEditor::TileSetScenesCollectionProxyObject::_set(const StringName &p_name, const Variant &p_value) {
String name = p_name;
if (name == "name") {
// Use the resource_name property to store the source's name.
name = "resource_name";
}
bool valid = false;
tile_set_scenes_collection_source->set(name, p_value, &valid);
if (valid) {
emit_signal(("changed"), String(name).utf8().get_data());
}
return valid;
}
bool RTileSetScenesCollectionSourceEditor::TileSetScenesCollectionProxyObject::_get(const StringName &p_name, Variant &r_ret) const {
if (!tile_set_scenes_collection_source) {
return false;
}
String name = p_name;
if (name == "name") {
// Use the resource_name property to store the source's name.
name = "resource_name";
}
bool valid = false;
r_ret = tile_set_scenes_collection_source->get(name, &valid);
return valid;
}
void RTileSetScenesCollectionSourceEditor::TileSetScenesCollectionProxyObject::_get_property_list(List<PropertyInfo> *p_list) const {
p_list->push_back(PropertyInfo(Variant::STRING, "name", PROPERTY_HINT_NONE, ""));
}
void RTileSetScenesCollectionSourceEditor::TileSetScenesCollectionProxyObject::_bind_methods() {
// -- Shape and layout --
ClassDB::bind_method(D_METHOD("set_id", "id"), &RTileSetScenesCollectionSourceEditor::TileSetScenesCollectionProxyObject::set_id);
ClassDB::bind_method(D_METHOD("get_id"), &RTileSetScenesCollectionSourceEditor::TileSetScenesCollectionProxyObject::get_id);
ADD_PROPERTY(PropertyInfo(Variant::INT, "id"), "set_id", "get_id");
ADD_SIGNAL(MethodInfo("changed", PropertyInfo(Variant::STRING, "what")));
}
void RTileSetScenesCollectionSourceEditor::TileSetScenesCollectionProxyObject::edit(Ref<RTileSet> p_tile_set, RTileSetScenesCollectionSource *p_tile_set_scenes_collection_source, int p_source_id) {
ERR_FAIL_COND(!p_tile_set.is_valid());
ERR_FAIL_COND(!p_tile_set_scenes_collection_source);
ERR_FAIL_COND(p_source_id < 0);
ERR_FAIL_COND(p_tile_set->get_source(p_source_id) != p_tile_set_scenes_collection_source);
if (tile_set == p_tile_set && tile_set_scenes_collection_source == p_tile_set_scenes_collection_source && source_id == p_source_id) {
return;
}
// Disconnect to changes.
//if (tile_set_scenes_collection_source) {
// tile_set_scenes_collection_source->disconnect(CoreStringNames::get_singleton()->property_list_changed, callable_mp((Object *)this, &Object::notify_property_list_changed));
//}
tile_set = p_tile_set;
tile_set_scenes_collection_source = p_tile_set_scenes_collection_source;
source_id = p_source_id;
// Connect to changes.
//if (tile_set_scenes_collection_source) {
// if (!tile_set_scenes_collection_source->is_connected(CoreStringNames::get_singleton()->property_list_changed, callable_mp((Object *)this, &Object::notify_property_list_changed))) {
// tile_set_scenes_collection_source->connect(CoreStringNames::get_singleton()->property_list_changed, callable_mp((Object *)this, &Object::notify_property_list_changed));
// }
//}
property_list_changed_notify();
}
// -- Proxy object used by the tile inspector --
bool RTileSetScenesCollectionSourceEditor::SceneTileProxyObject::_set(const StringName &p_name, const Variant &p_value) {
if (!tile_set_scenes_collection_source) {
return false;
}
if (p_name == "id") {
int as_int = int(p_value);
ERR_FAIL_COND_V(as_int < 0, false);
ERR_FAIL_COND_V(tile_set_scenes_collection_source->has_scene_tile_id(as_int), false);
tile_set_scenes_collection_source->set_scene_tile_id(scene_id, as_int);
scene_id = as_int;
emit_signal(("changed"), "id");
for (int i = 0; i < tile_set_scenes_collection_source_editor->scene_tiles_list->get_item_count(); i++) {
if (int(tile_set_scenes_collection_source_editor->scene_tiles_list->get_item_metadata(i)) == scene_id) {
tile_set_scenes_collection_source_editor->scene_tiles_list->select(i);
break;
}
}
return true;
} else if (p_name == "scene") {
tile_set_scenes_collection_source->set_scene_tile_scene(scene_id, p_value);
emit_signal(("changed"), "scene");
return true;
} else if (p_name == "display_placeholder") {
tile_set_scenes_collection_source->set_scene_tile_display_placeholder(scene_id, p_value);
emit_signal(("changed"), "display_placeholder");
return true;
}
return false;
}
bool RTileSetScenesCollectionSourceEditor::SceneTileProxyObject::_get(const StringName &p_name, Variant &r_ret) const {
if (!tile_set_scenes_collection_source) {
return false;
}
if (p_name == "id") {
r_ret = scene_id;
return true;
} else if (p_name == "scene") {
r_ret = tile_set_scenes_collection_source->get_scene_tile_scene(scene_id);
return true;
} else if (p_name == "display_placeholder") {
r_ret = tile_set_scenes_collection_source->get_scene_tile_display_placeholder(scene_id);
return true;
}
return false;
}
void RTileSetScenesCollectionSourceEditor::SceneTileProxyObject::_get_property_list(List<PropertyInfo> *p_list) const {
if (!tile_set_scenes_collection_source) {
return;
}
p_list->push_back(PropertyInfo(Variant::INT, "id", PROPERTY_HINT_NONE, ""));
p_list->push_back(PropertyInfo(Variant::OBJECT, "scene", PROPERTY_HINT_RESOURCE_TYPE, "PackedScene"));
p_list->push_back(PropertyInfo(Variant::BOOL, "display_placeholder", PROPERTY_HINT_NONE, ""));
}
void RTileSetScenesCollectionSourceEditor::SceneTileProxyObject::edit(RTileSetScenesCollectionSource *p_tile_set_scenes_collection_source, int p_scene_id) {
ERR_FAIL_COND(!p_tile_set_scenes_collection_source);
ERR_FAIL_COND(!p_tile_set_scenes_collection_source->has_scene_tile_id(p_scene_id));
if (tile_set_scenes_collection_source == p_tile_set_scenes_collection_source && scene_id == p_scene_id) {
return;
}
tile_set_scenes_collection_source = p_tile_set_scenes_collection_source;
scene_id = p_scene_id;
property_list_changed_notify();
}
void RTileSetScenesCollectionSourceEditor::SceneTileProxyObject::_bind_methods() {
ADD_SIGNAL(MethodInfo("changed", PropertyInfo(Variant::STRING, "what")));
}
void RTileSetScenesCollectionSourceEditor::_scenes_collection_source_proxy_object_changed(String p_what) {
if (p_what == "id") {
emit_signal(("source_id_changed"), scenes_collection_source_proxy_object->get_id());
}
}
void RTileSetScenesCollectionSourceEditor::_tile_set_scenes_collection_source_changed() {
tile_set_scenes_collection_source_changed_needs_update = true;
}
void RTileSetScenesCollectionSourceEditor::_scene_thumbnail_done(const String &p_path, const Ref<Texture> &p_preview, const Ref<Texture> &p_small_preview, Variant p_ud) {
int index = p_ud;
if (index >= 0 && index < scene_tiles_list->get_item_count()) {
scene_tiles_list->set_item_icon(index, p_preview);
}
}
void RTileSetScenesCollectionSourceEditor::_scenes_list_item_activated(int p_index) {
Ref<PackedScene> packed_scene = tile_set_scenes_collection_source->get_scene_tile_scene(scene_tiles_list->get_item_metadata(p_index));
if (packed_scene.is_valid()) {
EditorNode::get_singleton()->open_request(packed_scene->get_path());
}
}
void RTileSetScenesCollectionSourceEditor::_source_add_pressed() {
int scene_id = tile_set_scenes_collection_source->get_next_scene_tile_id();
undo_redo->create_action(TTR("Add a Scene Tile"));
undo_redo->add_do_method(tile_set_scenes_collection_source, "create_scene_tile", Ref<PackedScene>(), scene_id);
undo_redo->add_undo_method(tile_set_scenes_collection_source, "remove_scene_tile", scene_id);
undo_redo->commit_action();
_update_scenes_list();
_update_action_buttons();
_update_tile_inspector();
}
void RTileSetScenesCollectionSourceEditor::_source_delete_pressed() {
Vector<int> selected_indices = scene_tiles_list->get_selected_items();
ERR_FAIL_COND(selected_indices.size() <= 0);
int scene_id = scene_tiles_list->get_item_metadata(selected_indices[0]);
undo_redo->create_action(TTR("Remove a Scene Tile"));
undo_redo->add_do_method(tile_set_scenes_collection_source, "remove_scene_tile", scene_id);
undo_redo->add_undo_method(tile_set_scenes_collection_source, "create_scene_tile", tile_set_scenes_collection_source->get_scene_tile_scene(scene_id), scene_id);
undo_redo->commit_action();
_update_scenes_list();
_update_action_buttons();
_update_tile_inspector();
}
void RTileSetScenesCollectionSourceEditor::_update_source_inspector() {
// Update the proxy object.
scenes_collection_source_proxy_object->edit(tile_set, tile_set_scenes_collection_source, tile_set_source_id);
}
void RTileSetScenesCollectionSourceEditor::_update_tile_inspector(const int index) {
Vector<int> selected_indices = scene_tiles_list->get_selected_items();
bool has_atlas_tile_selected = (selected_indices.size() > 0);
// Update the proxy object.
if (has_atlas_tile_selected) {
int scene_id = scene_tiles_list->get_item_metadata(selected_indices[0]);
tile_proxy_object->edit(tile_set_scenes_collection_source, scene_id);
}
// Update visibility.
tile_inspector_label->set_visible(has_atlas_tile_selected);
tile_inspector->set_visible(has_atlas_tile_selected);
}
void RTileSetScenesCollectionSourceEditor::_update_action_buttons(const int index) {
Vector<int> selected_indices = scene_tiles_list->get_selected_items();
scene_tile_delete_button->set_disabled(selected_indices.size() <= 0);
}
void RTileSetScenesCollectionSourceEditor::_update_action_buttons_str(const String &a) {
_update_action_buttons();
}
void RTileSetScenesCollectionSourceEditor::_update_scenes_list(const int index) {
if (!tile_set_scenes_collection_source) {
return;
}
// Get the previously selected id.
Vector<int> selected_indices = scene_tiles_list->get_selected_items();
int old_selected_scene_id = (selected_indices.size() > 0) ? int(scene_tiles_list->get_item_metadata(selected_indices[0])) : -1;
// Clear the list.
scene_tiles_list->clear();
// Rebuild the list.
int to_reselect = -1;
for (int i = 0; i < tile_set_scenes_collection_source->get_scene_tiles_count(); i++) {
int scene_id = tile_set_scenes_collection_source->get_scene_tile_id(i);
Ref<PackedScene> scene = tile_set_scenes_collection_source->get_scene_tile_scene(scene_id);
int item_index = 0;
if (scene.is_valid()) {
scene_tiles_list->add_item(vformat("%s (path:%s id:%d)", scene->get_path().get_file().get_basename(), scene->get_path(), scene_id));
item_index = scene_tiles_list->get_item_count() - 1;
Variant udata = i;
EditorResourcePreview::get_singleton()->queue_edited_resource_preview(scene, this, "_scene_thumbnail_done", udata);
} else {
scene_tiles_list->add_item(TTR("Tile with Invalid Scene"), get_icon(("PackedScene"), ("EditorIcons")));
item_index = scene_tiles_list->get_item_count() - 1;
}
scene_tiles_list->set_item_metadata(item_index, scene_id);
if (old_selected_scene_id >= 0 && scene_id == old_selected_scene_id) {
to_reselect = i;
}
}
// Reselect if needed.
if (to_reselect >= 0) {
scene_tiles_list->select(to_reselect);
}
// Icon size update.
int int_size = int(EditorSettings::get_singleton()->get("filesystem/file_dialog/thumbnail_size")) * EDSCALE;
scene_tiles_list->set_fixed_icon_size(Vector2(int_size, int_size));
}
void RTileSetScenesCollectionSourceEditor::_update_scenes_list_str(const String &a) {
_update_scenes_list();
}
void RTileSetScenesCollectionSourceEditor::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE:
case NOTIFICATION_THEME_CHANGED:
scene_tile_add_button->set_icon(get_icon(("Add"), ("EditorIcons")));
scene_tile_delete_button->set_icon(get_icon(("Remove"), ("EditorIcons")));
_update_scenes_list();
break;
case NOTIFICATION_INTERNAL_PROCESS:
if (tile_set_scenes_collection_source_changed_needs_update) {
// Update everything.
_update_source_inspector();
_update_scenes_list();
_update_action_buttons();
_update_tile_inspector();
tile_set_scenes_collection_source_changed_needs_update = false;
}
break;
case NOTIFICATION_VISIBILITY_CHANGED:
// Update things just in case.
_update_scenes_list();
_update_action_buttons();
break;
default:
break;
}
}
void RTileSetScenesCollectionSourceEditor::edit(Ref<RTileSet> p_tile_set, RTileSetScenesCollectionSource *p_tile_set_scenes_collection_source, int p_source_id) {
ERR_FAIL_COND(!p_tile_set.is_valid());
ERR_FAIL_COND(!p_tile_set_scenes_collection_source);
ERR_FAIL_COND(p_source_id < 0);
ERR_FAIL_COND(p_tile_set->get_source(p_source_id) != p_tile_set_scenes_collection_source);
if (p_tile_set == tile_set && p_tile_set_scenes_collection_source == tile_set_scenes_collection_source && p_source_id == tile_set_source_id) {
return;
}
// Remove listener for old objects.
if (tile_set_scenes_collection_source) {
tile_set_scenes_collection_source->disconnect("changed", this, "_tile_set_scenes_collection_source_changed");
}
// Change the edited object.
tile_set = p_tile_set;
tile_set_scenes_collection_source = p_tile_set_scenes_collection_source;
tile_set_source_id = p_source_id;
// Add the listener again.
if (tile_set_scenes_collection_source) {
tile_set_scenes_collection_source->connect("changed", this, "_tile_set_scenes_collection_source_changed");
}
// Update everything.
_update_source_inspector();
_update_scenes_list();
_update_action_buttons();
_update_tile_inspector();
}
void RTileSetScenesCollectionSourceEditor::_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
if (!_can_drop_data_fw(p_point, p_data, p_from)) {
return;
}
if (p_from == scene_tiles_list) {
// Handle dropping a texture in the list of atlas resources.
int scene_id = -1;
Dictionary d = p_data;
Vector<String> files = d["files"];
for (int i = 0; i < files.size(); i++) {
Ref<PackedScene> resource = ResourceLoader::load(files[i]);
if (resource.is_valid()) {
scene_id = tile_set_scenes_collection_source->get_next_scene_tile_id();
undo_redo->create_action(TTR("Add a Scene Tile"));
undo_redo->add_do_method(tile_set_scenes_collection_source, "create_scene_tile", resource, scene_id);
undo_redo->add_undo_method(tile_set_scenes_collection_source, "remove_scene_tile", scene_id);
undo_redo->commit_action();
}
}
_update_scenes_list();
_update_action_buttons();
_update_tile_inspector();
}
}
bool RTileSetScenesCollectionSourceEditor::_can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const {
if (p_from == scene_tiles_list) {
Dictionary d = p_data;
if (!d.has("type")) {
return false;
}
// Check if we have a Texture.
if (String(d["type"]) == "files") {
Vector<String> files = d["files"];
if (files.size() == 0) {
return false;
}
for (int i = 0; i < files.size(); i++) {
String file = files[i];
String ftype = EditorFileSystem::get_singleton()->get_file_type(file);
if (!ClassDB::is_parent_class(ftype, "PackedScene")) {
return false;
}
}
return true;
}
}
return false;
}
void RTileSetScenesCollectionSourceEditor::_bind_methods() {
ADD_SIGNAL(MethodInfo("source_id_changed", PropertyInfo(Variant::INT, "source_id")));
ClassDB::bind_method(D_METHOD("_scene_thumbnail_done"), &RTileSetScenesCollectionSourceEditor::_scene_thumbnail_done);
ClassDB::bind_method(D_METHOD("_can_drop_data_fw"), &RTileSetScenesCollectionSourceEditor::_can_drop_data_fw);
ClassDB::bind_method(D_METHOD("_drop_data_fw"), &RTileSetScenesCollectionSourceEditor::_drop_data_fw);
ClassDB::bind_method(D_METHOD("_tile_set_scenes_collection_source_changed"), &RTileSetScenesCollectionSourceEditor::_tile_set_scenes_collection_source_changed);
ClassDB::bind_method(D_METHOD("_scenes_collection_source_proxy_object_changed"), &RTileSetScenesCollectionSourceEditor::_scenes_collection_source_proxy_object_changed);
ClassDB::bind_method(D_METHOD("_update_scenes_list"), &RTileSetScenesCollectionSourceEditor::_update_scenes_list);
ClassDB::bind_method(D_METHOD("_update_action_buttons"), &RTileSetScenesCollectionSourceEditor::_update_action_buttons);
ClassDB::bind_method(D_METHOD("_update_tile_inspector"), &RTileSetScenesCollectionSourceEditor::_update_tile_inspector);
ClassDB::bind_method(D_METHOD("_scenes_list_item_activated"), &RTileSetScenesCollectionSourceEditor::_scenes_list_item_activated);
ClassDB::bind_method(D_METHOD("_source_add_pressed"), &RTileSetScenesCollectionSourceEditor::_source_add_pressed);
ClassDB::bind_method(D_METHOD("_source_delete_pressed"), &RTileSetScenesCollectionSourceEditor::_source_delete_pressed);
ClassDB::bind_method(D_METHOD("_update_action_buttons_str"), &RTileSetScenesCollectionSourceEditor::_update_action_buttons_str);
ClassDB::bind_method(D_METHOD("_update_scenes_list_str"), &RTileSetScenesCollectionSourceEditor::_update_scenes_list_str);
}
RTileSetScenesCollectionSourceEditor::RTileSetScenesCollectionSourceEditor() {
// -- Right side --
HSplitContainer *split_container_right_side = memnew(HSplitContainer);
split_container_right_side->set_h_size_flags(SIZE_EXPAND_FILL);
add_child(split_container_right_side);
// Middle panel.
ScrollContainer *middle_panel = memnew(ScrollContainer);
middle_panel->set_enable_h_scroll(false);
middle_panel->set_custom_minimum_size(Size2i(200, 0) * EDSCALE);
split_container_right_side->add_child(middle_panel);
VBoxContainer *middle_vbox_container = memnew(VBoxContainer);
middle_vbox_container->set_h_size_flags(SIZE_EXPAND_FILL);
middle_panel->add_child(middle_vbox_container);
// Scenes collection source inspector.
scenes_collection_source_inspector_label = memnew(Label);
scenes_collection_source_inspector_label->set_text(TTR("Scenes collection properties:"));
middle_vbox_container->add_child(scenes_collection_source_inspector_label);
scenes_collection_source_proxy_object = memnew(TileSetScenesCollectionProxyObject());
scenes_collection_source_proxy_object->connect("changed", this, "_scenes_collection_source_proxy_object_changed");
scenes_collection_source_inspector = memnew(EditorInspector);
scenes_collection_source_inspector->set_undo_redo(undo_redo);
scenes_collection_source_inspector->set_enable_v_scroll(false);
scenes_collection_source_inspector->edit(scenes_collection_source_proxy_object);
middle_vbox_container->add_child(scenes_collection_source_inspector);
// Tile inspector.
tile_inspector_label = memnew(Label);
tile_inspector_label->set_text(TTR("Tile properties:"));
tile_inspector_label->hide();
middle_vbox_container->add_child(tile_inspector_label);
tile_proxy_object = memnew(SceneTileProxyObject(this));
tile_proxy_object->connect("changed", this, "_update_scenes_list_str");
tile_proxy_object->connect("changed", this, "_update_action_buttons_str");
tile_inspector = memnew(EditorInspector);
tile_inspector->set_undo_redo(undo_redo);
tile_inspector->set_enable_v_scroll(false);
tile_inspector->edit(tile_proxy_object);
tile_inspector->set_use_folding(true);
middle_vbox_container->add_child(tile_inspector);
// Scenes list.
VBoxContainer *right_vbox_container = memnew(VBoxContainer);
split_container_right_side->add_child(right_vbox_container);
scene_tiles_list = memnew(ItemList);
scene_tiles_list->set_h_size_flags(SIZE_EXPAND_FILL);
scene_tiles_list->set_v_size_flags(SIZE_EXPAND_FILL);
scene_tiles_list->set_drag_forwarding(this);
scene_tiles_list->connect("item_selected", this, "_update_tile_inspector");
scene_tiles_list->connect("item_selected", this, "_update_action_buttons");
scene_tiles_list->connect("item_activated", this, "_scenes_list_item_activated");
//scene_tiles_list->set_texture_filter(CanvasItem::TEXTURE_FILTER_NEAREST);
right_vbox_container->add_child(scene_tiles_list);
HBoxContainer *scenes_bottom_actions = memnew(HBoxContainer);
right_vbox_container->add_child(scenes_bottom_actions);
scene_tile_add_button = memnew(Button);
scene_tile_add_button->set_flat(true);
scene_tile_add_button->connect("pressed", this, "_source_add_pressed");
scenes_bottom_actions->add_child(scene_tile_add_button);
scene_tile_delete_button = memnew(Button);
scene_tile_delete_button->set_flat(true);
scene_tile_delete_button->set_disabled(true);
scene_tile_delete_button->connect("pressed", this, "_source_delete_pressed");
scenes_bottom_actions->add_child(scene_tile_delete_button);
}
RTileSetScenesCollectionSourceEditor::~RTileSetScenesCollectionSourceEditor() {
memdelete(scenes_collection_source_proxy_object);
memdelete(tile_proxy_object);
}
| 42.398198 | 197 | 0.765458 | [
"object",
"shape",
"vector"
] |
a01b523f445dbec1dc375971357cb5e6a3893d69 | 8,891 | cpp | C++ | core/python-module.cpp | markcda/cc-jeff | 4fe90e9510fe31fc74066b06b28a5dcb9ced0aed | [
"MIT"
] | 2 | 2019-01-19T08:08:07.000Z | 2020-08-15T17:58:29.000Z | core/python-module.cpp | markcda/cc-jeff | 4fe90e9510fe31fc74066b06b28a5dcb9ced0aed | [
"MIT"
] | null | null | null | core/python-module.cpp | markcda/cc-jeff | 4fe90e9510fe31fc74066b06b28a5dcb9ced0aed | [
"MIT"
] | null | null | null | #include "python-module.h"
using namespace std::chrono_literals;
/*! @brief The constructor. */
PythonModule::PythonModule(HProcessor *_hp, Basis *_basis, NotifyClient *_notifier, QObject *parent)
: QObject(parent), hp(_hp), basis(_basis), notifier(_notifier) {
_scripts = basis->json->read_scripts();
Py_InitializeEx(1);
// Adds current path to sys.path for importing scripts from this directory.
_current_path = QDir::toNativeSeparators(QDir::currentPath());
QString command = "import sys; sys.path.append('" + _current_path + "')";
PyRun_SimpleString(command.toStdString().c_str());
}
/*! @brief The destructor. */
PythonModule::~PythonModule() {
Py_Finalize();
for (auto *proc : _daemons) proc->kill();
basis->json->write_scripts(_scripts);
for (auto *script : _scripts) delete script;
_scripts.clear();
notifier->unsubscribe_all();
}
/*! @brief Runs functions in scripts intended to start when Jeff starts. */
void PythonModule::startup() {
for (auto *script : _scripts) {
if (script->stype == ScriptType::Startup) {
auto *startup_script = dynamic_cast<StartupScript *>(script);
if (not startup_script) continue;
QJsonObject transport;
if (not startup_script->memory_cells.isEmpty()) {
QJsonObject memory_cells;
for (auto key : startup_script->memory_cells) memory_cells[key] = basis->memory(key);
transport[basis->memoryValuesWk] = memory_cells;
}
run(startup_script->path, startup_script->fn_name, transport);
} else if (script->stype == ScriptType::Daemon) {
auto *daemon_script = dynamic_cast<DaemonScript *>(script);
if (not daemon_script) continue;
auto *proc = new QProcess(this);
connect(proc, &QProcess::errorOccurred, this, [this, daemon_script]() {
emit script_exception(
tr("An error occurred during script execution") + " (" + daemon_script->path + ")"
);
});
proc->start(QString("python"), QStringList(daemon_script->path));
_daemons.append(proc);
} else if (script->stype == ScriptType::Server) {
auto *server_script = dynamic_cast<ServerScript *>(script);
if (not server_script) continue;
auto *proc = new QProcess(this);
connect(proc, &QProcess::errorOccurred, this, [this, server_script]() {
emit script_exception(
tr("An error occurred during script execution") + " (" + server_script->path + ")"
);
});
proc->start(QString("python"), QStringList(server_script->path));
_daemons.append(proc);
notifier->subscribe(server_script);
}
}
}
/*! @brief Runs a function with parameters and returns the result. */
QJsonObject PythonModule::run(QString path, QString def_name, QJsonObject transport) {
QFileInfo module_info(path);
QString dir_path = QDir::toNativeSeparators(module_info.canonicalPath());
if (dir_path != _current_path) {
QString command = "import sys; sys.path.append('" + dir_path + "')";
PyRun_SimpleString(command.toStdString().c_str());
}
QString module_nick = module_info.fileName().split('.')[0];
Object module_name = PyUnicode_FromString(module_nick.toStdString().c_str());
Object mod = PyImport_Import(module_name);
if (not mod) {
emit script_exception(tr("Failed to connect the module."));
return {{basis->errorTypeWk, 1}};
}
Object answer_func = PyObject_GetAttrString(mod, def_name.toStdString().c_str());
if (not answer_func) {
emit script_exception(tr("Could not find \"answer\" attribute in module."));
return {{basis->errorTypeWk, 2}};
}
if (not (answer_func && PyCallable_Check(answer_func))) {
emit script_exception(tr("Cannot call \"answer\": this is not a function!"));
return {{basis->errorTypeWk, 3}};
}
QJsonDocument send_doc(transport);
Object arg = PyUnicode_FromString(send_doc.toJson(QJsonDocument::Compact).constData());
if (not arg) {
emit script_exception(tr("Failed to construct argument from string."));
return {{basis->errorTypeWk, 4}};
}
/*! If we pack in tuple our beautiful Object instead of PyObject, a segmentation fault will */
Object args = PyTuple_Pack(1, *arg); /*!< come out. Instead we send pure PyObject. */
if (not args) {
emit script_exception(tr("Failed to construct a tuple from a string."));
return {{basis->errorTypeWk, 5}};
}
auto f = std::async(&PythonModule::async_runner, this, answer_func, args);
PyThreadState *_state = PyEval_SaveThread();
if (f.wait_for(3s) != std::future_status::ready) return QJsonObject();
Object answer_result = f.get();
PyEval_RestoreThread(_state);
if (not answer_result) {
emit script_exception(tr(
"The function could not execute correctly because it did not return a result."
));
return {{basis->errorTypeWk, 6}};
}
Object objects_representation = PyObject_Repr(answer_result);
auto result = QString::fromUtf8(PyUnicode_AsUTF8(objects_representation)).chopped(1).remove(0, 1);
auto recv_doc = QJsonDocument::fromJson(result.toUtf8());
if (recv_doc.isNull()) {
emit script_exception(tr("No valid JSON received."));
return {{basis->errorTypeWk, 7}};
}
if (not recv_doc.isObject()) {
emit script_exception(tr("No JSON object received."));
return {{basis->errorTypeWk, 8}};
}
return recv_doc.object();
}
/*! @brief Executes a Python function asynchronously. */
Object PythonModule::async_runner(Object func, Object args) {
PyGILState_STATE _state = PyGILState_Ensure();
Object answer_result = PyObject_CallObject(func, args);
PyGILState_Release(_state);
return answer_result;
}
/*!
* @brief Processes the script configuration and gets the necessary information from it.
* @details Handles next things:
* 1. `number_of_hist_messages` prop
* 2. `memory_cells` prop
* 3. `properties` from @a expression
* 4. `path` and `fn_name` props
* 5. `user_expression` prop
* 6. <!-- script runs -->
* 7. `store_in_memory` prop from script
*/
QJsonObject PythonModule::request_answer(
ReactScript *script, const Expression &expression, const QString &user_expression
) {
QJsonObject transport;
if (not script->memory_cells.isEmpty()) {
QJsonObject memory_cells;
for (auto key : script->memory_cells) memory_cells[key] = basis->memory(key);
transport[basis->memoryValuesWk] = memory_cells;
}
if (script->number_of_hist_messages) {
QJsonArray history_array;
auto history = hp->recent(script->number_of_hist_messages);
for (auto msg : history)
history_array.append(
QString("%1: %2").arg(msg.author == Author::User ? "User" : "Jeff").arg(msg.content)
);
transport[basis->recentMessagesWk] = history_array;
}
if (script->needs_user_input) transport["user_expression"] = user_expression;
if (not expression.properties.isEmpty()) {
transport[basis->exprPropsWk] = Phrase::pack_props(expression.properties);
}
if (not script->path.length()) {
emit script_exception(tr("The path to the module is empty."));
return {{basis->errorTypeWk, 10}};
}
if (not script->fn_name.length()) {
emit script_exception(tr("The function name is empty."));
return {{basis->errorTypeWk, 12}};
}
QJsonObject result = run(script->path, script->fn_name, transport);
basis->handle_from_script(result, true);
return result;
}
/*! @brief Prepares data for custom scanning. */
QJsonObject PythonModule::request_scan(CustomScanScript *script, const QString &user_expression) {
QJsonObject transport;
transport["user_expression"] = user_expression;
return run(script->path, script->fn_name, transport);
}
/*! @brief Prepares data for custom composing. */
QJsonObject PythonModule::request_compose(
CustomComposeScript *script, const QString &user_expression, CacheWithIndices sorted
) {
QJsonObject transport;
transport["user_expression"] = user_expression;
QJsonArray candidates;
for (auto key : sorted.keys()) {
QJsonObject candidate;
QJsonObject indices;
for (auto first_indice : sorted[key].first.keys()) {
indices[QString::number(first_indice)] = sorted[key].first[first_indice];
}
candidate["indices"] = indices;
candidate["reagent_expression"] = sorted[key].second.to_json();
candidates.append(candidate);
}
transport["candidates"] = candidates;
return run(script->path, script->fn_name, transport);
}
/*! @brief Adds a script to the general list.
* @warning When the program ends, this module will delete the scripts from memory itself.
* @sa ~PythonModule() */
void PythonModule::add_script(ScriptMetadata *script) { _scripts.append(script); }
/*! @brief Removes a script from the general list. */
bool PythonModule::remove_script(ScriptMetadata *script) { return _scripts.removeOne(script); }
/*! @brief Returns the general list of scripts. */
Scripts PythonModule::get_scripts() { return _scripts; }
| 40.784404 | 100 | 0.698459 | [
"object"
] |
a02730a120834b2ddc237ff82ed72435bdc3ba6b | 136,671 | cc | C++ | Kuplung/kuplung/utilities/saveopen/KuplungAppScene.pb.cc | supudo/Kuplung | f0e11934fde0675fa531e6dc263bedcc20a5ea1a | [
"Unlicense"
] | 14 | 2017-02-17T17:12:40.000Z | 2021-12-22T01:55:06.000Z | Kuplung/kuplung/utilities/saveopen/KuplungAppScene.pb.cc | supudo/Kuplung | f0e11934fde0675fa531e6dc263bedcc20a5ea1a | [
"Unlicense"
] | null | null | null | Kuplung/kuplung/utilities/saveopen/KuplungAppScene.pb.cc | supudo/Kuplung | f0e11934fde0675fa531e6dc263bedcc20a5ea1a | [
"Unlicense"
] | 1 | 2019-10-15T08:10:10.000Z | 2019-10-15T08:10:10.000Z | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: KuplungAppScene.proto
#include "KuplungAppScene.pb.h"
#include <algorithm>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
extern PROTOBUF_INTERNAL_EXPORT_KuplungDefinitions_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_MaterialColor_KuplungDefinitions_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_KuplungDefinitions_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<4> scc_info_Mesh_KuplungDefinitions_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_KuplungAppScene_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<4> scc_info_MeshModel_KuplungAppScene_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_KuplungDefinitions_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_ObjectCoordinate_KuplungDefinitions_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_KuplungDefinitions_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_Vec3_KuplungDefinitions_2eproto;
namespace KuplungApp {
class SceneDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<Scene> _instance;
} _Scene_default_instance_;
class MeshModelDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<MeshModel> _instance;
} _MeshModel_default_instance_;
} // namespace KuplungApp
static void InitDefaultsscc_info_MeshModel_KuplungAppScene_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::KuplungApp::_MeshModel_default_instance_;
new (ptr) ::KuplungApp::MeshModel();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::KuplungApp::MeshModel::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<4> scc_info_MeshModel_KuplungAppScene_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 4, 0, InitDefaultsscc_info_MeshModel_KuplungAppScene_2eproto}, {
&scc_info_ObjectCoordinate_KuplungDefinitions_2eproto.base,
&scc_info_Vec3_KuplungDefinitions_2eproto.base,
&scc_info_MaterialColor_KuplungDefinitions_2eproto.base,
&scc_info_Mesh_KuplungDefinitions_2eproto.base,}};
static void InitDefaultsscc_info_Scene_KuplungAppScene_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::KuplungApp::_Scene_default_instance_;
new (ptr) ::KuplungApp::Scene();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::KuplungApp::Scene::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_Scene_KuplungAppScene_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, 0, InitDefaultsscc_info_Scene_KuplungAppScene_2eproto}, {
&scc_info_MeshModel_KuplungAppScene_2eproto.base,}};
static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_KuplungAppScene_2eproto[2];
static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_KuplungAppScene_2eproto = nullptr;
static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_KuplungAppScene_2eproto = nullptr;
const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_KuplungAppScene_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
PROTOBUF_FIELD_OFFSET(::KuplungApp::Scene, _has_bits_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::Scene, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::KuplungApp::Scene, models_),
~0u,
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, _has_bits_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, modelid_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, settings_deferredrender_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, setting_celshading_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, setting_wireframe_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, setting_usetessellation_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, setting_usecullface_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, setting_alpha_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, setting_tessellationsubdivision_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, positionx_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, positiony_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, positionz_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, scalex_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, scaley_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, scalez_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, rotatex_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, rotatey_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, rotatez_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, displacex_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, displacey_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, displacez_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, setting_materialrefraction_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, setting_materialspecularexp_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, setting_modelviewskin_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, solidlightskin_materialcolor_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, solidlightskin_ambient_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, solidlightskin_diffuse_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, solidlightskin_specular_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, solidlightskin_ambient_strength_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, solidlightskin_diffuse_strength_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, solidlightskin_specular_strength_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, setting_lightposition_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, setting_lightdirection_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, setting_lightambient_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, setting_lightdiffuse_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, setting_lightspecular_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, setting_lightstrengthambient_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, setting_lightstrengthdiffuse_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, setting_lightstrengthspecular_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, materialilluminationmodel_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, displacementheightscale_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, showmaterialeditor_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, materialambient_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, materialdiffuse_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, materialspecular_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, materialemission_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, setting_parallaxmapping_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, effect_gblur_mode_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, effect_gblur_radius_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, effect_gblur_width_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, effect_bloom_dobloom_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, effect_bloom_weighta_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, effect_bloom_weightb_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, effect_bloom_weightc_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, effect_bloom_weightd_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, effect_bloom_vignette_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, effect_bloom_vignetteatt_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, setting_lightingpass_drawmode_),
PROTOBUF_FIELD_OFFSET(::KuplungApp::MeshModel, meshobject_),
31,
32,
33,
34,
35,
42,
36,
37,
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
38,
14,
15,
16,
17,
39,
40,
41,
18,
19,
20,
21,
22,
46,
47,
48,
49,
23,
43,
24,
25,
26,
27,
44,
50,
28,
29,
45,
51,
52,
53,
54,
55,
56,
57,
30,
};
static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
{ 0, 6, sizeof(::KuplungApp::Scene)},
{ 7, 70, sizeof(::KuplungApp::MeshModel)},
};
static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = {
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::KuplungApp::_Scene_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::KuplungApp::_MeshModel_default_instance_),
};
const char descriptor_table_protodef_KuplungAppScene_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) =
"\n\025KuplungAppScene.proto\022\nKuplungApp\032\030Kup"
"lungDefinitions.proto\".\n\005Scene\022%\n\006models"
"\030\001 \003(\0132\025.KuplungApp.MeshModel\"\252\023\n\tMeshMo"
"del\022\017\n\007ModelID\030\001 \002(\005\022\037\n\027Settings_Deferre"
"dRender\030\002 \002(\010\022\032\n\022Setting_CelShading\030\003 \002("
"\010\022\031\n\021Setting_Wireframe\030\004 \002(\010\022\037\n\027Setting_"
"UseTessellation\030\005 \002(\010\022\033\n\023Setting_UseCull"
"Face\030\006 \002(\010\022\025\n\rSetting_Alpha\030\007 \002(\002\022\'\n\037Set"
"ting_TessellationSubdivision\030\010 \002(\005\022/\n\tpo"
"sitionX\030\t \002(\0132\034.KuplungApp.ObjectCoordin"
"ate\022/\n\tpositionY\030\n \002(\0132\034.KuplungApp.Obje"
"ctCoordinate\022/\n\tpositionZ\030\013 \002(\0132\034.Kuplun"
"gApp.ObjectCoordinate\022,\n\006scaleX\030\014 \002(\0132\034."
"KuplungApp.ObjectCoordinate\022,\n\006scaleY\030\r "
"\002(\0132\034.KuplungApp.ObjectCoordinate\022,\n\006sca"
"leZ\030\016 \002(\0132\034.KuplungApp.ObjectCoordinate\022"
"-\n\007rotateX\030\017 \002(\0132\034.KuplungApp.ObjectCoor"
"dinate\022-\n\007rotateY\030\020 \002(\0132\034.KuplungApp.Obj"
"ectCoordinate\022-\n\007rotateZ\030\021 \002(\0132\034.Kuplung"
"App.ObjectCoordinate\022/\n\tdisplaceX\030\022 \002(\0132"
"\034.KuplungApp.ObjectCoordinate\022/\n\tdisplac"
"eY\030\023 \002(\0132\034.KuplungApp.ObjectCoordinate\022/"
"\n\tdisplaceZ\030\024 \002(\0132\034.KuplungApp.ObjectCoo"
"rdinate\022@\n\032Setting_MaterialRefraction\030\025 "
"\002(\0132\034.KuplungApp.ObjectCoordinate\022A\n\033Set"
"ting_MaterialSpecularExp\030\026 \002(\0132\034.Kuplung"
"App.ObjectCoordinate\022\035\n\025Setting_ModelVie"
"wSkin\030\027 \002(\005\0226\n\034solidLightSkin_MaterialCo"
"lor\030\030 \002(\0132\020.KuplungApp.Vec3\0220\n\026solidLigh"
"tSkin_Ambient\030\031 \002(\0132\020.KuplungApp.Vec3\0220\n"
"\026solidLightSkin_Diffuse\030\032 \002(\0132\020.KuplungA"
"pp.Vec3\0221\n\027solidLightSkin_Specular\030\033 \002(\013"
"2\020.KuplungApp.Vec3\022\'\n\037solidLightSkin_Amb"
"ient_Strength\030\034 \002(\002\022\'\n\037solidLightSkin_Di"
"ffuse_Strength\030\035 \002(\002\022(\n solidLightSkin_S"
"pecular_Strength\030\036 \002(\002\022/\n\025Setting_LightP"
"osition\030\037 \002(\0132\020.KuplungApp.Vec3\0220\n\026Setti"
"ng_LightDirection\030 \002(\0132\020.KuplungApp.Vec"
"3\022.\n\024Setting_LightAmbient\030! \002(\0132\020.Kuplun"
"gApp.Vec3\022.\n\024Setting_LightDiffuse\030\" \002(\0132"
"\020.KuplungApp.Vec3\022/\n\025Setting_LightSpecul"
"ar\030# \002(\0132\020.KuplungApp.Vec3\022$\n\034Setting_Li"
"ghtStrengthAmbient\030$ \002(\002\022$\n\034Setting_Ligh"
"tStrengthDiffuse\030% \002(\002\022%\n\035Setting_LightS"
"trengthSpecular\030& \002(\002\022!\n\031materialIllumin"
"ationModel\030\' \002(\005\022=\n\027displacementHeightSc"
"ale\030( \002(\0132\034.KuplungApp.ObjectCoordinate\022"
"\032\n\022showMaterialEditor\030) \002(\010\0222\n\017materialA"
"mbient\030* \002(\0132\031.KuplungApp.MaterialColor\022"
"2\n\017materialDiffuse\030+ \002(\0132\031.KuplungApp.Ma"
"terialColor\0223\n\020materialSpecular\030, \002(\0132\031."
"KuplungApp.MaterialColor\0223\n\020materialEmis"
"sion\030- \002(\0132\031.KuplungApp.MaterialColor\022\037\n"
"\027Setting_ParallaxMapping\030. \002(\010\022\031\n\021Effect"
"_GBlur_Mode\030/ \002(\005\0229\n\023Effect_GBlur_Radius"
"\0300 \002(\0132\034.KuplungApp.ObjectCoordinate\0228\n\022"
"Effect_GBlur_Width\0301 \002(\0132\034.KuplungApp.Ob"
"jectCoordinate\022\034\n\024Effect_Bloom_doBloom\0302"
" \002(\010\022\034\n\024Effect_Bloom_WeightA\0303 \002(\002\022\034\n\024Ef"
"fect_Bloom_WeightB\0304 \002(\002\022\034\n\024Effect_Bloom"
"_WeightC\0305 \002(\002\022\034\n\024Effect_Bloom_WeightD\0306"
" \002(\002\022\035\n\025Effect_Bloom_Vignette\0307 \002(\002\022 \n\030E"
"ffect_Bloom_VignetteAtt\0308 \002(\002\022%\n\035Setting"
"_LightingPass_DrawMode\0309 \002(\005\022$\n\nmeshObje"
"ct\030: \002(\0132\020.KuplungApp.Mesh"
;
static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_KuplungAppScene_2eproto_deps[1] = {
&::descriptor_table_KuplungDefinitions_2eproto,
};
static ::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase*const descriptor_table_KuplungAppScene_2eproto_sccs[2] = {
&scc_info_MeshModel_KuplungAppScene_2eproto.base,
&scc_info_Scene_KuplungAppScene_2eproto.base,
};
static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_KuplungAppScene_2eproto_once;
static bool descriptor_table_KuplungAppScene_2eproto_initialized = false;
const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_KuplungAppScene_2eproto = {
&descriptor_table_KuplungAppScene_2eproto_initialized, descriptor_table_protodef_KuplungAppScene_2eproto, "KuplungAppScene.proto", 2586,
&descriptor_table_KuplungAppScene_2eproto_once, descriptor_table_KuplungAppScene_2eproto_sccs, descriptor_table_KuplungAppScene_2eproto_deps, 2, 1,
schemas, file_default_instances, TableStruct_KuplungAppScene_2eproto::offsets,
file_level_metadata_KuplungAppScene_2eproto, 2, file_level_enum_descriptors_KuplungAppScene_2eproto, file_level_service_descriptors_KuplungAppScene_2eproto,
};
// Force running AddDescriptors() at dynamic initialization time.
static bool dynamic_init_dummy_KuplungAppScene_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_KuplungAppScene_2eproto), true);
namespace KuplungApp {
// ===================================================================
void Scene::InitAsDefaultInstance() {
}
class Scene::_Internal {
public:
using HasBits = decltype(std::declval<Scene>()._has_bits_);
};
Scene::Scene()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:KuplungApp.Scene)
}
Scene::Scene(const Scene& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr),
_has_bits_(from._has_bits_),
models_(from.models_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:KuplungApp.Scene)
}
void Scene::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_Scene_KuplungAppScene_2eproto.base);
}
Scene::~Scene() {
// @@protoc_insertion_point(destructor:KuplungApp.Scene)
SharedDtor();
}
void Scene::SharedDtor() {
}
void Scene::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const Scene& Scene::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_Scene_KuplungAppScene_2eproto.base);
return *internal_default_instance();
}
void Scene::Clear() {
// @@protoc_insertion_point(message_clear_start:KuplungApp.Scene)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
models_.Clear();
_has_bits_.Clear();
_internal_metadata_.Clear();
}
const char* Scene::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// repeated .KuplungApp.MeshModel models = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) {
ptr -= 1;
do {
ptr += 1;
ptr = ctx->ParseMessage(_internal_add_models(), ptr);
CHK_(ptr);
if (!ctx->DataAvailable(ptr)) break;
} while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<10>(ptr));
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
::PROTOBUF_NAMESPACE_ID::uint8* Scene::_InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:KuplungApp.Scene)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated .KuplungApp.MeshModel models = 1;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->_internal_models_size()); i < n; i++) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(1, this->_internal_models(i), target, stream);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:KuplungApp.Scene)
return target;
}
size_t Scene::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:KuplungApp.Scene)
size_t total_size = 0;
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// repeated .KuplungApp.MeshModel models = 1;
total_size += 1UL * this->_internal_models_size();
for (const auto& msg : this->models_) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize(
_internal_metadata_, total_size, &_cached_size_);
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void Scene::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:KuplungApp.Scene)
GOOGLE_DCHECK_NE(&from, this);
const Scene* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<Scene>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:KuplungApp.Scene)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:KuplungApp.Scene)
MergeFrom(*source);
}
}
void Scene::MergeFrom(const Scene& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:KuplungApp.Scene)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
models_.MergeFrom(from.models_);
}
void Scene::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:KuplungApp.Scene)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void Scene::CopyFrom(const Scene& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:KuplungApp.Scene)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool Scene::IsInitialized() const {
if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(models_)) return false;
return true;
}
void Scene::InternalSwap(Scene* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
models_.InternalSwap(&other->models_);
}
::PROTOBUF_NAMESPACE_ID::Metadata Scene::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
void MeshModel::InitAsDefaultInstance() {
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->positionx_ = const_cast< ::KuplungApp::ObjectCoordinate*>(
::KuplungApp::ObjectCoordinate::internal_default_instance());
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->positiony_ = const_cast< ::KuplungApp::ObjectCoordinate*>(
::KuplungApp::ObjectCoordinate::internal_default_instance());
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->positionz_ = const_cast< ::KuplungApp::ObjectCoordinate*>(
::KuplungApp::ObjectCoordinate::internal_default_instance());
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->scalex_ = const_cast< ::KuplungApp::ObjectCoordinate*>(
::KuplungApp::ObjectCoordinate::internal_default_instance());
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->scaley_ = const_cast< ::KuplungApp::ObjectCoordinate*>(
::KuplungApp::ObjectCoordinate::internal_default_instance());
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->scalez_ = const_cast< ::KuplungApp::ObjectCoordinate*>(
::KuplungApp::ObjectCoordinate::internal_default_instance());
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->rotatex_ = const_cast< ::KuplungApp::ObjectCoordinate*>(
::KuplungApp::ObjectCoordinate::internal_default_instance());
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->rotatey_ = const_cast< ::KuplungApp::ObjectCoordinate*>(
::KuplungApp::ObjectCoordinate::internal_default_instance());
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->rotatez_ = const_cast< ::KuplungApp::ObjectCoordinate*>(
::KuplungApp::ObjectCoordinate::internal_default_instance());
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->displacex_ = const_cast< ::KuplungApp::ObjectCoordinate*>(
::KuplungApp::ObjectCoordinate::internal_default_instance());
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->displacey_ = const_cast< ::KuplungApp::ObjectCoordinate*>(
::KuplungApp::ObjectCoordinate::internal_default_instance());
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->displacez_ = const_cast< ::KuplungApp::ObjectCoordinate*>(
::KuplungApp::ObjectCoordinate::internal_default_instance());
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->setting_materialrefraction_ = const_cast< ::KuplungApp::ObjectCoordinate*>(
::KuplungApp::ObjectCoordinate::internal_default_instance());
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->setting_materialspecularexp_ = const_cast< ::KuplungApp::ObjectCoordinate*>(
::KuplungApp::ObjectCoordinate::internal_default_instance());
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->solidlightskin_materialcolor_ = const_cast< ::KuplungApp::Vec3*>(
::KuplungApp::Vec3::internal_default_instance());
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->solidlightskin_ambient_ = const_cast< ::KuplungApp::Vec3*>(
::KuplungApp::Vec3::internal_default_instance());
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->solidlightskin_diffuse_ = const_cast< ::KuplungApp::Vec3*>(
::KuplungApp::Vec3::internal_default_instance());
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->solidlightskin_specular_ = const_cast< ::KuplungApp::Vec3*>(
::KuplungApp::Vec3::internal_default_instance());
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->setting_lightposition_ = const_cast< ::KuplungApp::Vec3*>(
::KuplungApp::Vec3::internal_default_instance());
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->setting_lightdirection_ = const_cast< ::KuplungApp::Vec3*>(
::KuplungApp::Vec3::internal_default_instance());
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->setting_lightambient_ = const_cast< ::KuplungApp::Vec3*>(
::KuplungApp::Vec3::internal_default_instance());
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->setting_lightdiffuse_ = const_cast< ::KuplungApp::Vec3*>(
::KuplungApp::Vec3::internal_default_instance());
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->setting_lightspecular_ = const_cast< ::KuplungApp::Vec3*>(
::KuplungApp::Vec3::internal_default_instance());
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->displacementheightscale_ = const_cast< ::KuplungApp::ObjectCoordinate*>(
::KuplungApp::ObjectCoordinate::internal_default_instance());
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->materialambient_ = const_cast< ::KuplungApp::MaterialColor*>(
::KuplungApp::MaterialColor::internal_default_instance());
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->materialdiffuse_ = const_cast< ::KuplungApp::MaterialColor*>(
::KuplungApp::MaterialColor::internal_default_instance());
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->materialspecular_ = const_cast< ::KuplungApp::MaterialColor*>(
::KuplungApp::MaterialColor::internal_default_instance());
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->materialemission_ = const_cast< ::KuplungApp::MaterialColor*>(
::KuplungApp::MaterialColor::internal_default_instance());
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->effect_gblur_radius_ = const_cast< ::KuplungApp::ObjectCoordinate*>(
::KuplungApp::ObjectCoordinate::internal_default_instance());
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->effect_gblur_width_ = const_cast< ::KuplungApp::ObjectCoordinate*>(
::KuplungApp::ObjectCoordinate::internal_default_instance());
::KuplungApp::_MeshModel_default_instance_._instance.get_mutable()->meshobject_ = const_cast< ::KuplungApp::Mesh*>(
::KuplungApp::Mesh::internal_default_instance());
}
class MeshModel::_Internal {
public:
using HasBits = decltype(std::declval<MeshModel>()._has_bits_);
static void set_has_modelid(HasBits* has_bits) {
(*has_bits)[0] |= 2147483648u;
}
static void set_has_settings_deferredrender(HasBits* has_bits) {
(*has_bits)[1] |= 1u;
}
static void set_has_setting_celshading(HasBits* has_bits) {
(*has_bits)[1] |= 2u;
}
static void set_has_setting_wireframe(HasBits* has_bits) {
(*has_bits)[1] |= 4u;
}
static void set_has_setting_usetessellation(HasBits* has_bits) {
(*has_bits)[1] |= 8u;
}
static void set_has_setting_usecullface(HasBits* has_bits) {
(*has_bits)[1] |= 1024u;
}
static void set_has_setting_alpha(HasBits* has_bits) {
(*has_bits)[1] |= 16u;
}
static void set_has_setting_tessellationsubdivision(HasBits* has_bits) {
(*has_bits)[1] |= 32u;
}
static const ::KuplungApp::ObjectCoordinate& positionx(const MeshModel* msg);
static void set_has_positionx(HasBits* has_bits) {
(*has_bits)[0] |= 1u;
}
static const ::KuplungApp::ObjectCoordinate& positiony(const MeshModel* msg);
static void set_has_positiony(HasBits* has_bits) {
(*has_bits)[0] |= 2u;
}
static const ::KuplungApp::ObjectCoordinate& positionz(const MeshModel* msg);
static void set_has_positionz(HasBits* has_bits) {
(*has_bits)[0] |= 4u;
}
static const ::KuplungApp::ObjectCoordinate& scalex(const MeshModel* msg);
static void set_has_scalex(HasBits* has_bits) {
(*has_bits)[0] |= 8u;
}
static const ::KuplungApp::ObjectCoordinate& scaley(const MeshModel* msg);
static void set_has_scaley(HasBits* has_bits) {
(*has_bits)[0] |= 16u;
}
static const ::KuplungApp::ObjectCoordinate& scalez(const MeshModel* msg);
static void set_has_scalez(HasBits* has_bits) {
(*has_bits)[0] |= 32u;
}
static const ::KuplungApp::ObjectCoordinate& rotatex(const MeshModel* msg);
static void set_has_rotatex(HasBits* has_bits) {
(*has_bits)[0] |= 64u;
}
static const ::KuplungApp::ObjectCoordinate& rotatey(const MeshModel* msg);
static void set_has_rotatey(HasBits* has_bits) {
(*has_bits)[0] |= 128u;
}
static const ::KuplungApp::ObjectCoordinate& rotatez(const MeshModel* msg);
static void set_has_rotatez(HasBits* has_bits) {
(*has_bits)[0] |= 256u;
}
static const ::KuplungApp::ObjectCoordinate& displacex(const MeshModel* msg);
static void set_has_displacex(HasBits* has_bits) {
(*has_bits)[0] |= 512u;
}
static const ::KuplungApp::ObjectCoordinate& displacey(const MeshModel* msg);
static void set_has_displacey(HasBits* has_bits) {
(*has_bits)[0] |= 1024u;
}
static const ::KuplungApp::ObjectCoordinate& displacez(const MeshModel* msg);
static void set_has_displacez(HasBits* has_bits) {
(*has_bits)[0] |= 2048u;
}
static const ::KuplungApp::ObjectCoordinate& setting_materialrefraction(const MeshModel* msg);
static void set_has_setting_materialrefraction(HasBits* has_bits) {
(*has_bits)[0] |= 4096u;
}
static const ::KuplungApp::ObjectCoordinate& setting_materialspecularexp(const MeshModel* msg);
static void set_has_setting_materialspecularexp(HasBits* has_bits) {
(*has_bits)[0] |= 8192u;
}
static void set_has_setting_modelviewskin(HasBits* has_bits) {
(*has_bits)[1] |= 64u;
}
static const ::KuplungApp::Vec3& solidlightskin_materialcolor(const MeshModel* msg);
static void set_has_solidlightskin_materialcolor(HasBits* has_bits) {
(*has_bits)[0] |= 16384u;
}
static const ::KuplungApp::Vec3& solidlightskin_ambient(const MeshModel* msg);
static void set_has_solidlightskin_ambient(HasBits* has_bits) {
(*has_bits)[0] |= 32768u;
}
static const ::KuplungApp::Vec3& solidlightskin_diffuse(const MeshModel* msg);
static void set_has_solidlightskin_diffuse(HasBits* has_bits) {
(*has_bits)[0] |= 65536u;
}
static const ::KuplungApp::Vec3& solidlightskin_specular(const MeshModel* msg);
static void set_has_solidlightskin_specular(HasBits* has_bits) {
(*has_bits)[0] |= 131072u;
}
static void set_has_solidlightskin_ambient_strength(HasBits* has_bits) {
(*has_bits)[1] |= 128u;
}
static void set_has_solidlightskin_diffuse_strength(HasBits* has_bits) {
(*has_bits)[1] |= 256u;
}
static void set_has_solidlightskin_specular_strength(HasBits* has_bits) {
(*has_bits)[1] |= 512u;
}
static const ::KuplungApp::Vec3& setting_lightposition(const MeshModel* msg);
static void set_has_setting_lightposition(HasBits* has_bits) {
(*has_bits)[0] |= 262144u;
}
static const ::KuplungApp::Vec3& setting_lightdirection(const MeshModel* msg);
static void set_has_setting_lightdirection(HasBits* has_bits) {
(*has_bits)[0] |= 524288u;
}
static const ::KuplungApp::Vec3& setting_lightambient(const MeshModel* msg);
static void set_has_setting_lightambient(HasBits* has_bits) {
(*has_bits)[0] |= 1048576u;
}
static const ::KuplungApp::Vec3& setting_lightdiffuse(const MeshModel* msg);
static void set_has_setting_lightdiffuse(HasBits* has_bits) {
(*has_bits)[0] |= 2097152u;
}
static const ::KuplungApp::Vec3& setting_lightspecular(const MeshModel* msg);
static void set_has_setting_lightspecular(HasBits* has_bits) {
(*has_bits)[0] |= 4194304u;
}
static void set_has_setting_lightstrengthambient(HasBits* has_bits) {
(*has_bits)[1] |= 16384u;
}
static void set_has_setting_lightstrengthdiffuse(HasBits* has_bits) {
(*has_bits)[1] |= 32768u;
}
static void set_has_setting_lightstrengthspecular(HasBits* has_bits) {
(*has_bits)[1] |= 65536u;
}
static void set_has_materialilluminationmodel(HasBits* has_bits) {
(*has_bits)[1] |= 131072u;
}
static const ::KuplungApp::ObjectCoordinate& displacementheightscale(const MeshModel* msg);
static void set_has_displacementheightscale(HasBits* has_bits) {
(*has_bits)[0] |= 8388608u;
}
static void set_has_showmaterialeditor(HasBits* has_bits) {
(*has_bits)[1] |= 2048u;
}
static const ::KuplungApp::MaterialColor& materialambient(const MeshModel* msg);
static void set_has_materialambient(HasBits* has_bits) {
(*has_bits)[0] |= 16777216u;
}
static const ::KuplungApp::MaterialColor& materialdiffuse(const MeshModel* msg);
static void set_has_materialdiffuse(HasBits* has_bits) {
(*has_bits)[0] |= 33554432u;
}
static const ::KuplungApp::MaterialColor& materialspecular(const MeshModel* msg);
static void set_has_materialspecular(HasBits* has_bits) {
(*has_bits)[0] |= 67108864u;
}
static const ::KuplungApp::MaterialColor& materialemission(const MeshModel* msg);
static void set_has_materialemission(HasBits* has_bits) {
(*has_bits)[0] |= 134217728u;
}
static void set_has_setting_parallaxmapping(HasBits* has_bits) {
(*has_bits)[1] |= 4096u;
}
static void set_has_effect_gblur_mode(HasBits* has_bits) {
(*has_bits)[1] |= 262144u;
}
static const ::KuplungApp::ObjectCoordinate& effect_gblur_radius(const MeshModel* msg);
static void set_has_effect_gblur_radius(HasBits* has_bits) {
(*has_bits)[0] |= 268435456u;
}
static const ::KuplungApp::ObjectCoordinate& effect_gblur_width(const MeshModel* msg);
static void set_has_effect_gblur_width(HasBits* has_bits) {
(*has_bits)[0] |= 536870912u;
}
static void set_has_effect_bloom_dobloom(HasBits* has_bits) {
(*has_bits)[1] |= 8192u;
}
static void set_has_effect_bloom_weighta(HasBits* has_bits) {
(*has_bits)[1] |= 524288u;
}
static void set_has_effect_bloom_weightb(HasBits* has_bits) {
(*has_bits)[1] |= 1048576u;
}
static void set_has_effect_bloom_weightc(HasBits* has_bits) {
(*has_bits)[1] |= 2097152u;
}
static void set_has_effect_bloom_weightd(HasBits* has_bits) {
(*has_bits)[1] |= 4194304u;
}
static void set_has_effect_bloom_vignette(HasBits* has_bits) {
(*has_bits)[1] |= 8388608u;
}
static void set_has_effect_bloom_vignetteatt(HasBits* has_bits) {
(*has_bits)[1] |= 16777216u;
}
static void set_has_setting_lightingpass_drawmode(HasBits* has_bits) {
(*has_bits)[1] |= 33554432u;
}
static const ::KuplungApp::Mesh& meshobject(const MeshModel* msg);
static void set_has_meshobject(HasBits* has_bits) {
(*has_bits)[0] |= 1073741824u;
}
};
const ::KuplungApp::ObjectCoordinate&
MeshModel::_Internal::positionx(const MeshModel* msg) {
return *msg->positionx_;
}
const ::KuplungApp::ObjectCoordinate&
MeshModel::_Internal::positiony(const MeshModel* msg) {
return *msg->positiony_;
}
const ::KuplungApp::ObjectCoordinate&
MeshModel::_Internal::positionz(const MeshModel* msg) {
return *msg->positionz_;
}
const ::KuplungApp::ObjectCoordinate&
MeshModel::_Internal::scalex(const MeshModel* msg) {
return *msg->scalex_;
}
const ::KuplungApp::ObjectCoordinate&
MeshModel::_Internal::scaley(const MeshModel* msg) {
return *msg->scaley_;
}
const ::KuplungApp::ObjectCoordinate&
MeshModel::_Internal::scalez(const MeshModel* msg) {
return *msg->scalez_;
}
const ::KuplungApp::ObjectCoordinate&
MeshModel::_Internal::rotatex(const MeshModel* msg) {
return *msg->rotatex_;
}
const ::KuplungApp::ObjectCoordinate&
MeshModel::_Internal::rotatey(const MeshModel* msg) {
return *msg->rotatey_;
}
const ::KuplungApp::ObjectCoordinate&
MeshModel::_Internal::rotatez(const MeshModel* msg) {
return *msg->rotatez_;
}
const ::KuplungApp::ObjectCoordinate&
MeshModel::_Internal::displacex(const MeshModel* msg) {
return *msg->displacex_;
}
const ::KuplungApp::ObjectCoordinate&
MeshModel::_Internal::displacey(const MeshModel* msg) {
return *msg->displacey_;
}
const ::KuplungApp::ObjectCoordinate&
MeshModel::_Internal::displacez(const MeshModel* msg) {
return *msg->displacez_;
}
const ::KuplungApp::ObjectCoordinate&
MeshModel::_Internal::setting_materialrefraction(const MeshModel* msg) {
return *msg->setting_materialrefraction_;
}
const ::KuplungApp::ObjectCoordinate&
MeshModel::_Internal::setting_materialspecularexp(const MeshModel* msg) {
return *msg->setting_materialspecularexp_;
}
const ::KuplungApp::Vec3&
MeshModel::_Internal::solidlightskin_materialcolor(const MeshModel* msg) {
return *msg->solidlightskin_materialcolor_;
}
const ::KuplungApp::Vec3&
MeshModel::_Internal::solidlightskin_ambient(const MeshModel* msg) {
return *msg->solidlightskin_ambient_;
}
const ::KuplungApp::Vec3&
MeshModel::_Internal::solidlightskin_diffuse(const MeshModel* msg) {
return *msg->solidlightskin_diffuse_;
}
const ::KuplungApp::Vec3&
MeshModel::_Internal::solidlightskin_specular(const MeshModel* msg) {
return *msg->solidlightskin_specular_;
}
const ::KuplungApp::Vec3&
MeshModel::_Internal::setting_lightposition(const MeshModel* msg) {
return *msg->setting_lightposition_;
}
const ::KuplungApp::Vec3&
MeshModel::_Internal::setting_lightdirection(const MeshModel* msg) {
return *msg->setting_lightdirection_;
}
const ::KuplungApp::Vec3&
MeshModel::_Internal::setting_lightambient(const MeshModel* msg) {
return *msg->setting_lightambient_;
}
const ::KuplungApp::Vec3&
MeshModel::_Internal::setting_lightdiffuse(const MeshModel* msg) {
return *msg->setting_lightdiffuse_;
}
const ::KuplungApp::Vec3&
MeshModel::_Internal::setting_lightspecular(const MeshModel* msg) {
return *msg->setting_lightspecular_;
}
const ::KuplungApp::ObjectCoordinate&
MeshModel::_Internal::displacementheightscale(const MeshModel* msg) {
return *msg->displacementheightscale_;
}
const ::KuplungApp::MaterialColor&
MeshModel::_Internal::materialambient(const MeshModel* msg) {
return *msg->materialambient_;
}
const ::KuplungApp::MaterialColor&
MeshModel::_Internal::materialdiffuse(const MeshModel* msg) {
return *msg->materialdiffuse_;
}
const ::KuplungApp::MaterialColor&
MeshModel::_Internal::materialspecular(const MeshModel* msg) {
return *msg->materialspecular_;
}
const ::KuplungApp::MaterialColor&
MeshModel::_Internal::materialemission(const MeshModel* msg) {
return *msg->materialemission_;
}
const ::KuplungApp::ObjectCoordinate&
MeshModel::_Internal::effect_gblur_radius(const MeshModel* msg) {
return *msg->effect_gblur_radius_;
}
const ::KuplungApp::ObjectCoordinate&
MeshModel::_Internal::effect_gblur_width(const MeshModel* msg) {
return *msg->effect_gblur_width_;
}
const ::KuplungApp::Mesh&
MeshModel::_Internal::meshobject(const MeshModel* msg) {
return *msg->meshobject_;
}
void MeshModel::clear_positionx() {
if (positionx_ != nullptr) positionx_->Clear();
_has_bits_[0] &= ~0x00000001u;
}
void MeshModel::clear_positiony() {
if (positiony_ != nullptr) positiony_->Clear();
_has_bits_[0] &= ~0x00000002u;
}
void MeshModel::clear_positionz() {
if (positionz_ != nullptr) positionz_->Clear();
_has_bits_[0] &= ~0x00000004u;
}
void MeshModel::clear_scalex() {
if (scalex_ != nullptr) scalex_->Clear();
_has_bits_[0] &= ~0x00000008u;
}
void MeshModel::clear_scaley() {
if (scaley_ != nullptr) scaley_->Clear();
_has_bits_[0] &= ~0x00000010u;
}
void MeshModel::clear_scalez() {
if (scalez_ != nullptr) scalez_->Clear();
_has_bits_[0] &= ~0x00000020u;
}
void MeshModel::clear_rotatex() {
if (rotatex_ != nullptr) rotatex_->Clear();
_has_bits_[0] &= ~0x00000040u;
}
void MeshModel::clear_rotatey() {
if (rotatey_ != nullptr) rotatey_->Clear();
_has_bits_[0] &= ~0x00000080u;
}
void MeshModel::clear_rotatez() {
if (rotatez_ != nullptr) rotatez_->Clear();
_has_bits_[0] &= ~0x00000100u;
}
void MeshModel::clear_displacex() {
if (displacex_ != nullptr) displacex_->Clear();
_has_bits_[0] &= ~0x00000200u;
}
void MeshModel::clear_displacey() {
if (displacey_ != nullptr) displacey_->Clear();
_has_bits_[0] &= ~0x00000400u;
}
void MeshModel::clear_displacez() {
if (displacez_ != nullptr) displacez_->Clear();
_has_bits_[0] &= ~0x00000800u;
}
void MeshModel::clear_setting_materialrefraction() {
if (setting_materialrefraction_ != nullptr) setting_materialrefraction_->Clear();
_has_bits_[0] &= ~0x00001000u;
}
void MeshModel::clear_setting_materialspecularexp() {
if (setting_materialspecularexp_ != nullptr) setting_materialspecularexp_->Clear();
_has_bits_[0] &= ~0x00002000u;
}
void MeshModel::clear_solidlightskin_materialcolor() {
if (solidlightskin_materialcolor_ != nullptr) solidlightskin_materialcolor_->Clear();
_has_bits_[0] &= ~0x00004000u;
}
void MeshModel::clear_solidlightskin_ambient() {
if (solidlightskin_ambient_ != nullptr) solidlightskin_ambient_->Clear();
_has_bits_[0] &= ~0x00008000u;
}
void MeshModel::clear_solidlightskin_diffuse() {
if (solidlightskin_diffuse_ != nullptr) solidlightskin_diffuse_->Clear();
_has_bits_[0] &= ~0x00010000u;
}
void MeshModel::clear_solidlightskin_specular() {
if (solidlightskin_specular_ != nullptr) solidlightskin_specular_->Clear();
_has_bits_[0] &= ~0x00020000u;
}
void MeshModel::clear_setting_lightposition() {
if (setting_lightposition_ != nullptr) setting_lightposition_->Clear();
_has_bits_[0] &= ~0x00040000u;
}
void MeshModel::clear_setting_lightdirection() {
if (setting_lightdirection_ != nullptr) setting_lightdirection_->Clear();
_has_bits_[0] &= ~0x00080000u;
}
void MeshModel::clear_setting_lightambient() {
if (setting_lightambient_ != nullptr) setting_lightambient_->Clear();
_has_bits_[0] &= ~0x00100000u;
}
void MeshModel::clear_setting_lightdiffuse() {
if (setting_lightdiffuse_ != nullptr) setting_lightdiffuse_->Clear();
_has_bits_[0] &= ~0x00200000u;
}
void MeshModel::clear_setting_lightspecular() {
if (setting_lightspecular_ != nullptr) setting_lightspecular_->Clear();
_has_bits_[0] &= ~0x00400000u;
}
void MeshModel::clear_displacementheightscale() {
if (displacementheightscale_ != nullptr) displacementheightscale_->Clear();
_has_bits_[0] &= ~0x00800000u;
}
void MeshModel::clear_materialambient() {
if (materialambient_ != nullptr) materialambient_->Clear();
_has_bits_[0] &= ~0x01000000u;
}
void MeshModel::clear_materialdiffuse() {
if (materialdiffuse_ != nullptr) materialdiffuse_->Clear();
_has_bits_[0] &= ~0x02000000u;
}
void MeshModel::clear_materialspecular() {
if (materialspecular_ != nullptr) materialspecular_->Clear();
_has_bits_[0] &= ~0x04000000u;
}
void MeshModel::clear_materialemission() {
if (materialemission_ != nullptr) materialemission_->Clear();
_has_bits_[0] &= ~0x08000000u;
}
void MeshModel::clear_effect_gblur_radius() {
if (effect_gblur_radius_ != nullptr) effect_gblur_radius_->Clear();
_has_bits_[0] &= ~0x10000000u;
}
void MeshModel::clear_effect_gblur_width() {
if (effect_gblur_width_ != nullptr) effect_gblur_width_->Clear();
_has_bits_[0] &= ~0x20000000u;
}
void MeshModel::clear_meshobject() {
if (meshobject_ != nullptr) meshobject_->Clear();
_has_bits_[0] &= ~0x40000000u;
}
MeshModel::MeshModel()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:KuplungApp.MeshModel)
}
MeshModel::MeshModel(const MeshModel& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr),
_has_bits_(from._has_bits_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from._internal_has_positionx()) {
positionx_ = new ::KuplungApp::ObjectCoordinate(*from.positionx_);
} else {
positionx_ = nullptr;
}
if (from._internal_has_positiony()) {
positiony_ = new ::KuplungApp::ObjectCoordinate(*from.positiony_);
} else {
positiony_ = nullptr;
}
if (from._internal_has_positionz()) {
positionz_ = new ::KuplungApp::ObjectCoordinate(*from.positionz_);
} else {
positionz_ = nullptr;
}
if (from._internal_has_scalex()) {
scalex_ = new ::KuplungApp::ObjectCoordinate(*from.scalex_);
} else {
scalex_ = nullptr;
}
if (from._internal_has_scaley()) {
scaley_ = new ::KuplungApp::ObjectCoordinate(*from.scaley_);
} else {
scaley_ = nullptr;
}
if (from._internal_has_scalez()) {
scalez_ = new ::KuplungApp::ObjectCoordinate(*from.scalez_);
} else {
scalez_ = nullptr;
}
if (from._internal_has_rotatex()) {
rotatex_ = new ::KuplungApp::ObjectCoordinate(*from.rotatex_);
} else {
rotatex_ = nullptr;
}
if (from._internal_has_rotatey()) {
rotatey_ = new ::KuplungApp::ObjectCoordinate(*from.rotatey_);
} else {
rotatey_ = nullptr;
}
if (from._internal_has_rotatez()) {
rotatez_ = new ::KuplungApp::ObjectCoordinate(*from.rotatez_);
} else {
rotatez_ = nullptr;
}
if (from._internal_has_displacex()) {
displacex_ = new ::KuplungApp::ObjectCoordinate(*from.displacex_);
} else {
displacex_ = nullptr;
}
if (from._internal_has_displacey()) {
displacey_ = new ::KuplungApp::ObjectCoordinate(*from.displacey_);
} else {
displacey_ = nullptr;
}
if (from._internal_has_displacez()) {
displacez_ = new ::KuplungApp::ObjectCoordinate(*from.displacez_);
} else {
displacez_ = nullptr;
}
if (from._internal_has_setting_materialrefraction()) {
setting_materialrefraction_ = new ::KuplungApp::ObjectCoordinate(*from.setting_materialrefraction_);
} else {
setting_materialrefraction_ = nullptr;
}
if (from._internal_has_setting_materialspecularexp()) {
setting_materialspecularexp_ = new ::KuplungApp::ObjectCoordinate(*from.setting_materialspecularexp_);
} else {
setting_materialspecularexp_ = nullptr;
}
if (from._internal_has_solidlightskin_materialcolor()) {
solidlightskin_materialcolor_ = new ::KuplungApp::Vec3(*from.solidlightskin_materialcolor_);
} else {
solidlightskin_materialcolor_ = nullptr;
}
if (from._internal_has_solidlightskin_ambient()) {
solidlightskin_ambient_ = new ::KuplungApp::Vec3(*from.solidlightskin_ambient_);
} else {
solidlightskin_ambient_ = nullptr;
}
if (from._internal_has_solidlightskin_diffuse()) {
solidlightskin_diffuse_ = new ::KuplungApp::Vec3(*from.solidlightskin_diffuse_);
} else {
solidlightskin_diffuse_ = nullptr;
}
if (from._internal_has_solidlightskin_specular()) {
solidlightskin_specular_ = new ::KuplungApp::Vec3(*from.solidlightskin_specular_);
} else {
solidlightskin_specular_ = nullptr;
}
if (from._internal_has_setting_lightposition()) {
setting_lightposition_ = new ::KuplungApp::Vec3(*from.setting_lightposition_);
} else {
setting_lightposition_ = nullptr;
}
if (from._internal_has_setting_lightdirection()) {
setting_lightdirection_ = new ::KuplungApp::Vec3(*from.setting_lightdirection_);
} else {
setting_lightdirection_ = nullptr;
}
if (from._internal_has_setting_lightambient()) {
setting_lightambient_ = new ::KuplungApp::Vec3(*from.setting_lightambient_);
} else {
setting_lightambient_ = nullptr;
}
if (from._internal_has_setting_lightdiffuse()) {
setting_lightdiffuse_ = new ::KuplungApp::Vec3(*from.setting_lightdiffuse_);
} else {
setting_lightdiffuse_ = nullptr;
}
if (from._internal_has_setting_lightspecular()) {
setting_lightspecular_ = new ::KuplungApp::Vec3(*from.setting_lightspecular_);
} else {
setting_lightspecular_ = nullptr;
}
if (from._internal_has_displacementheightscale()) {
displacementheightscale_ = new ::KuplungApp::ObjectCoordinate(*from.displacementheightscale_);
} else {
displacementheightscale_ = nullptr;
}
if (from._internal_has_materialambient()) {
materialambient_ = new ::KuplungApp::MaterialColor(*from.materialambient_);
} else {
materialambient_ = nullptr;
}
if (from._internal_has_materialdiffuse()) {
materialdiffuse_ = new ::KuplungApp::MaterialColor(*from.materialdiffuse_);
} else {
materialdiffuse_ = nullptr;
}
if (from._internal_has_materialspecular()) {
materialspecular_ = new ::KuplungApp::MaterialColor(*from.materialspecular_);
} else {
materialspecular_ = nullptr;
}
if (from._internal_has_materialemission()) {
materialemission_ = new ::KuplungApp::MaterialColor(*from.materialemission_);
} else {
materialemission_ = nullptr;
}
if (from._internal_has_effect_gblur_radius()) {
effect_gblur_radius_ = new ::KuplungApp::ObjectCoordinate(*from.effect_gblur_radius_);
} else {
effect_gblur_radius_ = nullptr;
}
if (from._internal_has_effect_gblur_width()) {
effect_gblur_width_ = new ::KuplungApp::ObjectCoordinate(*from.effect_gblur_width_);
} else {
effect_gblur_width_ = nullptr;
}
if (from._internal_has_meshobject()) {
meshobject_ = new ::KuplungApp::Mesh(*from.meshobject_);
} else {
meshobject_ = nullptr;
}
::memcpy(&modelid_, &from.modelid_,
static_cast<size_t>(reinterpret_cast<char*>(&setting_lightingpass_drawmode_) -
reinterpret_cast<char*>(&modelid_)) + sizeof(setting_lightingpass_drawmode_));
// @@protoc_insertion_point(copy_constructor:KuplungApp.MeshModel)
}
void MeshModel::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_MeshModel_KuplungAppScene_2eproto.base);
::memset(&positionx_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&setting_lightingpass_drawmode_) -
reinterpret_cast<char*>(&positionx_)) + sizeof(setting_lightingpass_drawmode_));
}
MeshModel::~MeshModel() {
// @@protoc_insertion_point(destructor:KuplungApp.MeshModel)
SharedDtor();
}
void MeshModel::SharedDtor() {
if (this != internal_default_instance()) delete positionx_;
if (this != internal_default_instance()) delete positiony_;
if (this != internal_default_instance()) delete positionz_;
if (this != internal_default_instance()) delete scalex_;
if (this != internal_default_instance()) delete scaley_;
if (this != internal_default_instance()) delete scalez_;
if (this != internal_default_instance()) delete rotatex_;
if (this != internal_default_instance()) delete rotatey_;
if (this != internal_default_instance()) delete rotatez_;
if (this != internal_default_instance()) delete displacex_;
if (this != internal_default_instance()) delete displacey_;
if (this != internal_default_instance()) delete displacez_;
if (this != internal_default_instance()) delete setting_materialrefraction_;
if (this != internal_default_instance()) delete setting_materialspecularexp_;
if (this != internal_default_instance()) delete solidlightskin_materialcolor_;
if (this != internal_default_instance()) delete solidlightskin_ambient_;
if (this != internal_default_instance()) delete solidlightskin_diffuse_;
if (this != internal_default_instance()) delete solidlightskin_specular_;
if (this != internal_default_instance()) delete setting_lightposition_;
if (this != internal_default_instance()) delete setting_lightdirection_;
if (this != internal_default_instance()) delete setting_lightambient_;
if (this != internal_default_instance()) delete setting_lightdiffuse_;
if (this != internal_default_instance()) delete setting_lightspecular_;
if (this != internal_default_instance()) delete displacementheightscale_;
if (this != internal_default_instance()) delete materialambient_;
if (this != internal_default_instance()) delete materialdiffuse_;
if (this != internal_default_instance()) delete materialspecular_;
if (this != internal_default_instance()) delete materialemission_;
if (this != internal_default_instance()) delete effect_gblur_radius_;
if (this != internal_default_instance()) delete effect_gblur_width_;
if (this != internal_default_instance()) delete meshobject_;
}
void MeshModel::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const MeshModel& MeshModel::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_MeshModel_KuplungAppScene_2eproto.base);
return *internal_default_instance();
}
void MeshModel::Clear() {
// @@protoc_insertion_point(message_clear_start:KuplungApp.MeshModel)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x000000ffu) {
if (cached_has_bits & 0x00000001u) {
GOOGLE_DCHECK(positionx_ != nullptr);
positionx_->Clear();
}
if (cached_has_bits & 0x00000002u) {
GOOGLE_DCHECK(positiony_ != nullptr);
positiony_->Clear();
}
if (cached_has_bits & 0x00000004u) {
GOOGLE_DCHECK(positionz_ != nullptr);
positionz_->Clear();
}
if (cached_has_bits & 0x00000008u) {
GOOGLE_DCHECK(scalex_ != nullptr);
scalex_->Clear();
}
if (cached_has_bits & 0x00000010u) {
GOOGLE_DCHECK(scaley_ != nullptr);
scaley_->Clear();
}
if (cached_has_bits & 0x00000020u) {
GOOGLE_DCHECK(scalez_ != nullptr);
scalez_->Clear();
}
if (cached_has_bits & 0x00000040u) {
GOOGLE_DCHECK(rotatex_ != nullptr);
rotatex_->Clear();
}
if (cached_has_bits & 0x00000080u) {
GOOGLE_DCHECK(rotatey_ != nullptr);
rotatey_->Clear();
}
}
if (cached_has_bits & 0x0000ff00u) {
if (cached_has_bits & 0x00000100u) {
GOOGLE_DCHECK(rotatez_ != nullptr);
rotatez_->Clear();
}
if (cached_has_bits & 0x00000200u) {
GOOGLE_DCHECK(displacex_ != nullptr);
displacex_->Clear();
}
if (cached_has_bits & 0x00000400u) {
GOOGLE_DCHECK(displacey_ != nullptr);
displacey_->Clear();
}
if (cached_has_bits & 0x00000800u) {
GOOGLE_DCHECK(displacez_ != nullptr);
displacez_->Clear();
}
if (cached_has_bits & 0x00001000u) {
GOOGLE_DCHECK(setting_materialrefraction_ != nullptr);
setting_materialrefraction_->Clear();
}
if (cached_has_bits & 0x00002000u) {
GOOGLE_DCHECK(setting_materialspecularexp_ != nullptr);
setting_materialspecularexp_->Clear();
}
if (cached_has_bits & 0x00004000u) {
GOOGLE_DCHECK(solidlightskin_materialcolor_ != nullptr);
solidlightskin_materialcolor_->Clear();
}
if (cached_has_bits & 0x00008000u) {
GOOGLE_DCHECK(solidlightskin_ambient_ != nullptr);
solidlightskin_ambient_->Clear();
}
}
if (cached_has_bits & 0x00ff0000u) {
if (cached_has_bits & 0x00010000u) {
GOOGLE_DCHECK(solidlightskin_diffuse_ != nullptr);
solidlightskin_diffuse_->Clear();
}
if (cached_has_bits & 0x00020000u) {
GOOGLE_DCHECK(solidlightskin_specular_ != nullptr);
solidlightskin_specular_->Clear();
}
if (cached_has_bits & 0x00040000u) {
GOOGLE_DCHECK(setting_lightposition_ != nullptr);
setting_lightposition_->Clear();
}
if (cached_has_bits & 0x00080000u) {
GOOGLE_DCHECK(setting_lightdirection_ != nullptr);
setting_lightdirection_->Clear();
}
if (cached_has_bits & 0x00100000u) {
GOOGLE_DCHECK(setting_lightambient_ != nullptr);
setting_lightambient_->Clear();
}
if (cached_has_bits & 0x00200000u) {
GOOGLE_DCHECK(setting_lightdiffuse_ != nullptr);
setting_lightdiffuse_->Clear();
}
if (cached_has_bits & 0x00400000u) {
GOOGLE_DCHECK(setting_lightspecular_ != nullptr);
setting_lightspecular_->Clear();
}
if (cached_has_bits & 0x00800000u) {
GOOGLE_DCHECK(displacementheightscale_ != nullptr);
displacementheightscale_->Clear();
}
}
if (cached_has_bits & 0x7f000000u) {
if (cached_has_bits & 0x01000000u) {
GOOGLE_DCHECK(materialambient_ != nullptr);
materialambient_->Clear();
}
if (cached_has_bits & 0x02000000u) {
GOOGLE_DCHECK(materialdiffuse_ != nullptr);
materialdiffuse_->Clear();
}
if (cached_has_bits & 0x04000000u) {
GOOGLE_DCHECK(materialspecular_ != nullptr);
materialspecular_->Clear();
}
if (cached_has_bits & 0x08000000u) {
GOOGLE_DCHECK(materialemission_ != nullptr);
materialemission_->Clear();
}
if (cached_has_bits & 0x10000000u) {
GOOGLE_DCHECK(effect_gblur_radius_ != nullptr);
effect_gblur_radius_->Clear();
}
if (cached_has_bits & 0x20000000u) {
GOOGLE_DCHECK(effect_gblur_width_ != nullptr);
effect_gblur_width_->Clear();
}
if (cached_has_bits & 0x40000000u) {
GOOGLE_DCHECK(meshobject_ != nullptr);
meshobject_->Clear();
}
}
modelid_ = 0;
cached_has_bits = _has_bits_[1];
if (cached_has_bits & 0x000000ffu) {
::memset(&settings_deferredrender_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&solidlightskin_ambient_strength_) -
reinterpret_cast<char*>(&settings_deferredrender_)) + sizeof(solidlightskin_ambient_strength_));
}
if (cached_has_bits & 0x0000ff00u) {
::memset(&solidlightskin_diffuse_strength_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&setting_lightstrengthdiffuse_) -
reinterpret_cast<char*>(&solidlightskin_diffuse_strength_)) + sizeof(setting_lightstrengthdiffuse_));
}
if (cached_has_bits & 0x00ff0000u) {
::memset(&setting_lightstrengthspecular_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&effect_bloom_vignette_) -
reinterpret_cast<char*>(&setting_lightstrengthspecular_)) + sizeof(effect_bloom_vignette_));
}
if (cached_has_bits & 0x03000000u) {
::memset(&effect_bloom_vignetteatt_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&setting_lightingpass_drawmode_) -
reinterpret_cast<char*>(&effect_bloom_vignetteatt_)) + sizeof(setting_lightingpass_drawmode_));
}
_has_bits_.Clear();
_internal_metadata_.Clear();
}
const char* MeshModel::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// required int32 ModelID = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
_Internal::set_has_modelid(&_has_bits_);
modelid_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required bool Settings_DeferredRender = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) {
_Internal::set_has_settings_deferredrender(&_has_bits_);
settings_deferredrender_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required bool Setting_CelShading = 3;
case 3:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24)) {
_Internal::set_has_setting_celshading(&_has_bits_);
setting_celshading_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required bool Setting_Wireframe = 4;
case 4:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) {
_Internal::set_has_setting_wireframe(&_has_bits_);
setting_wireframe_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required bool Setting_UseTessellation = 5;
case 5:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) {
_Internal::set_has_setting_usetessellation(&_has_bits_);
setting_usetessellation_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required bool Setting_UseCullFace = 6;
case 6:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 48)) {
_Internal::set_has_setting_usecullface(&_has_bits_);
setting_usecullface_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required float Setting_Alpha = 7;
case 7:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 61)) {
_Internal::set_has_setting_alpha(&_has_bits_);
setting_alpha_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr);
ptr += sizeof(float);
} else goto handle_unusual;
continue;
// required int32 Setting_TessellationSubdivision = 8;
case 8:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 64)) {
_Internal::set_has_setting_tessellationsubdivision(&_has_bits_);
setting_tessellationsubdivision_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .KuplungApp.ObjectCoordinate positionX = 9;
case 9:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 74)) {
ptr = ctx->ParseMessage(_internal_mutable_positionx(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .KuplungApp.ObjectCoordinate positionY = 10;
case 10:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 82)) {
ptr = ctx->ParseMessage(_internal_mutable_positiony(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .KuplungApp.ObjectCoordinate positionZ = 11;
case 11:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 90)) {
ptr = ctx->ParseMessage(_internal_mutable_positionz(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .KuplungApp.ObjectCoordinate scaleX = 12;
case 12:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 98)) {
ptr = ctx->ParseMessage(_internal_mutable_scalex(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .KuplungApp.ObjectCoordinate scaleY = 13;
case 13:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 106)) {
ptr = ctx->ParseMessage(_internal_mutable_scaley(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .KuplungApp.ObjectCoordinate scaleZ = 14;
case 14:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 114)) {
ptr = ctx->ParseMessage(_internal_mutable_scalez(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .KuplungApp.ObjectCoordinate rotateX = 15;
case 15:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 122)) {
ptr = ctx->ParseMessage(_internal_mutable_rotatex(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .KuplungApp.ObjectCoordinate rotateY = 16;
case 16:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 130)) {
ptr = ctx->ParseMessage(_internal_mutable_rotatey(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .KuplungApp.ObjectCoordinate rotateZ = 17;
case 17:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 138)) {
ptr = ctx->ParseMessage(_internal_mutable_rotatez(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .KuplungApp.ObjectCoordinate displaceX = 18;
case 18:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 146)) {
ptr = ctx->ParseMessage(_internal_mutable_displacex(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .KuplungApp.ObjectCoordinate displaceY = 19;
case 19:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 154)) {
ptr = ctx->ParseMessage(_internal_mutable_displacey(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .KuplungApp.ObjectCoordinate displaceZ = 20;
case 20:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 162)) {
ptr = ctx->ParseMessage(_internal_mutable_displacez(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .KuplungApp.ObjectCoordinate Setting_MaterialRefraction = 21;
case 21:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 170)) {
ptr = ctx->ParseMessage(_internal_mutable_setting_materialrefraction(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .KuplungApp.ObjectCoordinate Setting_MaterialSpecularExp = 22;
case 22:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 178)) {
ptr = ctx->ParseMessage(_internal_mutable_setting_materialspecularexp(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required int32 Setting_ModelViewSkin = 23;
case 23:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 184)) {
_Internal::set_has_setting_modelviewskin(&_has_bits_);
setting_modelviewskin_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .KuplungApp.Vec3 solidLightSkin_MaterialColor = 24;
case 24:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 194)) {
ptr = ctx->ParseMessage(_internal_mutable_solidlightskin_materialcolor(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .KuplungApp.Vec3 solidLightSkin_Ambient = 25;
case 25:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 202)) {
ptr = ctx->ParseMessage(_internal_mutable_solidlightskin_ambient(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .KuplungApp.Vec3 solidLightSkin_Diffuse = 26;
case 26:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 210)) {
ptr = ctx->ParseMessage(_internal_mutable_solidlightskin_diffuse(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .KuplungApp.Vec3 solidLightSkin_Specular = 27;
case 27:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 218)) {
ptr = ctx->ParseMessage(_internal_mutable_solidlightskin_specular(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required float solidLightSkin_Ambient_Strength = 28;
case 28:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 229)) {
_Internal::set_has_solidlightskin_ambient_strength(&_has_bits_);
solidlightskin_ambient_strength_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr);
ptr += sizeof(float);
} else goto handle_unusual;
continue;
// required float solidLightSkin_Diffuse_Strength = 29;
case 29:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 237)) {
_Internal::set_has_solidlightskin_diffuse_strength(&_has_bits_);
solidlightskin_diffuse_strength_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr);
ptr += sizeof(float);
} else goto handle_unusual;
continue;
// required float solidLightSkin_Specular_Strength = 30;
case 30:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 245)) {
_Internal::set_has_solidlightskin_specular_strength(&_has_bits_);
solidlightskin_specular_strength_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr);
ptr += sizeof(float);
} else goto handle_unusual;
continue;
// required .KuplungApp.Vec3 Setting_LightPosition = 31;
case 31:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 250)) {
ptr = ctx->ParseMessage(_internal_mutable_setting_lightposition(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .KuplungApp.Vec3 Setting_LightDirection = 32;
case 32:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 2)) {
ptr = ctx->ParseMessage(_internal_mutable_setting_lightdirection(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .KuplungApp.Vec3 Setting_LightAmbient = 33;
case 33:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) {
ptr = ctx->ParseMessage(_internal_mutable_setting_lightambient(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .KuplungApp.Vec3 Setting_LightDiffuse = 34;
case 34:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) {
ptr = ctx->ParseMessage(_internal_mutable_setting_lightdiffuse(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .KuplungApp.Vec3 Setting_LightSpecular = 35;
case 35:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) {
ptr = ctx->ParseMessage(_internal_mutable_setting_lightspecular(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required float Setting_LightStrengthAmbient = 36;
case 36:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 37)) {
_Internal::set_has_setting_lightstrengthambient(&_has_bits_);
setting_lightstrengthambient_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr);
ptr += sizeof(float);
} else goto handle_unusual;
continue;
// required float Setting_LightStrengthDiffuse = 37;
case 37:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 45)) {
_Internal::set_has_setting_lightstrengthdiffuse(&_has_bits_);
setting_lightstrengthdiffuse_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr);
ptr += sizeof(float);
} else goto handle_unusual;
continue;
// required float Setting_LightStrengthSpecular = 38;
case 38:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 53)) {
_Internal::set_has_setting_lightstrengthspecular(&_has_bits_);
setting_lightstrengthspecular_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr);
ptr += sizeof(float);
} else goto handle_unusual;
continue;
// required int32 materialIlluminationModel = 39;
case 39:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 56)) {
_Internal::set_has_materialilluminationmodel(&_has_bits_);
materialilluminationmodel_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .KuplungApp.ObjectCoordinate displacementHeightScale = 40;
case 40:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 66)) {
ptr = ctx->ParseMessage(_internal_mutable_displacementheightscale(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required bool showMaterialEditor = 41;
case 41:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 72)) {
_Internal::set_has_showmaterialeditor(&_has_bits_);
showmaterialeditor_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .KuplungApp.MaterialColor materialAmbient = 42;
case 42:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 82)) {
ptr = ctx->ParseMessage(_internal_mutable_materialambient(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .KuplungApp.MaterialColor materialDiffuse = 43;
case 43:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 90)) {
ptr = ctx->ParseMessage(_internal_mutable_materialdiffuse(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .KuplungApp.MaterialColor materialSpecular = 44;
case 44:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 98)) {
ptr = ctx->ParseMessage(_internal_mutable_materialspecular(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .KuplungApp.MaterialColor materialEmission = 45;
case 45:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 106)) {
ptr = ctx->ParseMessage(_internal_mutable_materialemission(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required bool Setting_ParallaxMapping = 46;
case 46:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 112)) {
_Internal::set_has_setting_parallaxmapping(&_has_bits_);
setting_parallaxmapping_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required int32 Effect_GBlur_Mode = 47;
case 47:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 120)) {
_Internal::set_has_effect_gblur_mode(&_has_bits_);
effect_gblur_mode_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .KuplungApp.ObjectCoordinate Effect_GBlur_Radius = 48;
case 48:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 130)) {
ptr = ctx->ParseMessage(_internal_mutable_effect_gblur_radius(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .KuplungApp.ObjectCoordinate Effect_GBlur_Width = 49;
case 49:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 138)) {
ptr = ctx->ParseMessage(_internal_mutable_effect_gblur_width(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required bool Effect_Bloom_doBloom = 50;
case 50:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 144)) {
_Internal::set_has_effect_bloom_dobloom(&_has_bits_);
effect_bloom_dobloom_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required float Effect_Bloom_WeightA = 51;
case 51:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 157)) {
_Internal::set_has_effect_bloom_weighta(&_has_bits_);
effect_bloom_weighta_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr);
ptr += sizeof(float);
} else goto handle_unusual;
continue;
// required float Effect_Bloom_WeightB = 52;
case 52:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 165)) {
_Internal::set_has_effect_bloom_weightb(&_has_bits_);
effect_bloom_weightb_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr);
ptr += sizeof(float);
} else goto handle_unusual;
continue;
// required float Effect_Bloom_WeightC = 53;
case 53:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 173)) {
_Internal::set_has_effect_bloom_weightc(&_has_bits_);
effect_bloom_weightc_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr);
ptr += sizeof(float);
} else goto handle_unusual;
continue;
// required float Effect_Bloom_WeightD = 54;
case 54:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 181)) {
_Internal::set_has_effect_bloom_weightd(&_has_bits_);
effect_bloom_weightd_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr);
ptr += sizeof(float);
} else goto handle_unusual;
continue;
// required float Effect_Bloom_Vignette = 55;
case 55:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 189)) {
_Internal::set_has_effect_bloom_vignette(&_has_bits_);
effect_bloom_vignette_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr);
ptr += sizeof(float);
} else goto handle_unusual;
continue;
// required float Effect_Bloom_VignetteAtt = 56;
case 56:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 197)) {
_Internal::set_has_effect_bloom_vignetteatt(&_has_bits_);
effect_bloom_vignetteatt_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr);
ptr += sizeof(float);
} else goto handle_unusual;
continue;
// required int32 Setting_LightingPass_DrawMode = 57;
case 57:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 200)) {
_Internal::set_has_setting_lightingpass_drawmode(&_has_bits_);
setting_lightingpass_drawmode_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required .KuplungApp.Mesh meshObject = 58;
case 58:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 210)) {
ptr = ctx->ParseMessage(_internal_mutable_meshobject(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
::PROTOBUF_NAMESPACE_ID::uint8* MeshModel::_InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:KuplungApp.MeshModel)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// required int32 ModelID = 1;
if (cached_has_bits & 0x80000000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(1, this->_internal_modelid(), target);
}
cached_has_bits = _has_bits_[1];
// required bool Settings_DeferredRender = 2;
if (cached_has_bits & 0x00000001u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(2, this->_internal_settings_deferredrender(), target);
}
// required bool Setting_CelShading = 3;
if (cached_has_bits & 0x00000002u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(3, this->_internal_setting_celshading(), target);
}
// required bool Setting_Wireframe = 4;
if (cached_has_bits & 0x00000004u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(4, this->_internal_setting_wireframe(), target);
}
// required bool Setting_UseTessellation = 5;
if (cached_has_bits & 0x00000008u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(5, this->_internal_setting_usetessellation(), target);
}
// required bool Setting_UseCullFace = 6;
if (cached_has_bits & 0x00000400u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(6, this->_internal_setting_usecullface(), target);
}
// required float Setting_Alpha = 7;
if (cached_has_bits & 0x00000010u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteFloatToArray(7, this->_internal_setting_alpha(), target);
}
// required int32 Setting_TessellationSubdivision = 8;
if (cached_has_bits & 0x00000020u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(8, this->_internal_setting_tessellationsubdivision(), target);
}
cached_has_bits = _has_bits_[0];
// required .KuplungApp.ObjectCoordinate positionX = 9;
if (cached_has_bits & 0x00000001u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
9, _Internal::positionx(this), target, stream);
}
// required .KuplungApp.ObjectCoordinate positionY = 10;
if (cached_has_bits & 0x00000002u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
10, _Internal::positiony(this), target, stream);
}
// required .KuplungApp.ObjectCoordinate positionZ = 11;
if (cached_has_bits & 0x00000004u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
11, _Internal::positionz(this), target, stream);
}
// required .KuplungApp.ObjectCoordinate scaleX = 12;
if (cached_has_bits & 0x00000008u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
12, _Internal::scalex(this), target, stream);
}
// required .KuplungApp.ObjectCoordinate scaleY = 13;
if (cached_has_bits & 0x00000010u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
13, _Internal::scaley(this), target, stream);
}
// required .KuplungApp.ObjectCoordinate scaleZ = 14;
if (cached_has_bits & 0x00000020u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
14, _Internal::scalez(this), target, stream);
}
// required .KuplungApp.ObjectCoordinate rotateX = 15;
if (cached_has_bits & 0x00000040u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
15, _Internal::rotatex(this), target, stream);
}
// required .KuplungApp.ObjectCoordinate rotateY = 16;
if (cached_has_bits & 0x00000080u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
16, _Internal::rotatey(this), target, stream);
}
// required .KuplungApp.ObjectCoordinate rotateZ = 17;
if (cached_has_bits & 0x00000100u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
17, _Internal::rotatez(this), target, stream);
}
// required .KuplungApp.ObjectCoordinate displaceX = 18;
if (cached_has_bits & 0x00000200u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
18, _Internal::displacex(this), target, stream);
}
// required .KuplungApp.ObjectCoordinate displaceY = 19;
if (cached_has_bits & 0x00000400u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
19, _Internal::displacey(this), target, stream);
}
// required .KuplungApp.ObjectCoordinate displaceZ = 20;
if (cached_has_bits & 0x00000800u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
20, _Internal::displacez(this), target, stream);
}
// required .KuplungApp.ObjectCoordinate Setting_MaterialRefraction = 21;
if (cached_has_bits & 0x00001000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
21, _Internal::setting_materialrefraction(this), target, stream);
}
// required .KuplungApp.ObjectCoordinate Setting_MaterialSpecularExp = 22;
if (cached_has_bits & 0x00002000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
22, _Internal::setting_materialspecularexp(this), target, stream);
}
cached_has_bits = _has_bits_[1];
// required int32 Setting_ModelViewSkin = 23;
if (cached_has_bits & 0x00000040u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(23, this->_internal_setting_modelviewskin(), target);
}
cached_has_bits = _has_bits_[0];
// required .KuplungApp.Vec3 solidLightSkin_MaterialColor = 24;
if (cached_has_bits & 0x00004000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
24, _Internal::solidlightskin_materialcolor(this), target, stream);
}
// required .KuplungApp.Vec3 solidLightSkin_Ambient = 25;
if (cached_has_bits & 0x00008000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
25, _Internal::solidlightskin_ambient(this), target, stream);
}
// required .KuplungApp.Vec3 solidLightSkin_Diffuse = 26;
if (cached_has_bits & 0x00010000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
26, _Internal::solidlightskin_diffuse(this), target, stream);
}
// required .KuplungApp.Vec3 solidLightSkin_Specular = 27;
if (cached_has_bits & 0x00020000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
27, _Internal::solidlightskin_specular(this), target, stream);
}
cached_has_bits = _has_bits_[1];
// required float solidLightSkin_Ambient_Strength = 28;
if (cached_has_bits & 0x00000080u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteFloatToArray(28, this->_internal_solidlightskin_ambient_strength(), target);
}
// required float solidLightSkin_Diffuse_Strength = 29;
if (cached_has_bits & 0x00000100u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteFloatToArray(29, this->_internal_solidlightskin_diffuse_strength(), target);
}
// required float solidLightSkin_Specular_Strength = 30;
if (cached_has_bits & 0x00000200u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteFloatToArray(30, this->_internal_solidlightskin_specular_strength(), target);
}
cached_has_bits = _has_bits_[0];
// required .KuplungApp.Vec3 Setting_LightPosition = 31;
if (cached_has_bits & 0x00040000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
31, _Internal::setting_lightposition(this), target, stream);
}
// required .KuplungApp.Vec3 Setting_LightDirection = 32;
if (cached_has_bits & 0x00080000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
32, _Internal::setting_lightdirection(this), target, stream);
}
// required .KuplungApp.Vec3 Setting_LightAmbient = 33;
if (cached_has_bits & 0x00100000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
33, _Internal::setting_lightambient(this), target, stream);
}
// required .KuplungApp.Vec3 Setting_LightDiffuse = 34;
if (cached_has_bits & 0x00200000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
34, _Internal::setting_lightdiffuse(this), target, stream);
}
// required .KuplungApp.Vec3 Setting_LightSpecular = 35;
if (cached_has_bits & 0x00400000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
35, _Internal::setting_lightspecular(this), target, stream);
}
cached_has_bits = _has_bits_[1];
// required float Setting_LightStrengthAmbient = 36;
if (cached_has_bits & 0x00004000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteFloatToArray(36, this->_internal_setting_lightstrengthambient(), target);
}
// required float Setting_LightStrengthDiffuse = 37;
if (cached_has_bits & 0x00008000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteFloatToArray(37, this->_internal_setting_lightstrengthdiffuse(), target);
}
// required float Setting_LightStrengthSpecular = 38;
if (cached_has_bits & 0x00010000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteFloatToArray(38, this->_internal_setting_lightstrengthspecular(), target);
}
// required int32 materialIlluminationModel = 39;
if (cached_has_bits & 0x00020000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(39, this->_internal_materialilluminationmodel(), target);
}
cached_has_bits = _has_bits_[0];
// required .KuplungApp.ObjectCoordinate displacementHeightScale = 40;
if (cached_has_bits & 0x00800000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
40, _Internal::displacementheightscale(this), target, stream);
}
cached_has_bits = _has_bits_[1];
// required bool showMaterialEditor = 41;
if (cached_has_bits & 0x00000800u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(41, this->_internal_showmaterialeditor(), target);
}
cached_has_bits = _has_bits_[0];
// required .KuplungApp.MaterialColor materialAmbient = 42;
if (cached_has_bits & 0x01000000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
42, _Internal::materialambient(this), target, stream);
}
// required .KuplungApp.MaterialColor materialDiffuse = 43;
if (cached_has_bits & 0x02000000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
43, _Internal::materialdiffuse(this), target, stream);
}
// required .KuplungApp.MaterialColor materialSpecular = 44;
if (cached_has_bits & 0x04000000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
44, _Internal::materialspecular(this), target, stream);
}
// required .KuplungApp.MaterialColor materialEmission = 45;
if (cached_has_bits & 0x08000000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
45, _Internal::materialemission(this), target, stream);
}
cached_has_bits = _has_bits_[1];
// required bool Setting_ParallaxMapping = 46;
if (cached_has_bits & 0x00001000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(46, this->_internal_setting_parallaxmapping(), target);
}
// required int32 Effect_GBlur_Mode = 47;
if (cached_has_bits & 0x00040000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(47, this->_internal_effect_gblur_mode(), target);
}
cached_has_bits = _has_bits_[0];
// required .KuplungApp.ObjectCoordinate Effect_GBlur_Radius = 48;
if (cached_has_bits & 0x10000000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
48, _Internal::effect_gblur_radius(this), target, stream);
}
// required .KuplungApp.ObjectCoordinate Effect_GBlur_Width = 49;
if (cached_has_bits & 0x20000000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
49, _Internal::effect_gblur_width(this), target, stream);
}
cached_has_bits = _has_bits_[1];
// required bool Effect_Bloom_doBloom = 50;
if (cached_has_bits & 0x00002000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(50, this->_internal_effect_bloom_dobloom(), target);
}
// required float Effect_Bloom_WeightA = 51;
if (cached_has_bits & 0x00080000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteFloatToArray(51, this->_internal_effect_bloom_weighta(), target);
}
// required float Effect_Bloom_WeightB = 52;
if (cached_has_bits & 0x00100000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteFloatToArray(52, this->_internal_effect_bloom_weightb(), target);
}
// required float Effect_Bloom_WeightC = 53;
if (cached_has_bits & 0x00200000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteFloatToArray(53, this->_internal_effect_bloom_weightc(), target);
}
// required float Effect_Bloom_WeightD = 54;
if (cached_has_bits & 0x00400000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteFloatToArray(54, this->_internal_effect_bloom_weightd(), target);
}
// required float Effect_Bloom_Vignette = 55;
if (cached_has_bits & 0x00800000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteFloatToArray(55, this->_internal_effect_bloom_vignette(), target);
}
// required float Effect_Bloom_VignetteAtt = 56;
if (cached_has_bits & 0x01000000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteFloatToArray(56, this->_internal_effect_bloom_vignetteatt(), target);
}
// required int32 Setting_LightingPass_DrawMode = 57;
if (cached_has_bits & 0x02000000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(57, this->_internal_setting_lightingpass_drawmode(), target);
}
cached_has_bits = _has_bits_[0];
// required .KuplungApp.Mesh meshObject = 58;
if (cached_has_bits & 0x40000000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
58, _Internal::meshobject(this), target, stream);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:KuplungApp.MeshModel)
return target;
}
size_t MeshModel::RequiredFieldsByteSizeFallback() const {
// @@protoc_insertion_point(required_fields_byte_size_fallback_start:KuplungApp.MeshModel)
size_t total_size = 0;
if (_internal_has_positionx()) {
// required .KuplungApp.ObjectCoordinate positionX = 9;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*positionx_);
}
if (_internal_has_positiony()) {
// required .KuplungApp.ObjectCoordinate positionY = 10;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*positiony_);
}
if (_internal_has_positionz()) {
// required .KuplungApp.ObjectCoordinate positionZ = 11;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*positionz_);
}
if (_internal_has_scalex()) {
// required .KuplungApp.ObjectCoordinate scaleX = 12;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*scalex_);
}
if (_internal_has_scaley()) {
// required .KuplungApp.ObjectCoordinate scaleY = 13;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*scaley_);
}
if (_internal_has_scalez()) {
// required .KuplungApp.ObjectCoordinate scaleZ = 14;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*scalez_);
}
if (_internal_has_rotatex()) {
// required .KuplungApp.ObjectCoordinate rotateX = 15;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*rotatex_);
}
if (_internal_has_rotatey()) {
// required .KuplungApp.ObjectCoordinate rotateY = 16;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*rotatey_);
}
if (_internal_has_rotatez()) {
// required .KuplungApp.ObjectCoordinate rotateZ = 17;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*rotatez_);
}
if (_internal_has_displacex()) {
// required .KuplungApp.ObjectCoordinate displaceX = 18;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*displacex_);
}
if (_internal_has_displacey()) {
// required .KuplungApp.ObjectCoordinate displaceY = 19;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*displacey_);
}
if (_internal_has_displacez()) {
// required .KuplungApp.ObjectCoordinate displaceZ = 20;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*displacez_);
}
if (_internal_has_setting_materialrefraction()) {
// required .KuplungApp.ObjectCoordinate Setting_MaterialRefraction = 21;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*setting_materialrefraction_);
}
if (_internal_has_setting_materialspecularexp()) {
// required .KuplungApp.ObjectCoordinate Setting_MaterialSpecularExp = 22;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*setting_materialspecularexp_);
}
if (_internal_has_solidlightskin_materialcolor()) {
// required .KuplungApp.Vec3 solidLightSkin_MaterialColor = 24;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*solidlightskin_materialcolor_);
}
if (_internal_has_solidlightskin_ambient()) {
// required .KuplungApp.Vec3 solidLightSkin_Ambient = 25;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*solidlightskin_ambient_);
}
if (_internal_has_solidlightskin_diffuse()) {
// required .KuplungApp.Vec3 solidLightSkin_Diffuse = 26;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*solidlightskin_diffuse_);
}
if (_internal_has_solidlightskin_specular()) {
// required .KuplungApp.Vec3 solidLightSkin_Specular = 27;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*solidlightskin_specular_);
}
if (_internal_has_setting_lightposition()) {
// required .KuplungApp.Vec3 Setting_LightPosition = 31;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*setting_lightposition_);
}
if (_internal_has_setting_lightdirection()) {
// required .KuplungApp.Vec3 Setting_LightDirection = 32;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*setting_lightdirection_);
}
if (_internal_has_setting_lightambient()) {
// required .KuplungApp.Vec3 Setting_LightAmbient = 33;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*setting_lightambient_);
}
if (_internal_has_setting_lightdiffuse()) {
// required .KuplungApp.Vec3 Setting_LightDiffuse = 34;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*setting_lightdiffuse_);
}
if (_internal_has_setting_lightspecular()) {
// required .KuplungApp.Vec3 Setting_LightSpecular = 35;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*setting_lightspecular_);
}
if (_internal_has_displacementheightscale()) {
// required .KuplungApp.ObjectCoordinate displacementHeightScale = 40;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*displacementheightscale_);
}
if (_internal_has_materialambient()) {
// required .KuplungApp.MaterialColor materialAmbient = 42;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*materialambient_);
}
if (_internal_has_materialdiffuse()) {
// required .KuplungApp.MaterialColor materialDiffuse = 43;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*materialdiffuse_);
}
if (_internal_has_materialspecular()) {
// required .KuplungApp.MaterialColor materialSpecular = 44;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*materialspecular_);
}
if (_internal_has_materialemission()) {
// required .KuplungApp.MaterialColor materialEmission = 45;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*materialemission_);
}
if (_internal_has_effect_gblur_radius()) {
// required .KuplungApp.ObjectCoordinate Effect_GBlur_Radius = 48;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*effect_gblur_radius_);
}
if (_internal_has_effect_gblur_width()) {
// required .KuplungApp.ObjectCoordinate Effect_GBlur_Width = 49;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*effect_gblur_width_);
}
if (_internal_has_meshobject()) {
// required .KuplungApp.Mesh meshObject = 58;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*meshobject_);
}
if (_internal_has_modelid()) {
// required int32 ModelID = 1;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size(
this->_internal_modelid());
}
if (_internal_has_settings_deferredrender()) {
// required bool Settings_DeferredRender = 2;
total_size += 1 + 1;
}
if (_internal_has_setting_celshading()) {
// required bool Setting_CelShading = 3;
total_size += 1 + 1;
}
if (_internal_has_setting_wireframe()) {
// required bool Setting_Wireframe = 4;
total_size += 1 + 1;
}
if (_internal_has_setting_usetessellation()) {
// required bool Setting_UseTessellation = 5;
total_size += 1 + 1;
}
if (_internal_has_setting_alpha()) {
// required float Setting_Alpha = 7;
total_size += 1 + 4;
}
if (_internal_has_setting_tessellationsubdivision()) {
// required int32 Setting_TessellationSubdivision = 8;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size(
this->_internal_setting_tessellationsubdivision());
}
if (_internal_has_setting_modelviewskin()) {
// required int32 Setting_ModelViewSkin = 23;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size(
this->_internal_setting_modelviewskin());
}
if (_internal_has_solidlightskin_ambient_strength()) {
// required float solidLightSkin_Ambient_Strength = 28;
total_size += 2 + 4;
}
if (_internal_has_solidlightskin_diffuse_strength()) {
// required float solidLightSkin_Diffuse_Strength = 29;
total_size += 2 + 4;
}
if (_internal_has_solidlightskin_specular_strength()) {
// required float solidLightSkin_Specular_Strength = 30;
total_size += 2 + 4;
}
if (_internal_has_setting_usecullface()) {
// required bool Setting_UseCullFace = 6;
total_size += 1 + 1;
}
if (_internal_has_showmaterialeditor()) {
// required bool showMaterialEditor = 41;
total_size += 2 + 1;
}
if (_internal_has_setting_parallaxmapping()) {
// required bool Setting_ParallaxMapping = 46;
total_size += 2 + 1;
}
if (_internal_has_effect_bloom_dobloom()) {
// required bool Effect_Bloom_doBloom = 50;
total_size += 2 + 1;
}
if (_internal_has_setting_lightstrengthambient()) {
// required float Setting_LightStrengthAmbient = 36;
total_size += 2 + 4;
}
if (_internal_has_setting_lightstrengthdiffuse()) {
// required float Setting_LightStrengthDiffuse = 37;
total_size += 2 + 4;
}
if (_internal_has_setting_lightstrengthspecular()) {
// required float Setting_LightStrengthSpecular = 38;
total_size += 2 + 4;
}
if (_internal_has_materialilluminationmodel()) {
// required int32 materialIlluminationModel = 39;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size(
this->_internal_materialilluminationmodel());
}
if (_internal_has_effect_gblur_mode()) {
// required int32 Effect_GBlur_Mode = 47;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size(
this->_internal_effect_gblur_mode());
}
if (_internal_has_effect_bloom_weighta()) {
// required float Effect_Bloom_WeightA = 51;
total_size += 2 + 4;
}
if (_internal_has_effect_bloom_weightb()) {
// required float Effect_Bloom_WeightB = 52;
total_size += 2 + 4;
}
if (_internal_has_effect_bloom_weightc()) {
// required float Effect_Bloom_WeightC = 53;
total_size += 2 + 4;
}
if (_internal_has_effect_bloom_weightd()) {
// required float Effect_Bloom_WeightD = 54;
total_size += 2 + 4;
}
if (_internal_has_effect_bloom_vignette()) {
// required float Effect_Bloom_Vignette = 55;
total_size += 2 + 4;
}
if (_internal_has_effect_bloom_vignetteatt()) {
// required float Effect_Bloom_VignetteAtt = 56;
total_size += 2 + 4;
}
if (_internal_has_setting_lightingpass_drawmode()) {
// required int32 Setting_LightingPass_DrawMode = 57;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size(
this->_internal_setting_lightingpass_drawmode());
}
return total_size;
}
size_t MeshModel::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:KuplungApp.MeshModel)
size_t total_size = 0;
if ((((_has_bits_[0] & 0xffffffff) ^ 0xffffffff)
| ((_has_bits_[1] & 0x03ffffff) ^ 0x03ffffff)) == 0) { // All required fields are present.
// required .KuplungApp.ObjectCoordinate positionX = 9;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*positionx_);
// required .KuplungApp.ObjectCoordinate positionY = 10;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*positiony_);
// required .KuplungApp.ObjectCoordinate positionZ = 11;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*positionz_);
// required .KuplungApp.ObjectCoordinate scaleX = 12;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*scalex_);
// required .KuplungApp.ObjectCoordinate scaleY = 13;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*scaley_);
// required .KuplungApp.ObjectCoordinate scaleZ = 14;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*scalez_);
// required .KuplungApp.ObjectCoordinate rotateX = 15;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*rotatex_);
// required .KuplungApp.ObjectCoordinate rotateY = 16;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*rotatey_);
// required .KuplungApp.ObjectCoordinate rotateZ = 17;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*rotatez_);
// required .KuplungApp.ObjectCoordinate displaceX = 18;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*displacex_);
// required .KuplungApp.ObjectCoordinate displaceY = 19;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*displacey_);
// required .KuplungApp.ObjectCoordinate displaceZ = 20;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*displacez_);
// required .KuplungApp.ObjectCoordinate Setting_MaterialRefraction = 21;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*setting_materialrefraction_);
// required .KuplungApp.ObjectCoordinate Setting_MaterialSpecularExp = 22;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*setting_materialspecularexp_);
// required .KuplungApp.Vec3 solidLightSkin_MaterialColor = 24;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*solidlightskin_materialcolor_);
// required .KuplungApp.Vec3 solidLightSkin_Ambient = 25;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*solidlightskin_ambient_);
// required .KuplungApp.Vec3 solidLightSkin_Diffuse = 26;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*solidlightskin_diffuse_);
// required .KuplungApp.Vec3 solidLightSkin_Specular = 27;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*solidlightskin_specular_);
// required .KuplungApp.Vec3 Setting_LightPosition = 31;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*setting_lightposition_);
// required .KuplungApp.Vec3 Setting_LightDirection = 32;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*setting_lightdirection_);
// required .KuplungApp.Vec3 Setting_LightAmbient = 33;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*setting_lightambient_);
// required .KuplungApp.Vec3 Setting_LightDiffuse = 34;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*setting_lightdiffuse_);
// required .KuplungApp.Vec3 Setting_LightSpecular = 35;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*setting_lightspecular_);
// required .KuplungApp.ObjectCoordinate displacementHeightScale = 40;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*displacementheightscale_);
// required .KuplungApp.MaterialColor materialAmbient = 42;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*materialambient_);
// required .KuplungApp.MaterialColor materialDiffuse = 43;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*materialdiffuse_);
// required .KuplungApp.MaterialColor materialSpecular = 44;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*materialspecular_);
// required .KuplungApp.MaterialColor materialEmission = 45;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*materialemission_);
// required .KuplungApp.ObjectCoordinate Effect_GBlur_Radius = 48;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*effect_gblur_radius_);
// required .KuplungApp.ObjectCoordinate Effect_GBlur_Width = 49;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*effect_gblur_width_);
// required .KuplungApp.Mesh meshObject = 58;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*meshobject_);
// required int32 ModelID = 1;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size(
this->_internal_modelid());
// required bool Settings_DeferredRender = 2;
total_size += 1 + 1;
// required bool Setting_CelShading = 3;
total_size += 1 + 1;
// required bool Setting_Wireframe = 4;
total_size += 1 + 1;
// required bool Setting_UseTessellation = 5;
total_size += 1 + 1;
// required float Setting_Alpha = 7;
total_size += 1 + 4;
// required int32 Setting_TessellationSubdivision = 8;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size(
this->_internal_setting_tessellationsubdivision());
// required int32 Setting_ModelViewSkin = 23;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size(
this->_internal_setting_modelviewskin());
// required float solidLightSkin_Ambient_Strength = 28;
total_size += 2 + 4;
// required float solidLightSkin_Diffuse_Strength = 29;
total_size += 2 + 4;
// required float solidLightSkin_Specular_Strength = 30;
total_size += 2 + 4;
// required bool Setting_UseCullFace = 6;
total_size += 1 + 1;
// required bool showMaterialEditor = 41;
total_size += 2 + 1;
// required bool Setting_ParallaxMapping = 46;
total_size += 2 + 1;
// required bool Effect_Bloom_doBloom = 50;
total_size += 2 + 1;
// required float Setting_LightStrengthAmbient = 36;
total_size += 2 + 4;
// required float Setting_LightStrengthDiffuse = 37;
total_size += 2 + 4;
// required float Setting_LightStrengthSpecular = 38;
total_size += 2 + 4;
// required int32 materialIlluminationModel = 39;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size(
this->_internal_materialilluminationmodel());
// required int32 Effect_GBlur_Mode = 47;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size(
this->_internal_effect_gblur_mode());
// required float Effect_Bloom_WeightA = 51;
total_size += 2 + 4;
// required float Effect_Bloom_WeightB = 52;
total_size += 2 + 4;
// required float Effect_Bloom_WeightC = 53;
total_size += 2 + 4;
// required float Effect_Bloom_WeightD = 54;
total_size += 2 + 4;
// required float Effect_Bloom_Vignette = 55;
total_size += 2 + 4;
// required float Effect_Bloom_VignetteAtt = 56;
total_size += 2 + 4;
// required int32 Setting_LightingPass_DrawMode = 57;
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size(
this->_internal_setting_lightingpass_drawmode());
} else {
total_size += RequiredFieldsByteSizeFallback();
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize(
_internal_metadata_, total_size, &_cached_size_);
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void MeshModel::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:KuplungApp.MeshModel)
GOOGLE_DCHECK_NE(&from, this);
const MeshModel* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<MeshModel>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:KuplungApp.MeshModel)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:KuplungApp.MeshModel)
MergeFrom(*source);
}
}
void MeshModel::MergeFrom(const MeshModel& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:KuplungApp.MeshModel)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
if (cached_has_bits & 0x000000ffu) {
if (cached_has_bits & 0x00000001u) {
_internal_mutable_positionx()->::KuplungApp::ObjectCoordinate::MergeFrom(from._internal_positionx());
}
if (cached_has_bits & 0x00000002u) {
_internal_mutable_positiony()->::KuplungApp::ObjectCoordinate::MergeFrom(from._internal_positiony());
}
if (cached_has_bits & 0x00000004u) {
_internal_mutable_positionz()->::KuplungApp::ObjectCoordinate::MergeFrom(from._internal_positionz());
}
if (cached_has_bits & 0x00000008u) {
_internal_mutable_scalex()->::KuplungApp::ObjectCoordinate::MergeFrom(from._internal_scalex());
}
if (cached_has_bits & 0x00000010u) {
_internal_mutable_scaley()->::KuplungApp::ObjectCoordinate::MergeFrom(from._internal_scaley());
}
if (cached_has_bits & 0x00000020u) {
_internal_mutable_scalez()->::KuplungApp::ObjectCoordinate::MergeFrom(from._internal_scalez());
}
if (cached_has_bits & 0x00000040u) {
_internal_mutable_rotatex()->::KuplungApp::ObjectCoordinate::MergeFrom(from._internal_rotatex());
}
if (cached_has_bits & 0x00000080u) {
_internal_mutable_rotatey()->::KuplungApp::ObjectCoordinate::MergeFrom(from._internal_rotatey());
}
}
if (cached_has_bits & 0x0000ff00u) {
if (cached_has_bits & 0x00000100u) {
_internal_mutable_rotatez()->::KuplungApp::ObjectCoordinate::MergeFrom(from._internal_rotatez());
}
if (cached_has_bits & 0x00000200u) {
_internal_mutable_displacex()->::KuplungApp::ObjectCoordinate::MergeFrom(from._internal_displacex());
}
if (cached_has_bits & 0x00000400u) {
_internal_mutable_displacey()->::KuplungApp::ObjectCoordinate::MergeFrom(from._internal_displacey());
}
if (cached_has_bits & 0x00000800u) {
_internal_mutable_displacez()->::KuplungApp::ObjectCoordinate::MergeFrom(from._internal_displacez());
}
if (cached_has_bits & 0x00001000u) {
_internal_mutable_setting_materialrefraction()->::KuplungApp::ObjectCoordinate::MergeFrom(from._internal_setting_materialrefraction());
}
if (cached_has_bits & 0x00002000u) {
_internal_mutable_setting_materialspecularexp()->::KuplungApp::ObjectCoordinate::MergeFrom(from._internal_setting_materialspecularexp());
}
if (cached_has_bits & 0x00004000u) {
_internal_mutable_solidlightskin_materialcolor()->::KuplungApp::Vec3::MergeFrom(from._internal_solidlightskin_materialcolor());
}
if (cached_has_bits & 0x00008000u) {
_internal_mutable_solidlightskin_ambient()->::KuplungApp::Vec3::MergeFrom(from._internal_solidlightskin_ambient());
}
}
if (cached_has_bits & 0x00ff0000u) {
if (cached_has_bits & 0x00010000u) {
_internal_mutable_solidlightskin_diffuse()->::KuplungApp::Vec3::MergeFrom(from._internal_solidlightskin_diffuse());
}
if (cached_has_bits & 0x00020000u) {
_internal_mutable_solidlightskin_specular()->::KuplungApp::Vec3::MergeFrom(from._internal_solidlightskin_specular());
}
if (cached_has_bits & 0x00040000u) {
_internal_mutable_setting_lightposition()->::KuplungApp::Vec3::MergeFrom(from._internal_setting_lightposition());
}
if (cached_has_bits & 0x00080000u) {
_internal_mutable_setting_lightdirection()->::KuplungApp::Vec3::MergeFrom(from._internal_setting_lightdirection());
}
if (cached_has_bits & 0x00100000u) {
_internal_mutable_setting_lightambient()->::KuplungApp::Vec3::MergeFrom(from._internal_setting_lightambient());
}
if (cached_has_bits & 0x00200000u) {
_internal_mutable_setting_lightdiffuse()->::KuplungApp::Vec3::MergeFrom(from._internal_setting_lightdiffuse());
}
if (cached_has_bits & 0x00400000u) {
_internal_mutable_setting_lightspecular()->::KuplungApp::Vec3::MergeFrom(from._internal_setting_lightspecular());
}
if (cached_has_bits & 0x00800000u) {
_internal_mutable_displacementheightscale()->::KuplungApp::ObjectCoordinate::MergeFrom(from._internal_displacementheightscale());
}
}
if (cached_has_bits & 0xff000000u) {
if (cached_has_bits & 0x01000000u) {
_internal_mutable_materialambient()->::KuplungApp::MaterialColor::MergeFrom(from._internal_materialambient());
}
if (cached_has_bits & 0x02000000u) {
_internal_mutable_materialdiffuse()->::KuplungApp::MaterialColor::MergeFrom(from._internal_materialdiffuse());
}
if (cached_has_bits & 0x04000000u) {
_internal_mutable_materialspecular()->::KuplungApp::MaterialColor::MergeFrom(from._internal_materialspecular());
}
if (cached_has_bits & 0x08000000u) {
_internal_mutable_materialemission()->::KuplungApp::MaterialColor::MergeFrom(from._internal_materialemission());
}
if (cached_has_bits & 0x10000000u) {
_internal_mutable_effect_gblur_radius()->::KuplungApp::ObjectCoordinate::MergeFrom(from._internal_effect_gblur_radius());
}
if (cached_has_bits & 0x20000000u) {
_internal_mutable_effect_gblur_width()->::KuplungApp::ObjectCoordinate::MergeFrom(from._internal_effect_gblur_width());
}
if (cached_has_bits & 0x40000000u) {
_internal_mutable_meshobject()->::KuplungApp::Mesh::MergeFrom(from._internal_meshobject());
}
if (cached_has_bits & 0x80000000u) {
modelid_ = from.modelid_;
}
_has_bits_[0] |= cached_has_bits;
}
cached_has_bits = from._has_bits_[1];
if (cached_has_bits & 0x000000ffu) {
if (cached_has_bits & 0x00000001u) {
settings_deferredrender_ = from.settings_deferredrender_;
}
if (cached_has_bits & 0x00000002u) {
setting_celshading_ = from.setting_celshading_;
}
if (cached_has_bits & 0x00000004u) {
setting_wireframe_ = from.setting_wireframe_;
}
if (cached_has_bits & 0x00000008u) {
setting_usetessellation_ = from.setting_usetessellation_;
}
if (cached_has_bits & 0x00000010u) {
setting_alpha_ = from.setting_alpha_;
}
if (cached_has_bits & 0x00000020u) {
setting_tessellationsubdivision_ = from.setting_tessellationsubdivision_;
}
if (cached_has_bits & 0x00000040u) {
setting_modelviewskin_ = from.setting_modelviewskin_;
}
if (cached_has_bits & 0x00000080u) {
solidlightskin_ambient_strength_ = from.solidlightskin_ambient_strength_;
}
_has_bits_[1] |= cached_has_bits;
}
if (cached_has_bits & 0x0000ff00u) {
if (cached_has_bits & 0x00000100u) {
solidlightskin_diffuse_strength_ = from.solidlightskin_diffuse_strength_;
}
if (cached_has_bits & 0x00000200u) {
solidlightskin_specular_strength_ = from.solidlightskin_specular_strength_;
}
if (cached_has_bits & 0x00000400u) {
setting_usecullface_ = from.setting_usecullface_;
}
if (cached_has_bits & 0x00000800u) {
showmaterialeditor_ = from.showmaterialeditor_;
}
if (cached_has_bits & 0x00001000u) {
setting_parallaxmapping_ = from.setting_parallaxmapping_;
}
if (cached_has_bits & 0x00002000u) {
effect_bloom_dobloom_ = from.effect_bloom_dobloom_;
}
if (cached_has_bits & 0x00004000u) {
setting_lightstrengthambient_ = from.setting_lightstrengthambient_;
}
if (cached_has_bits & 0x00008000u) {
setting_lightstrengthdiffuse_ = from.setting_lightstrengthdiffuse_;
}
_has_bits_[1] |= cached_has_bits;
}
if (cached_has_bits & 0x00ff0000u) {
if (cached_has_bits & 0x00010000u) {
setting_lightstrengthspecular_ = from.setting_lightstrengthspecular_;
}
if (cached_has_bits & 0x00020000u) {
materialilluminationmodel_ = from.materialilluminationmodel_;
}
if (cached_has_bits & 0x00040000u) {
effect_gblur_mode_ = from.effect_gblur_mode_;
}
if (cached_has_bits & 0x00080000u) {
effect_bloom_weighta_ = from.effect_bloom_weighta_;
}
if (cached_has_bits & 0x00100000u) {
effect_bloom_weightb_ = from.effect_bloom_weightb_;
}
if (cached_has_bits & 0x00200000u) {
effect_bloom_weightc_ = from.effect_bloom_weightc_;
}
if (cached_has_bits & 0x00400000u) {
effect_bloom_weightd_ = from.effect_bloom_weightd_;
}
if (cached_has_bits & 0x00800000u) {
effect_bloom_vignette_ = from.effect_bloom_vignette_;
}
_has_bits_[1] |= cached_has_bits;
}
if (cached_has_bits & 0x03000000u) {
if (cached_has_bits & 0x01000000u) {
effect_bloom_vignetteatt_ = from.effect_bloom_vignetteatt_;
}
if (cached_has_bits & 0x02000000u) {
setting_lightingpass_drawmode_ = from.setting_lightingpass_drawmode_;
}
_has_bits_[1] |= cached_has_bits;
}
}
void MeshModel::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:KuplungApp.MeshModel)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void MeshModel::CopyFrom(const MeshModel& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:KuplungApp.MeshModel)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool MeshModel::IsInitialized() const {
if ((_has_bits_[0] & 0xffffffff) != 0xffffffff) return false;
if ((_has_bits_[1] & 0x03ffffff) != 0x03ffffff) return false;
if (_internal_has_positionx()) {
if (!positionx_->IsInitialized()) return false;
}
if (_internal_has_positiony()) {
if (!positiony_->IsInitialized()) return false;
}
if (_internal_has_positionz()) {
if (!positionz_->IsInitialized()) return false;
}
if (_internal_has_scalex()) {
if (!scalex_->IsInitialized()) return false;
}
if (_internal_has_scaley()) {
if (!scaley_->IsInitialized()) return false;
}
if (_internal_has_scalez()) {
if (!scalez_->IsInitialized()) return false;
}
if (_internal_has_rotatex()) {
if (!rotatex_->IsInitialized()) return false;
}
if (_internal_has_rotatey()) {
if (!rotatey_->IsInitialized()) return false;
}
if (_internal_has_rotatez()) {
if (!rotatez_->IsInitialized()) return false;
}
if (_internal_has_displacex()) {
if (!displacex_->IsInitialized()) return false;
}
if (_internal_has_displacey()) {
if (!displacey_->IsInitialized()) return false;
}
if (_internal_has_displacez()) {
if (!displacez_->IsInitialized()) return false;
}
if (_internal_has_setting_materialrefraction()) {
if (!setting_materialrefraction_->IsInitialized()) return false;
}
if (_internal_has_setting_materialspecularexp()) {
if (!setting_materialspecularexp_->IsInitialized()) return false;
}
if (_internal_has_solidlightskin_materialcolor()) {
if (!solidlightskin_materialcolor_->IsInitialized()) return false;
}
if (_internal_has_solidlightskin_ambient()) {
if (!solidlightskin_ambient_->IsInitialized()) return false;
}
if (_internal_has_solidlightskin_diffuse()) {
if (!solidlightskin_diffuse_->IsInitialized()) return false;
}
if (_internal_has_solidlightskin_specular()) {
if (!solidlightskin_specular_->IsInitialized()) return false;
}
if (_internal_has_setting_lightposition()) {
if (!setting_lightposition_->IsInitialized()) return false;
}
if (_internal_has_setting_lightdirection()) {
if (!setting_lightdirection_->IsInitialized()) return false;
}
if (_internal_has_setting_lightambient()) {
if (!setting_lightambient_->IsInitialized()) return false;
}
if (_internal_has_setting_lightdiffuse()) {
if (!setting_lightdiffuse_->IsInitialized()) return false;
}
if (_internal_has_setting_lightspecular()) {
if (!setting_lightspecular_->IsInitialized()) return false;
}
if (_internal_has_displacementheightscale()) {
if (!displacementheightscale_->IsInitialized()) return false;
}
if (_internal_has_materialambient()) {
if (!materialambient_->IsInitialized()) return false;
}
if (_internal_has_materialdiffuse()) {
if (!materialdiffuse_->IsInitialized()) return false;
}
if (_internal_has_materialspecular()) {
if (!materialspecular_->IsInitialized()) return false;
}
if (_internal_has_materialemission()) {
if (!materialemission_->IsInitialized()) return false;
}
if (_internal_has_effect_gblur_radius()) {
if (!effect_gblur_radius_->IsInitialized()) return false;
}
if (_internal_has_effect_gblur_width()) {
if (!effect_gblur_width_->IsInitialized()) return false;
}
if (_internal_has_meshobject()) {
if (!meshobject_->IsInitialized()) return false;
}
return true;
}
void MeshModel::InternalSwap(MeshModel* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
swap(_has_bits_[1], other->_has_bits_[1]);
swap(positionx_, other->positionx_);
swap(positiony_, other->positiony_);
swap(positionz_, other->positionz_);
swap(scalex_, other->scalex_);
swap(scaley_, other->scaley_);
swap(scalez_, other->scalez_);
swap(rotatex_, other->rotatex_);
swap(rotatey_, other->rotatey_);
swap(rotatez_, other->rotatez_);
swap(displacex_, other->displacex_);
swap(displacey_, other->displacey_);
swap(displacez_, other->displacez_);
swap(setting_materialrefraction_, other->setting_materialrefraction_);
swap(setting_materialspecularexp_, other->setting_materialspecularexp_);
swap(solidlightskin_materialcolor_, other->solidlightskin_materialcolor_);
swap(solidlightskin_ambient_, other->solidlightskin_ambient_);
swap(solidlightskin_diffuse_, other->solidlightskin_diffuse_);
swap(solidlightskin_specular_, other->solidlightskin_specular_);
swap(setting_lightposition_, other->setting_lightposition_);
swap(setting_lightdirection_, other->setting_lightdirection_);
swap(setting_lightambient_, other->setting_lightambient_);
swap(setting_lightdiffuse_, other->setting_lightdiffuse_);
swap(setting_lightspecular_, other->setting_lightspecular_);
swap(displacementheightscale_, other->displacementheightscale_);
swap(materialambient_, other->materialambient_);
swap(materialdiffuse_, other->materialdiffuse_);
swap(materialspecular_, other->materialspecular_);
swap(materialemission_, other->materialemission_);
swap(effect_gblur_radius_, other->effect_gblur_radius_);
swap(effect_gblur_width_, other->effect_gblur_width_);
swap(meshobject_, other->meshobject_);
swap(modelid_, other->modelid_);
swap(settings_deferredrender_, other->settings_deferredrender_);
swap(setting_celshading_, other->setting_celshading_);
swap(setting_wireframe_, other->setting_wireframe_);
swap(setting_usetessellation_, other->setting_usetessellation_);
swap(setting_alpha_, other->setting_alpha_);
swap(setting_tessellationsubdivision_, other->setting_tessellationsubdivision_);
swap(setting_modelviewskin_, other->setting_modelviewskin_);
swap(solidlightskin_ambient_strength_, other->solidlightskin_ambient_strength_);
swap(solidlightskin_diffuse_strength_, other->solidlightskin_diffuse_strength_);
swap(solidlightskin_specular_strength_, other->solidlightskin_specular_strength_);
swap(setting_usecullface_, other->setting_usecullface_);
swap(showmaterialeditor_, other->showmaterialeditor_);
swap(setting_parallaxmapping_, other->setting_parallaxmapping_);
swap(effect_bloom_dobloom_, other->effect_bloom_dobloom_);
swap(setting_lightstrengthambient_, other->setting_lightstrengthambient_);
swap(setting_lightstrengthdiffuse_, other->setting_lightstrengthdiffuse_);
swap(setting_lightstrengthspecular_, other->setting_lightstrengthspecular_);
swap(materialilluminationmodel_, other->materialilluminationmodel_);
swap(effect_gblur_mode_, other->effect_gblur_mode_);
swap(effect_bloom_weighta_, other->effect_bloom_weighta_);
swap(effect_bloom_weightb_, other->effect_bloom_weightb_);
swap(effect_bloom_weightc_, other->effect_bloom_weightc_);
swap(effect_bloom_weightd_, other->effect_bloom_weightd_);
swap(effect_bloom_vignette_, other->effect_bloom_vignette_);
swap(effect_bloom_vignetteatt_, other->effect_bloom_vignetteatt_);
swap(setting_lightingpass_drawmode_, other->setting_lightingpass_drawmode_);
}
::PROTOBUF_NAMESPACE_ID::Metadata MeshModel::GetMetadata() const {
return GetMetadataStatic();
}
// @@protoc_insertion_point(namespace_scope)
} // namespace KuplungApp
PROTOBUF_NAMESPACE_OPEN
template<> PROTOBUF_NOINLINE ::KuplungApp::Scene* Arena::CreateMaybeMessage< ::KuplungApp::Scene >(Arena* arena) {
return Arena::CreateInternal< ::KuplungApp::Scene >(arena);
}
template<> PROTOBUF_NOINLINE ::KuplungApp::MeshModel* Arena::CreateMaybeMessage< ::KuplungApp::MeshModel >(Arena* arena) {
return Arena::CreateInternal< ::KuplungApp::MeshModel >(arena);
}
PROTOBUF_NAMESPACE_CLOSE
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
| 40.639607 | 160 | 0.723006 | [
"mesh"
] |
a031a87f11ba4a9e949d3b45f19a54de0b250abf | 10,291 | cpp | C++ | Source/Core/Visualization/Filter/LineIntegralConvolution.cpp | X1aoyueyue/KVS | ad47d62bef4fdd9ddd3412a26ee6557b63f0543b | [
"BSD-3-Clause"
] | 42 | 2015-07-24T23:05:07.000Z | 2022-03-16T01:31:04.000Z | Source/Core/Visualization/Filter/LineIntegralConvolution.cpp | X1aoyueyue/KVS | ad47d62bef4fdd9ddd3412a26ee6557b63f0543b | [
"BSD-3-Clause"
] | 4 | 2015-03-17T05:42:49.000Z | 2020-08-09T15:21:45.000Z | Source/Core/Visualization/Filter/LineIntegralConvolution.cpp | X1aoyueyue/KVS | ad47d62bef4fdd9ddd3412a26ee6557b63f0543b | [
"BSD-3-Clause"
] | 29 | 2015-01-03T05:56:32.000Z | 2021-10-05T15:28:33.000Z | /*****************************************************************************/
/**
* @file LineIntegralConvolution.cpp
* @author Naohisa Sakamoto
*/
/*****************************************************************************/
#include "LineIntegralConvolution.h"
#include <kvs/DebugNew>
#include <kvs/MersenneTwister>
#include <kvs/Vector3>
namespace kvs
{
/*===========================================================================*/
/**
* @brief Constructs a new LineIntegralConvolution class.
*/
/*===========================================================================*/
LineIntegralConvolution::LineIntegralConvolution():
m_length( 0.0 ),
m_noise( NULL )
{
}
/*===========================================================================*/
/**
* @brief Constructs a new LineIntegralConvolution class.
* @param volume [in] pointer to the input volume data
*/
/*===========================================================================*/
LineIntegralConvolution::LineIntegralConvolution( const kvs::StructuredVolumeObject* volume ):
m_noise( NULL )
{
const kvs::Vector3ui& r = volume->resolution();
m_length = kvs::Math::Max<double>( r.x(), r.y(), r.z() ) * 0.1;
this->exec( volume );
}
/*===========================================================================*/
/**
* @brief Constructs a new LineIntegralConvolution class.
* @param volume [in] pointer to the input volume data
* @param length [in] strem length
*/
/*===========================================================================*/
LineIntegralConvolution::LineIntegralConvolution( const kvs::StructuredVolumeObject* volume, const double length ):
m_length( length ),
m_noise( NULL )
{
this->exec( volume );
}
/*===========================================================================*/
/**
* @brief Destructs the LineIntegralConvolution class.
*/
/*===========================================================================*/
LineIntegralConvolution::~LineIntegralConvolution()
{
if ( m_noise ){ delete m_noise; m_noise = NULL; }
}
/*===========================================================================*/
/**
* @brief Sets the stream length.
* @param length [in] stream length
*/
/*===========================================================================*/
void LineIntegralConvolution::setLength( const double length )
{
m_length = length;
}
/*===========================================================================*/
/**
* @brief Executes the filter process.
* @param volume [i] pointer to a uniform volume data
* @return pointer to the filtered structured volume object
*/
/*===========================================================================*/
LineIntegralConvolution::SuperClass* LineIntegralConvolution::exec( const kvs::ObjectBase* object )
{
if ( !object )
{
BaseClass::setSuccess( false );
kvsMessageError("Input object is NULL.");
return NULL;
}
const kvs::StructuredVolumeObject* volume = kvs::StructuredVolumeObject::DownCast( object );
if ( !volume )
{
BaseClass::setSuccess( false );
kvsMessageError("Input object is not supported.");
return NULL;
}
if ( volume->veclen() == 1 )
{
BaseClass::setSuccess( false );
kvsMessageError("Input object is not vector data.");
return NULL;
}
this->create_noise_volume( volume );
this->filtering( volume );
return this;
}
/*===========================================================================*/
/**
* @brief Filter the input volume.
* @param volume [in] pointer to the input structured volume object
*/
/*===========================================================================*/
void LineIntegralConvolution::filtering( const kvs::StructuredVolumeObject* volume )
{
// Set the min/max coordinates.
SuperClass::setMinMaxObjectCoords( volume->minObjectCoord(), volume->maxObjectCoord() );
SuperClass::setMinMaxExternalCoords( volume->minExternalCoord(), volume->maxExternalCoord() );
const std::type_info& type = volume->values().typeInfo()->type();
if( type == typeid(float) ) this->convolution<float>( volume );
else if( type == typeid(double) ) this->convolution<double>( volume );
else
{
BaseClass::setSuccess( false );
kvsMessageError("Input volume data type is not float/double.");
return;
}
}
/*===========================================================================*/
/**
* @brief Create a noise volume.
* @param volume [i] pointer to a uniform volume data
*/
/*===========================================================================*/
void LineIntegralConvolution::create_noise_volume( const kvs::StructuredVolumeObject* volume )
{
//kvs::StructuredVolumeObject::Values data;
kvs::ValueArray<kvs::UInt8> data( volume->numberOfNodes() );
kvs::UInt8* pdata = data.data();
// Random number generator. R = [0,1)
kvs::MersenneTwister R;
// Create a white noise volume.
for ( size_t i = 0; i < volume->numberOfNodes(); i++ )
{
*(pdata++) = static_cast<kvs::UInt8>( R() * 255.0 );
}
// Copy the white noise volume to m_noise.
m_noise = new kvs::StructuredVolumeObject();
m_noise->setVeclen( 1 );
m_noise->setValues( kvs::AnyValueArray( data ) );
m_noise->setGridType( Uniform );
m_noise->setResolution( volume->resolution() );
}
/*===========================================================================*/
/**
* @brief Convolution.
* @param volume [i] pointer to a uniform volume data
*/
/*===========================================================================*/
template <typename T>
void LineIntegralConvolution::convolution( const kvs::StructuredVolumeObject* volume )
{
kvs::Vector3<T> u; // vector of node
kvs::Vector3<T> p; // position of node
kvs::Vector3<T> travel_t; //
kvs::Vector3<T> entry_pos; //
const kvs::UInt8* noise_data = static_cast<const kvs::UInt8*>( m_noise->values().data() );
const T* src_data = static_cast<const T*>( volume->values().data() );
kvs::ValueArray<kvs::UInt8> dst_data( volume->numberOfNodes() );
const kvs::Vector3ui resol( volume->resolution() );
unsigned int counter = 0;
for( size_t k = 0; k < resol.z(); k++ )
{
for( size_t j = 0; j < resol.y(); j++ )
{
for( size_t i = 0; i < resol.x(); i++ )
{
int i_c = i;
int j_c = j;
int k_c = k;
T acc_length = T(0);
T acc_data = T(0);
unsigned int loc_c = counter;
for( int m = 1; m > -2; m -= 2 )
{
i_c = i;
j_c = j;
k_c = k;
entry_pos[0] = T( i + 0.5 );
entry_pos[1] = T( j + 0.5 );
entry_pos[2] = T( k + 0.5 );
loc_c = counter;
while( acc_length < m_length )
{
T t_min = 1.0e+10;
int l_min = -1;
int inc;
int scalar = noise_data[loc_c];
u = (T)m * kvs::Vector3<T>( src_data + 3 * loc_c );
p[0] = T( i_c );
p[1] = T( j_c );
p[2] = T( k_c );
for( int l = 0; l < 3; l++ )
{
if( kvs::Math::IsZero( u[l] ) )
{
travel_t[l] = T( 1.1e+10 );
}
else if( u[l] < T(0) )
{
travel_t[l] = ( p[l] - entry_pos[l] ) / u[l];
}
else
{
travel_t[l] = ( p[l] + 1 - entry_pos[l] ) / u[l];
}
if( travel_t[l] < t_min )
{
t_min = travel_t[l];
l_min = l;
}
}
if( l_min == -1 ) break;
entry_pos += u * t_min;
inc = u[l_min] < T(0) ? -1 : 1;
if( l_min == 0 )
{
loc_c += inc;
i_c += inc;
}
else if( l_min == 1 )
{
loc_c += inc * resol.x();
j_c += inc;
}
else if( l_min == 2 )
{
loc_c += inc * resol.x() * resol.y();
k_c += inc;
}
T length = t_min * static_cast<T>( u.length() );
/* For small length (close to 0.0) it enters in a infinite loop */
if( kvs::Math::IsZero( length ) ) length = T( 1.1e+10 );
if( acc_length < 1.1e-10 ) acc_length = T(0);
acc_data += length * scalar;
acc_length += length;
if( i_c < 0 || i_c >= static_cast<int>(resol.x()) ||
j_c < 0 || j_c >= static_cast<int>(resol.y()) ||
k_c < 0 || k_c >= static_cast<int>(resol.z()) ) break;
}
}
acc_data /= acc_length;
dst_data[counter] = (kvs::UInt8)( (int)(acc_data) % 256 );
counter++;
}
}
}
SuperClass::setGridType( volume->gridType() );
SuperClass::setVeclen( 1 );
SuperClass::setResolution( volume->resolution() );
SuperClass::setValues( kvs::AnyValueArray( dst_data ) );
SuperClass::setMinMaxValues( 0, 255 );
}
} // end of namespace kvs
| 33.851974 | 115 | 0.412302 | [
"object",
"vector"
] |
a0340d577e5a8fa387c945c281a862f4a18e2576 | 23,450 | cpp | C++ | inetsrv/msmq/src/mqsec/acssctrl/acsschck.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetsrv/msmq/src/mqsec/acssctrl/acsschck.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetsrv/msmq/src/mqsec/acssctrl/acsschck.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 1998 Microsoft Corporation
Module Name: acsschck.cpp
Abstract:
Code to checkk access permission.
Author:
Doron Juster (DoronJ) 27-Oct-1998
Revision History:
--*/
#include <stdh_sec.h>
#include "acssctrl.h"
#include "mqnames.h"
#include "acsschck.tmh"
static WCHAR *s_FN=L"acssctrl/acsschck";
#define OBJECT_TYPE_NAME_MAX_LENGTH 32
static
HRESULT
ReplaceSidWithSystemService(
IN OUT SECURITY_DESCRIPTOR *pNewSD,
IN SECURITY_DESCRIPTOR *pOldSD,
IN PSID pMachineSid,
IN PSID pSystemServiceSid,
OUT ACL **ppSysDacl,
OUT BOOL *pfReplaced
)
/*++
Routine Description:
Replace existing security descriptor DACL with DACL that machine$ sid ACE is replaced with
SystemService (LocalSystem or NetworkService) sid ACE.
If machine$ ACE was replaced, *pfReplaced will be set to TRUE.
Arguments:
pNewSD - new security descriptor to be updated.
pOldSD - previous security descriptor.
pMachineSid - machine$ sid.
pSystemServiceSid - SystemServiceSid. LocalSystem or NetworkService.
ppSysDacl - new DACL (with system ACE instead of machine$ ACE)
pfReplaced - set to TRUE if a machine$ ACE was indeed replaced. Otherwise, FALSE.
Returned Value:
MQ_OK, if successful, else error code.
--*/
{
ASSERT((g_pSystemSid != NULL) && IsValidSid(g_pSystemSid));
*pfReplaced = FALSE;
BOOL fReplaced = FALSE;
BOOL bPresent;
BOOL bDefaulted;
ACL *pOldAcl = NULL;
if(!GetSecurityDescriptorDacl(
pOldSD,
&bPresent,
&pOldAcl,
&bDefaulted
))
{
DWORD gle = GetLastError();
ASSERT(("GetSecurityDescriptorDacl failed", 0));
TrERROR(SECURITY, "GetSecurityDescriptorDacl failed, gle = %!winerr!", gle);
return HRESULT_FROM_WIN32(gle);
}
if (!pOldAcl || !bPresent)
{
//
// It's OK to have a security descriptor without a DACL.
//
return MQSec_OK;
}
else if (pOldAcl->AclRevision != ACL_REVISION)
{
//
// we expect to get a DACL with NT4 format.
//
ASSERT(pOldAcl->AclRevision == ACL_REVISION);
TrERROR(SECURITY, "Wrong DACL version %d", pOldAcl->AclRevision);
return MQSec_E_WRONG_DACL_VERSION;
}
//
// size of SYSTEM acl is not longer than original acl, as the
// length of system SID is shorter then machine account sid.
//
ASSERT(GetLengthSid(g_pSystemSid) <= GetLengthSid(pMachineSid));
DWORD dwAclSize = (pOldAcl)->AclSize;
*ppSysDacl = (PACL) new BYTE[dwAclSize];
if(!InitializeAcl(*ppSysDacl, dwAclSize, ACL_REVISION))
{
DWORD gle = GetLastError();
ASSERT(("InitializeAcl failed", 0));
TrERROR(SECURITY, "InitializeAcl failed, gle = %!winerr!", gle);
return HRESULT_FROM_WIN32(gle);
}
//
// Build the new DACL
//
DWORD dwNumberOfACEs = (DWORD) pOldAcl->AceCount;
for (DWORD i = 0 ; i < dwNumberOfACEs ; i++)
{
PSID pSidTmp;
ACCESS_ALLOWED_ACE *pAce;
if(!GetAce(pOldAcl, i, (LPVOID* )&(pAce)))
{
TrERROR(SECURITY, "Failed to get ACE (index=%lu) while replacing SID with System SID. %!winerr!", i, GetLastError());
return MQSec_E_SDCONVERT_GETACE;
}
//
// Get the ACE sid
//
if (EqualSid((PSID) &(pAce->SidStart), pMachineSid))
{
//
// Found MachineSid, replace it with SystemService sid.
//
pSidTmp = pSystemServiceSid;
fReplaced = TRUE;
}
else
{
pSidTmp = &(pAce->SidStart);
}
//
// Add ACE to DACL
//
if (pAce->Header.AceType == ACCESS_ALLOWED_ACE_TYPE)
{
if(!AddAccessAllowedAce(
*ppSysDacl,
ACL_REVISION,
pAce->Mask,
pSidTmp
))
{
DWORD gle = GetLastError();
ASSERT(("AddAccessAllowedAce failed", 0));
TrERROR(SECURITY, "AddAccessAllowedAce failed, gle = %!winerr!", gle);
return HRESULT_FROM_WIN32(gle);
}
}
else
{
ASSERT(pAce->Header.AceType == ACCESS_DENIED_ACE_TYPE);
if(!AddAccessDeniedAceEx(
*ppSysDacl,
ACL_REVISION,
0,
pAce->Mask,
pSidTmp
))
{
DWORD gle = GetLastError();
ASSERT(("AddAccessDeniedAceEx failed", 0));
TrERROR(SECURITY, "AddAccessDeniedAceEx failed, gle = %!winerr!", gle);
return HRESULT_FROM_WIN32(gle);
}
}
}
if (fReplaced)
{
//
// Set the new DACL with the replaced ACE (MachineSid was replaced with SystemSid)
//
if(!SetSecurityDescriptorDacl(
pNewSD,
TRUE, // dacl present
*ppSysDacl,
FALSE
))
{
DWORD gle = GetLastError();
ASSERT(("SetSecurityDescriptorDacl failed", 0));
TrERROR(SECURITY, "SetSecurityDescriptorDacl failed, gle = %!winerr!", gle);
return HRESULT_FROM_WIN32(gle);
}
}
*pfReplaced = fReplaced;
return MQ_OK;
}
//+---------------------------------------------------------
//
// LPCWSTR _GetAuditObjectTypeName(DWORD dwObjectType)
//
//+---------------------------------------------------------
static LPCWSTR _GetAuditObjectTypeName(DWORD dwObjectType)
{
switch (dwObjectType)
{
case MQDS_QUEUE:
return L"Queue";
case MQDS_MACHINE:
return L"msmqConfiguration";
case MQDS_CN:
return L"Foreign queue";
default:
ASSERT(0);
return NULL;
}
}
//+-----------------------------------
//
// BOOL MQSec_CanGenerateAudit()
//
//+-----------------------------------
inline BOOL operator==(const LUID& a, const LUID& b)
{
return ((a.LowPart == b.LowPart) && (a.HighPart == b.HighPart));
}
BOOL APIENTRY MQSec_CanGenerateAudit()
{
static BOOL s_bInitialized = FALSE;
static BOOL s_bCanGenerateAudits = FALSE ;
if (s_bInitialized)
{
return s_bCanGenerateAudits;
}
s_bInitialized = TRUE;
CAutoCloseHandle hProcessToken;
//
// Enable the SE_AUDIT privilege that allows the QM to write audits to
// the events log.
//
BOOL bRet = OpenProcessToken(
GetCurrentProcess(),
(TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES),
&hProcessToken
);
if (bRet)
{
HRESULT hr = SetSpecificPrivilegeInAccessToken(
hProcessToken,
SE_AUDIT_NAME,
TRUE
);
if (SUCCEEDED(hr))
{
s_bCanGenerateAudits = TRUE;
}
}
else
{
DWORD gle = GetLastError() ;
TrERROR(SECURITY, "MQSec_CanGenerateAudit() fail to open process token, err- %!winerr!", gle);
}
if (s_bCanGenerateAudits)
{
s_bCanGenerateAudits = FALSE;
LUID luidPrivilegeLUID;
if(!LookupPrivilegeValue(NULL, SE_AUDIT_NAME, &luidPrivilegeLUID))
{
DWORD gle = GetLastError();
TrERROR(SECURITY, "Failed to Lookup Privilege Value %ls, gle = %!winerr!", SE_AUDIT_NAME, gle);
return s_bCanGenerateAudits;
}
DWORD dwLen = 0;
GetTokenInformation(
hProcessToken,
TokenPrivileges,
NULL,
0,
&dwLen
);
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
{
DWORD gle = GetLastError();
TrERROR(SECURITY, "Failed to GetTokenInformation(TokenPrivileges), gle = %!winerr!", gle);
return s_bCanGenerateAudits;
}
AP<char> TokenPrivs_buff = new char[dwLen];
TOKEN_PRIVILEGES *TokenPrivs;
TokenPrivs = (TOKEN_PRIVILEGES *)(char *)TokenPrivs_buff;
if(!GetTokenInformation(
hProcessToken,
TokenPrivileges,
(PVOID)TokenPrivs,
dwLen,
&dwLen
))
{
DWORD gle = GetLastError();
TrERROR(SECURITY, "Failed to GetTokenInformation(TokenPrivileges), gle = %!winerr!", gle);
return s_bCanGenerateAudits;
}
for (DWORD i = 0; i < TokenPrivs->PrivilegeCount ; i++)
{
if (TokenPrivs->Privileges[i].Luid == luidPrivilegeLUID)
{
s_bCanGenerateAudits = (TokenPrivs->Privileges[i].Attributes & SE_PRIVILEGE_ENABLED) != 0;
TrTRACE(SECURITY, "Found %ls luid", SE_AUDIT_NAME);
break;
}
}
}
TrTRACE(SECURITY, "s_bCanGenerateAudits = %d", s_bCanGenerateAudits);
return s_bCanGenerateAudits;
}
DWORD
GetAccessToken(
OUT HANDLE *phAccessToken,
IN BOOL fImpersonate,
IN DWORD dwAccessType,
IN BOOL fThreadTokenOnly
)
/*++
Routine Description:
Get thread\process access token
Arguments:
phAccessToken - Access token.
fImpersonate - flag for impersonating the calling thread.
dwAccessType - Desired access.
fThreadTokenOnly - Get Thread token only.
Returned Value:
ERROR_SUCCESS, if successful, else error code.
--*/
{
P<CImpersonate> pImpersonate = NULL;
if (fImpersonate)
{
pImpersonate = new CImpersonate(TRUE, TRUE);
if (pImpersonate->GetImpersonationStatus() != 0)
{
TrERROR(SECURITY, "Failed to impersonate client");
return ERROR_CANNOT_IMPERSONATE;
}
}
if (!OpenThreadToken(
GetCurrentThread(),
dwAccessType,
TRUE, // OpenAsSelf, use process security context for doing access check.
phAccessToken
))
{
DWORD dwErr = GetLastError();
if (dwErr != ERROR_NO_TOKEN)
{
*phAccessToken = NULL; // To be on the safe side.
TrERROR(SECURITY, "Failed to get thread token, gle = %!winerr!", dwErr);
return dwErr;
}
if (fThreadTokenOnly)
{
//
// We're interested only in thread token (for doing client
// access check). If token not available then it's a failure.
//
*phAccessToken = NULL; // To be on the safe side.
TrERROR(SECURITY, "Failed to get thread token, gle = %!winerr!", dwErr);
return dwErr;
}
//
// The process has only one main thread. IN this case we should
// open the process token.
//
ASSERT(!fImpersonate);
if (!OpenProcessToken(
GetCurrentProcess(),
dwAccessType,
phAccessToken
))
{
dwErr = GetLastError();
*phAccessToken = NULL; // To be on the safe side.
TrERROR(SECURITY, "Failed to get process token, gle = %!winerr!", dwErr);
return dwErr;
}
}
return ERROR_SUCCESS;
}
static
HRESULT
_DoAccessCheck(
IN SECURITY_DESCRIPTOR *pSD,
IN DWORD dwObjectType,
IN LPCWSTR pwszObjectName,
IN DWORD dwDesiredAccess,
IN LPVOID pId,
IN HANDLE hAccessToken
)
/*++
Routine Description:
Perform access check and audit.
Arguments:
pSD - Security descriptor.
dwObjectType - Object type.
pwszObjectName - Object name.
dwDesiredAccess - Desired accessGet Thread token only.
pId - uniqe id.
hAccessToken - Access token
Returned Value:
MQ_OK if access was granted, else error code.
--*/
{
ASSERT(hAccessToken != NULL);
DWORD dwGrantedAccess = 0;
BOOL fAccessStatus = FALSE;
if (!MQSec_CanGenerateAudit() || !pwszObjectName)
{
char ps_buff[sizeof(PRIVILEGE_SET) +
((2 - ANYSIZE_ARRAY) * sizeof(LUID_AND_ATTRIBUTES))];
PPRIVILEGE_SET ps = (PPRIVILEGE_SET)ps_buff;
DWORD dwPrivilegeSetLength = sizeof(ps_buff);
if(!AccessCheck(
pSD,
hAccessToken,
dwDesiredAccess,
GetObjectGenericMapping(dwObjectType),
ps,
&dwPrivilegeSetLength,
&dwGrantedAccess,
&fAccessStatus
))
{
DWORD gle = GetLastError();
ASSERT(("AccessCheck failed", 0));
TrERROR(SECURITY, "AccessCheck failed, gle = %!winerr!", gle);
return MQ_ERROR_ACCESS_DENIED;
}
}
else
{
BOOL bAuditGenerated;
BOOL bCreate = FALSE;
switch (dwObjectType)
{
case MQDS_QUEUE:
case MQDS_CN:
bCreate = FALSE;
break;
case MQDS_MACHINE:
bCreate = (dwDesiredAccess & MQSEC_CREATE_QUEUE) != 0;
break;
default:
ASSERT(0);
break;
}
LPCWSTR pAuditSubsystemName = L"MSMQ";
if(!AccessCheckAndAuditAlarm(
pAuditSubsystemName,
pId,
const_cast<LPWSTR>(_GetAuditObjectTypeName(dwObjectType)),
const_cast<LPWSTR>(pwszObjectName),
pSD,
dwDesiredAccess,
GetObjectGenericMapping(dwObjectType),
bCreate,
&dwGrantedAccess,
&fAccessStatus,
&bAuditGenerated
))
{
DWORD gle = GetLastError();
ASSERT_BENIGN(("AccessCheckAndAuditAlarm failed", 0));
TrERROR(SECURITY, "AccessCheckAndAuditAlarm failed, gle = %!winerr!", gle);
return MQ_ERROR_ACCESS_DENIED;
}
if(!ObjectCloseAuditAlarm(pAuditSubsystemName, pId, bAuditGenerated))
{
//
// Don't return error here, just trace that generates an audit message in the event log failed.
//
DWORD gle = GetLastError();
ASSERT(("ObjectCloseAuditAlarm failed", 0));
TrERROR(SECURITY, "ObjectCloseAuditAlarm failed, gle = %!winerr!", gle);
}
}
if (fAccessStatus && AreAllAccessesGranted(dwGrantedAccess, dwDesiredAccess))
{
//
// Access granted.
//
TrTRACE(SECURITY, "Access is granted: ObjectType = %d, DesiredAccess = 0x%x, ObjectName = %ls", dwObjectType, dwDesiredAccess, pwszObjectName);
return MQSec_OK;
}
//
// Access is denied
//
if (GetLastError() == ERROR_PRIVILEGE_NOT_HELD)
{
TrERROR(SECURITY, "Privilage not held: ObjectType = %d, DesiredAccess = 0x%x, ObjectName = %ls", dwObjectType, dwDesiredAccess, pwszObjectName);
return MQ_ERROR_PRIVILEGE_NOT_HELD;
}
TrERROR(SECURITY, "Access is denied: ObjectType = %d, DesiredAccess = 0x%x, ObjectName = %ls", dwObjectType, dwDesiredAccess, pwszObjectName);
return MQ_ERROR_ACCESS_DENIED;
}
HRESULT
APIENTRY
MQSec_AccessCheck(
IN SECURITY_DESCRIPTOR *pSD,
IN DWORD dwObjectType,
IN LPCWSTR pwszObjectName,
IN DWORD dwDesiredAccess,
IN LPVOID pId,
IN BOOL fImpAsClient,
IN BOOL fImpersonate
)
/*++
Routine Description:
Perform access check for the runnig thread. The access token is
retreived from the thread token.
Arguments:
pSD - Security descriptor.
dwObjectType - Object type.
pwszObjectName - Object name.
dwDesiredAccess - Desired accessGet Thread token only.
pId - uniqe id.
fImpAsClient - Flag for how to impersonate, Rpc impersonation or ImpersonateSelf.
fImpersonate - Flag indicating if we need to impersonate the client.
Returned Value:
MQ_OK if access was granted, else error code.
--*/
{
//
// Bug 8567. AV due to NULL pSD.
// Let's log this. At present we have no idea why pSD is null.
// fix is below, when doing access check for service account.
//
if (pSD == NULL)
{
ASSERT(pSD);
TrERROR(SECURITY, "MQSec_AccessCheck() got NULL pSecurityDescriptor");
}
//
// Impersonate the client
//
P<CImpersonate> pImpersonate = NULL;
if (fImpersonate)
{
pImpersonate = new CImpersonate(fImpAsClient, TRUE);
if (pImpersonate->GetImpersonationStatus() != 0)
{
TrERROR(SECURITY, "Failed to impersonate client");
return MQ_ERROR_CANNOT_IMPERSONATE_CLIENT;
}
TrTRACE(SECURITY, "Performing AccessCheck for the current thread");
MQSec_TraceThreadTokenInfo();
}
//
// Get thread access token
//
CAutoCloseHandle hAccessToken = NULL;
DWORD rc = GetAccessToken(
&hAccessToken,
FALSE,
TOKEN_QUERY,
TRUE
);
if (rc != ERROR_SUCCESS)
{
//
// Return this error for backward compatibility.
//
TrERROR(SECURITY, "Failed to get access token, gle = %!winerr!", rc);
return MQ_ERROR_ACCESS_DENIED;
}
//
// Access Check
//
HRESULT hr = _DoAccessCheck(
pSD,
dwObjectType,
pwszObjectName,
dwDesiredAccess,
pId,
hAccessToken
);
PSID pSystemServiceSid = NULL;
if (FAILED(hr) &&
(pSD != NULL) &&
pImpersonate->IsImpersonatedAsSystemService(&pSystemServiceSid))
{
TrTRACE(SECURITY, "Thread is impersonating as system service %!sid!", pSystemServiceSid);
//
// In all ACEs with the machine account sid, replace sid with
// SYSTEM sid and try again. This is a workaround to problems in
// Widnows 2000 where rpc call from service to service may be
// interpreted as machine account sid or as SYSTEM sid. This depends
// on either it's local rpc or tcp/ip and on using Kerberos.
//
PSID pMachineSid = MQSec_GetLocalMachineSid(FALSE, NULL);
if (!pMachineSid)
{
//
// Machine SID not available. Quit.
//
TrERROR(SECURITY, "Machine Sid not available, Access is denied");
return hr;
}
ASSERT(IsValidSid(pMachineSid));
SECURITY_DESCRIPTOR sd;
if(!InitializeSecurityDescriptor(
&sd,
SECURITY_DESCRIPTOR_REVISION
))
{
DWORD gle = GetLastError();
ASSERT(("InitializeSecurityDescriptor failed", 0));
TrERROR(SECURITY, "Fail to Initialize Security Descriptor security, gle = %!winerr!", gle) ;
return hr;
}
//
// use e_DoNotCopyControlBits at present, to be compatible with
// previous code.
//
if(!MQSec_CopySecurityDescriptor(
&sd,
pSD,
(OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION),
e_DoNotCopyControlBits
))
{
DWORD gle = GetLastError();
ASSERT(("MQSec_CopySecurityDescriptor failed", 0));
TrERROR(SECURITY, "Fail to copy security descriptor, gle = %!winerr!", gle);
return hr;
}
BOOL fReplaced = FALSE;
P<ACL> pSysDacl = NULL;
HRESULT hr1 = ReplaceSidWithSystemService(
&sd,
pSD,
pMachineSid,
pSystemServiceSid,
&pSysDacl,
&fReplaced
);
if (SUCCEEDED(hr1) && fReplaced)
{
TrTRACE(SECURITY, "Security descriptor was updated with System sid instead on machine$ sid");
//
// OK, retry the Access Check, with new security desctiptor that replaced
// the machine account sid with the well-known SYSTEM sid.
//
hr = _DoAccessCheck(
&sd,
dwObjectType,
pwszObjectName,
dwDesiredAccess,
pId,
hAccessToken
);
}
}
return LogHR(hr, s_FN, 120);
}
HRESULT
APIENTRY
MQSec_AccessCheckForSelf(
IN SECURITY_DESCRIPTOR *pSD,
IN DWORD dwObjectType,
IN PSID pSelfSid,
IN DWORD dwDesiredAccess,
IN BOOL fImpersonate
)
/*++
Routine Description:
Perform access check for the runnig thread.
The access is done for the thread sid and for selfSid.
Arguments:
pSD - Security descriptor.
dwObjectType - Object type.
pSelfSid - Self sid (computer sid).
dwDesiredAccess - Desired accessGet Thread token only.
fImpersonate - Flag indicating if we need to impersonate the client.
Returned Value:
MQ_OK if access was granted, else error code.
--*/
{
if (dwObjectType != MQDS_COMPUTER)
{
//
// Not supported. this function is clled only to check
// access rights for join-domain.
//
TrERROR(SECURITY, "Object type %d, is not computer", dwObjectType);
return MQ_ERROR_ACCESS_DENIED;
}
P<CImpersonate> pImpersonate = NULL;
if (fImpersonate)
{
pImpersonate = new CImpersonate(TRUE, TRUE);
if (pImpersonate->GetImpersonationStatus() != 0)
{
TrERROR(SECURITY, "Failed to impersonate client");
return MQ_ERROR_CANNOT_IMPERSONATE_CLIENT;
}
}
CAutoCloseHandle hAccessToken = NULL;
DWORD rc = GetAccessToken(
&hAccessToken,
FALSE,
TOKEN_QUERY,
TRUE
);
if (rc != ERROR_SUCCESS)
{
//
// Return this error for backward compatibility.
//
TrERROR(SECURITY, "Failed to get access token, gle = %!winerr!", rc);
return MQ_ERROR_ACCESS_DENIED;
}
char ps_buff[sizeof(PRIVILEGE_SET) +
((2 - ANYSIZE_ARRAY) * sizeof(LUID_AND_ATTRIBUTES))];
PPRIVILEGE_SET ps = (PPRIVILEGE_SET)ps_buff;
DWORD dwPrivilegeSetLength = sizeof(ps_buff);
DWORD dwGrantedAccess = 0;
DWORD fAccessStatus = 1;
//
// this is the guid of msmqConfiguration class.
// Hardcoded here, to save the effort of querying schema.
// taken from schemaIDGUID attribute of CN=MSMQ-Configuration object
// in schema naming context.
//
BYTE guidMsmqConfiguration[sizeof(GUID)] = {
0x44,
0xc3,
0x0d,
0x9a,
0x00,
0xc1,
0xd1,
0x11,
0xbb,
0xc5,
0x00,
0x80,
0xc7,
0x66,
0x70,
0xc0
};
OBJECT_TYPE_LIST objType = {
ACCESS_OBJECT_GUID,
0,
(GUID*) guidMsmqConfiguration
};
if(!AccessCheckByTypeResultList(
pSD,
pSelfSid,
hAccessToken,
dwDesiredAccess,
&objType,
1,
GetObjectGenericMapping(dwObjectType),
ps,
&dwPrivilegeSetLength,
&dwGrantedAccess,
&fAccessStatus
))
{
DWORD gle = GetLastError();
ASSERT(("AccessCheckByTypeResultList failed", 0));
TrERROR(SECURITY, "Access Check By Type Result List failed, gle = %!winerr!", gle);
return MQ_ERROR_ACCESS_DENIED;
}
if ((fAccessStatus == 0) && AreAllAccessesGranted(dwGrantedAccess, dwDesiredAccess))
{
//
// Access granted.
// for this api, fAccessStatus being 0 mean success. see msdn.
//
TrTRACE(SECURITY, "Access is granted: DesiredAccess = 0x%x", dwDesiredAccess);
return MQSec_OK;
}
//
// Access is denied
//
if (GetLastError() == ERROR_PRIVILEGE_NOT_HELD)
{
TrERROR(SECURITY, "Privilage not held: DesiredAccess = 0x%x", dwDesiredAccess);
return MQ_ERROR_PRIVILEGE_NOT_HELD;
}
TrERROR(SECURITY, "Access is denied: DesiredAccess = 0x%x", dwDesiredAccess);
return MQ_ERROR_ACCESS_DENIED;
}
| 26.61748 | 147 | 0.585757 | [
"object"
] |
a0465d3f314f8549f48486917f2048ca7a5bed97 | 2,379 | inl | C++ | source/hougfx/include/hou/gfx/mipmapped_texture3.inl | DavideCorradiDev/houzi-game-engine | d704aa9c5b024300578aafe410b7299c4af4fcec | [
"MIT"
] | 2 | 2018-04-12T20:59:20.000Z | 2018-07-26T16:04:07.000Z | source/hougfx/include/hou/gfx/mipmapped_texture3.inl | DavideCorradiDev/houzi-game-engine | d704aa9c5b024300578aafe410b7299c4af4fcec | [
"MIT"
] | null | null | null | source/hougfx/include/hou/gfx/mipmapped_texture3.inl | DavideCorradiDev/houzi-game-engine | d704aa9c5b024300578aafe410b7299c4af4fcec | [
"MIT"
] | null | null | null | // Houzi Game Engine
// Copyright (c) 2018 Davide Corradi
// Licensed under the MIT license.
namespace hou
{
template <pixel_format PF>
image3<PF> mipmapped_texture3::get_image() const
{
return get_sub_image<PF>(vec3u::zero(), get_size());
}
template <pixel_format PF>
image3<PF> mipmapped_texture3::get_sub_image(
const vec3u& offset, const vec3u& size) const
{
std::vector<uint8_t> pixels = get_sub_pixels(offset, size);
switch(get_format())
{
case texture_format::r:
return image3<PF>(image3_r(size,
reinterpret_span<const pixel_r>(
span<const uint8_t>(pixels.data(), pixels.size()))));
case texture_format::rg:
return image3<PF>(image3_rg(size,
reinterpret_span<const pixel_rg>(
span<const uint8_t>(pixels.data(), pixels.size()))));
case texture_format::rgb:
return image3<PF>(image3_rgb(size,
reinterpret_span<const pixel_rgb>(
span<const uint8_t>(pixels.data(), pixels.size()))));
case texture_format::rgba:
case texture_format::depth_stencil:
return image3<PF>(image3_rgba(size,
reinterpret_span<const pixel_rgba>(
span<const uint8_t>(pixels.data(), pixels.size()))));
}
}
template <pixel_format PF>
void mipmapped_texture3::set_image(const image3<PF>& img)
{
HOU_PRECOND(img.get_size() == get_size());
return set_sub_image(vec3u::zero(), img);
}
template <pixel_format PF>
void mipmapped_texture3::set_sub_image(
const vec3u& offset, const image3<PF>& img)
{
switch(get_format())
{
case texture_format::r:
set_sub_pixels(offset, img.get_size(),
reinterpret_span<const uint8_t>(
span<const pixel_r>(image3_r(img).get_pixels())));
break;
case texture_format::rg:
set_sub_pixels(offset, img.get_size(),
reinterpret_span<const uint8_t>(
span<const pixel_rg>(image3_rg(img).get_pixels())));
break;
case texture_format::rgb:
set_sub_pixels(offset, img.get_size(),
reinterpret_span<const uint8_t>(
span<const pixel_rgb>(image3_rgb(img).get_pixels())));
break;
case texture_format::rgba:
case texture_format::depth_stencil:
set_sub_pixels(offset, img.get_size(),
reinterpret_span<const uint8_t>(
span<const pixel_rgba>(image3_rgba(img).get_pixels())));
break;
}
}
} // namespace hou
| 27.034091 | 66 | 0.672131 | [
"vector"
] |
a049422ef1b0b50abb2bd94baa0c1f00bfa17385 | 7,323 | cc | C++ | src/tool/server.cc | gypkg/boringssl | 3565b1dc699cf72664f840e5179c0c57fdb9bb14 | [
"Intel",
"ISC",
"OpenSSL",
"Unlicense"
] | 2 | 2016-12-10T19:42:12.000Z | 2016-12-11T16:54:58.000Z | src/tool/server.cc | gypkg/boringssl | 3565b1dc699cf72664f840e5179c0c57fdb9bb14 | [
"Intel",
"ISC",
"OpenSSL",
"Unlicense"
] | null | null | null | src/tool/server.cc | gypkg/boringssl | 3565b1dc699cf72664f840e5179c0c57fdb9bb14 | [
"Intel",
"ISC",
"OpenSSL",
"Unlicense"
] | null | null | null | /* Copyright (c) 2014, Google Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
#include <openssl/base.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/ssl.h>
#include "internal.h"
#include "transport_common.h"
static const struct argument kArguments[] = {
{
"-accept", kRequiredArgument,
"The port of the server to bind on; eg 45102",
},
{
"-cipher", kOptionalArgument,
"An OpenSSL-style cipher suite string that configures the offered ciphers",
},
{
"-max-version", kOptionalArgument,
"The maximum acceptable protocol version",
},
{
"-min-version", kOptionalArgument,
"The minimum acceptable protocol version",
},
{
"-key", kOptionalArgument,
"PEM-encoded file containing the private key, leaf certificate and "
"optional certificate chain. A self-signed certificate is generated "
"at runtime if this argument is not provided.",
},
{
"-ocsp-response", kOptionalArgument,
"OCSP response file to send",
},
{
"", kOptionalArgument, "",
},
};
static bool LoadOCSPResponse(SSL_CTX *ctx, const char *filename) {
void *data = NULL;
bool ret = false;
size_t bytes_read;
long length;
FILE *f = fopen(filename, "rb");
if (f == NULL ||
fseek(f, 0, SEEK_END) != 0) {
goto out;
}
length = ftell(f);
if (length < 0) {
goto out;
}
data = malloc(length);
if (data == NULL) {
goto out;
}
rewind(f);
bytes_read = fread(data, 1, length, f);
if (ferror(f) != 0 ||
bytes_read != (size_t)length ||
!SSL_CTX_set_ocsp_response(ctx, (uint8_t*)data, bytes_read)) {
goto out;
}
ret = true;
out:
if (f != NULL) {
fclose(f);
}
free(data);
return ret;
}
static bssl::UniquePtr<EVP_PKEY> MakeKeyPairForSelfSignedCert() {
bssl::UniquePtr<EC_KEY> ec_key(EC_KEY_new_by_curve_name(NID_X9_62_prime256v1));
if (!ec_key || !EC_KEY_generate_key(ec_key.get())) {
fprintf(stderr, "Failed to generate key pair.\n");
return nullptr;
}
bssl::UniquePtr<EVP_PKEY> evp_pkey(EVP_PKEY_new());
if (!evp_pkey || !EVP_PKEY_assign_EC_KEY(evp_pkey.get(), ec_key.release())) {
fprintf(stderr, "Failed to assign key pair.\n");
return nullptr;
}
return evp_pkey;
}
static bssl::UniquePtr<X509> MakeSelfSignedCert(EVP_PKEY *evp_pkey,
const int valid_days) {
bssl::UniquePtr<X509> x509(X509_new());
uint32_t serial;
RAND_bytes(reinterpret_cast<uint8_t*>(&serial), sizeof(serial));
ASN1_INTEGER_set(X509_get_serialNumber(x509.get()), serial >> 1);
X509_gmtime_adj(X509_get_notBefore(x509.get()), 0);
X509_gmtime_adj(X509_get_notAfter(x509.get()), 60 * 60 * 24 * valid_days);
X509_NAME* subject = X509_get_subject_name(x509.get());
X509_NAME_add_entry_by_txt(subject, "C", MBSTRING_ASC,
reinterpret_cast<const uint8_t *>("US"), -1, -1,
0);
X509_NAME_add_entry_by_txt(subject, "O", MBSTRING_ASC,
reinterpret_cast<const uint8_t *>("BoringSSL"), -1,
-1, 0);
X509_set_issuer_name(x509.get(), subject);
if (!X509_set_pubkey(x509.get(), evp_pkey)) {
fprintf(stderr, "Failed to set public key.\n");
return nullptr;
}
if (!X509_sign(x509.get(), evp_pkey, EVP_sha256())) {
fprintf(stderr, "Failed to sign certificate.\n");
return nullptr;
}
return x509;
}
bool Server(const std::vector<std::string> &args) {
if (!InitSocketLibrary()) {
return false;
}
std::map<std::string, std::string> args_map;
if (!ParseKeyValueArguments(&args_map, args, kArguments)) {
PrintUsage(kArguments);
return false;
}
bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
SSL_CTX_set_options(ctx.get(), SSL_OP_NO_SSLv3);
// Server authentication is required.
if (args_map.count("-key") != 0) {
std::string key_file = args_map["-key"];
if (!SSL_CTX_use_PrivateKey_file(ctx.get(), key_file.c_str(), SSL_FILETYPE_PEM)) {
fprintf(stderr, "Failed to load private key: %s\n", key_file.c_str());
return false;
}
if (!SSL_CTX_use_certificate_chain_file(ctx.get(), key_file.c_str())) {
fprintf(stderr, "Failed to load cert chain: %s\n", key_file.c_str());
return false;
}
} else {
bssl::UniquePtr<EVP_PKEY> evp_pkey = MakeKeyPairForSelfSignedCert();
if (!evp_pkey) {
return false;
}
bssl::UniquePtr<X509> cert =
MakeSelfSignedCert(evp_pkey.get(), 365 /* valid_days */);
if (!cert) {
return false;
}
if (!SSL_CTX_use_PrivateKey(ctx.get(), evp_pkey.get())) {
fprintf(stderr, "Failed to set private key.\n");
return false;
}
if (!SSL_CTX_use_certificate(ctx.get(), cert.get())) {
fprintf(stderr, "Failed to set certificate.\n");
return false;
}
}
if (args_map.count("-cipher") != 0 &&
!SSL_CTX_set_cipher_list(ctx.get(), args_map["-cipher"].c_str())) {
fprintf(stderr, "Failed setting cipher list\n");
return false;
}
if (args_map.count("-max-version") != 0) {
uint16_t version;
if (!VersionFromString(&version, args_map["-max-version"])) {
fprintf(stderr, "Unknown protocol version: '%s'\n",
args_map["-max-version"].c_str());
return false;
}
if (!SSL_CTX_set_max_proto_version(ctx.get(), version)) {
return false;
}
}
if (args_map.count("-min-version") != 0) {
uint16_t version;
if (!VersionFromString(&version, args_map["-min-version"])) {
fprintf(stderr, "Unknown protocol version: '%s'\n",
args_map["-min-version"].c_str());
return false;
}
if (!SSL_CTX_set_min_proto_version(ctx.get(), version)) {
return false;
}
}
if (args_map.count("-ocsp-response") != 0 &&
!LoadOCSPResponse(ctx.get(), args_map["-ocsp-response"].c_str())) {
fprintf(stderr, "Failed to load OCSP response: %s\n", args_map["-ocsp-response"].c_str());
return false;
}
int sock = -1;
if (!Accept(&sock, args_map["-accept"])) {
return false;
}
BIO *bio = BIO_new_socket(sock, BIO_CLOSE);
bssl::UniquePtr<SSL> ssl(SSL_new(ctx.get()));
SSL_set_bio(ssl.get(), bio, bio);
int ret = SSL_accept(ssl.get());
if (ret != 1) {
int ssl_err = SSL_get_error(ssl.get(), ret);
fprintf(stderr, "Error while connecting: %d\n", ssl_err);
ERR_print_errors_cb(PrintErrorCallback, stderr);
return false;
}
fprintf(stderr, "Connected.\n");
PrintConnectionInfo(ssl.get());
return TransferData(ssl.get(), sock);
}
| 30.012295 | 94 | 0.640038 | [
"vector"
] |
a0516524e2ffc7b9ded5f646b017694afc2d450b | 8,495 | cpp | C++ | src/ai/cpu.cpp | jdermont/QtYavalath | ed98022a9afb9ca6e9382b6fb3444a01790915b4 | [
"Apache-2.0"
] | null | null | null | src/ai/cpu.cpp | jdermont/QtYavalath | ed98022a9afb9ca6e9382b6fb3444a01790915b4 | [
"Apache-2.0"
] | null | null | null | src/ai/cpu.cpp | jdermont/QtYavalath | ed98022a9afb9ca6e9382b6fb3444a01790915b4 | [
"Apache-2.0"
] | null | null | null | #include "cpu.h"
Cpu::Cpu()
{
auto now = high_resolution_clock::now();
auto nanos = duration_cast<nanoseconds>(now.time_since_epoch()).count();
seed = 123456969ULL * (uint64_t)nanos + (uint64_t)(&now);
simulationGame = new Game();
}
void Cpu::setPlayer(int player) {
this->player = player;
}
int Cpu::getPlayer() {
return player;
}
void Cpu::setGame(Game *game) {
this->game = game;
}
Move* Cpu::getBestMove(long timeInMicro/*, vector<Para> & pary*/) {
auto start = high_resolution_clock::now();
vector<Move*> moves = generateMoves(nullptr,0);
games = 0;
provenEnd = false;
long duration = duration_cast<microseconds>( high_resolution_clock::now() - start).count();
while (!provenEnd && duration < timeInMicro) {
selectAndExpand(moves,games+1,0);
games++;
duration = duration_cast<microseconds>( high_resolution_clock::now() - start).count();
}
sort(moves.begin(),moves.end(), [](const Move *a, const Move *b) -> bool
{
double avg1 = a->score / (a->games+1e-3);
double avg2 = b->score / (b->games+1e-3);
return avg1 > avg2;
});
for (int i=1;i<moves.size();i++) {
delete moves[i];
}
return moves[0];
}
uint64_t Cpu::nextInt(uint64_t n) {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
return seed % n;
}
void Cpu::selectAndExpand(vector<Move*> & moves, int games, int level) {
vector<int> indexes;
double maxArg = -2 * INF;
double a,b;
double logCache = log(games);
for (size_t i=0; i < moves.size(); i++) {
Move *move = moves[i];
if (move->terminal) {
a = (double)move->score / move->games;
b = 0.0;
} else if (move->games == 0) {
a = 1000.0;
b = 1000.0;
} else {
a = (double)move->score / move->games;
b = CEXP * sqrt(logCache / move->games);
}
if (a + b > maxArg) {
maxArg = a + b;
indexes.clear();
indexes.push_back(i);
} else if (a + b == maxArg) {
indexes.push_back(i);
}
}
Move *move = moves[indexes[nextInt(indexes.size())]];
if (move->terminal) {
move->games += 1;
if (move->score == INF) {
if (level == 0) {
provenEnd = true;
return;
}
Move *parent = move->parent;
if (parent != nullptr) {
parent->score = -INF;
parent->games++;
parent->terminal = true;
parent = parent->parent;
}
while (parent != nullptr) {
parent->score += parent->player == move->player ? 1 : -1;
parent->games++;
parent = parent->parent;
}
} else {
bool allChildrenTerminal = true;
int maxScore = -INF;
for (auto & m : moves) {
maxScore = max(maxScore,m->score);
if (!m->terminal) {
allChildrenTerminal = false;
break;
}
}
Move *parent = move->parent;
if (allChildrenTerminal) {
if (level == 0) {
provenEnd = true;
return;
}
if (maxScore == -INF) {
if (parent != nullptr) {
parent->score = INF;
parent->games++;
parent->terminal = true;
parent = parent->parent;
}
if (parent != nullptr) {
parent->score = -INF;
parent->games++;
parent->terminal = true;
parent = parent->parent;
}
while (parent != nullptr) {
parent->score += parent->player == move->player ? -1 : 1;
parent->games++;
parent = parent->parent;
}
} else {
if (parent != nullptr) {
parent->games++;
parent->score = 0;
parent->terminal = true;
parent = parent->parent;
}
while (parent != nullptr) {
parent->score += 0;
parent->games++;
parent = parent->parent;
}
}
} else {
if (move->score == -INF) {
while (parent != nullptr) {
parent->score += parent->player == move->player ? -1 : 1;
parent->games++;
parent = parent->parent;
}
} else {
move->score += 0;
while (parent != nullptr) {
parent->score += 0;
parent->games++;
parent = parent->parent;
}
}
}
}
return;
}
game->makeMove(move->move);
if (move->games > 0) {
if (move->children.size() == 0) {
move->children = generateMoves(move, level+1);
}
selectAndExpand(move->children, move->games+1, level+1);
} else {
int score = simulateOneGame(move->player);
move->score = score;
move->games = 1;
Move *parent = move->parent;
while (parent != nullptr) {
parent->score += parent->player == move->player ? score : -score;
parent->games++;
parent = parent->parent;
}
}
game->undoMove();
}
vector<Move*> Cpu::generateMoves(Move *parent, int level) {
vector<int> movesNum = game->getAvailableMoves();
int player = game->getCurrentPlayer();
vector<Move*> moves; moves.reserve(movesNum.size());
for (auto & moveNum : movesNum) {
game->makeMove(moveNum);
if (game->isOver()) {
int winner = game->getWinner();
if (winner == player) {
Move *move = new Move(parent,player,moveNum);
move->score = INF;
move->games = 1;
move->terminal = true;
moves.push_back(move);
game->undoMove();
return moves;
} else if (winner == PLAYER_NONE) {
Move *move = new Move(parent,player,moveNum);
move->score = 0;
move->games = 1;
move->terminal = true;
moves.push_back(move);
} else if (moves.size() == 0) {
Move *move = new Move(parent,player,moveNum);
move->score = -INF;
move->games = 1;
move->terminal = true;
moves.push_back(move);
}
} else {
moves.push_back(new Move(parent,player,moveNum));
}
game->undoMove();
}
return moves;
}
int Cpu::simulateOneGame(int forPlayer) {
simulationGame->setGameNoHistory(game);
moves = simulationGame->getAvailableMoves();
while (!simulationGame->isOver()) {
int n = 0;
int player = simulationGame->getCurrentPlayer();
for (int move : moves) {
if (simulationGame->isFilled(move)) continue;
simulationGame->makeMove(move);
if (simulationGame->isOver()) {
int winner = simulationGame->getWinner();
if (winner == player) {
return winner == forPlayer ? 1 : -1;
} else if (winner == PLAYER_NONE) {
moves2[n++] = move;
}
} else {
moves2[n++] = move;
}
simulationGame->undoMove();
}
if (n > 0) {
int move = moves2[nextInt(n)];
simulationGame->makeMove(move);
} else {
int move = moves[nextInt(moves.size())];
simulationGame->makeMove(move);
}
}
int winner = simulationGame->getWinner();
if (winner == forPlayer) {
return 1;
} else if (winner == PLAYER_NONE) {
return 0;
} else {
return -1;
}
}
| 31.231618 | 95 | 0.445085 | [
"vector"
] |
a054a0592dbfab3ff210f40f6a021bf64072abd1 | 5,810 | cpp | C++ | deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgFX/SpecularHighlights.cpp | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | 3 | 2018-08-20T12:12:43.000Z | 2021-06-06T09:43:27.000Z | deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgFX/SpecularHighlights.cpp | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | null | null | null | deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgFX/SpecularHighlights.cpp | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | 1 | 2022-03-31T03:12:23.000Z | 2022-03-31T03:12:23.000Z | #include <osgFX/SpecularHighlights>
#include <osgFX/Registry>
#include <osg/TextureCubeMap>
#include <osg/TexGen>
#include <osg/TexEnv>
#include <osg/ColorMatrix>
#include <osgUtil/HighlightMapGenerator>
using namespace osgFX;
namespace
{
class AutoTextureMatrix: public osg::StateAttribute {
public:
AutoTextureMatrix()
: osg::StateAttribute(),
_lightnum(0),
_active(false)
{
}
AutoTextureMatrix(const AutoTextureMatrix& copy, const osg::CopyOp& copyop)
: osg::StateAttribute(copy, copyop),
_lightnum(copy._lightnum),
_active(copy._active)
{
}
AutoTextureMatrix(int lightnum, bool active = true)
: osg::StateAttribute(),
_lightnum(lightnum),
_active(active)
{
}
META_StateAttribute(osgFX, AutoTextureMatrix, osg::StateAttribute::TEXMAT);
virtual bool isTextureAttribute() const { return true; }
int compare(const osg::StateAttribute &sa) const
{
COMPARE_StateAttribute_Types(AutoTextureMatrix, sa);
if (_lightnum < rhs._lightnum) return -1;
if (_lightnum > rhs._lightnum) return 1;
return 0;
}
void apply(osg::State& state) const
{
glMatrixMode(GL_TEXTURE);
if (_active) {
osg::Matrix M = state.getInitialViewMatrix();
M(3, 0) = 0; M(3, 1) = 0; M(3, 2) = 0;
M(3, 3) = 1; M(0, 3) = 0; M(1, 3) = 0;
M(2, 3) = 0;
osg::Vec4 lightvec;
glGetLightfv(GL_LIGHT0+_lightnum, GL_POSITION, lightvec._v);
osg::Vec3 eye_light_ref = osg::Vec3(0, 0, 1) * M;
osg::Matrix LM = osg::Matrix::rotate(
osg::Vec3(lightvec.x(), lightvec.y(), lightvec.z()),
eye_light_ref);
glLoadMatrix((LM * osg::Matrix::inverse(M)).ptr());
} else {
glLoadIdentity();
}
glMatrixMode(GL_MODELVIEW);
}
private:
int _lightnum;
bool _active;
};
}
namespace
{
Registry::Proxy proxy(new SpecularHighlights);
class DefaultTechnique: public Technique {
public:
DefaultTechnique(int lightnum, int unit, const osg::Vec4& color, float sexp)
: Technique(),
_lightnum(lightnum),
_unit(unit),
_color(color),
_sexp(sexp)
{
}
virtual void getRequiredExtensions(std::vector<std::string>& extensions)
{
extensions.push_back("GL_ARB_texture_env_add");
}
bool validate(osg::State& state) const
{
if (!Technique::validate(state)) return false;
osg::TextureCubeMap::Extensions *ext =
osg::TextureCubeMap::getExtensions(state.getContextID(), true);
if (ext) {
return ext->isCubeMapSupported();
}
return false;
}
protected:
void define_passes()
{
osg::ref_ptr<osg::StateSet> ss = new osg::StateSet;
ss->setTextureAttributeAndModes(_unit, new AutoTextureMatrix(_lightnum), osg::StateAttribute::OVERRIDE|osg::StateAttribute::ON);
osg::ref_ptr<osgUtil::HighlightMapGenerator> hmg = new osgUtil::HighlightMapGenerator(osg::Vec3(0, 0, -1), _color, _sexp);
hmg->generateMap(false);
osg::ref_ptr<osg::TextureCubeMap> texture = new osg::TextureCubeMap;
texture->setImage(osg::TextureCubeMap::POSITIVE_X, hmg->getImage(osg::TextureCubeMap::POSITIVE_X));
texture->setImage(osg::TextureCubeMap::POSITIVE_Y, hmg->getImage(osg::TextureCubeMap::POSITIVE_Y));
texture->setImage(osg::TextureCubeMap::POSITIVE_Z, hmg->getImage(osg::TextureCubeMap::POSITIVE_Z));
texture->setImage(osg::TextureCubeMap::NEGATIVE_X, hmg->getImage(osg::TextureCubeMap::NEGATIVE_X));
texture->setImage(osg::TextureCubeMap::NEGATIVE_Y, hmg->getImage(osg::TextureCubeMap::NEGATIVE_Y));
texture->setImage(osg::TextureCubeMap::NEGATIVE_Z, hmg->getImage(osg::TextureCubeMap::NEGATIVE_Z));
texture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
texture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
texture->setWrap(osg::Texture::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
ss->setTextureAttributeAndModes(_unit, texture.get(), osg::StateAttribute::OVERRIDE|osg::StateAttribute::ON);
osg::ref_ptr<osg::TexGen> texgen = new osg::TexGen;
texgen->setMode(osg::TexGen::REFLECTION_MAP);
ss->setTextureAttributeAndModes(_unit, texgen.get(), osg::StateAttribute::OVERRIDE|osg::StateAttribute::ON);
osg::ref_ptr<osg::TexEnv> texenv = new osg::TexEnv;
texenv->setMode(osg::TexEnv::ADD);
ss->setTextureAttributeAndModes(_unit, texenv.get(), osg::StateAttribute::OVERRIDE|osg::StateAttribute::ON);
addPass(ss.get());
}
private:
int _lightnum;
int _unit;
osg::Vec4 _color;
float _sexp;
};
}
SpecularHighlights::SpecularHighlights()
: Effect(),
_lightnum(0),
_unit(0),
_color(1, 1, 1, 1),
_sexp(16)
{
}
SpecularHighlights::SpecularHighlights(const SpecularHighlights& copy, const osg::CopyOp& copyop)
: Effect(copy, copyop),
_lightnum(copy._lightnum),
_unit(copy._unit),
_color(copy._color),
_sexp(copy._sexp)
{
}
bool SpecularHighlights::define_techniques()
{
addTechnique(new DefaultTechnique(_lightnum, _unit, _color, _sexp));
return true;
}
| 31.069519 | 140 | 0.59346 | [
"vector"
] |
a05831c380adc5febd56686b932e3b540425f969 | 11,062 | cpp | C++ | src/axom/quest/detail/shaping/shaping_helpers.cpp | bmhan12/axom | fbee125aec6357340f35b6fd5d0d4a62a3c80733 | [
"BSD-3-Clause"
] | null | null | null | src/axom/quest/detail/shaping/shaping_helpers.cpp | bmhan12/axom | fbee125aec6357340f35b6fd5d0d4a62a3c80733 | [
"BSD-3-Clause"
] | null | null | null | src/axom/quest/detail/shaping/shaping_helpers.cpp | bmhan12/axom | fbee125aec6357340f35b6fd5d0d4a62a3c80733 | [
"BSD-3-Clause"
] | null | null | null | #include "shaping_helpers.hpp"
#include "axom/config.hpp"
#include "axom/core.hpp"
#include "axom/slic.hpp"
#include "axom/fmt.hpp"
#include "axom/fmt/locale.h"
#ifndef AXOM_USE_MFEM
#error Shaping functionality requires Axom to be configured with MFEM and the AXOM_ENABLE_MFEM_SIDRE_DATACOLLECTION option
#endif
namespace axom
{
namespace quest
{
namespace shaping
{
void replaceMaterial(mfem::QuadratureFunction* shapeQFunc,
mfem::QuadratureFunction* materialQFunc,
bool shapeReplacesMaterial)
{
SLIC_ASSERT(shapeQFunc != nullptr);
SLIC_ASSERT(materialQFunc != nullptr);
SLIC_ASSERT(materialQFunc->Size() == shapeQFunc->Size());
const int SZ = materialQFunc->Size();
double* mData = materialQFunc->GetData();
double* sData = shapeQFunc->GetData();
if(shapeReplacesMaterial)
{
// If shapeReplacesMaterial, clear material samples that are inside current shape
for(int j = 0; j < SZ; ++j)
{
mData[j] = sData[j] > 0 ? 0 : mData[j];
}
}
else
{
// Otherwise, clear current shape samples that are in the material
for(int j = 0; j < SZ; ++j)
{
sData[j] = mData[j] > 0 ? 0 : sData[j];
}
}
}
/// Utility function to copy in_out quadrature samples from one QFunc to another
void copyShapeIntoMaterial(const mfem::QuadratureFunction* shapeQFunc,
mfem::QuadratureFunction* materialQFunc)
{
SLIC_ASSERT(shapeQFunc != nullptr);
SLIC_ASSERT(materialQFunc != nullptr);
SLIC_ASSERT(materialQFunc->Size() == shapeQFunc->Size());
const int SZ = materialQFunc->Size();
double* mData = materialQFunc->GetData();
const double* sData = shapeQFunc->GetData();
for(int j = 0; j < SZ; ++j)
{
mData[j] = sData[j] > 0 ? 1 : mData[j];
}
}
/// Generates a quadrature function corresponding to the mesh "positions" field
void generatePositionsQFunction(mfem::Mesh* mesh,
QFunctionCollection& inoutQFuncs,
int sampleRes)
{
SLIC_ASSERT(mesh != nullptr);
const int NE = mesh->GetNE();
const int dim = mesh->Dimension();
if(NE < 1)
{
SLIC_WARNING("Mesh has no elements!");
return;
}
// convert requested samples into a compatible polynomial order
// that will use that many samples: 2n-1 and 2n-2 will work
// NOTE: Might be different for simplices
const int sampleOrder = 2 * sampleRes - 1;
mfem::QuadratureSpace* sp = new mfem::QuadratureSpace(mesh, sampleOrder);
// TODO: Should the samples be along a uniform grid
// instead of Guassian quadrature?
// This would need quadrature weights for the uniform
// samples -- Newton-Cotes ?
// With uniform points, we could do HO polynomial fitting
// Using 0s and 1s is non-oscillatory in Bernstein basis
// Assume all elements have the same integration rule
const auto& ir = sp->GetElementIntRule(0);
const int nq = ir.GetNPoints();
const auto* geomFactors =
mesh->GetGeometricFactors(ir, mfem::GeometricFactors::COORDINATES);
mfem::QuadratureFunction* pos_coef = new mfem::QuadratureFunction(sp, dim);
pos_coef->SetOwnsSpace(true);
// Rearrange positions into quadrature function
{
for(int i = 0; i < NE; ++i)
{
const int elStartIdx = i * nq * dim;
for(int j = 0; j < dim; ++j)
{
for(int k = 0; k < nq; ++k)
{
//X has dims nqpts x sdim x ne
(*pos_coef)(elStartIdx + (k * dim) + j) =
geomFactors->X(elStartIdx + (j * nq) + k);
}
}
}
}
// register positions with the QFunction collection, which wil handle its deletion
inoutQFuncs.Register("positions", pos_coef, true);
}
/**
* Compute volume fractions function for shape on a grid of resolution \a gridRes
* in region defined by bounding box \a queryBounds
*/
void computeVolumeFractions(const std::string& matField,
mfem::DataCollection* dc,
QFunctionCollection& inoutQFuncs,
int outputOrder)
{
using axom::utilities::string::rsplitN;
auto matName = rsplitN(matField, 2, '_')[1];
auto volFracName = axom::fmt::format("vol_frac_{}", matName);
// Grab a pointer to the inout samples QFunc
mfem::QuadratureFunction* inout = inoutQFuncs.Get(matField);
const int sampleOrder = inout->GetSpace()->GetElementIntRule(0).GetOrder();
const int sampleNQ = inout->GetSpace()->GetElementIntRule(0).GetNPoints();
const int sampleSZ = inout->GetSpace()->GetSize();
SLIC_INFO(axom::fmt::format(std::locale("en_US.UTF-8"),
"In computeVolumeFractions(): sample order {} | "
"sample num qpts {} | total samples {:L}",
sampleOrder,
sampleNQ,
sampleSZ));
mfem::Mesh* mesh = dc->GetMesh();
const int dim = mesh->Dimension();
const int NE = mesh->GetNE();
SLIC_INFO(axom::fmt::format(std::locale("en_US.UTF-8"),
"Mesh has dim {} and {:L} elements",
dim,
NE));
// Project QField onto volume fractions field
mfem::L2_FECollection* fec =
new mfem::L2_FECollection(outputOrder, dim, mfem::BasisType::Positive);
mfem::FiniteElementSpace* fes = new mfem::FiniteElementSpace(mesh, fec);
mfem::GridFunction* volFrac = new mfem::GridFunction(fes);
volFrac->MakeOwner(fec);
dc->RegisterField(volFracName, volFrac);
axom::utilities::Timer timer(true);
{
mfem::MassIntegrator mass_integrator; // use the default for exact integration; lower for approximate
mfem::QuadratureFunctionCoefficient qfc(*inout);
mfem::DomainLFIntegrator rhs(qfc);
// assume all elts are the same
const auto& ir = inout->GetSpace()->GetElementIntRule(0);
rhs.SetIntRule(&ir);
mfem::DenseMatrix m;
mfem::DenseMatrixInverse mInv;
mfem::Vector b, x;
mfem::Array<int> dofs;
mfem::Vector one;
const double minY = 0.;
const double maxY = 1.;
for(int i = 0; i < NE; ++i)
{
auto* T = mesh->GetElementTransformation(i);
auto* el = fes->GetFE(i);
mass_integrator.AssembleElementMatrix(*el, *T, m);
rhs.AssembleRHSElementVect(*el, *T, b);
mInv.Factor(m);
// Use FCT limiting -- similar to Remap
// Limit the function to be between 0 and 1
// Q: Is there a better way limiting algorithm for this?
if(one.Size() != b.Size())
{
one.SetSize(b.Size());
one = 1.0;
}
FCT_project(m, mInv, b, one, minY, maxY, x);
fes->GetElementDofs(i, dofs);
volFrac->SetSubVector(dofs, x);
}
}
timer.stop();
SLIC_INFO(axom::fmt::format(
std::locale("en_US.UTF-8"),
"\t Generating volume fractions '{}' took {:.3f} seconds (@ "
"{:L} dofs processed per second)",
volFracName,
timer.elapsed(),
static_cast<int>(fes->GetNDofs() / timer.elapsed())));
}
/**
* Implements flux-corrected transport (FCT) to convert the inout samples (ones and zeros)
* to a grid function on the degrees of freedom such that the volume fractions are doubles
* between 0 and 1 ( \a y_min and \a y_max )
*/
void FCT_project(mfem::DenseMatrix& M,
mfem::DenseMatrixInverse& M_inv,
mfem::Vector& m,
mfem::Vector& x, // indicators
double y_min,
double y_max,
mfem::Vector& xy) // indicators * rho
{
// [IN] - M, M_inv, m, x, y_min, y_max
// [OUT] - xy
using namespace mfem;
const int s = M.Size();
xy.SetSize(s);
// Compute the high-order projection in xy
M_inv.Mult(m, xy);
// Q0 solutions can't be adjusted conservatively. It's what it is.
if(xy.Size() == 1)
{
return;
}
// Compute the lumped mass matrix in ML
Vector ML(s);
M.GetRowSums(ML);
//Ensure dot product is done on the CPU
double dMLX(0);
for(int i = 0; i < x.Size(); ++i)
{
dMLX += ML(i) * x(i);
}
const double y_avg = m.Sum() / dMLX;
#ifdef AXOM_DEBUG
SLIC_WARNING_IF(!(y_min < y_avg + 1e-12 && y_avg < y_max + 1e-12),
axom::fmt::format("Average ({}) is out of bounds [{},{}]: ",
y_avg,
y_min - 1e-12,
y_max + 1e-12));
#endif
Vector z(s);
Vector beta(s);
Vector Mxy(s);
M.Mult(xy, Mxy);
for(int i = 0; i < s; i++)
{
// Some different options for beta:
//beta(i) = 1.0;
beta(i) = ML(i) * x(i);
//beta(i) = ML(i)*(x(i) + 1e-14);
//beta(i) = ML(i);
//beta(i) = Mxy(i);
// The low order flux correction
z(i) = m(i) - ML(i) * x(i) * y_avg;
}
// Make beta_i sum to 1
beta /= beta.Sum();
DenseMatrix F(s);
// Note: indexing F(i,j) where 0 <= j < i < s
for(int i = 1; i < s; i++)
{
for(int j = 0; j < i; j++)
{
F(i, j) = M(i, j) * (xy(i) - xy(j)) + (beta(j) * z(i) - beta(i) * z(j));
}
}
Vector gp(s), gm(s);
gp = 0.0;
gm = 0.0;
for(int i = 1; i < s; i++)
{
for(int j = 0; j < i; j++)
{
double fij = F(i, j);
if(fij >= 0.0)
{
gp(i) += fij;
gm(j) -= fij;
}
else
{
gm(i) += fij;
gp(j) -= fij;
}
}
}
for(int i = 0; i < s; i++)
{
xy(i) = x(i) * y_avg;
}
for(int i = 0; i < s; i++)
{
double mi = ML(i), xyLi = xy(i);
double rp = std::max(mi * (x(i) * y_max - xyLi), 0.0);
double rm = std::min(mi * (x(i) * y_min - xyLi), 0.0);
double sp = gp(i), sm = gm(i);
gp(i) = (rp < sp) ? rp / sp : 1.0;
gm(i) = (rm > sm) ? rm / sm : 1.0;
}
for(int i = 1; i < s; i++)
{
for(int j = 0; j < i; j++)
{
double fij = F(i, j), aij;
if(fij >= 0.0)
{
aij = std::min(gp(i), gm(j));
}
else
{
aij = std::min(gm(i), gp(j));
}
fij *= aij;
xy(i) += fij / ML(i);
xy(j) -= fij / ML(j);
}
}
}
// Note: This function is not currently being used, but might be in the near future
void computeVolumeFractionsIdentity(mfem::DataCollection* dc,
mfem::QuadratureFunction* inout,
const std::string& name)
{
const int order = inout->GetSpace()->GetElementIntRule(0).GetOrder();
mfem::Mesh* mesh = dc->GetMesh();
const int dim = mesh->Dimension();
const int NE = mesh->GetNE();
std::cout << axom::fmt::format("Mesh has dim {} and {} elements", dim, NE)
<< std::endl;
mfem::L2_FECollection* fec =
new mfem::L2_FECollection(order, dim, mfem::BasisType::Positive);
mfem::FiniteElementSpace* fes = new mfem::FiniteElementSpace(mesh, fec);
mfem::GridFunction* volFrac = new mfem::GridFunction(fes);
volFrac->MakeOwner(fec);
dc->RegisterField(name, volFrac);
(*volFrac) = (*inout);
}
} // end namespace shaping
} // end namespace quest
} // end namespace axom
| 28.29156 | 124 | 0.575755 | [
"mesh",
"shape",
"vector"
] |
a05ed80929df3118926679fa32eeff043d66ed3d | 10,477 | cpp | C++ | aws-cpp-sdk-s3-encryption/source/s3-encryption/S3EncryptionClient.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-s3-encryption/source/s3-encryption/S3EncryptionClient.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-s3-encryption/source/s3-encryption/S3EncryptionClient.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T12:02:58.000Z | 2021-11-09T12:02:58.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/s3/model/HeadObjectRequest.h>
#include <aws/core/utils/memory/stl/AWSAllocator.h>
#include <aws/core/utils/logging/LogMacros.h>
// TODO: temporary fix for naming conflicts on Windows.
#ifdef _WIN32
#ifdef GetMessage
#undef GetMessage
#endif
#ifdef GetObject
#undef GetObject
#endif
#endif
#include <aws/s3-encryption/modules/CryptoModule.h>
#include <aws/s3-encryption/S3EncryptionClient.h>
using namespace Aws::Utils::Crypto;
using namespace Aws::Client;
namespace Aws
{
namespace S3Encryption
{
static const char* const ALLOCATION_TAG = "S3EncryptionClient";
using namespace Aws::S3;
using namespace Aws::S3::Model;
S3EncryptionClientBase::S3EncryptionClientBase(const std::shared_ptr<EncryptionMaterials>& encryptionMaterials, const Aws::S3Encryption::CryptoConfiguration& cryptoConfig,
const Client::ClientConfiguration& clientConfiguration) :
m_s3Client(Aws::MakeUnique<S3Client>(ALLOCATION_TAG, clientConfiguration)), m_cryptoModuleFactory(), m_encryptionMaterials(encryptionMaterials), m_cryptoConfig(cryptoConfig)
{
m_s3Client->SetServiceClientName("S3CryptoV1n");
}
S3EncryptionClientBase::S3EncryptionClientBase(const std::shared_ptr<EncryptionMaterials>& encryptionMaterials, const Aws::S3Encryption::CryptoConfiguration& cryptoConfig,
const Auth::AWSCredentials& credentials, const Client::ClientConfiguration& clientConfiguration) :
m_s3Client(Aws::MakeUnique<S3Client>(ALLOCATION_TAG, credentials, clientConfiguration)), m_cryptoModuleFactory(), m_encryptionMaterials(encryptionMaterials), m_cryptoConfig(cryptoConfig)
{
m_s3Client->SetServiceClientName("S3CryptoV1n");
}
S3EncryptionClientBase::S3EncryptionClientBase(const std::shared_ptr<EncryptionMaterials>& encryptionMaterials,
const Aws::S3Encryption::CryptoConfiguration& cryptoConfig, const std::shared_ptr<Auth::AWSCredentialsProvider>& credentialsProvider, const Client::ClientConfiguration& clientConfiguration) :
m_s3Client(Aws::MakeUnique<S3Client>(ALLOCATION_TAG, credentialsProvider, clientConfiguration)), m_cryptoModuleFactory(), m_encryptionMaterials(encryptionMaterials), m_cryptoConfig(cryptoConfig)
{
m_s3Client->SetServiceClientName("S3CryptoV1n");
}
S3EncryptionPutObjectOutcome S3EncryptionClientBase::PutObject(const Aws::S3::Model::PutObjectRequest& request, const Aws::Map<Aws::String, Aws::String>& contextMap) const
{
auto module = m_cryptoModuleFactory.FetchCryptoModule(m_encryptionMaterials, m_cryptoConfig);
auto putObjectFunction = [this](const Aws::S3::Model::PutObjectRequest& putRequest) { return m_s3Client->PutObject(putRequest); };
return module->PutObjectSecurely(request, putObjectFunction, contextMap);
}
S3EncryptionGetObjectOutcome S3EncryptionClientBase::GetObject(const Aws::S3::Model::GetObjectRequest & request) const
{
Aws::S3::Model::HeadObjectRequest headRequest;
headRequest.WithBucket(request.GetBucket());
headRequest.WithKey(request.GetKey());
Aws::S3::Model::HeadObjectOutcome headOutcome = m_s3Client->HeadObject(headRequest);
if (!headOutcome.IsSuccess())
{
AWS_LOGSTREAM_ERROR(ALLOCATION_TAG, "Head Request not successful: "
<< headOutcome.GetError().GetExceptionName() << " : "
<< headOutcome.GetError().GetMessage());
return S3EncryptionGetObjectOutcome(BuildS3EncryptionError(headOutcome.GetError()));
}
auto headMetadata = headOutcome.GetResult().GetMetadata();
auto metadataEnd = headMetadata.end();
CryptoConfiguration decryptionCryptoConfig;
headMetadata.find(CONTENT_KEY_HEADER) != metadataEnd && headMetadata.find(IV_HEADER) != metadataEnd
? decryptionCryptoConfig.SetStorageMethod(StorageMethod::METADATA)
: decryptionCryptoConfig.SetStorageMethod(StorageMethod::INSTRUCTION_FILE);
ContentCryptoMaterial contentCryptoMaterial;
if (decryptionCryptoConfig.GetStorageMethod() == StorageMethod::INSTRUCTION_FILE)
{
GetObjectOutcome instructionOutcome = GetInstructionFileObject(request);
if (!instructionOutcome.IsSuccess())
{
return S3EncryptionGetObjectOutcome(BuildS3EncryptionError(instructionOutcome.GetError()));
}
Handlers::InstructionFileHandler handler;
contentCryptoMaterial = handler.ReadContentCryptoMaterial(instructionOutcome.GetResult());
}
else
{
Handlers::MetadataHandler handler;
contentCryptoMaterial = handler.ReadContentCryptoMaterial(headOutcome.GetResult());
}
// security check
if (request.RangeHasBeenSet() && m_cryptoConfig.GetUnAuthenticatedRangeGet() == RangeGetMode::DISABLED)
{
AWS_LOGSTREAM_ERROR(ALLOCATION_TAG, "Unable to perform range get request: Range get support has been disabled. See https://docs.aws.amazon.com/general/latest/gr/aws_sdk_cryptography.html");
return S3EncryptionGetObjectOutcome(BuildS3EncryptionError(AWSError<S3Errors>(S3Errors::INVALID_ACTION, "RangeGetFailed",
"Unable to perform range get request: Range get support has been disabled. See https://docs.aws.amazon.com/general/latest/gr/aws_sdk_cryptography.html", false/*not retryable*/)));
}
if (m_cryptoConfig.GetSecurityProfile() == SecurityProfile::V2)
{
if (contentCryptoMaterial.GetKeyWrapAlgorithm() != KeyWrapAlgorithm::AES_GCM &&
contentCryptoMaterial.GetKeyWrapAlgorithm() != KeyWrapAlgorithm::KMS_CONTEXT)
{
AWS_LOGSTREAM_ERROR(ALLOCATION_TAG, "The requested object is encrypted with V1 encryption schemas that have been disabled by client configuration securityProfile=V2. Retry with V2_AND_LEGACY enabled or re-encrypt the object");
return S3EncryptionGetObjectOutcome(BuildS3EncryptionError(AWSError<S3Errors>(S3Errors::INVALID_ACTION, "DecryptV1EncryptSchemaFailed",
"The requested object is encrypted with V1 encryption schemas that have been disabled by client configuration securityProfile=V2. Retry with V2_AND_LEGACY enabled or re-encrypt the object.", false/*not retryable*/)));
}
if (contentCryptoMaterial.GetContentCryptoScheme() != ContentCryptoScheme::GCM)
{
AWS_LOGSTREAM_ERROR(ALLOCATION_TAG, "The requested object is encrypted with V1 encryption schemas that have been disabled by client configuration securityProfile=V2. Retry with V2_AND_LEGACY enabled or re-encrypt the object");
return S3EncryptionGetObjectOutcome(BuildS3EncryptionError(AWSError<S3Errors>(S3Errors::INVALID_ACTION, "DecryptV1EncryptSchemaFailed",
"The requested object is encrypted with V1 encryption schemas that have been disabled by client configuration securityProfile=V2. Retry with V2_AND_LEGACY enabled or re-encrypt the object.", false/*not retryable*/)));
}
}
if (contentCryptoMaterial.GetContentCryptoScheme() == ContentCryptoScheme::CBC)
{
decryptionCryptoConfig.SetCryptoMode(CryptoMode::ENCRYPTION_ONLY);
}
else if (m_cryptoConfig.GetCryptoMode() != CryptoMode::STRICT_AUTHENTICATED_ENCRYPTION &&
contentCryptoMaterial.GetContentCryptoScheme() == ContentCryptoScheme::GCM)
{
decryptionCryptoConfig.SetCryptoMode(CryptoMode::AUTHENTICATED_ENCRYPTION);
}
else
{
assert(request.GetRange().empty());
decryptionCryptoConfig.SetCryptoMode(CryptoMode::STRICT_AUTHENTICATED_ENCRYPTION);
}
auto module = m_cryptoModuleFactory.FetchCryptoModule(m_encryptionMaterials, decryptionCryptoConfig);
auto getObjectFunction = [this](const Aws::S3::Model::GetObjectRequest& getRequest) { return m_s3Client->GetObject(getRequest); };
return module->GetObjectSecurely(request, headOutcome.GetResult(), contentCryptoMaterial, getObjectFunction);
}
Aws::S3::Model::GetObjectOutcome S3EncryptionClientBase::GetInstructionFileObject(const Aws::S3::Model::GetObjectRequest & originalGetRequest) const
{
GetObjectRequest instructionFileRequest;
instructionFileRequest.SetKey(originalGetRequest.GetKey() + Handlers::DEFAULT_INSTRUCTION_FILE_SUFFIX);
instructionFileRequest.SetBucket(originalGetRequest.GetBucket());
GetObjectOutcome instructionOutcome = m_s3Client->GetObject(instructionFileRequest);
if (!instructionOutcome.IsSuccess())
{
AWS_LOGSTREAM_ERROR(ALLOCATION_TAG, "Instruction file get operation not successful: "
<< instructionOutcome.GetError().GetExceptionName() << " : "
<< instructionOutcome.GetError().GetMessage());
return instructionOutcome;
}
return instructionOutcome;
}
void S3EncryptionClientV2::Init(const Aws::S3Encryption::CryptoConfigurationV2& cryptoConfig)
{
m_cryptoConfig.SetSecurityProfile(cryptoConfig.GetSecurityProfile());
m_cryptoConfig.SetUnAuthenticatedRangeGet(cryptoConfig.GetUnAuthenticatedRangeGet());
m_s3Client->SetServiceClientName("S3CryptoV2");
if (cryptoConfig.GetSecurityProfile() == SecurityProfile::V2_AND_LEGACY)
{
AWS_LOGSTREAM_WARN(ALLOCATION_TAG, "The S3 Encryption Client is configured to read encrypted data with legacy encryption modes. If you don't have objects encrypted with these legacy modes, you should disable support for them to enhance security. See https://docs.aws.amazon.com/general/latest/gr/aws_sdk_cryptography.html");
}
}
}
}
| 60.212644 | 340 | 0.69371 | [
"object",
"model"
] |
a0635f87404895775aa86ba97aee0b41b64df057 | 1,067 | cpp | C++ | cpp/0200-0299/257. Binary Tree Paths/solution.cpp | RapDoodle/LeetCode-Solutions | 6f14b7621bc6db12303be7f85508f3a5b2c2c30a | [
"MIT"
] | null | null | null | cpp/0200-0299/257. Binary Tree Paths/solution.cpp | RapDoodle/LeetCode-Solutions | 6f14b7621bc6db12303be7f85508f3a5b2c2c30a | [
"MIT"
] | null | null | null | cpp/0200-0299/257. Binary Tree Paths/solution.cpp | RapDoodle/LeetCode-Solutions | 6f14b7621bc6db12303be7f85508f3a5b2c2c30a | [
"MIT"
] | null | null | null | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> ans;
dfs(root, "", ans);
return ans;
}
private:
void dfs(TreeNode* root, string s, vector<string>& ans) {
if (root == nullptr)
return;
// Append root.val to string
s += to_string(root->val);
// When reached the leaf node, append and return
if (root->left == nullptr && root->right == nullptr) {
ans.push_back(s);
return;
}
// Not a leaf node, divide the string s into two
s += "->";
dfs(root->left, s, ans);
dfs(root->right, s, ans);
}
}; | 28.078947 | 93 | 0.523899 | [
"vector"
] |
a066c38acb52b7c02328d713d014d904a807bc44 | 12,802 | cpp | C++ | vlc_linux/vlc-3.0.16/modules/gui/skins2/x11/x11_graphics.cpp | Brook1711/biubiu_Qt6 | 5c4d22a1d1beef63bc6c7738dce6c477c4642803 | [
"MIT"
] | null | null | null | vlc_linux/vlc-3.0.16/modules/gui/skins2/x11/x11_graphics.cpp | Brook1711/biubiu_Qt6 | 5c4d22a1d1beef63bc6c7738dce6c477c4642803 | [
"MIT"
] | null | null | null | vlc_linux/vlc-3.0.16/modules/gui/skins2/x11/x11_graphics.cpp | Brook1711/biubiu_Qt6 | 5c4d22a1d1beef63bc6c7738dce6c477c4642803 | [
"MIT"
] | null | null | null | /*****************************************************************************
* x11_graphics.cpp
*****************************************************************************
* Copyright (C) 2003 the VideoLAN team
* $Id: b6a34f2bdb3b0ba766a710eed37db5b96bc6a249 $
*
* Authors: Cyril Deguet <asmax@via.ecp.fr>
* Olivier Teulière <ipkiss@via.ecp.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef X11_SKINS
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/extensions/shape.h>
#include "x11_display.hpp"
#include "x11_graphics.hpp"
#include "x11_window.hpp"
#include "../src/generic_bitmap.hpp"
#include "../utils/position.hpp"
X11Graphics::X11Graphics( intf_thread_t *pIntf, X11Display &rDisplay,
int width, int height ):
OSGraphics( pIntf ), m_rDisplay( rDisplay ), m_width( width ),
m_height( height )
{
// Get the display paramaters
int screen = DefaultScreen( XDISPLAY );
int depth = DefaultDepth( XDISPLAY, screen );
// X11 doesn't accept that !
if( width == 0 || height == 0 )
{
// Avoid a X11 Bad Value error
width = height = 1;
msg_Err( getIntf(), "invalid image size (null width or height)" );
}
// Create a pixmap
m_pixmap = XCreatePixmap( XDISPLAY, DefaultRootWindow( XDISPLAY ),
width, height, depth);
// Create the transparency mask (everything is transparent initially)
m_mask = XCreateRegion();
// Create a Graphics Context that does not generate GraphicsExpose events
XGCValues xgcvalues;
xgcvalues.graphics_exposures = False;
m_gc = XCreateGC( XDISPLAY, m_pixmap, GCGraphicsExposures, &xgcvalues );
}
X11Graphics::~X11Graphics()
{
XFreeGC( XDISPLAY, m_gc );
XDestroyRegion( m_mask );
XFreePixmap( XDISPLAY, m_pixmap );
}
void X11Graphics::clear( int xDest, int yDest, int width, int height )
{
if( width <= 0 || height <= 0 )
{
// Clear the transparency mask completely
XDestroyRegion( m_mask );
m_mask = XCreateRegion();
}
else
{
// remove this area from the mask
XRectangle rect;
rect.x = xDest;
rect.y = yDest;
rect.width = width;
rect.height = height;
Region regMask = XCreateRegion();
XUnionRectWithRegion( &rect, regMask, regMask );
XSubtractRegion( m_mask, regMask, m_mask );
XDestroyRegion( regMask );
}
}
void X11Graphics::drawGraphics( const OSGraphics &rGraphics, int xSrc,
int ySrc, int xDest, int yDest, int width,
int height )
{
const X11Graphics& rGraph = (X11Graphics&)rGraphics;
// check and adapt to source if needed
if( !checkBoundaries( 0, 0, rGraph.getWidth(), rGraph.getHeight(),
xSrc, ySrc, width, height ) )
{
msg_Err( getIntf(), "nothing to draw from graphics source" );
return;
}
// check destination
if( !checkBoundaries( 0, 0, m_width, m_height,
xDest, yDest, width, height ) )
{
msg_Err( getIntf(), "out of reach destination! pls, debug your skin" );
return;
}
// Source drawable
Drawable src = rGraph.getDrawable();
// Create the mask for transparency
Region voidMask = XCreateRegion();
XRectangle rect;
rect.x = xSrc;
rect.y = ySrc;
rect.width = width;
rect.height = height;
Region clipMask = XCreateRegion();
XUnionRectWithRegion( &rect, voidMask, clipMask );
Region mask = XCreateRegion();
XIntersectRegion( rGraph.getMask(), clipMask, mask );
XDestroyRegion( clipMask );
XDestroyRegion( voidMask );
XOffsetRegion( mask, xDest - xSrc, yDest - ySrc );
// Copy the pixmap
XSetRegion( XDISPLAY, m_gc, mask );
XCopyArea( XDISPLAY, src, m_pixmap, m_gc, xSrc, ySrc, width, height,
xDest, yDest );
// Add the source mask to the mask of the graphics
Region newMask = XCreateRegion();
XUnionRegion( m_mask, mask, newMask );
XDestroyRegion( mask );
XDestroyRegion( m_mask );
m_mask = newMask;
}
void X11Graphics::drawBitmap( const GenericBitmap &rBitmap, int xSrc,
int ySrc, int xDest, int yDest, int width,
int height, bool blend )
{
// check and adapt to source if needed
if( !checkBoundaries( 0, 0, rBitmap.getWidth(), rBitmap.getHeight(),
xSrc, ySrc, width, height ) )
{
msg_Err( getIntf(), "empty source! pls, debug your skin" );
return;
}
// check destination
if( !checkBoundaries( 0, 0, m_width, m_height,
xDest, yDest, width, height ) )
{
msg_Err( getIntf(), "out of reach destination! pls, debug your skin" );
return;
}
// Get a buffer on the image data
uint8_t *pBmpData = rBitmap.getData();
if( pBmpData == NULL )
{
// Nothing to draw
return;
}
// Force pending XCopyArea to be sent to the X Server
// before issuing an XGetImage.
XSync( XDISPLAY, False );
// Get the image from the pixmap
XImage *pImage = XGetImage( XDISPLAY, m_pixmap, xDest, yDest, width,
height, AllPlanes, ZPixmap );
if( pImage == NULL )
{
msg_Dbg( getIntf(), "XGetImage returned NULL" );
return;
}
char *pData = pImage->data;
// Get the padding of this image
int pad = pImage->bitmap_pad >> 3;
int shift = ( pad - ( (width * XPIXELSIZE) % pad ) ) % pad;
// Mask for transparency
Region mask = XCreateRegion();
// Get a pointer on the right X11Display::makePixel method
X11Display::MakePixelFunc_t makePixelFunc = ( blend ?
m_rDisplay.getBlendPixel() : m_rDisplay.getPutPixel() );
// Skip the first lines of the image
pBmpData += 4 * ySrc * rBitmap.getWidth();
// Copy the bitmap on the image and compute the mask
for( int y = 0; y < height; y++ )
{
// Skip uninteresting bytes at the beginning of the line
pBmpData += 4 * xSrc;
// Flag to say whether the previous pixel on the line was visible
bool wasVisible = false;
// Beginning of the current visible segment on the line
int visibleSegmentStart = 0;
for( int x = 0; x < width; x++ )
{
uint8_t b = *(pBmpData++);
uint8_t g = *(pBmpData++);
uint8_t r = *(pBmpData++);
uint8_t a = *(pBmpData++);
// Draw the pixel
(m_rDisplay.*makePixelFunc)( (uint8_t*)pData, r, g, b, a );
pData += XPIXELSIZE;
if( a > 0 )
{
// Pixel is visible
if( ! wasVisible )
{
// Beginning of a visible segment
visibleSegmentStart = x;
}
wasVisible = true;
}
else
{
// Pixel is transparent
if( wasVisible )
{
// End of a visible segment: add it to the mask
addHSegmentInRegion( mask, visibleSegmentStart, x, y );
}
wasVisible = false;
}
}
if( wasVisible )
{
// End of a visible segment: add it to the mask
addHSegmentInRegion( mask, visibleSegmentStart, width, y );
}
pData += shift;
// Skip uninteresting bytes at the end of the line
pBmpData += 4 * (rBitmap.getWidth() - width - xSrc);
}
// Apply the mask to the graphics context
XOffsetRegion( mask, xDest, yDest );
XSetRegion( XDISPLAY, m_gc, mask );
// Copy the image on the pixmap
XPutImage( XDISPLAY, m_pixmap, m_gc, pImage, 0, 0, xDest, yDest, width,
height);
XDestroyImage( pImage );
// Add the bitmap mask to the global graphics mask
Region newMask = XCreateRegion();
XUnionRegion( mask, m_mask, newMask );
XDestroyRegion( m_mask );
m_mask = newMask;
XDestroyRegion( mask );
}
void X11Graphics::fillRect( int left, int top, int width, int height,
uint32_t color )
{
// Update the mask with the rectangle area
Region newMask = XCreateRegion();
XRectangle rect;
rect.x = left;
rect.y = top;
rect.width = width;
rect.height = height;
XUnionRectWithRegion( &rect, m_mask, newMask );
XDestroyRegion( m_mask );
m_mask = newMask;
// Draw the rectangle
XGCValues gcVal;
gcVal.foreground = m_rDisplay.getPixelValue( color >> 16, color >> 8, color );
XChangeGC( XDISPLAY, m_gc, GCForeground, &gcVal );
XSetRegion( XDISPLAY, m_gc, m_mask );
XFillRectangle( XDISPLAY, m_pixmap, m_gc, left, top, width, height );
}
void X11Graphics::drawRect( int left, int top, int width, int height,
uint32_t color )
{
// Update the mask with the rectangle
addHSegmentInRegion( m_mask, left, left + width, top );
addHSegmentInRegion( m_mask, left, left + width, top + height );
addVSegmentInRegion( m_mask, top, top + height, left );
addVSegmentInRegion( m_mask, top, top + height, left + width );
// Draw the rectangle
XGCValues gcVal;
gcVal.foreground = m_rDisplay.getPixelValue( color >> 16, color >> 8, color );
XChangeGC( XDISPLAY, m_gc, GCForeground, &gcVal );
XSetRegion( XDISPLAY, m_gc, m_mask );
XDrawRectangle( XDISPLAY, m_pixmap, m_gc, left, top, width - 1, height - 1 );
}
void X11Graphics::applyMaskToWindow( OSWindow &rWindow )
{
// Get the target window
Window win = ((X11Window&)rWindow).getDrawable();
// ensure the window size is right
XResizeWindow( XDISPLAY, win, m_width, m_height );
// Change the shape of the window
XShapeCombineRegion( XDISPLAY, win, ShapeBounding, 0, 0, m_mask,
ShapeSet );
}
void X11Graphics::copyToWindow( OSWindow &rWindow, int xSrc, int ySrc,
int width, int height, int xDest, int yDest )
{
// Destination window
Drawable dest = ((X11Window&)rWindow).getDrawable();
XCopyArea( XDISPLAY, m_pixmap, dest, XGC, xSrc, ySrc, width, height,
xDest, yDest );
}
bool X11Graphics::hit( int x, int y ) const
{
return XPointInRegion( m_mask, x, y );
}
inline void X11Graphics::addHSegmentInRegion( Region &rMask, int xStart,
int xEnd, int y )
{
XRectangle rect;
rect.x = xStart;
rect.y = y;
rect.width = xEnd - xStart;
rect.height = 1;
Region newMask = XCreateRegion();
XUnionRectWithRegion( &rect, rMask, newMask );
XDestroyRegion( rMask );
rMask = newMask;
}
inline void X11Graphics::addVSegmentInRegion( Region &rMask, int yStart,
int yEnd, int x )
{
XRectangle rect;
rect.x = x;
rect.y = yStart;
rect.width = 1;
rect.height = yEnd - yStart;
Region newMask = XCreateRegion();
XUnionRectWithRegion( &rect, rMask, newMask );
XDestroyRegion( rMask );
rMask = newMask;
}
bool X11Graphics::checkBoundaries( int x_src, int y_src,
int w_src, int h_src,
int& x_target, int& y_target,
int& w_target, int& h_target )
{
// set valid width and height
w_target = (w_target > 0) ? w_target : w_src;
h_target = (h_target > 0) ? h_target : h_src;
// clip source if needed
rect srcRegion( x_src, y_src, w_src, h_src );
rect targetRegion( x_target, y_target, w_target, h_target );
rect inter;
if( rect::intersect( srcRegion, targetRegion, &inter ) )
{
x_target = inter.x;
y_target = inter.y;
w_target = inter.width;
h_target = inter.height;
return true;
}
return false;
}
#endif
| 31.688119 | 82 | 0.584284 | [
"shape"
] |
a066c85c6522a5e5e794e119192b8d27a9daf7db | 10,413 | cpp | C++ | Editor/src/Panels/FoldersPanel.cpp | Stolkerve/RoraymaEngine | e8dcddcb6679bb7417b22eaec1d5beb9c0c82cc2 | [
"Apache-2.0"
] | null | null | null | Editor/src/Panels/FoldersPanel.cpp | Stolkerve/RoraymaEngine | e8dcddcb6679bb7417b22eaec1d5beb9c0c82cc2 | [
"Apache-2.0"
] | null | null | null | Editor/src/Panels/FoldersPanel.cpp | Stolkerve/RoraymaEngine | e8dcddcb6679bb7417b22eaec1d5beb9c0c82cc2 | [
"Apache-2.0"
] | null | null | null |
#include "FoldersPanel.hh"
#include "../CustomImGuiWidgets.hh"
#include <RoraymaEngine/Utils/FileSystem.hh>
#include <algorithm>
#include <cstdio>
#include <fstream>
#include <string>
namespace rym
{
// TODO: std::filesystem::is_directory is so expensive. Use only for one call function, not inside loops
void FoldersPanel::IterateNodeFolder(const std::shared_ptr<NodeFolder>& node)
{
auto capacity = (std::size_t)std::distance(
std::filesystem::directory_iterator{ node->Data.Path },
std::filesystem::directory_iterator{});
//node->Reserve(capacity);
size_t counter = 0;
// Look for a new file
for (const auto& entry : std::filesystem::directory_iterator(node->Data.Path,
std::filesystem::directory_options::skip_permission_denied))
{
// Ignore the existing files
auto it = std::find_if(node->begin(), node->end(), [&entry](const std::shared_ptr<NodeFolder>& n) {
return n->Data.Path == entry.path();
});
if (it != node->end())
{
// files ignored
}
else
{
node->AddChild(std::make_shared<NodeFolder>());
auto& last = node->Back();
last->Data.Path = entry.path();
last->Data.isDirectory = std::filesystem::is_directory(last->Data.Path);
last->Parent = node;
}
counter++;
}
// Deleted deleted files (Outsize of this context)
auto it = std::find_if(node->begin(), node->end(), [&](const std::shared_ptr<NodeFolder>& n) {
return !std::filesystem::exists(n->Data.Path);
});
if (it != node->end())
{
node->DeleteChild(it);
}
// Deleted files (Peticion of the user)
if (node->Data.NeedDelete)
{
//auto de = node->Data.Path == m_DeletedItem.FilePath
auto it = std::find_if(node->begin(), node->end(), [&](const std::shared_ptr<NodeFolder>& n) {
return (n->Data.Path == m_DeletedItem.FilePath);
});
if (it != node->end())
{
auto& a = *it;
node->DeleteChild(it);
}
node->Data.NeedDelete = false;
}
std::stable_partition(node->begin(), node->end(), [](const std::shared_ptr<NodeFolder>& n1) {
return n1->Data.isDirectory;
});
node->Data.NeedUpdate = false;
}
FoldersPanel::FoldersPanel()
{
// Init extencions map
m_Extencions[".rym"] = Extencions::rym;
m_Extencions[".glsl"] = Extencions::code;
m_Extencions[".h"] = Extencions::code;
m_Extencions[".h++"] = Extencions::code;
m_Extencions[".hh"] = Extencions::code;
m_Extencions[".hpp"] = Extencions::code;
m_Extencions[".cpp"] = Extencions::code;
m_Extencions[".cxx"] = Extencions::code;
m_Extencions[".inl"] = Extencions::code;
m_Extencions[".py"] = Extencions::code;
m_Extencions[".pyd"] = Extencions::code;
m_Extencions[".cs"] = Extencions::code;
m_Extencions[".sh"] = Extencions::code;
m_Extencions[".bat"] = Extencions::code;
m_Extencions[".lua"] = Extencions::code;
m_Extencions[".as"] = Extencions::code;
m_Extencions[".png"] = Extencions::image;
m_Extencions[".jpg"] = Extencions::image;
m_Extencions[".jpeg"] = Extencions::image;
m_Extencions[".bmp"] = Extencions::image;
m_Extencions[".mp3"] = Extencions::music;
m_Extencions[".ogg"] = Extencions::music;
m_Extencions[".git"] = Extencions::git;
m_Extencions[".txt"] = Extencions::text;
m_Extencions[".yaml"] = Extencions::text;
m_Extencions[".ini"] = Extencions::text;
m_Extencions[".json"] = Extencions::text;
m_Extencions[".log"] = Extencions::text;
m_Root = std::make_shared<NodeFolder>();
m_Root->Data.Path = FileSystem::GetWorkSpacePath();
m_Root->AddChild(std::make_shared<NodeFolder>());
auto& last = m_Root->Back();
last->Data.Path = FileSystem::GetWorkSpacePath();
last->Data.isDirectory = true;
last->Parent = m_Root;
IterateNodeFolder(last);
}
std::string FoldersPanel::IconFilter(const std::filesystem::path& path)
{
Extencions ex;
const auto it = m_Extencions.find(path.extension().string());
if (it != m_Extencions.end())
ex = m_Extencions[path.extension().string()];
else
ex = Extencions::unknow;
switch (ex)
{
case Extencions::code: return ICON_FA_FILE_CODE; break;
case Extencions::image: return ICON_FA_FILE_IMAGE; break;
case Extencions::git: return ICON_FA_CODE_BRANCH; break;
case Extencions::music: return ICON_FA_FILE_AUDIO; break;
case Extencions::rym: return ICON_FA_GAMEPAD; break;
case Extencions::text: return ICON_FA_FILE_SIGNATURE; break;
default: return ICON_FA_FILE_ALT; break;
}
}
/*
make a enum with the extencion casted to int
*/
void FoldersPanel::Render()
{
ImGui::Begin(ICON_FA_FOLDER_OPEN" Folders Panel");
int i = 0;
for (auto& c : *m_Root)
{
DrawNode(c, i);
i++;
}
ImGui::End();
}
void FoldersPanel::Refresh()
{
IterateNodeFolder(m_Root->Back());
}
void FoldersPanel::DrawNode(std::shared_ptr<NodeFolder>& node, int id)
{
ImGui::PushID(&node);
static const std::filesystem::path* droppedItem = nullptr;
static const std::filesystem::path* draggedItem = nullptr;
const std::string sfilename = node->Data.Path.filename().string();
const std::string folderName(ICON_FA_FOLDER" "+ sfilename);
const std::string fileName(IconFilter(sfilename) + " " + sfilename);
const ImGuiTreeNodeFlags flags =
(m_SelectedItem == node.get() ? ImGuiTreeNodeFlags_Selected : 0) |
(!node->Data.isDirectory ? ImGuiTreeNodeFlags_Leaf : 0) |
ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_FramePadding;
bool opened = ImGui::TreeNodeEx((void*)id, flags,
!node->Data.isDirectory ?
fileName.c_str() : folderName.c_str());
if (ImGui::IsItemToggledOpen() && node->Data.isDirectory)
{
//RYM_INFO(node->Data.Path.filename().string());
if (node->Data.Open)
{
node->Data.Open = false;
}
else
{
node->Data.Open = true;
node->Data.NeedUpdate = true;
}
}
if (ImGui::IsItemClicked())
{
m_SelectedItem = node.get();
}
if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
{
m_HoveredItem = node.get();
if (ImGui::IsMouseDoubleClicked(0))
{
if (m_HoveredItem->Data.Path.extension() == ".rym")
{
m_ChangeSceneFunc(m_HoveredItem->Data.Path.string());
RYM_INFO("Scene xd {}", m_HoveredItem->Data.Path.string());
}
}
}
ImGui::PushID(id);
if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_SourceNoDisableHover))
{
ImGui::SetDragDropPayload("FOLDDERS_PANEL", &m_SelectedItem->Data, sizeof(FoldersData));
const auto& hoverPath = m_HoveredItem->Data.Path;
const auto& itemPath = m_SelectedItem->Data.Path;
std::string text("Moveing ");
if (m_HoveredItem->Data.isDirectory)
{
text.append(itemPath.filename().string() + " to ");
text.append(hoverPath.filename().string() + " folder");
}
else
{
text.append(itemPath.filename().string() + " is not allow here");
}
ImGui::Text(text.c_str());
ImGui::EndDragDropSource();
}
if (ImGui::BeginDragDropTarget() && m_HoveredItem)
{
if (m_HoveredItem->Data.isDirectory && (m_SelectedItem->Data.Path.parent_path() != m_HoveredItem->Data.Path))
{
if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("FOLDDERS_PANEL"))
{
// TODO: use payload, now its work
if (FileSystem::Move(m_SelectedItem->Data.Path, m_HoveredItem->Data.Path))
{
m_HoveredItem->Data.NeedUpdate = true;
auto& selectedParent = m_SelectedItem->Parent;
selectedParent->Data.NeedUpdate = true;
selectedParent->Data.NeedDelete = true;
//m_Root->Data.NeedUpdate = true;
//m_DeletedItem.ParentPath = draggedItem->parent_path();
m_DeletedItem.FilePath = m_SelectedItem->Data.Path;
}
}
ImGui::EndDragDropTarget();
}
}
ImGui::PopID();
if (ImGui::BeginPopupContextItem())
{
// the cursor can be outsize of the original hovered item
static NodeFolder* lastHovered;
static bool isEdited = false;
static bool cancelDelete = false;
static bool okDelete = false;
static bool askTrash = false;
lastHovered = m_HoveredItem;
//RYM_INFO(lastHovered->Path.filename().string());
if (lastHovered->Data.Path != FileSystem::GetWorkSpacePath())
{
//ImGui::PushItemWidth(ImGui::CalcItemWidth() / 2);
if (ImGui::Selectable("New folder", false, ImGuiSelectableFlags_DontClosePopups))
{
ImGui::OpenPopup("Morelater");
}
if (ImGui::Selectable("New file", false, ImGuiSelectableFlags_DontClosePopups))
{
ImGui::OpenPopup("Morelater");
}
bool lok;
CreateModalOk("Morelater", "More later", &lok);
if (ImGui::Selectable("Move to trash", false, ImGuiSelectableFlags_DontClosePopups))
{
if (lastHovered->Data.Open)
{
ImGui::OpenPopup("CloseFolder");
}
else
ImGui::OpenPopup("Delete?");
}
static bool ok = false;
CreateModalOk("CloseFolder", "Please close the target folder", &ok);
CreateModalOkCancel("Delete?", "All thoses files going to be move to the recicle bin\n\n", &okDelete, &cancelDelete);
if (okDelete)
{
lastHovered->Data.Open = false;
auto& parent = lastHovered->Parent;
parent->Data.NeedDelete = true;
parent->Data.NeedUpdate = true;
m_DeletedItem.FilePath = lastHovered->Data.Path;
FileSystem::MoveToReciclyBin(m_DeletedItem.FilePath);
okDelete = false;
ImGui::CloseCurrentPopup();
}
/* Rename */
char buffer[35];
std::strcpy(buffer, lastHovered->Data.Path.filename().string().c_str());
if (ImGui::InputText("###name", buffer, sizeof(buffer), ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_CharsNoBlank))
{
RYM_INFO("Nuevo nombre: {}", std::string(buffer));
auto v = std::getenv("HOME");
if(v)
RYM_INFO(std::string(v));
//m_EntitySelected->Tag = std::string(buffer);
auto newName = (lastHovered->Data.Path.parent_path() / buffer);
bool renameSucces = std::rename(lastHovered->Data.Path.string().c_str(),
newName.string().c_str());
lastHovered->Data.Path = newName;
ImGui::CloseCurrentPopup();
}
//ImGui::PopItemWidth();
}
ImGui::EndPopup();
}
if (node->Data.Open)
{
int id = 0;
for (auto& c : *node)
{
DrawNode(c, id);
id++;
}
if (node->Data.NeedUpdate || timer >= 150.0f) {
IterateNodeFolder(node);
timer = 0.f;
}
}
if (opened)
ImGui::TreePop();
ImGui::PopID();
timer += 1.f / 60.f;
}
};
| 28.143243 | 133 | 0.661865 | [
"render"
] |
a067e89a515a8236924fa866361d495c087cc695 | 5,525 | cpp | C++ | tests/easyzip_test.cpp | winsoft666/easyzip | 967b8977cfd1bd2fb15c9507b928fbfc49e73162 | [
"MIT"
] | 3 | 2021-04-07T02:34:13.000Z | 2022-01-20T02:39:27.000Z | tests/easyzip_test.cpp | winsoft666/easyzip | 967b8977cfd1bd2fb15c9507b928fbfc49e73162 | [
"MIT"
] | null | null | null | tests/easyzip_test.cpp | winsoft666/easyzip | 967b8977cfd1bd2fb15c9507b928fbfc49e73162 | [
"MIT"
] | 2 | 2021-09-28T09:53:34.000Z | 2021-12-08T13:27:39.000Z | #include <fstream>
#include <iostream>
#include <map>
#include <ostream>
#include <string>
#include <vector>
#include "gtest/gtest.h"
#include "test_tools.h"
#include "easyzip/easyzip.h"
using namespace easyzip;
TEST(StringZipTest, Test1) {
if (IsFileExists(L"zip测试.zip"))
std::remove("zip测试.zip");
Zipper zipper(L"zip测试.zip");
std::stringstream strdata;
strdata << "test string data compression";
zipper.add(strdata, L"strdata");
zipper.close();
Unzipper unzipper(L"zip测试.zip");
EXPECT_TRUE(unzipper.entries().size() == 1);
EXPECT_TRUE(unzipper.entries().front().name == L"strdata");
unzipper.extract();
EXPECT_TRUE(IsFileExists(L"strdata"));
std::ifstream testfile("strdata");
EXPECT_TRUE(testfile.good());
std::string test((std::istreambuf_iterator<char>(testfile)), std::istreambuf_iterator<char>());
testfile.close();
EXPECT_TRUE(test == "test string data compression");
std::map<std::wstring, std::wstring> alt_names;
alt_names[L"strdata"] = L"alternative_strdata.dat";
unzipper.extract(L"", alt_names);
EXPECT_TRUE(IsFileExists(L"alternative_strdata.dat"));
std::ifstream testfile2("alternative_strdata.dat");
EXPECT_TRUE(testfile2.good());
std::string test2((std::istreambuf_iterator<char>(testfile2)), std::istreambuf_iterator<char>());
testfile2.close();
EXPECT_TRUE(test2 == "test string data compression");
EXPECT_TRUE(false == unzipper.extractEntry(L"fake.dat"));
unzipper.close();
std::remove("strdata");
std::remove("alternative_strdata.dat");
std::remove("zip测试.zip");
}
TEST(FileZipTest, Test1) {
if (IsFileExists(L"zip测试.zip"))
std::remove("zip测试.zip");
Zipper zipper(L"zip测试.zip");
std::ofstream test1("test文件1.txt");
test1 << "test file compression";
test1.flush();
test1.close();
std::ifstream test1stream("test文件1.txt");
// add test文件1.txt
zipper.add(test1stream, L"test文件1.txt");
test1stream.close();
zipper.close();
std::remove("test文件1.txt");
Unzipper unzipper(L"zip测试.zip");
std::vector<ZipEntry> entries = unzipper.entries();
EXPECT_TRUE(entries.size() == 1);
EXPECT_TRUE(entries.front().name == L"test文件1.txt");
unzipper.extractEntry(L"test文件1.txt");
// due to sections forking or creating different stacks we need to make
// sure the local instance is closed to prevent mixing the closing when
// both instances are freed at the end of the scope
unzipper.close();
EXPECT_TRUE(IsFileExists(L"test文件1.txt"));
std::ifstream testfile("test文件1.txt");
EXPECT_TRUE(testfile.good());
std::string test((std::istreambuf_iterator<char>(testfile)), std::istreambuf_iterator<char>());
testfile.close();
EXPECT_TRUE(test == "test file compression");
std::ofstream test2("test文件2.dat");
test2 << "other data to compression test";
test2.flush();
test2.close();
std::ifstream test2stream("test文件2.dat");
zipper.open();
// add 测试Folder/test文件2.dat
zipper.add(test2stream, L"测试Folder/test文件2.dat");
zipper.close();
test2stream.close();
std::remove("test文件2.dat");
do {
Unzipper unzipper(L"zip测试.zip");
EXPECT_TRUE(unzipper.entries().size() == 2);
EXPECT_TRUE(unzipper.entries().front().name == L"test文件1.txt");
EXPECT_TRUE(unzipper.entries()[1].name == L"测试Folder/test文件2.dat");
unzipper.extract();
unzipper.close();
EXPECT_TRUE(IsFileExists(L"测试Folder/test文件2.dat"));
std::ifstream testfile("测试Folder/test文件2.dat");
EXPECT_TRUE(testfile.good());
std::string file_content((std::istreambuf_iterator<char>(testfile)),
std::istreambuf_iterator<char>());
testfile.close();
EXPECT_TRUE(file_content == "other data to compression test");
MakeDir(GetCurrentPath() + L"/测试Files/子文件夹");
std::ofstream test("测试Files/test文件1.txt");
test << "test file compression";
test.flush();
test.close();
std::ofstream test1("测试Files/test2.pdf");
test1 << "test file compression";
test1.flush();
test1.close();
std::ofstream test2("测试Files/子文件夹/test-sub.txt");
test2 << "test file compression";
test2.flush();
test2.close();
zipper.open();
// add 测试Files folder
zipper.add(L"测试Files\\");
zipper.close();
do {
Unzipper unzipper(L"zip测试.zip");
EXPECT_TRUE(unzipper.entries().size() == 5);
MakeDir(GetCurrentPath() + L"/新建文件夹");
unzipper.extract(GetCurrentPath() + L"/新建文件夹");
std::vector<std::wstring> files = GetFilesFromDir(GetCurrentPath() + L"/新建文件夹");
EXPECT_TRUE(IsFileExists(L"新建文件夹/测试Files/test文件1.txt"));
EXPECT_TRUE(IsFileExists(L"新建文件夹/测试Files/test2.pdf"));
EXPECT_TRUE(IsFileExists(L"新建文件夹/测试Files/子文件夹/test-sub.txt"));
unzipper.close();
} while (false);
RemoveDir(L"测试Folder");
RemoveDir(L"测试Files");
RemoveDir(L"新建文件夹");
std::remove("test文件1.txt");
} while (false);
std::remove("zip测试.zip");
}
TEST(MemoryZipTest, Test1) {
std::stringstream output;
Zipper zipper(output);
std::stringstream strdata;
strdata << "test string data compression";
EXPECT_TRUE(zipper.add(strdata, L"str"));
zipper.close();
std::stringstream strdata2;
Unzipper unzipper(output);
EXPECT_TRUE(unzipper.extractEntryToStream(L"str", strdata2));
unzipper.close();
EXPECT_TRUE(strdata.str() == strdata2.str());
}
//TEST(FileUnzipTest, Test1) {
// std::string s = "D:\\新建文件夹\\GogoWallapperResource\\937\\2000133704.zip";
// Unzipper unzipper(s);
// if (!unzipper.extract("D:\\123\\")) {
//
// }
//} | 26.184834 | 99 | 0.675294 | [
"vector"
] |
a06b8bd7e3faa8d491ebff2c8fcf5e806a7d305c | 2,661 | cpp | C++ | src/constants.cpp | deba-cyber/PES_Catecholate | bc71821f2ac277cb3e2c4c3146d1297b3e851b85 | [
"MIT"
] | null | null | null | src/constants.cpp | deba-cyber/PES_Catecholate | bc71821f2ac277cb3e2c4c3146d1297b3e851b85 | [
"MIT"
] | null | null | null | src/constants.cpp | deba-cyber/PES_Catecholate | bc71821f2ac277cb3e2c4c3146d1297b3e851b85 | [
"MIT"
] | null | null | null |
# include <PES_catecholate/constants.hpp>
# include <iosfwd>
# include <vector>
# include <string>
namespace PES_PARAMS {
extern const std::string modeflagfile = "../input_data/mode_flag_TS";
extern const std::string ref_ts_file = "../input_data/ref_com_rmv_TS";
extern const std::string ref_eqm_file = "../input_data/ref_com_rmv_eqm";
extern const std::string l_TS_file = "../input_data/catecholate_TS_l-matrix";
extern const std::string eqm_rot_mat_file = "../input_data/Eckart_mat_eqm";
extern const std::string l_eqm_file = "../input_data/l_eqm_muw_rnrm";
extern const std::string massfile = "../input_data/mass_sqrt";
extern const std::string ratio_ts_file = "../input_data/ratio_TS";
extern const std::string B_vect_file = "../input_data/Q_fitparams_";
extern const std::string freq_eqm_file = "../input_data/freq_eqm";
extern const std::string diabat_quad_coeff_file = "../input_data/chk_morse_hessian_only_diag_1";
extern const std::string diabat_cub_coeff_file = "../input_data/chk_morse_com_ref_cubic_9_pt";
extern const std::string diabat_quartic_coeff_file = "../input_data/chk_morse_com_ref_quartic_9_pt";
extern const std::string diabat_high_crr_file = "../input_data/QS_CRR_OFF_DIAG";
extern const std::string gridfile = "../input_data/E_IM_grid_RMS";
extern const std::string pot_savefile = "../output_data/Potential_IM_grid";
extern const std::vector<double> alpha_vect = {6.9, 2.58, 2.60, 2.50, 2.0, 2.0};
extern const std::string datasavetype = "dat";
}
namespace SD_PARAMS {
extern const std::string gridfile_2_optimise = "../input_data/Q1_Q10_relax_input_grid";
extern const std::string gridfile_2_start = "../input_data/Q1_Q10_relax_starvect";
extern const std::vector<int> mode_id_vect = {1,5,7,8,10,13,16,17,18,19,21,22,23,24,25,26,27,28,29,30,31,32,33};
extern const std::vector<int> mode_id_2_optimise = {1,5,7,8,13,16,17,18,19,21,22,23,24,25,26,27,28,30,31,32,33};
// extern const std::vector<int> mode_id_fixed = {1,5,10,29};
// extern const std::vector<double> startvect = {-2.0,0.5,0.3,2.8,-0.3,-0.116141,0.202347,0.152987,0.0969398,-0.225726,0.1,1.0};
extern const std::vector<double> startvect = {-2.86,0.55,0.34,0.07,2.77,-0.34,0.12,-0.09,-0.09,0.0075,-0.1942,-0.1485,0.1013,-0.2284,0.0088,-0.0952,0.2884,-0.0361,0.83,0.0034,-0.0003,0.0052,0.001};
// extern const std::vector<double> startvect = {7.180125e-01,5.605201e-01,-1.877045e-01,-5.937518e-01,
// -1.646329e-01,-7.822349e-02,9.285675e-02,-4.417326e-02,3.478453e-01,1.164222e-01,2.681571e-01,-3.813042e-01,
// 5.104468e-02,-1.897087e-01,4.958839e-01,-6.497944e-02,1.457136e+00,-2.610049e-03,-8.922957e-03,9.870465e-04,
// -4.750531e-03};
}
| 64.902439 | 198 | 0.735062 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.