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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7c8bcc36f96552992397f1ec7f5131d311f822bb | 653 | hpp | C++ | graph/lib/inc/graphs_elementary.hpp | Volkodavchik/Fudzi | 0a5c8286a20187d69940557a930bb5111dacbe26 | [
"MIT"
] | null | null | null | graph/lib/inc/graphs_elementary.hpp | Volkodavchik/Fudzi | 0a5c8286a20187d69940557a930bb5111dacbe26 | [
"MIT"
] | null | null | null | graph/lib/inc/graphs_elementary.hpp | Volkodavchik/Fudzi | 0a5c8286a20187d69940557a930bb5111dacbe26 | [
"MIT"
] | null | null | null | /**
* @file graphs_elementary.hpp
* @brief Self education project. Focus on interesting algorithms
* @author Ivan Deviatkin <devyatkin.ivan@gmail.com>
**/
#include <vector>
#include <array>
#pragma once
template <typename V, typename E> class Vertex; // forward declaration for Edge class
// V - is the content stored by vertices
// E - is the content stored by edges
template <typename V, typename E>
class Edge {
struct Incidence {
size_t index;
Vertex<V,E>& v;
};
std::array<Incidence,2> vertices;
E content;
};
template <typename V, typename E>
class Vertex {
std::vector<Edge<V,E>*> edges;
};
| 21.766667 | 86 | 0.666156 | [
"vector"
] |
7c8fffc058b61a7c3c54ac87443eba634efc933e | 1,369 | hpp | C++ | Assignment6/Renderer.hpp | DanielDFY/GAMES101 | f04148d0d0e44ee6e25769daefc45dad6011d42d | [
"MIT"
] | 2 | 2021-05-28T12:28:33.000Z | 2022-01-18T12:46:01.000Z | Assignment6/Renderer.hpp | DanielDFY/GAMES101 | f04148d0d0e44ee6e25769daefc45dad6011d42d | [
"MIT"
] | null | null | null | Assignment6/Renderer.hpp | DanielDFY/GAMES101 | f04148d0d0e44ee6e25769daefc45dad6011d42d | [
"MIT"
] | null | null | null | #pragma once
#include "Scene.hpp"
class Renderer {
public:
// The main render function. This where we iterate over all pixels in the image,
// generate primary rays and cast these rays into the scene. The content of the
// framebuffer is saved to a png image file with tools from stb library.
void render(const Scene& scene);
private:
// Implementation of the Whitted-syle ray tracing algorithm
//
// This function is the function that compute the color at the intersection point
// of a ray defined by a position and a direction. Note that thus function is recursive.
//
// If the material of the intersected object is either reflective or reflective and refractive,
// then we compute the reflection/refracton direction and cast two new rays into the scene
// by calling the cast_ray() function recursively. When the surface is transparent, we mix
// the reflection and refraction color using the result of the fresnel equations (it computes
// the amount of reflection and refractin depending on the surface normal, incident view direction
// and surface refractive index).
//
// If the surface is duffuse/glossy we use the Phong illumation model to compute the color
// at the intersection point.
[[nodiscard]] Vector3f cast_ray(const Scene& scene, const Ray& ray, int depth) const;
};
| 47.206897 | 102 | 0.731191 | [
"render",
"object",
"model"
] |
7c9520c7b5eb92c7a2ff3eccbfd9e9154c3b10cc | 947 | cpp | C++ | Source/FishEngine/System/AnimationSystem.cpp | yushroom/FishEngine_-Experiment | 81e4c06f20f6b94dc561b358f8a11a092678aeeb | [
"MIT"
] | 1 | 2018-12-20T02:38:44.000Z | 2018-12-20T02:38:44.000Z | Source/FishEngine/System/AnimationSystem.cpp | yushroom/FishEngine_-Experiment | 81e4c06f20f6b94dc561b358f8a11a092678aeeb | [
"MIT"
] | null | null | null | Source/FishEngine/System/AnimationSystem.cpp | yushroom/FishEngine_-Experiment | 81e4c06f20f6b94dc561b358f8a11a092678aeeb | [
"MIT"
] | 1 | 2018-10-25T19:40:22.000Z | 2018-10-25T19:40:22.000Z | #include <FishEngine/System/AnimationSystem.hpp>
#include <FishEngine/Scene.hpp>
#include <FishEngine/Animation/Animation.hpp>
//#include <FishEngine/Gizmos.hpp>
//using namespace FishEngine;
//void DrawSkeleton(const std::map<std::string, Transform*> & skeleton)
//{
// for (auto&& p : skeleton)
// {
// auto t = p.second;
// auto parent = t->GetParent();
// if (parent != nullptr)
// {
// Gizmos::DrawLine(parent->GetPosition(), t->GetPosition());
// }
// }
//}
void FishEngine::AnimationSystem::Start()
{
auto scene = SceneManager::GetActiveScene();
auto animations = scene->FindComponents<Animation>();
for (auto animation : animations)
{
animation->Start();
}
}
void FishEngine::AnimationSystem::Update()
{
auto scene = SceneManager::GetActiveScene();
auto animations = scene->FindComponents<Animation>();
for (auto animation : animations)
{
animation->Update(0.03333f);
//DrawSkeleton(animation->m_skeleton);
}
}
| 22.547619 | 71 | 0.691658 | [
"transform"
] |
7c96bf25d8ef03248dafc377ae2ef3792cc4db44 | 9,915 | cpp | C++ | src/cpp/rtps/resources/ListenResourceImpl.cpp | zhangzhimin/Fast-RTPS | 3032f11d0c62d226eea39ea4f8428afef4558693 | [
"Apache-2.0"
] | null | null | null | src/cpp/rtps/resources/ListenResourceImpl.cpp | zhangzhimin/Fast-RTPS | 3032f11d0c62d226eea39ea4f8428afef4558693 | [
"Apache-2.0"
] | null | null | null | src/cpp/rtps/resources/ListenResourceImpl.cpp | zhangzhimin/Fast-RTPS | 3032f11d0c62d226eea39ea4f8428afef4558693 | [
"Apache-2.0"
] | 1 | 2021-08-23T01:09:51.000Z | 2021-08-23T01:09:51.000Z | // Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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.
/**
* @file ListenResourceImpl.cpp
*
*/
#include "ListenResourceImpl.h"
#include <fastrtps/rtps/resources/ListenResource.h>
#include <fastrtps/rtps/messages/MessageReceiver.h>
#include "../participant/RTPSParticipantImpl.h"
#include <fastrtps/utils/IPFinder.h>
#include <fastrtps/log/Log.h>
#define IDSTRING "(ID:"<<this->mp_listenResource->m_ID<<") "<<
using boost::asio::ip::udp;
namespace eprosima {
namespace fastrtps{
namespace rtps {
typedef std::vector<RTPSWriter*>::iterator Wit;
typedef std::vector<RTPSReader*>::iterator Rit;
ListenResourceImpl::MessageReceiver(ListenResource* LR):
mp_RTPSParticipantImpl(nullptr),
mp_listenResource(LR),
mp_thread(nullptr),
m_listen_socket(m_io_service),
runningAsync_(false), stopped_(false)
{
}
ListenResourceImpl::~ListenResourceImpl()
{
if(mp_thread !=nullptr)
{
boost::unique_lock<boost::mutex> lock(mutex_);
if(runningAsync_)
cond_.wait(lock);
logInfo(RTPS_MSG_IN,IDSTRING"Removing listening thread " << mp_thread->get_id() <<" socket: "
<<m_listen_socket.local_endpoint() << " locators: " << mv_listenLoc);
m_listen_socket.cancel();
m_listen_socket.close();
m_io_service.stop();
stopped_ = true;
lock.unlock();
logInfo(RTPS_MSG_IN,"Joining with thread");
mp_thread->join();
delete(mp_thread);
logInfo(RTPS_MSG_IN,"Listening thread closed succesfully");
}
}
bool ListenResourceImpl::isListeningTo(const Locator_t& loc)
{
if(IsAddressDefined(loc))
{
LocatorList_t locList = mv_listenLoc;
return locList.contains(loc);
}
else
{
if(loc.port == mv_listenLoc.begin()->port)
return true;
}
return false;
}
void ListenResourceImpl::newCDRMessage(const boost::system::error_code& err, std::size_t msg_size)
{
if(err == boost::system::errc::success)
{
boost::unique_lock<boost::mutex> lock(mutex_);
if(stopped_)
return;
runningAsync_ = true;
lock.unlock();
mp_listenResource->setMsgRecMsgLength((uint32_t)msg_size);
if(msg_size == 0)
return;
try{
logInfo(RTPS_MSG_IN,IDSTRING mp_listenResource->mp_receiver->m_rec_msg.length
<< " bytes FROM: " << m_sender_endpoint << " TO: " << m_listen_socket.local_endpoint());
//Get address into Locator
m_senderLocator.port = m_sender_endpoint.port();
LOCATOR_ADDRESS_INVALID(m_senderLocator.address);
if(m_sender_endpoint.address().is_v4())
{
for(int i=0;i<4;i++)
{
m_senderLocator.address[i+12] = m_sender_endpoint.address().to_v4().to_bytes()[i];
}
}
else
{
for(int i=0;i<16;i++)
{
m_senderLocator.address[i] = m_sender_endpoint.address().to_v6().to_bytes()[i];
}
}
}
catch(boost::system::system_error const& e)
{
logError(RTPS_MSG_IN,"Boost error: " << e.what());
lock.lock();
runningAsync_ = false;
lock.unlock();
cond_.notify_one();
this->putToListen();
return;
}
try
{
mp_listenResource->mp_receiver->processCDRMsg(mp_RTPSParticipantImpl->getGuid().guidPrefix,
&m_senderLocator,
&mp_listenResource->mp_receiver->m_rec_msg);
}
catch(int e)
{
logError(RTPS_MSG_IN,IDSTRING"Error processing message: " << e);
}
logInfo(RTPS_MSG_IN,IDSTRING " Message of size "<< mp_listenResource->mp_receiver->m_rec_msg.length <<" processed" );
lock.lock();
runningAsync_ = false;
lock.unlock();
cond_.notify_one();
this->putToListen();
}
else if(err == boost::asio::error::operation_aborted)
{
logInfo(RTPS_MSG_IN,IDSTRING"Operation in listening socket aborted...");
return;
}
else
{
//CDRMessage_t msg;
logInfo(RTPS_MSG_IN,IDSTRING"Msg processed, Socket async receive put again to listen ");
this->putToListen();
}
}
// NOTE This version allways listen in ANY.
void ListenResourceImpl::getLocatorAddresses(Locator_t& loc, bool isMulti)
{
logInfo(RTPS_MSG_IN,"Defined Locator IP with 0s (listen to all interfaces), listening to all interfaces");
LocatorList_t myIP;
if(loc.kind == LOCATOR_KIND_UDPv4)
{
IPFinder::getIP4Address(&myIP);
m_listen_endpoint.address(boost::asio::ip::address_v4());
}
else if(loc.kind == LOCATOR_KIND_UDPv6)
{
IPFinder::getIP6Address(&myIP);
m_listen_endpoint.address(boost::asio::ip::address_v6());
}
if(!isMulti)
{
for(auto lit = myIP.begin();lit!= myIP.end();++lit)
{
lit->port = loc.port;
mv_listenLoc.push_back(*lit);
}
}
else
{
mv_listenLoc.push_back(loc);
}
m_listen_endpoint.port((uint16_t)loc.port);
}
bool ListenResourceImpl::init_thread(RTPSParticipantImpl* pimpl,Locator_t& loc, uint32_t listenSocketSize, bool isMulti, bool isFixed)
{
this->mp_RTPSParticipantImpl = pimpl;
if(loc.kind == LOCATOR_KIND_INVALID)
return false;
getLocatorAddresses(loc, isMulti);
logInfo(RTPS_MSG_IN,"Initializing in : "<<mv_listenLoc);
boost::asio::ip::address multiaddress;
//OPEN THE SOCKET:
m_listen_socket.open(m_listen_endpoint.protocol());
m_listen_socket.set_option(boost::asio::socket_base::receive_buffer_size(listenSocketSize));
if(isMulti)
{
m_listen_socket.set_option( boost::asio::ip::udp::socket::reuse_address( true ) );
m_listen_socket.set_option( boost::asio::ip::multicast::enable_loopback( true ) );
if(loc.kind == LOCATOR_KIND_UDPv4)
{
multiaddress = boost::asio::ip::address_v4::from_string(loc.to_IP4_string().c_str());
}
else if(loc.kind == LOCATOR_KIND_UDPv6)
{
boost::asio::ip::address_v6::bytes_type bt;
for (uint8_t i = 0; i < 16; ++i)
bt[i] = loc.address[i];
multiaddress = boost::asio::ip::address_v6(bt);
}
}
if(isFixed)
{
try
{
m_listen_socket.bind(m_listen_endpoint);
}
catch (boost::system::system_error const& e)
{
logError(RTPS_MSG_IN,"Error: " << e.what() << " : " << m_listen_endpoint);
return false;
}
}
else
{
bool binded = false;
for(uint8_t i = 0; i < 100; ++i) //TODO make it configurable by user.
{
m_listen_endpoint.port(m_listen_endpoint.port()+i);
try
{
m_listen_socket.bind(m_listen_endpoint);
binded = true;
break;
}
catch(boost::system::system_error const& )
{
logInfo(RTPS_MSG_IN,"Tried port "<< m_listen_endpoint.port() << ", trying next...");
}
}
if(!binded)
{
logError(RTPS_MSG_IN,"Tried 100 ports and none was working, last tried: "<< m_listen_endpoint);
return false;
}
else
{
for(auto lit = mv_listenLoc.begin();lit!=mv_listenLoc.end();++lit)
lit->port = m_listen_endpoint.port();
}
}
boost::asio::socket_base::receive_buffer_size option;
m_listen_socket.get_option(option);
logInfo(RTPS_MSG_IN,"Created: " << m_listen_endpoint<< " || Listen buffer size: " << option.value());
if(isMulti)
{
joinMulticastGroup(multiaddress);
}
this->putToListen();
mp_thread = new boost::thread(&ListenResourceImpl::run_io_service,this);
mp_RTPSParticipantImpl->ResourceSemaphoreWait();
return true;
}
void ListenResourceImpl::joinMulticastGroup(boost::asio::ip::address& addr)
{
logInfo(RTPS_MSG_IN,"Joining group: "<<mv_listenLoc);
try
{
LocatorList_t loclist;
if(m_listen_endpoint.address().is_v4())
{
IPFinder::getIP4Address(&loclist);
for(LocatorListIterator it=loclist.begin();it!=loclist.end();++it)
m_listen_socket.set_option( boost::asio::ip::multicast::join_group(addr.to_v4(),
boost::asio::ip::address_v4::from_string(it->to_IP4_string())) );
}
else if(m_listen_endpoint.address().is_v6())
{
IPFinder::getIP6Address(&loclist);
int index = 0;
for(LocatorListIterator it=loclist.begin();it!=loclist.end();++it)
{
// boost::asio::ip::address_v6::bytes_type bt;
// for (uint8_t i = 0; i < 16;++i)
// bt[i] = it->address[i];
m_listen_socket.set_option(
boost::asio::ip::multicast::join_group(
addr.to_v6(),index
));
++index;
}
}
}
catch(boost::system::system_error const& e)
{
logError(RTPS_MSG_IN,"Boost error: "<< e.what());
}
}
void ListenResourceImpl::putToListen()
{
CDRMessage::initCDRMsg(&mp_listenResource->mp_receiver->m_rec_msg);
try
{
m_listen_socket.async_receive_from(
boost::asio::buffer((void*)mp_listenResource->mp_receiver->m_rec_msg.buffer,
mp_listenResource->mp_receiver->m_rec_msg.max_size),
m_sender_endpoint,
boost::bind(&ListenResourceImpl::newCDRMessage, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
catch(boost::system::system_error const& e)
{
logError(RTPS_MSG_IN,"Boost error: "<< e.what());
}
}
void ListenResourceImpl::run_io_service()
{
try
{
logInfo(RTPS_MSG_IN,"Thread: " << boost::this_thread::get_id() << " listening in IP: " << m_listen_socket.local_endpoint()) ;
mp_RTPSParticipantImpl->ResourceSemaphorePost();
this->m_io_service.run();
}
catch(boost::system::system_error const& e)
{
logError(RTPS_MSG_IN,"Boost error: "<<e.what());
}
}
}
}
}
| 27.016349 | 134 | 0.66475 | [
"vector"
] |
7c9c7805d762e5367979c22663e8910082c68d16 | 21,100 | cpp | C++ | src/zincreader.cpp | kushaldalsania/haystack-cpp | 95997ae2bca9ea096dc7e61c000291f3ac08d9d7 | [
"AFL-3.0"
] | null | null | null | src/zincreader.cpp | kushaldalsania/haystack-cpp | 95997ae2bca9ea096dc7e61c000291f3ac08d9d7 | [
"AFL-3.0"
] | null | null | null | src/zincreader.cpp | kushaldalsania/haystack-cpp | 95997ae2bca9ea096dc7e61c000291f3ac08d9d7 | [
"AFL-3.0"
] | null | null | null | //
// Copyright (c) 2015, J2 Innovations
// Copyright (c) 2012 Brian Frank
// Licensed under the Academic Free License version 3.0
// History:
// 29 Aug 2014 Radu Racariu<radur@2inn.com> Ported to C++
// 06 Jun 2011 Brian Frank Creation
//
#include "zincreader.hpp"
#include "bin.hpp"
#include "bool.hpp"
#include "coord.hpp"
#include "date.hpp"
#include "datetime.hpp"
#include "marker.hpp"
#include "num.hpp"
#include "ref.hpp"
#include "str.hpp"
#include "uri.hpp"
#include "time.hpp"
#include "timezone.hpp"
#include "dict.hpp"
#include "grid.hpp"
// std
#include <sstream>
#include <stdexcept>
// boost
#include <boost/scoped_ptr.hpp>
#include <boost/lexical_cast.hpp>
////////////////////////////////////////////////
// ZincReader
////////////////////////////////////////////////
using namespace haystack;
//////////////////////////////////////////////////////////////////////////
// Public
//////////////////////////////////////////////////////////////////////////
ZincReader::ZincReader(std::istream& is) : m_is(is),
m_local_is(std::auto_ptr<std::istream>()),
m_cur(0),
m_peek(0),
m_line_num(1),
m_version(0),
m_is_filter(0)
{
consume();
consume();
}
std::auto_ptr<ZincReader> ZincReader::make(const std::string& s)
{
std::auto_ptr<std::istream> iss(new std::istringstream(s));
return std::auto_ptr<ZincReader>(new ZincReader(iss));
}
// Read a grid
Grid::auto_ptr_t ZincReader::read_grid()
{
Grid::auto_ptr_t g(new Grid());
// meta line
read_ver();
read_meta(g->meta());
consume_new_line();
// empty grid
if (m_cur == '\n')
{
consume_new_line();
if (m_cur == '\n') consume_new_line();
return g;
}
// read cols
size_t numCols = 0;
for (;;)
{
std::string name = read_id();
skip_space();
numCols++;
read_meta(g->add_col(name));
if (m_cur != ',') break;
consume();
skip_space();
}
consume_new_line();
// rows
while (m_cur != '\n' && m_cur > 0)
{
boost::scoped_ptr<Val*> cells(new Val*[numCols]);
for (size_t i = 0; i < numCols; ++i)
{
skip_space();
if (m_cur != ',' && m_cur != '\n')
{
// ownership transfered to cells vector
(cells.get())[i] = (Val*)read_val().release();
}
else
(cells.get())[i] = NULL;
skip_space();
if (i + 1 < numCols)
{
if (m_cur != ',') throw std::runtime_error("Expecting comma in row");
consume();
}
}
consume_new_line();
// Val** ownership transfered to the grid
g->add_row(cells.get(), numCols);
}
if (m_cur == '\n') consume_new_line();
return g;
}
Filter::shared_ptr_t ZincReader::read_filter()
{
m_is_filter = true;
skip_space();
Filter::shared_ptr_t q = read_filter_or();
skip_space();
if (m_cur >= 0) throw std::runtime_error("Expected end of stream");
return q;
}
// Read set of name/value tags as dictionary
std::auto_ptr<Dict> ZincReader::read_dict()
{
std::auto_ptr<Dict> d(new Dict());
read_meta(*d);
if (m_cur >= 0) throw std::runtime_error("Expected end of stream");
return d;
}
// Read scalar value.
Val::auto_ptr_t ZincReader::read_scalar()
{
Val::auto_ptr_t val = read_val();
if (m_cur >= 0) throw std::runtime_error("Expected end of stream");
return val;
}
// ctor with own stream handlers
ZincReader::ZincReader(std::auto_ptr<std::istream> isAptr) : m_is(*isAptr),
m_local_is(isAptr),
m_cur(0),
m_peek(0),
m_line_num(1),
m_version(0),
m_is_filter(0)
{
consume();
consume();
}
//////////////////////////////////////////////////////////////////////////
// Implementation
//////////////////////////////////////////////////////////////////////////
std::string ZincReader::read_id()
{
if (!is_id_start(m_cur)) throw std::runtime_error("Invalid name start char");
std::stringstream s;
while (is_id(m_cur)) { s << (char)m_cur; consume(); }
return s.str();
}
void ZincReader::read_meta(Dict& d)
{
// parse pairs
while (is_id_start(m_cur))
{
// name
std::string name = read_id();
// marker or :val
Val::auto_ptr_t val(Marker::VAL.clone());
skip_space();
if (m_cur == ':')
{
consume();
skip_space();
val = read_val();
skip_space();
}
// ownership transfered to the dict
d.add(name, val);
skip_space();
}
}
void ZincReader::read_ver()
{
std::string id = read_id();
if (id != ("ver")) throw std::runtime_error("Expecting zinc header 'ver:2.0', not '" + id);
if (m_cur != ':') throw std::runtime_error("Expecting ':' colon");
consume();
std::string ver = read_str_literal();
if (ver == "2.0") m_version = 2;
else throw std::runtime_error("Unsupported zinc version: " + ver);
skip_space();
}
Val::auto_ptr_t ZincReader::read_val()
{
if (is_digit(m_cur)) return read_num_val();
if (is_alpha(m_cur)) return read_word_val();
switch (m_cur)
{
case '@': return read_ref_val();
case '"': return read_str_val();
case '`': return read_uri_val();
case '-':
if (m_peek == 'I') return read_word_val();
return read_num_val();
default: throw std::runtime_error("Unexpected char for start of value");
}
}
Val::auto_ptr_t ZincReader::read_word_val()
{
// read into string
std::stringstream s;
do { s << (char)m_cur; consume(); } while (is_alpha(m_cur));
std::string word = s.str();
// match identifier
if (m_is_filter)
{
if (word == "true") return Bool(true).clone();
if (word == "false") return Bool(false).clone();
}
else
{
if (word == "N") return Val::auto_ptr_t();
if (word == "M") return Marker::VAL.clone();
if (word == "R") return Str("_remove_").clone();
if (word == "T") return Bool::TRUE_VAL.clone();
if (word == "F") return Bool::FALSE_VAL.clone();
if (word == "Bin") return read_bin_val();
if (word == "C") return read_coord_val();
}
if (word == "NaN") return Num::NaN.clone();
if (word == "INF") return Num::POS_INF.clone();
if (word == "-INF") return Num::NEG_INF.clone();
throw std::runtime_error("Unknown value identifier: " + word);
}
Val::auto_ptr_t ZincReader::read_bin_val()
{
if (m_cur < 0) throw std::runtime_error("Expected '(' after Bin");
consume();
std::stringstream s;
while (m_cur != ')')
{
if (m_cur < 0) throw std::runtime_error("Unexpected end of bin literal");
if (m_cur == '\n' || m_cur == '\r') throw std::runtime_error("Unexpected newline in bin literal");
s << (char)m_cur;
consume();
}
consume();
return Val::auto_ptr_t(new Bin(s.str()));
}
Val::auto_ptr_t ZincReader::read_coord_val()
{
if (m_cur < 0) throw std::runtime_error("Expected '(' after Coord");
consume();
std::stringstream s;
s << "C(";
while (m_cur != ')')
{
if (m_cur < 0) throw std::runtime_error("Unexpected end of coord literal");
if (m_cur == '\n' || m_cur == '\r') throw std::runtime_error("Unexpected newline in coord literal");
s << (char)m_cur;
consume();
}
consume();
s << ")";
return Coord::make(s.str()).clone();
}
Val::auto_ptr_t ZincReader::read_num_val()
{
// parse numeric part
std::stringstream s;
s << (char)m_cur;
consume();
while (is_digit(m_cur) || m_cur == '.' || m_cur == '_')
{
if (m_cur != '_') s << (char)m_cur;
consume();
if (m_cur == 'e' || m_cur == 'E')
{
if (m_peek == '-' || m_peek == '+' || is_digit(m_peek))
{
s << (char)m_cur; consume();
s << (char)m_cur; consume();
}
}
}
double val = boost::lexical_cast<double>(s.str());
// Date - check for dash
Val::auto_ptr_t date;
Val::auto_ptr_t time;
int hour = -1;
if (m_cur == '-')
{
int32_t year;
try { year = boost::lexical_cast<int>(s.str()); }
catch (std::exception&) { throw std::runtime_error("Invalid year for date value: " + s.str()); }
consume(); // dash
int month = read_two_digits("Invalid digit for month in date value");
if (m_cur != '-') throw std::runtime_error("Expected '-' for date value");
consume();
int day = read_two_digits("Invalid digit for day in date value");
date.reset(new Date(year, month, day));
// check for 'T' date time
if (m_cur != 'T') return date;
// parse next two digits and drop down to HTime parsing
consume();
hour = read_two_digits("Invalid digit for hour in date time value");
}
// Time - check for colon
if (m_cur == ':')
{
// hour (may have been parsed already in date time)
if (hour < 0)
{
if (s.str().size() != 2) { throw std::runtime_error("Hour must be two digits for time value: " + s.str()); }
try { hour = boost::lexical_cast<int>(s.str()); }
catch (std::exception&) { throw std::runtime_error("Invalid hour for time value: " + s.str()); }
}
consume(); // colon
int min = read_two_digits("Invalid digit for minute in time value");
if (m_cur != ':') throw std::runtime_error("Expected ':' for time value");
consume();
int sec = read_two_digits("Invalid digit for seconds in time value");
int ms = 0;
if (m_cur == '.')
{
consume();
int places = 0;
while (is_digit(m_cur))
{
ms = (ms * 10) + (m_cur - '0');
consume();
places++;
}
switch (places)
{
case 1: ms *= 100; break;
case 2: ms *= 10; break;
case 3: break;
default: throw std::runtime_error("Too many digits for milliseconds in time value");
}
}
time.reset(new Time(hour, min, sec, ms));
if (date.get() == NULL) return time;
}
// DateTime (if we have date and time)
bool zUtc = false;
if (date.get() != NULL)
{
// timezone offset "Z" or "-/+hh:mm"
int tzOffset = 0;
if (m_cur == 'Z') { consume(); zUtc = true; }
else
{
bool neg = m_cur == '-';
if (m_cur != '-' && m_cur != '+') throw std::runtime_error("Expected -/+ for timezone offset");
consume();
int tzHours = read_two_digits("Invalid digit for timezone offset");
if (m_cur != ':') throw std::runtime_error("Expected colon for timezone offset");
consume();
int tzMins = read_two_digits("Invalid digit for timezone offset");
tzOffset = (tzHours * 3600) + (tzMins * 60);
if (neg) tzOffset = -tzOffset;
}
// timezone name
boost::scoped_ptr<TimeZone> tz;
if (m_cur != ' ')
{
if (!zUtc)
throw std::runtime_error("Expected space between timezone offset and name");
else
tz.reset(new TimeZone(TimeZone::UTC.name, TimeZone::UTC.offset));
}
else if (zUtc && !('A' <= m_peek && m_peek <= 'Z'))
{
tz.reset(new TimeZone(TimeZone::UTC.name, TimeZone::UTC.offset));
}
else
{
consume();
std::stringstream tzBuf;
if (!is_tz(m_cur)) throw std::runtime_error("Expected timezone name");
while (is_tz(m_cur)) { tzBuf << (char)m_cur; consume(); }
tz.reset(new TimeZone(tzBuf.str()));
}
return Val::auto_ptr_t(new DateTime((Date&)*date, (Time&)*time, *tz));
}
// if we have unit, parse that
std::string unit;
if (is_unit(m_cur))
{
std::stringstream s;
while (is_unit(m_cur)) { s << (char)m_cur; consume(); }
unit = s.str();
}
return Val::auto_ptr_t(new Num(val, unit));
}
int32_t ZincReader::read_two_digits(std::string errMsg)
{
if (!is_digit(m_cur)) throw std::runtime_error(errMsg);
int tens = (m_cur - '0') * 10;
consume();
if (!is_digit(m_cur)) throw std::runtime_error(errMsg);
int val = tens + (m_cur - '0');
consume();
return val;
}
Val::auto_ptr_t ZincReader::read_ref_val()
{
consume(); // opening @
std::stringstream s;
if (m_cur < 0) throw std::runtime_error("Unexpected end of ref literal");
while (Ref::is_id_char(m_cur))
{
if (m_cur < 0) throw std::runtime_error("Unexpected end of ref literal");
if (m_cur == '\n' || m_cur == '\r') throw std::runtime_error("Unexpected newline in ref literal");
s << (char)m_cur;
consume();
}
skip_space();
std::string dis;
if (m_cur == '"') dis = read_str_literal();
return Val::auto_ptr_t(new Ref(s.str(), dis));
}
Val::auto_ptr_t ZincReader::read_str_val()
{
return Val::auto_ptr_t(new Str(read_str_literal()));
}
inline void utf8_encode(const int32_t code_point, std::stringstream& ss)
{
if (code_point <= 0x7F)
{
ss << (char)code_point;
}
else if (code_point >= 0x80 && code_point <= 0x7FF)
{
ss << (char)((code_point >> 6) | 0xC0)
<< (char)((code_point & 0x3F) | 0x80);
}
else if (code_point >= 0x800 && code_point <= 0xFFFF)
{
ss << (char)((code_point >> 12) | 0xE0)
<< (char)(((code_point >> 6) & 0x3F) | 0x80)
<< (char)((code_point & 0x3F) | 0x80);
}
else if (code_point >= 0x10000 && code_point <= 0x1FFFFF)
{
ss << (char)((code_point >> 18) | 0xF0)
<< (char)(((code_point >> 12) & 0x3F) | 0x80)
<< (char)(((code_point >> 6) & 0x3F) | 0x80)
<< (char)((code_point & 0x3F) | 0x80);
}
}
std::string ZincReader::read_str_literal()
{
consume(); // opening quote
std::stringstream s;
while (m_cur != '"')
{
if (m_cur < 0) throw std::runtime_error("Unexpected end of str literal");
if (m_cur == '\n' || m_cur == '\r') throw std::runtime_error("Unexpected newline in str literal");
if (m_cur == '\\')
{
utf8_encode(read_esc_char(), s);
}
else
{
s << (char)m_cur;
consume();
}
}
consume(); // closing quote
return s.str();
}
int32_t ZincReader::read_esc_char()
{
consume(); // back slash
// check basics
switch (m_cur)
{
case 'b': consume(); return '\b';
case 'f': consume(); return '\f';
case 'n': consume(); return '\n';
case 'r': consume(); return '\r';
case 't': consume(); return '\t';
case '"': consume(); return '"';
case '$': consume(); return '$';
case '\\': consume(); return '\\';
}
// check for uxxxx
if (m_cur == 'u')
{
consume();
int32_t n3 = to_nibble(m_cur); consume();
int32_t n2 = to_nibble(m_cur); consume();
int32_t n1 = to_nibble(m_cur); consume();
int32_t n0 = to_nibble(m_cur); consume();
return (n3 << 12) | (n2 << 8) | (n1 << 4) | (n0);
}
throw std::runtime_error("Invalid escape sequence: \\");
}
int32_t ZincReader::to_nibble(int32_t c)
{
if ('0' <= c && c <= '9') return c - '0';
if ('a' <= c && c <= 'f') return c - 'a' + 10;
if ('A' <= c && c <= 'F') return c - 'A' + 10;
throw std::runtime_error("Invalid hex char");
}
Val::auto_ptr_t ZincReader::read_uri_val()
{
consume(); // opening backtick
std::stringstream s;
for (;;)
{
if (m_cur < 0) throw std::runtime_error("Unexpected end of uri literal");
if (m_cur == '\n' || m_cur == '\r') throw std::runtime_error("Unexpected newline in uri literal");
if (m_cur == '`') break;
if (m_cur == '\\')
{
switch (m_peek)
{
case ':': case '/': case '?': case '#':
case '[': case ']': case '@': case '\\':
case '&': case '=': case ';':
s << (char)m_cur;
s << (char)m_peek;
consume();
consume();
break;
case '`':
s << '`';
consume();
consume();
break;
default:
if (m_peek == 'u' || m_peek == '\\') s << (char)read_esc_char();
else throw std::runtime_error("Invalid URI escape sequence \\");
break;
}
}
else
{
s << (char)m_cur;
consume();
}
}
consume(); // closing backtick
return Val::auto_ptr_t(new Uri(s.str()));
}
void ZincReader::skip_space()
{
while (m_cur == ' ' || m_cur == '\t') consume();
}
void ZincReader::consume_new_line()
{
if (m_cur != '\n') throw std::runtime_error("Expecting newline");
consume();
}
void ZincReader::consume()
{
m_cur = m_peek;
int c = m_is.get();
//if (!m_is.good())
//throw std::runtime_error("Bad stream.");
m_peek = c;
if (m_cur == '\n') m_line_num++;
}
//////////////////////////////////////////////////////////////////////////
// HFilter
//////////////////////////////////////////////////////////////////////////
Filter::shared_ptr_t ZincReader::read_filter_or()
{
Filter::shared_ptr_t q = read_filter_and();
skip_space();
if (m_cur != 'o') return q;
if (read_id() != "or") throw std::runtime_error("Expecting 'or' keyword");
skip_space();
return q->OR(read_filter_or());
}
Filter::shared_ptr_t ZincReader::read_filter_and()
{
Filter::shared_ptr_t q = read_filter_atomic();
skip_space();
if (m_cur != 'a') return q;
if (read_id() != "and") throw std::runtime_error("Expecting 'and' keyword");
skip_space();
return q->AND(read_filter_and());
}
Filter::shared_ptr_t ZincReader::read_filter_atomic()
{
skip_space();
if (m_cur == '(') return read_filter_parens();
std::string path = read_filter_path();
skip_space();
if (path == "not") { return Filter::missing(read_filter_path()); }
if (m_cur == '=' && m_peek == '=') { consume_cmp(); return Filter::eq(path, read_val()); }
if (m_cur == '!' && m_peek == '=') { consume_cmp(); return Filter::ne(path, read_val()); }
if (m_cur == '<' && m_peek == '=') { consume_cmp(); return Filter::le(path, read_val()); }
if (m_cur == '>' && m_peek == '=') { consume_cmp(); return Filter::ge(path, read_val()); }
if (m_cur == '<') { consume_cmp(); return Filter::lt(path, read_val()); }
if (m_cur == '>') { consume_cmp(); return Filter::gt(path, read_val()); }
return Filter::has(path);
}
Filter::shared_ptr_t ZincReader::read_filter_parens()
{
consume();
skip_space();
Filter::shared_ptr_t q = read_filter_or();
if (m_cur != ')') throw std::runtime_error("Expecting ')'");
consume();
return q;
}
void ZincReader::consume_cmp()
{
consume();
if (m_cur == '=') consume();
skip_space();
}
std::string ZincReader::read_filter_path()
{
// read first tag name
std::string id = read_id();
// if not pathed, optimize for common case
if (m_cur != '-' || m_peek != '>') return id;
// parse path
std::stringstream s;
s << id;
while (m_cur == '-' || m_peek == '>')
{
consume();
consume();
id = read_id();
s << '-' << '>' << id;
}
return s.str();
}
#define DIGIT 0x01
#define ALPHA_LO 0x02
#define ALPHA_UP 0x04
#define ALPHA (ALPHA_UP | ALPHA_LO)
#define UNIT 0x08
#define TZ 0x10
#define ID_START 0x20
#define ID 0x40
char* ZincReader::init_table()
{
static char charTypes[128];
for (int i = '0'; i <= '9'; ++i) charTypes[i] = (DIGIT | TZ | ID);
for (int i = 'a'; i <= 'z'; ++i) charTypes[i] = (ALPHA_LO | UNIT | TZ | ID_START | ID);
for (int i = 'A'; i <= 'Z'; ++i) charTypes[i] = (ALPHA_UP | UNIT | TZ | ID);
charTypes['%'] = UNIT;
charTypes['_'] = UNIT | TZ | ID;
charTypes['/'] = UNIT;
charTypes['$'] = UNIT;
charTypes['-'] = TZ;
charTypes['+'] = TZ;
return (char*)charTypes;
}
const char *ZincReader::charType = ZincReader::init_table();
bool ZincReader::is_digit(int c) { return c > 0 && c < 128 && (charType[c] & DIGIT) != 0; }
bool ZincReader::is_alpha(int c) { return c > 0 && c < 128 && (charType[c] & ALPHA) != 0; }
bool ZincReader::is_unit(int c) { return c > 0 && (c >= 128 || (charType[c] & UNIT) != 0); }
bool ZincReader::is_tz(int c) { return c > 0 && c < 128 && (charType[c] & TZ) != 0; }
bool ZincReader::is_id_start(int c) { return c > 0 && c < 128 && (charType[c] & ID_START) != 0; }
bool ZincReader::is_id(int c) { return c > 0 && c < 128 && (charType[c] & ID) != 0; } | 28.208556 | 120 | 0.524028 | [
"vector"
] |
7ca3e11cfeca7f548f9854de84b816ea8ae0727f | 2,015 | cpp | C++ | src/enemy.cpp | evanbowman/Blind-Jump | 971bbfabb7a43a0de90c6131035b081b94a0bc08 | [
"BSD-2-Clause"
] | 79 | 2016-11-05T12:41:46.000Z | 2022-03-23T07:05:01.000Z | src/enemy.cpp | evanbowman/Blind-Jump | 971bbfabb7a43a0de90c6131035b081b94a0bc08 | [
"BSD-2-Clause"
] | 14 | 2017-02-28T02:47:43.000Z | 2021-04-25T20:08:15.000Z | src/enemy.cpp | evanbowman/Blind-Jump | 971bbfabb7a43a0de90c6131035b081b94a0bc08 | [
"BSD-2-Clause"
] | 22 | 2017-02-12T00:12:30.000Z | 2021-12-04T08:44:35.000Z | #include "enemy.hpp"
Enemy::Enemy(float _xPos, float _yPos)
: Object(_xPos, _yPos), colored(false), colorAmount(0.f), frameIndex(0),
colorTimer(0), frameTimer(0) {}
float Enemy::getColorAmount() const { return colorAmount; }
bool Enemy::isColored() const { return colored; }
uint_fast8_t Enemy::checkWallCollision(const std::vector<wall> & w, float xPos,
float yPos) {
uint_fast8_t collisionMask = 0;
for (auto & element : w) {
if ((xPos + 6 < (element.getPosX() + element.getWidth()) &&
(xPos + 6 > (element.getPosX()))) &&
(fabs((yPos + 16) - element.getPosY()) <= 13)) {
collisionMask |= 0x01;
}
if ((xPos + 24 > (element.getPosX()) &&
(xPos + 24 < (element.getPosX() + element.getWidth()))) &&
(fabs((yPos + 16) - element.getPosY()) <= 13)) {
collisionMask |= 0x02;
}
if (((yPos + 22 < (element.getPosY() + element.getHeight())) &&
(yPos + 22 > (element.getPosY()))) &&
(fabs((xPos)-element.getPosX()) <= 16)) {
collisionMask |= 0x04;
}
if (((yPos + 36 > element.getPosY()) &&
(yPos + 36 < element.getPosY() + element.getHeight())) &&
(fabs((xPos)-element.getPosX()) <= 16)) {
collisionMask |= 0x08;
}
}
return collisionMask;
}
bool Enemy::wallInPath(const std::vector<wall> & w, float dir, float xPos,
float yPos) {
for (int i{10}; i < 100; i += 16) {
if (checkWallCollision(w, xPos + cos(dir) * i, yPos + sin(dir) * i)) {
return true;
}
}
return false;
}
void Enemy::updateColor(const sf::Time & elapsedTime) {
if (colored) {
colorTimer += elapsedTime.asMilliseconds();
if (colorTimer > 20.f) {
colorTimer -= 20.f;
colorAmount -= 0.1f;
}
}
if (colorAmount <= 0.f) {
colored = false;
}
}
| 31 | 79 | 0.510174 | [
"object",
"vector"
] |
7ca55f0d662945b4f8ef8a535c08ab527c502ce6 | 7,413 | cpp | C++ | src/point_AABBTree_squared_distance.cpp | ericpko/computer-graphics-bounding-volume-hierarchy | 9f4781ab2308ebf57d4ac89e1d37e51c311a17f4 | [
"MIT"
] | null | null | null | src/point_AABBTree_squared_distance.cpp | ericpko/computer-graphics-bounding-volume-hierarchy | 9f4781ab2308ebf57d4ac89e1d37e51c311a17f4 | [
"MIT"
] | null | null | null | src/point_AABBTree_squared_distance.cpp | ericpko/computer-graphics-bounding-volume-hierarchy | 9f4781ab2308ebf57d4ac89e1d37e51c311a17f4 | [
"MIT"
] | null | null | null | #include "point_AABBTree_squared_distance.h"
#include <queue> // std::priority_queue
#include <limits>
typedef std::pair<double, std::shared_ptr<AABBTree> > MyPair;
bool point_AABBTree_squared_distance(
const Eigen::RowVector3d & query,
const std::shared_ptr<AABBTree> & root,
const double min_sqrd,
const double max_sqrd,
double & sqrd,
std::shared_ptr<Object> & descendant)
{
////////////////////////////////////////////////////////////////////////////
/**
* They key of our priority queue is represented as a std::pair of
* double, and ptr to AABBTree, and the key is the double of the pair.
* i.e. the squared distance from query to root bbox.
* We are following the algorithm from class on
* Nearest Neighbour / Closest Point. See ipad Oct 2 notes.
*/
// Set up some variables
bool found = false;
double min_sqrd_dist = std::numeric_limits<double>::infinity();
// Priority queue of a pair, and a vector of pairs
// NOTE: std::greater will compare by the first element of the pair
std::priority_queue<MyPair, std::vector<MyPair>, std::greater<MyPair> > PQ;
// Add the first pair<double, ptr->tree> to the queue
// NOTE: We use emplace, otherwise we need PQ.push(make_pair(...))
PQ.emplace(point_box_squared_distance(query, root->box), root);
while (!PQ.empty()) {
// Remove the top node from the PQ
double sqrd_dist = PQ.top().first;
std::shared_ptr<AABBTree> aabb_ptr = PQ.top().second;
PQ.pop();
// Check if we have leaves (primitive objects) below
if (aabb_ptr->num_leaves <= 2) {
// Then we can get the squared distance to each object in the leaves
// Then we have two primitives (objects)
double _sqrd;
std::shared_ptr<Object> _descendant;
// Get the squared distance from query to each primitive
if (aabb_ptr->left) {
if (aabb_ptr->left->point_squared_distance(query, min_sqrd, max_sqrd, _sqrd, _descendant)) {
if (_sqrd < min_sqrd_dist) {
min_sqrd_dist = _sqrd;
sqrd = min_sqrd_dist;
descendant = aabb_ptr->left;
found = true;
}
}
}
if (aabb_ptr->right) {
if (aabb_ptr->right->point_squared_distance(query, min_sqrd, max_sqrd, _sqrd, _descendant)) {
if (_sqrd < min_sqrd_dist) {
min_sqrd_dist = _sqrd;
sqrd = min_sqrd_dist;
descendant = aabb_ptr->right;
found = true;
}
}
}
} else if (sqrd_dist > min_sqrd_dist) {
// Then we're not at a leaf, so check if the squred distance from query
// to the bounding box is greater than the min so far.
; // do nothing
} else {
// Then we are in the middle of the tree, so we can enqueue the left
// and right subtrees.
MyPair left_pair = std::make_pair(point_box_squared_distance(query, aabb_ptr->left->box),
std::static_pointer_cast<AABBTree>(aabb_ptr->left));
MyPair right_pair = std::make_pair(point_box_squared_distance(query, aabb_ptr->right->box),
std::static_pointer_cast<AABBTree>(aabb_ptr->right));
PQ.emplace(left_pair);
PQ.emplace(right_pair);
}
}
return found;
////////////////////////////////////////////////////////////////////////////
}
/**
* Version 2: Same as in-class algorithm, but modified a bit.
*/
// #include "point_AABBTree_squared_distance.h"
// #include <queue> // std::priority_queue
// #include <limits>
// typedef std::pair<double, std::shared_ptr<AABBTree> > MyPair;
// bool point_AABBTree_squared_distance(
// const Eigen::RowVector3d & query,
// const std::shared_ptr<AABBTree> & root,
// const double min_sqrd,
// const double max_sqrd,
// double & sqrd,
// std::shared_ptr<Object> & descendant)
// {
// ////////////////////////////////////////////////////////////////////////////
// /**
// * They key of our priority queue is represented as a std::pair of
// * double, and ptr to AABBTree, and the key is the double of the pair.
// * i.e. the squared distance from query to root bbox.
// * We are following the algorithm from class on
// * Nearest Neighbour / Closest Point. See ipad Oct 2 notes.
// */
// // Set up some variables
// bool found = false;
// double min_sqrd_dist = std::numeric_limits<double>::infinity();
// // Priority queue of a pair, and a vector of pairs
// // NOTE: std::greater will compare by the first element of the pair
// std::priority_queue<MyPair, std::vector<MyPair>, std::greater<MyPair> > PQ;
// // Add the first pair<double, ptr->tree> to the queue
// // NOTE: We use emplace, otherwise we need PQ.push(make_pair(...))
// PQ.emplace(point_box_squared_distance(query, root->box), root);
// while (!PQ.empty()) {
// // Remove the top node from the PQ
// double sqrd_dist_to_bbox = PQ.top().first;
// std::shared_ptr<AABBTree> aabb_ptr = PQ.top().second;
// PQ.pop();
// // Check the squared distance to the outtermost bounding box
// if (sqrd_dist_to_bbox < min_sqrd_dist) {
// // Then we need to check the distance to primative objects (leaves)
// if (aabb_ptr->num_leaves < 3) {
// // Then we can get the squared distance to each object in the leaves
// // Then we have two primitives (objects)
// double _sqrd;
// std::shared_ptr<Object> _descendant;
// // Get the squared distance from query to each primitive
// if (aabb_ptr->left) {
// if (aabb_ptr->left->point_squared_distance(query, min_sqrd, max_sqrd, _sqrd, _descendant)) {
// if (_sqrd < min_sqrd_dist) {
// min_sqrd_dist = _sqrd;
// sqrd = min_sqrd_dist;
// descendant = aabb_ptr->left;
// found = true;
// }
// }
// }
// if (aabb_ptr->right) {
// if (aabb_ptr->right->point_squared_distance(query, min_sqrd, max_sqrd, _sqrd, _descendant)) {
// if (_sqrd < min_sqrd_dist) {
// min_sqrd_dist = _sqrd;
// sqrd = min_sqrd_dist;
// descendant = aabb_ptr->right;
// found = true;
// }
// }
// }
// } else {
// // Then we are in the middle of the tree, so we can enqueue the left
// // and right subtrees.
// MyPair left_pair = std::make_pair(point_box_squared_distance(query, aabb_ptr->left->box),
// std::static_pointer_cast<AABBTree>(aabb_ptr->left));
// MyPair right_pair = std::make_pair(point_box_squared_distance(query, aabb_ptr->right->box),
// std::static_pointer_cast<AABBTree>(aabb_ptr->right));
// PQ.emplace(left_pair);
// PQ.emplace(right_pair);
// }
// } else {
// // If we get here, then the squared distance from query to the bound
// // box is greater than the minimum sqrd distance found so far, so
// // we don't want to add any subtrees to the queue since they can't
// // possibly be less distance than their outermost bounding box
// ;
// }
// }
// return found;
// ////////////////////////////////////////////////////////////////////////////
// }
| 36.160976 | 106 | 0.581681 | [
"object",
"vector"
] |
7ca634b8afa6c3eaf28826546dc37e19c5f50165 | 3,390 | cpp | C++ | lumino/LuminoCore/src/Math/Geometries.cpp | GameDevery/Lumino | abce2ddca4b7678b04dbfd0ae5348e196c3c9379 | [
"MIT"
] | 113 | 2020-03-05T01:27:59.000Z | 2022-03-28T13:20:51.000Z | lumino/LuminoCore/src/Math/Geometries.cpp | GameDevery/Lumino | abce2ddca4b7678b04dbfd0ae5348e196c3c9379 | [
"MIT"
] | 35 | 2016-04-18T06:14:08.000Z | 2020-02-09T15:51:58.000Z | lumino/LuminoCore/src/Math/Geometries.cpp | GameDevery/Lumino | abce2ddca4b7678b04dbfd0ae5348e196c3c9379 | [
"MIT"
] | 12 | 2020-12-21T12:03:59.000Z | 2021-12-15T02:07:49.000Z |
#include <LuminoCore/Math/Math.hpp>
#include <LuminoCore/Math/Vector3.hpp>
#include <LuminoCore/Math/Matrix.hpp>
#include <LuminoCore/Math/Geometries.hpp>
namespace ln {
//==============================================================================
// Ray
Ray::Ray()
: origin(0.0f, 0.0f, 0.0f)
, direction(0.0f, 0.0f, 0.0f)
, distance(Math::Inf)
{
}
Ray::Ray(const Vector3& origin_, const Vector3& direction_)
: origin(origin_)
, direction(direction_)
, distance(Math::Inf)
{
}
Ray::Ray(const Vector3& origin_, const Vector3& direction_, float distance_)
: origin(origin_)
, direction(direction_)
, distance(distance_)
{
}
//==============================================================================
// Box
Box::Box()
: center(Vector3::Zero)
, width(0)
, height(0)
, depth(0)
{
}
Box::Box(float sizeXYZ)
: center(Vector3::Zero)
, width(sizeXYZ)
, height(sizeXYZ)
, depth(sizeXYZ)
{
}
Box::Box(const Vector3& center_, float sizeXYZ)
: center(center_)
, width(sizeXYZ)
, height(sizeXYZ)
, depth(sizeXYZ)
{
}
Box::Box(const Vector3& center_, float width_, float height_, float depth_)
: center(center_)
, width(width_)
, height(height_)
, depth(depth_)
{
}
Box::Box(const Vector3& min, const Vector3& max)
{
width = max.x - min.x;
center.x = min.x + (width / 2);
height = max.y - min.y;
center.y = min.y + (height / 2);
depth = max.z - min.z;
center.z = min.z + (depth / 2);
}
Vector3 Box::minPoint() const
{
float hw = width / 2;
float hh = height / 2;
float hd = depth / 2;
return Vector3(center.x - hw, center.y - hh, center.z - hd);
}
Vector3 Box::maxPoint() const
{
float hw = width / 2;
float hh = height / 2;
float hd = depth / 2;
return Vector3(center.x + hw, center.y + hh, center.z + hd);
}
void Box::getMinMax(Vector3* outMin, Vector3* outMax) const
{
float hw = width / 2;
float hh = height / 2;
float hd = depth / 2;
if (outMin != nullptr) {
outMin->x = center.x - hw;
outMin->y = center.y - hh;
outMin->z = center.z - hd;
}
if (outMax != nullptr) {
outMax->x = center.x + hw;
outMax->y = center.y + hh;
outMax->z = center.z + hd;
}
}
// http://dev.theomader.com/transform-bounding-boxes/
Box Box::transform(const Box& box, const Matrix& mat)
{
Vector3 boxMin, boxMax;
box.getMinMax(&boxMin, &boxMax);
auto xa = mat.right() * boxMin.x;
auto xb = mat.right() * boxMax.x;
auto ya = mat.up() * boxMin.y;
auto yb = mat.up() * boxMax.y;
auto za = mat.front() * boxMin.z;
auto zb = mat.front() * boxMax.z;
return Box(
Vector3::min(xa, xb) + Vector3::min(ya, yb) + Vector3::min(za, zb) + mat.position(),
Vector3::max(xa, xb) + Vector3::max(ya, yb) + Vector3::max(za, zb) + mat.position());
}
//==============================================================================
// OrientedBox
OrientedBox::OrientedBox()
: center(Vector3::Zero)
, axisX(Vector3::UnitX)
, axisY(Vector3::UnitY)
, axisZ(Vector3::UnitZ)
, extentX(0)
, extentY(0)
, extentZ(0)
{
}
OrientedBox::OrientedBox(float sizeXYZ)
: center(Vector3::Zero)
, axisX(Vector3::UnitX)
, axisY(Vector3::UnitY)
, axisZ(Vector3::UnitZ)
, extentX(sizeXYZ)
, extentY(sizeXYZ)
, extentZ(sizeXYZ)
{
}
} // namespace ln
| 21.455696 | 87 | 0.558112 | [
"transform"
] |
7cbc02f807a2320b6349e91080e76454160dbfc1 | 1,635 | hpp | C++ | src/id.hpp | bcumming/arbor-gui | 3b966aa56dd403d0bdf94ec76c6ec6f1fffe1add | [
"BSD-3-Clause"
] | 2 | 2021-03-18T15:09:22.000Z | 2021-03-18T15:25:21.000Z | src/id.hpp | bcumming/arbor-gui | 3b966aa56dd403d0bdf94ec76c6ec6f1fffe1add | [
"BSD-3-Clause"
] | 54 | 2020-11-12T10:23:03.000Z | 2021-09-08T08:28:52.000Z | src/id.hpp | arbor-sim/gui | 67e3f0318b9ea66e7be12cc4ee55a0cd2f2e945a | [
"BSD-3-Clause"
] | 8 | 2020-11-13T19:18:59.000Z | 2021-08-30T10:19:51.000Z | #pragma once
#include <compare>
#include <unordered_map>
#include <vector>
struct id_type {
size_t value;
auto operator<=>(const id_type&) const = default;
};
namespace std {
namespace {
template<typename T>
inline size_t combine(std::size_t seed, T const& v) {
return std::hash<T>()(v) + 0x9e3779b9 + (seed<<6) + (seed>>2); // From boost hash
}
inline size_t combine_all(std::size_t seed) { return seed; }
template<typename T, typename... Ts>
inline size_t combine_all(std::size_t seed, T const& t, Ts... ts) {
return combine_all(combine(seed, t), ts...);
}
template<typename... Ts>
inline size_t combine_all0(Ts... ts) {
return combine_all(0, ts...);
}
}
template<> struct hash<id_type> {
std::size_t operator()(const id_type& k) const { return std::hash<decltype(k.value)>{}(k.value); }
};
template<typename A, typename B> struct hash<std::pair<A, B>> {
std::size_t operator()(const std::pair<A, B>& p) const { return combine_all0(p.first, p.second); }
};
template<typename... As> struct hash<std::tuple<As...>> {
std::size_t operator()(const std::tuple<As...>& t) const {
return std::apply([](auto... as){ return combine_all0(as...); }, t);
}
};
}
using vec_type = std::vector<id_type>;
using mmap_type = std::unordered_map<id_type, std::vector<id_type>>;
template<typename V> using map_type = std::unordered_map<id_type, V>;
template<typename V> using join_type = std::unordered_map<std::tuple<id_type, id_type>, V>;
| 32.058824 | 106 | 0.604281 | [
"vector"
] |
7cc899340265bb86be455d47d79b11332adde4d4 | 20,069 | hpp | C++ | src/histogram.hpp | mclauchlinc/analysis_twopi_clas6 | 620e8f032e225ba90d228563c702f5c9ac2a6f75 | [
"MIT"
] | null | null | null | src/histogram.hpp | mclauchlinc/analysis_twopi_clas6 | 620e8f032e225ba90d228563c702f5c9ac2a6f75 | [
"MIT"
] | null | null | null | src/histogram.hpp | mclauchlinc/analysis_twopi_clas6 | 620e8f032e225ba90d228563c702f5c9ac2a6f75 | [
"MIT"
] | null | null | null | #ifndef HISTOGRAM_HPP
#define HISTOGRAM_HPP
#include "TH1.h"
#include "TH2.h"
#include "TFile.h"
#include "TCanvas.h"
#include "TDirectory.h"
#include "constants.hpp"
#include "functions.hpp"
#include "CartesianGenerator.hpp"
#include "physics.hpp"
#include "detectors.hpp"
#include "THnSparse.h"
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include "TGraph.h"
#include <iterator>
#include "cuts.hpp"
#include <cmath>
#include "TLatex.h"
#include <mutex>//For pausing the multithreading for the filling of THnSparse histograms
//#include <unistd.h>//to allow us to use chdir
//#include "TImage.h"
//#include "particle.hpp"
//#include "variables.h"
//#include "CartesianGenerator.hh"
//Binning Info
//W Q2
static float _wq2_xmin_ = -0.01;//GeV
static float _wq2_xmax_ = 3.99; //GeV
static int _wq2_xbin_ = 200;//GeV
static float _wq2_ymin_ = -0.01;//GeV^2
static float _wq2_ymax_ = 8.99; //GeV^2
static int _wq2_ybin_ = 200;//GeV^2
//PID Plots
//Fiducial
static float _fid_xmin_ = -30.0;//Degrees
static float _fid_xmax_ = 30.0; //Degrees
static int _fid_xbin_ = 400;//Degrees
static float _fid_ymin_ = 0.0;//Degrees
static float _fid_ymax_ = 180.0; //Degrees
static int _fid_ybin_ = 300;//Degrees
//Delta T
static float _delta_xmin_ = 0.0;//GeV
static float _delta_xmax_ = 6.0; //GeV
static int _delta_xbin_ = 1000;//GeV
static float _delta_ymin_ = -6.0;//ns
static float _delta_ymax_ = 6.0; //ns
static int _delta_ybin_ = 400;//ns
//SF
static float _sf_xmin_ = 0.0;//GeV
static float _sf_xmax_ = 6.0; //GeV
static int _sf_xbin_ = 500;//GeV
static float _sf_ymin_ = 0;//unitless
static float _sf_ymax_ = 1.0; //unitless
static int _sf_ybin_ = 300;//unitless
//CC
//nphe
static float _cc_xmin_ = -0.5;//Segment
static float _cc_xmax_ = 500.5; //Segment
static int _cc_xbin_ = 501;//Segment
//EC
static float _ec_xmin_ = 0.0;//GeV
static float _ec_xmax_ = 6.0; //GeV
static int _ec_xbin_ = 100;//GeV
//MM
static float _mm_min_[4] = {0.7,0.0,0.0,-0.2};
static float _mm_max_[4] = {1.5,0.3,0.3,0.2};
static int _mm_bin_[4] = {200,200,200,200};
//MM2
static float _mm2_min_[4] = {0.7,0.0,0.0,-0.02};
static float _mm2_max_[4] = {1.5,0.09,0.09,0.02};
static int _mm2_bin_[4] = {100,100,100,100};
//EC
static float _ec_min_ = 0.0;
static float _ec_max_ = 6.0;
static int _ec_bin_ = 200;
//Detector Plots
//Vertex
static float _vertex_min_ = -12.0;
static float _vertex_max_ = 5.0;
static int _vertex_bin_ = 200;
//CC Eff
//Momentum vs. Theta
static float _cc_eff1_xmin_ = 0.0;//GeV
static float _cc_eff1_xmax_ = 5.0;//GeV
static int _cc_eff1_xbin_ = 300;
static float _cc_eff1_ymin_ = 0.0;//Degrees
static float _cc_eff1_ymax_ = 80.0;//Degrees
static int _cc_eff1_ybin_ = 300;
//Sector and Segment yields
static float _cc_eff2_xmin_ = 0.5;//Sector
static float _cc_eff2_xmax_ = 6.5; //Sector
static int _cc_eff2_xbin_ = 6;//Sector
//For Momentum Binning
static float _p_bin_min_ = 0.5;//GeV
static float _p_bin_max_ = 5.0;//GeV
static int _p_bin_bins_= 25;//Steps
//Detector Parsing
static int _n_cc_seg_ = 18;
static int _n_cc_lrc_ = 3;
static int _n_sec_ = 6;
//THnSparse Binning
static int _n_var_ = 3; //Number of variable sets
static float _W_min_ = 1.4;
static float _W_max_ = 2.125;
static float _W_res_ = 0.025;
static float _Q2_min_ = 2.0;
static float _Q2_max_ = 5.0;
static float _Q2_bins_[6] = {2.0,2.4,3.0,3.5,4.2,5.0};
static float _MM_min_[3] = {1.1,0.3,1.1};
static float _MM_max_[3] = {2.0,1.1,2.0};
static int _MM_bins_ = 14;
static float _MM2_min_[3] = {0.3,1.1,1.1};
static float _MM2_max_[3] = {1.1,2.0,2.0};
static int _theta_bins_ = 10;
static float _theta_min_ = 0.0;
static float _theta_max_ = 180.0;
static int _alpha_bins_ = 10;
static float _alpha_min_ = 0.0;
static float _alpha_max_ = 360.;
static int _phi_bins_ = 10;
static float _phi_min_ = 0.0;
static float _phi_max_ = 360.0;
//using TH2F_ptr = std::make_shared<TH2F*>;
//using TH1F_ptr = std::make_shared<TH1F*>;
//using THn_ptr = std::make_shared<THnSparseD*>;
//using TGraph_ptr = std::make_shared<TGraph*>;
//using TDir_ptr = std::make_shared<TDirectory*>;
using Bool_1d = std::vector<bool>;
using Bool_2d = std::vector<std::vector<bool>>;
using Bool_3d = std::vector<std::vector<std::vector<bool>>>;
using Bool_4d = std::vector<std::vector<std::vector<std::vector<bool>>>>;
using Bool_5d = std::vector<std::vector<std::vector<std::vector<std::vector<bool>>>>>;
using Bool_6d = std::vector<std::vector<std::vector<std::vector<std::vector<std::vector<bool>>>>>>;
using TH2F_ptr = std::shared_ptr<TH2F>;
using TH2F_ptr_1d = std::vector<TH2F*>;
using TH2F_ptr_2d = std::vector<std::vector<TH2F*>>;
using TH2F_ptr_3d = std::vector<std::vector<std::vector<TH2F*>>>;
using TH2F_ptr_4d = std::vector<std::vector<std::vector<std::vector<TH2F*>>>>;
using TH2F_ptr_5d = std::vector<std::vector<std::vector<std::vector<std::vector<TH2F*>>>>>;
using TH2F_ptr_6d = std::vector<std::vector<std::vector<std::vector<std::vector<std::vector<TH2F*>>>>>>;
using TH2F_ptr_7d = std::vector<std::vector<std::vector<std::vector<std::vector<std::vector<std::vector<TH2F*>>>>>>>;
using TH1F_ptr = std::shared_ptr<TH1F>;
using TH1F_ptr_1d = std::vector<TH1F*>;
using TH1F_ptr_2d = std::vector<std::vector<TH1F*>>;
using TH1F_ptr_3d = std::vector<std::vector<std::vector<TH1F*>>>;
using TH1F_ptr_4d = std::vector<std::vector<std::vector<std::vector<TH1F*>>>>;
using TH1F_ptr_5d = std::vector<std::vector<std::vector<std::vector<std::vector<TH1F*>>>>>;
using TH1F_ptr_6d = std::vector<std::vector<std::vector<std::vector<std::vector<std::vector<TH1F*>>>>>>;
using TDir_ptr_1d = std::vector<TDirectory*>;
using TDir_ptr_2d = std::vector<std::vector<TDirectory*>>;
using TDir_ptr_3d = std::vector<std::vector<std::vector<TDirectory*>>>;
using TDir_ptr_4d = std::vector<std::vector<std::vector<std::vector<TDirectory*>>>>;
using TDir_ptr_5d = std::vector<std::vector<std::vector<std::vector<std::vector<TDirectory*>>>>>;
//Canvas information
//const Double_t WQ2_cw = 1200;
//const Double_t WQ2_ch = 600;
//using TH1I_ptr = std::shared_ptr<TH1I>;
//Lengths of different arrays
const static int _len_ecuts_ = std::distance(std::begin(_ecuts_), std::end(_ecuts_));
const static int _len_top_ = std::distance(std::begin(_top_), std::end(_top_));
const static int _len_cut_ = std::distance(std::begin(_cut_), std::end(_cut_));
const static int _len_recon_ = std::distance(std::begin(_recon_), std::end(_recon_));
const static int _len_weight_ = std::distance(std::begin(_weight_), std::end(_weight_));
const static int _len_species_ = std::distance(std::begin(_species_), std::end(_species_));
class Histogram {
protected:
std::shared_ptr<TFile> _RootOutputFile;
std::shared_ptr<TFile> _SparseFile;
std::shared_ptr<TFile> _HistImageFile;
TCanvas* def;
//Plot Formation Constants
//W Q2
int WQxres = 200;
int WQyres = 200;
double WQxmin = -0.01;
double WQymin = -0.01;
double WQxmax = 3.99;
double WQymax = 8.99;
//Electron Sampling Fraction
int SFxres = 500;
int SFyres = 300;
double SFxmin = 0.0;
double SFymin = 0.0;
double SFxmax = 6.0;
double SFymax = 1.0;
//Minimum Electron Energy
int MEExres = 300;
int MEEyres = 300;
double MEExmin = 0.0;
double MEEymin = 0.0;
double MEExmax = 6.0;
double MEEymax = 1.0;
//Fiducial Cuts
int FIDxres = 400;
int FIDyres = 300;
double FIDxmin = -30.0;
double FIDymin = 0.0;
double FIDxmax = 30.0;
double FIDymax = 180.0;
//Delta_t
int DTxres = 1000;//300;
int DTyres = 400;
double DTxmin = 0.0;
double DTymin = -10.0;//-4.0;
double DTxmax = 4.5;//7.0;
double DTymax = 10.0;//4.0;
//Missing Mass
int MMxres = 400;
double MMxmin = -0.2;
double MMxmax = 3.0;
//Alpha
int alphaxres = 100;
double alphaxmin = 0.0;
double alphaxmax = 3.2;
//Binning for Analysis
double Wmin = 1;
double Wres = 0.5;
double Wmax = 3;
double Q2min = 1.5;
double Q2max = 5.0;
double Q2res = 0.5;
//CC Min
double MinCCmin = -0.5;
double MinCCmax = 501.5;
int MinCCres = 502;
//binning
float Wbin_res = 0.025;//The width of a W bin //30 steps
float Wbin_start = 1.4;//The starting of W bins
float Q2bin_res = 0.5;//6 steps
float Q2bin_start = 2.0;
double Yth_start = 9.0;
double Yth_res = 18.0;
double Yal_start = 18.0;//10.0; 0-36, 36-72, 72-108,
double Yal_res = 36.0;//40.0;
double YM_start[3] = {1.1,1.1,0.3};
double YM_res[3] = {0.06,0.06,0.06};
//Making the Histograms
TH2F_ptr_5d _WQ2_hist;
Bool_5d _WQ2_made;
//TH2F_ptr_5d _Made_WQ2_hist;//[11][6][2][2];//electron cuts, topologies (including pre), Recon vs. thrown, weight (for data this should always be "Recon")
TH2F_ptr_7d _Fid_hist;
Bool_6d _Fid_made;
//CC Histograms
Bool_6d _CC_made;
TH1F_ptr_6d _CC_hist;
TH1F_ptr_3d _CC_Eff2_hist;
TH2F_ptr_4d _CC_Eff1_hist;
//MM Histograms
TH1F_ptr_5d _MM_hist;
Bool_4d _MM_made;
TH2F_ptr_5d _SF_hist;
Bool_5d _SF_made;
//Vertex Histograms
TH1F_ptr_4d _Vertex_hist;
//EC Histograms
TH1F_ptr _EC_hist;
//Delta Histograms
TH2F_ptr_6d _Delta_hist;
//THnSparse Friend Histograms
THnSparseD* _Friend[3][5];//{Variable sets,topologies} => top->{pro,pip,pim,zero,all}
THnSparseD* _Friend2[3][5];//For negative Helicity {Variable sets,topologies} => top->{pro,pip,pim,zero,all}
THnSparseD* _Thrown[3];//Variable Sets
THnSparseD* _Weight_Sum[3][5];
TH1F_ptr_3d _PCorr_Check_hist;
//TH2F_ptr_5d _Made_Fid_hist;//[7][4][11][30][26][6][2][2];//sector, species, cut, W binning, p binning, topology, anti, weight
/*TH2F_ptr _SF_hist[10][30][7][6][2];//cuts, W Binning, Sector, topology, anti, weight
TH2F_ptr _Delta_hist[4][7][30][7][6][2]; //particle, cuts, W binning, sector, topology, anti, weight
TH1F_ptr _CC_hist[6][18][11][4][6][2]; //Sector, segment, cut, side of detector, topology, anti, weight
TH1F_ptr _MM_hist[4][3][2][2];//topology, cut, squared v linear, fitting vs. not fitting plots, weight
TH1F_ptr _Cross_hist[2]; //Showing how many events counted in mulitiple topologies,weight
TH2F_ptr _Delta_2_hist[4][48][7][6][6][2][2];////particle, paddle, cuts, sector, topology, anti, weight
//Other Misc
TH1F_ptr Charge_hist;
double Charge_max = 31500.5;
double Charge_min = 30499.5;
int Charge_res = 1001;
//Checking Detector Hits
TH2F_ptr XY_hist[3][2][4];//Show distribution of hits in detector systems {detector systems},{recon/thrown},species
TH2F_ptr Fid_Det_hist[3][4][7];//{cc,sc,ec},{species},{all,sector}{recon/thrown}
bool Fid_made_hist[7][4][11][30][26][6][2][2];
bool Fid_fill_hist[7][4][11][30][26][6][2][2];
bool Fid_write_hist[7][4][11][30][26][6][2][2];
bool CC_made_hist[6][18][11][4][6][2];
bool CC_fill_hist[6][18][11][4][6][2];
bool CC_write_hist[6][18][11][4][6][2];
bool DT_made_hist[4][7][30][7][6][2];//Added one to the second bin for cuts to all for the electron WQ2
bool DT_fill_hist[4][7][30][7][6][2];
bool DT_dir_hist[4][7][30][7][6][2];
bool DT_dir_made[4][8][2][8][6];
bool DT_2_made_hist[4][48][7][7][6][2];//Added one to the second bin for cuts to all for the electron WQ2
bool DT_2_fill_hist[4][48][7][7][6][2];
bool DT_2_dir_hist[4][48][7][7][6][2];
bool DT_2_dir_made[4][48][8][8][6];
bool WQ2_made_hist[11][6][2][2];
bool WQ2_dir_made[11][6][2];
THn_ptr Friend[3][5];//This will be the 7 dimensional histogram from which I can project out different pieces
Int_t _Friend_bins[7] = {29,5,14,14,10,10,10}; //topology, W, Q2, MM1, MM2, Theta, Alpha, Phi
THn_ptr Friend_5d[3][5][29][5];//[_Friend_bins[0]][_Friend_bins[1]];//These are the 5D histograms separated into W,Q2 bins
float _W_min = 1.4;
float _W_max = 2.125;
float _Q2_min = 2.0;
float _Q2_max = 5.0;
float _Q2_bins[6] = {2.0,2.4,3.0,3.5,4.2,5.0};
float _MM_min[3] = {1.1,0.3,1.1};
float _MM_max[3] = {2.0,1.1,2.0};
float _MM2_min[3] = {0.3,1.1,1.1};
float _MM2_max[3] = {1.1,2.0,2.0};
float _theta_min = 0.0;
float _theta_max = 180.0;
float _alpha_min = 0.0;
float _alpha_max = 360.;
float _phi_min = 0.0;
float _phi_max = 360.0;
THn_ptr Thrown[3];
THn_ptr Reconstructed[3][5];
THn_ptr Acceptance[3][5];
THn_ptr Bin_Sizes[3];
THn_ptr Virtual_Flux[3];
//Int_t _Accepance_bins[7] = {5,29,5,14,10,10,10}; //topology, W, Q2, MM, Theta, Alpha, Phi
//Exploring SF valley of death
TH2F_ptr WQ2_hist_sf[2];
//TGraph_ptr IntCharge;
std::shared_ptr<TFile> OtherFile;
TH1F_ptr Find_Gold;
//TGraph_ptr NormFaraCharge;
*/
public:
Histogram(std::shared_ptr<Flags> flags_);
bool OK_Idx(std::vector<int> idx_);
void Write(std::shared_ptr<Flags> flags_);
//void Print(const std::string& output_dir_, std::shared_ptr<Flags> flags_);
//W Qsquared plots
int P_bin(float p_);
float P_Min(int p_bin_);
float P_Max(int p_bin_);
float P_center(int p_bin_);
int W_bins();
int W_bin(float W_);
float W_bot(int bin_);
float W_top(int bin_);
float W_center(int bin_);
int W_binning(float W_);
int p_binning(float p_);
char Part_cut(int species, int cut);
int ecut_idx(char * ecut_, std::shared_ptr<Flags> flags_);
int ecut_idx(const char * ecut_, std::shared_ptr<Flags> flags_);
//*--------------------------------Begin W Q2 Plot----------------------------*
void WQ2_Make(std::shared_ptr<Flags> flags_);
std::vector<int> WQ2_cut_idx(const char* ecut_, const char * cut_, const char * top_, const char * weight_, const char * recon_, std::shared_ptr<Flags> flags_);
bool Made_WQ2_idx(const char* ecut_, const char * cut_, const char* top_, const char * weight_, const char * recon_);
void WQ2_Fill(float W_, float Q2_,const char* ecut_,const char *cut_, const char * top_, const char * thrown_, std::shared_ptr<Flags> flags_, float weight_);
void WQ2_Write(std::shared_ptr<Flags> flags_);
//*--------------------------------End W Q2 Plot----------------------------*
//*-------------------------------Start Fid Plot----------------------------*
void Fid_Make(std::shared_ptr<Flags> flags_);
int hcut_idx(char * hcut_, int hadron_, std::shared_ptr<Flags> flags_);
int hcut_idx(const char * hcut_, int hadron_, std::shared_ptr<Flags> flags_);
bool Made_Fid_idx(const char* species_, const char* pcut_,const char * sector_, const char * cut_, const char * top_, const char * weight_);
std::vector<int> Fid_cut_idx(const char* species_, const char* pcut_,const char * sector_, const char * cut_, const char * top_, const char * weight_,const char * p_dep_, float p_, std::shared_ptr<Flags> flags_);
void Fid_Fill(const char * species_, float theta_, float phi_,const char* pcut_,const char * sector_,const char *cut_, const char* top_, float p_, std::shared_ptr<Flags> flags_, float weight_);
void Fid_Write(std::shared_ptr<Flags> flags_);
//*--------------------------------End Fid Plot----------------------------*
//*--------------------------------End SF Plot----------------------------*
void SF_Make(std::shared_ptr<Flags> flags_);
std::vector<int> SF_idx(const char* ecut_, const char* cut_, const char* top_, const char* sector_, const char * W_dep_, std::shared_ptr<Flags> flags_, float W_=NAN);
void SF_Fill(float p_, float sf_, float W_, const char* ecut_, const char* cut_, const char* top_, const char * sector_, float weight_, std::shared_ptr<Flags> flags_);
std::vector<int> SF_dir_idx(const char* ecut_, const char* cut_, const char* top_, const char* sector_, const char* W_dep_, std::shared_ptr<Flags> flags_);
void SF_Write(std::shared_ptr<Flags> flags_);
//*--------------------------------End SF Plot----------------------------*
//*-------------------------------Start CC Plot----------------------------*
void CC_Make(std::shared_ptr<Flags> flags_);
std::vector<int> CC_idx(const char * ecut_, const char * cut_, const char* top_, const char * sector_, const char* side_, int seg_, std::shared_ptr<Flags> flags_);
void CC_Fill(int nphe, int seg_, const char * ecut_, const char* cut_, const char* top_, const char * sector_, const char* side_, std::shared_ptr<Flags> flags_);
void CC_Write(std::shared_ptr<Flags> flags_);
//*-------------------------------End CC Plot-----------------------------*
//*-------------------------------Start EC Plot----------------------------*
//*-------------------------------End EC Plot------------------------------*
//*-------------------------------Start Vertex Plot----------------------------*
void Vertex_Make(std::shared_ptr<Flags> flags_);
std::vector<int> Vertex_idx(const char* ecut_, const char* cut_, const char* top_, const char* sector_, std::shared_ptr<Flags> flags_);
void Vertex_Fill(float vz_, float weight_, const char* ecut_, const char* cut_, const char* top_, const char* sector_, std::shared_ptr<Flags> flags_);
void Vertex_Write(std::shared_ptr<Flags> flags_);
//*-------------------------------End Vertex Plot------------------------------*
//*-------------------------------Start Delta T Plot----------------------------*
void Delta_Make(std::shared_ptr<Flags> flags_);
std::vector<int> Delta_idx(float W_, const char* sector_,const char* species_, const char* pcut_, const char* cut_, const char* top_, const char* W_dep_, std::shared_ptr<Flags> flags_);
void Delta_Fill(float p_, float dt_, float weight_, float W_, const char* species_, const char* pcut_, const char* cut_, const char* top_, const char* sector_,std::shared_ptr<Flags> flags_ );
void Delta_Write(std::shared_ptr<Flags> flags_);
//*-------------------------------End Delta T Plot------------------------------*
//*-------------------------------Start MM Plot----------------------------*
void MM_Make(std::shared_ptr<Flags> flags_);
std::vector<int> MM_idx(const char* top_, const char* cut_, const char * clean_, const char * sector_, const char * W_dep_, float W_, std::shared_ptr<Flags> flags_);
void MM_Fill(const char* top_, const char* cut_, const char * clean_, const char * sector_, float MM_, float W_, float weight_, std::shared_ptr<Flags> flags_);
void MM_Write(std::shared_ptr<Flags> flags_);
//*-------------------------------End MM Plot----------------------------*
//*-------------------------------Start CC Efficiency Plot----------------------------*
void CC_Eff_Make(std::shared_ptr<Flags> flags_);
std::vector<int> CC_Eff_idx(int which_, const char * ecut_, const char* cut_, const char* sector_, const char* top_, std::shared_ptr<Flags> flags_);
void CC_Eff_Fill(float p_, float theta_, float weight_, const char* ecut_, const char* cut_, const char* sector_, const char* top_, std::shared_ptr<Flags> flags_);
void CC_Eff_Write(std::shared_ptr<Flags> flags_);
//*-------------------------------End CC Efficiency Plot----------------------------*
//*-------------------------------Start Friend Plot----------------------------*
std::vector<int> Friend_Bin_Sizes(std::shared_ptr<Flags> flags_);
void Friend_Make(std::shared_ptr<Flags> flags_);
int Friend_W_idx(float W_);
int Friend_Q2_idx(float Q2_);
int Friend_MM_idx(float MM_, int var_);
int Friend_MM2_idx(float MM_, int var_);
int Friend_theta_idx(float theta_);
int Friend_alpha_idx(float alpha_);
int Friend_phi_idx(float phi_);
std::vector<int> Friend_idx( float W_, float Q2_, float MM_, float MM2_, float theta_, float alpha_, float phi_ , int var_);
void Print_Friend_Bin(float W_, float Q2_, float MM_, float MM2_, float theta_, float alpha_, float phi_, int var_);
void Friend_Fill(const char* top_, float W_, float Q2_, float MM_, float MM2_, float theta_, float alpha_, float phi_ , int var_, bool thrown_, float weight_, std::shared_ptr<Flags> flags_);
void Friend_Write(std::shared_ptr<Flags> flags_);
//*-------------------------------End Friend Plot----------------------------*
//*-------------------------------Start PCorr Check Plot----------------------------*
void PCorr_Check_Make(std::shared_ptr<Flags> flags_);
std::vector<int> PCorr_Check_idx(int sector_, const char* top_, const char* corr_, std::shared_ptr<Flags> flags_);
void PCorr_Check_Fill(float MM2_, int sector_, const char* top_, const char* corr_, std::shared_ptr<Flags> flags_);
void PCorr_Check_Write(std::shared_ptr<Flags> flags_);
//*-------------------------------End PCorr Check Plot----------------------------*
};
#endif | 41.0409 | 213 | 0.665454 | [
"vector"
] |
7ccc06a898b1f770ba1391dd54f0c57a80a2cadb | 3,128 | cxx | C++ | src/Cxx/Images/ImageText.cxx | ajpmaclean/vtk-examples | 1a55fc8c6af67a3c07791807c7d1ec0ab97607a2 | [
"Apache-2.0"
] | 81 | 2020-08-10T01:44:30.000Z | 2022-03-23T06:46:36.000Z | src/Cxx/Images/ImageText.cxx | ajpmaclean/vtk-examples | 1a55fc8c6af67a3c07791807c7d1ec0ab97607a2 | [
"Apache-2.0"
] | 2 | 2020-09-12T17:33:52.000Z | 2021-04-15T17:33:09.000Z | src/Cxx/Images/ImageText.cxx | ajpmaclean/vtk-examples | 1a55fc8c6af67a3c07791807c7d1ec0ab97607a2 | [
"Apache-2.0"
] | 27 | 2020-08-17T07:09:30.000Z | 2022-02-15T03:44:58.000Z | #include <vtkFreeTypeTools.h>
#include <vtkImageActor.h>
#include <vtkImageBlend.h>
#include <vtkImageCanvasSource2D.h>
#include <vtkImageData.h>
#include <vtkImageMapper3D.h>
#include <vtkInteractorStyleImage.h>
#include <vtkNamedColors.h>
#include <vtkNew.h>
#include <vtkPNGWriter.h>
#include <vtkPointData.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkStdString.h>
#include <vtkTextProperty.h>
#include <array>
int main(int argc, char* argv[])
{
vtkNew<vtkNamedColors> colors;
std::array<double, 3> drawColor1{0, 0, 0};
std::array<double, 3> drawColor2{0, 0, 0};
auto color1 = colors->GetColor3ub("Blue").GetData();
auto color2 = colors->GetColor3ub("Red").GetData();
for (auto i = 0; i < 3; ++i)
{
drawColor1[i] = color1[i];
drawColor2[i] = color2[i];
}
// Create a blue image with a red circle of radius 50 centered at (60, 60)
vtkNew<vtkImageCanvasSource2D> drawing;
drawing->SetScalarTypeToUnsignedChar(); // PNGWriter requires unsigned char
// (or unsigned short)
drawing->SetNumberOfScalarComponents(3);
drawing->SetExtent(0, 150, 0, 120, 0,
0); // xmin, xmax, ymin, ymax, zmin, zmax
drawing->SetDrawColor(drawColor1.data());
drawing->FillBox(0, 150, 0, 120);
drawing->SetDrawColor(drawColor2.data());
drawing->DrawCircle(60, 60, 50); // parameters: x, y, radius
// Create an image of text
vtkFreeTypeTools* freeType = vtkFreeTypeTools::GetInstance();
vtkNew<vtkTextProperty> textProperty;
textProperty->SetColor(colors->GetColor3d("Yellow").GetData());
textProperty->SetJustificationToLeft();
textProperty->SetFontSize(24);
textProperty->SetOrientation(25);
vtkStdString text(" Test String");
vtkNew<vtkImageData> textImage;
freeType->RenderString(textProperty, text, 70, textImage.GetPointer());
// Combine the images
vtkNew<vtkImageBlend> blend;
blend->AddInputConnection(drawing->GetOutputPort());
blend->AddInputData(textImage);
blend->SetOpacity(0, 1.0); // background image: 50% opaque
blend->SetOpacity(1, 1.0); // text: 100% opaque
blend->Update();
vtkNew<vtkImageActor> blendActor;
blendActor->GetMapper()->SetInputConnection(blend->GetOutputPort());
vtkNew<vtkRenderer> blendRenderer;
blendRenderer->AddActor(blendActor);
blendRenderer->ResetCamera();
blendRenderer->SetBackground(colors->GetColor3d("DodgerBlue").GetData());
// vtkNew<vtkPNGWriter> writer;
// writer->SetFileName("output.png");
// writer->SetInputConnection(blend->GetOutputPort());
// writer->Write();
vtkNew<vtkRenderWindow> renderWindow;
renderWindow->SetSize(300, 300);
renderWindow->AddRenderer(blendRenderer);
renderWindow->SetWindowName("ImageText");
vtkNew<vtkRenderWindowInteractor> renderWindowInteractor;
vtkNew<vtkInteractorStyleImage> style;
renderWindowInteractor->SetInteractorStyle(style);
renderWindowInteractor->SetRenderWindow(renderWindow);
renderWindow->Render();
renderWindowInteractor->Initialize();
renderWindowInteractor->Start();
return EXIT_SUCCESS;
}
| 33.634409 | 77 | 0.722826 | [
"render"
] |
7cd9766c925f68bf4dbb4f171d006aa0654b833d | 7,014 | cpp | C++ | third_party/WebKit/Source/core/dom/ScriptedAnimationController.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/core/dom/ScriptedAnimationController.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/core/dom/ScriptedAnimationController.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2011 Google Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "core/dom/ScriptedAnimationController.h"
#include "core/css/MediaQueryListListener.h"
#include "core/dom/Document.h"
#include "core/dom/FrameRequestCallback.h"
#include "core/events/Event.h"
#include "core/frame/LocalDOMWindow.h"
#include "core/frame/LocalFrameView.h"
#include "core/inspector/InspectorTraceEvents.h"
#include "core/loader/DocumentLoader.h"
#include "core/probe/CoreProbes.h"
namespace blink {
std::pair<EventTarget*, StringImpl*> EventTargetKey(const Event* event) {
return std::make_pair(event->target(), event->type().Impl());
}
ScriptedAnimationController::ScriptedAnimationController(Document* document)
: document_(document), callback_collection_(document), suspend_count_(0) {}
DEFINE_TRACE(ScriptedAnimationController) {
visitor->Trace(document_);
visitor->Trace(callback_collection_);
visitor->Trace(event_queue_);
visitor->Trace(media_query_list_listeners_);
visitor->Trace(per_frame_events_);
}
void ScriptedAnimationController::Suspend() {
++suspend_count_;
}
void ScriptedAnimationController::Resume() {
// It would be nice to put an DCHECK(m_suspendCount > 0) here, but in WK1
// resume() can be called even when suspend hasn't (if a tab was created in
// the background).
if (suspend_count_ > 0)
--suspend_count_;
ScheduleAnimationIfNeeded();
}
void ScriptedAnimationController::DispatchEventsAndCallbacksForPrinting() {
DispatchEvents(EventNames::MediaQueryListEvent);
CallMediaQueryListListeners();
}
ScriptedAnimationController::CallbackId
ScriptedAnimationController::RegisterCallback(FrameRequestCallback* callback) {
CallbackId id = callback_collection_.RegisterCallback(callback);
ScheduleAnimationIfNeeded();
return id;
}
void ScriptedAnimationController::CancelCallback(CallbackId id) {
callback_collection_.CancelCallback(id);
}
void ScriptedAnimationController::RunTasks() {
Vector<std::unique_ptr<WTF::Closure>> tasks;
tasks.swap(task_queue_);
for (auto& task : tasks)
(*task)();
}
void ScriptedAnimationController::DispatchEvents(
const AtomicString& event_interface_filter) {
HeapVector<Member<Event>> events;
if (event_interface_filter.IsEmpty()) {
events.swap(event_queue_);
per_frame_events_.clear();
} else {
HeapVector<Member<Event>> remaining;
for (auto& event : event_queue_) {
if (event && event->InterfaceName() == event_interface_filter) {
per_frame_events_.erase(EventTargetKey(event.Get()));
events.push_back(event.Release());
} else {
remaining.push_back(event.Release());
}
}
remaining.swap(event_queue_);
}
for (const auto& event : events) {
EventTarget* event_target = event->target();
// FIXME: we should figure out how to make dispatchEvent properly virtual to
// avoid special casting window.
// FIXME: We should not fire events for nodes that are no longer in the
// tree.
probe::AsyncTask async_task(event_target->GetExecutionContext(), event);
if (LocalDOMWindow* window = event_target->ToLocalDOMWindow())
window->DispatchEvent(event, nullptr);
else
event_target->DispatchEvent(event);
}
}
void ScriptedAnimationController::ExecuteCallbacks(double monotonic_time_now) {
// dispatchEvents() runs script which can cause the document to be destroyed.
if (!document_)
return;
double high_res_now_ms =
1000.0 *
document_->Loader()->GetTiming().MonotonicTimeToZeroBasedDocumentTime(
monotonic_time_now);
double legacy_high_res_now_ms =
1000.0 * document_->Loader()->GetTiming().MonotonicTimeToPseudoWallTime(
monotonic_time_now);
callback_collection_.ExecuteCallbacks(high_res_now_ms,
legacy_high_res_now_ms);
}
void ScriptedAnimationController::CallMediaQueryListListeners() {
MediaQueryListListeners listeners;
listeners.Swap(media_query_list_listeners_);
for (const auto& listener : listeners) {
listener->NotifyMediaQueryChanged();
}
}
bool ScriptedAnimationController::HasScheduledItems() const {
if (suspend_count_)
return false;
return !callback_collection_.IsEmpty() || !task_queue_.IsEmpty() ||
!event_queue_.IsEmpty() || !media_query_list_listeners_.IsEmpty();
}
void ScriptedAnimationController::ServiceScriptedAnimations(
double monotonic_time_now) {
if (!HasScheduledItems())
return;
CallMediaQueryListListeners();
DispatchEvents();
RunTasks();
ExecuteCallbacks(monotonic_time_now);
ScheduleAnimationIfNeeded();
}
void ScriptedAnimationController::EnqueueTask(
std::unique_ptr<WTF::Closure> task) {
task_queue_.push_back(std::move(task));
ScheduleAnimationIfNeeded();
}
void ScriptedAnimationController::EnqueueEvent(Event* event) {
probe::AsyncTaskScheduled(event->target()->GetExecutionContext(),
event->type(), event);
event_queue_.push_back(event);
ScheduleAnimationIfNeeded();
}
void ScriptedAnimationController::EnqueuePerFrameEvent(Event* event) {
if (!per_frame_events_.insert(EventTargetKey(event)).is_new_entry)
return;
EnqueueEvent(event);
}
void ScriptedAnimationController::EnqueueMediaQueryChangeListeners(
HeapVector<Member<MediaQueryListListener>>& listeners) {
for (const auto& listener : listeners) {
media_query_list_listeners_.insert(listener);
}
ScheduleAnimationIfNeeded();
}
void ScriptedAnimationController::ScheduleAnimationIfNeeded() {
if (!HasScheduledItems())
return;
if (!document_)
return;
if (LocalFrameView* frame_view = document_->View())
frame_view->ScheduleAnimation();
}
} // namespace blink
| 33.559809 | 80 | 0.745081 | [
"vector"
] |
7cd97be53c9e15ad978287dfece3cf778d36e87c | 31,634 | cpp | C++ | src/core/menu/tabs/visuals.cpp | mov-rax-rax/gamesneeze | 09b2d9d6ef5b6ad7c9c820f98f1a6339bf1405a1 | [
"MIT"
] | 1 | 2022-01-13T07:05:26.000Z | 2022-01-13T07:05:26.000Z | src/core/menu/tabs/visuals.cpp | mov-rax-rax/gamesneeze | 09b2d9d6ef5b6ad7c9c820f98f1a6339bf1405a1 | [
"MIT"
] | null | null | null | src/core/menu/tabs/visuals.cpp | mov-rax-rax/gamesneeze | 09b2d9d6ef5b6ad7c9c820f98f1a6339bf1405a1 | [
"MIT"
] | 1 | 2021-12-31T13:02:42.000Z | 2021-12-31T13:02:42.000Z | #include "../menu.hpp"
const char *chamsMaterials[] = {"None", "Shaded", "Flat", "Screen Pulse", "Energy Ball", "Glow", "Plastic", "Darude", "Oil"};
void drawChamsWidget(
const char *label,
int *material,
ImColor *color,
int *overlayMaterial = nullptr,
ImColor *overlayColor = nullptr,
int *occludedMaterial = nullptr,
ImColor *occludedColor = nullptr,
int *ragdollMaterial = nullptr,
ImColor *ragdollColor = nullptr,
int *targetMaterial = nullptr,
ImColor *targetColor = nullptr,
int *backtrackMaterial = nullptr,
ImColor *backtrackColor = nullptr,
bool *backtrackTrail = nullptr,
bool *wireframe = nullptr,
bool *overlayWireframe = nullptr
) {
char btnLabel[64];
snprintf(btnLabel, sizeof(btnLabel), "Chams##%s", label);
if (ImGui::Button(btnLabel)) {
ImGui::OpenPopup(btnLabel);
}
if (ImGui::BeginPopup(btnLabel)) {
ImGui::Text("%s Chams", label);
ImGui::Separator();
ImGui::Text("%s Chams", label);
ImGui::Combo("##Chams Material", material, chamsMaterials, IM_ARRAYSIZE(chamsMaterials));
ImGui::SameLine();
ImGui::ColorEdit4("##Chams Color", (float *)color, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_PickerHueWheel);
if (wireframe != nullptr) {
ImGui::SameLine();
ImGui::Checkbox("Wireframe ##Visible Wireframe", wireframe);
}
if (overlayMaterial != nullptr) {
ImGui::Text("%s Chams Overlay", label);
ImGui::Combo("##Chams Overlay Material", overlayMaterial, chamsMaterials, IM_ARRAYSIZE(chamsMaterials));
ImGui::SameLine();
ImGui::ColorEdit4("Chams Overlay Color", (float *)overlayColor, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_PickerHueWheel);
}
if (overlayWireframe != nullptr) {
ImGui::SameLine();
ImGui::Checkbox("Wireframe ##Visible Overlay Wireframe", overlayWireframe);
}
if (occludedMaterial != nullptr) {
ImGui::Separator();
ImGui::Text("%s Occluded Chams", label);
ImGui::Combo("##Occluded Chams Material", occludedMaterial, chamsMaterials, IM_ARRAYSIZE(chamsMaterials));
ImGui::SameLine();
ImGui::ColorEdit4("Occluded Chams Color", (float *)occludedColor, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_PickerHueWheel);
}
if (ragdollMaterial != nullptr) {
ImGui::Separator();
ImGui::Text("%s Ragdoll Chams", label);
ImGui::Combo("##Ragdoll Chams Material", ragdollMaterial, chamsMaterials, IM_ARRAYSIZE(chamsMaterials));
ImGui::SameLine();
ImGui::ColorEdit4("Ragdoll Chams Color", (float *)ragdollColor, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_PickerHueWheel);
}
if (targetMaterial != nullptr) {
ImGui::Separator();
ImGui::Text("%s Target Chams", label);
ImGui::Combo("##Target Chams Material", targetMaterial, chamsMaterials, IM_ARRAYSIZE(chamsMaterials));
ImGui::SameLine();
ImGui::ColorEdit4("Target Chams Color", (float *)targetColor, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_PickerHueWheel);
}
if (backtrackMaterial != nullptr) {
ImGui::Separator();
ImGui::Text("%s Backtrack Chams", label);
ImGui::Combo("##Backtrack Chams Material", backtrackMaterial, chamsMaterials, IM_ARRAYSIZE(chamsMaterials));
ImGui::SameLine();
ImGui::ColorEdit4("Backtrack Chams Color", (float *)backtrackColor, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_PickerHueWheel);
ImGui::Checkbox("Trail", backtrackTrail);
}
ImGui::EndPopup();
}
}
void impactsSelectBox(const char* configVarName) {
ImGui::Text("Show Impacts");
ImGui::SetNextItemWidth(ImGui::GetWindowContentRegionWidth());
const char *selectedDisplay = "Off";
int curSelected = CONFIGINT(configVarName);
switch (curSelected) {
// Client-only.
case 3: {
selectedDisplay = "Client-only";
break;
}
// Server-only.
case 2: {
selectedDisplay = "Server-only";
break;
}
// Both.
case 1: {
selectedDisplay = "Both";
break;
} }
if (ImGui::BeginCombo("##HitBoxes", selectedDisplay)) {
if (ImGui::Selectable("Off", curSelected == 0, ImGuiSelectableFlags_DontClosePopups))
CONFIGINT(configVarName) = 0;
if (ImGui::Selectable("Client-only", curSelected == 3, ImGuiSelectableFlags_DontClosePopups))
CONFIGINT(configVarName) = 3;
if (ImGui::Selectable("Server-only", curSelected == 2, ImGuiSelectableFlags_DontClosePopups))
CONFIGINT(configVarName) = 2;
if (ImGui::Selectable("Both", curSelected == 1, ImGuiSelectableFlags_DontClosePopups))
CONFIGINT(configVarName) = 1;
ImGui::EndCombo();
}
}
void Menu::drawVisualsTab() {
if (ImGui::BeginTabBar("##visTabs")) {
if (ImGui::BeginTabItem("Players")) {
ImGui::BeginChild("Teammates", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.325f, ImGui::GetWindowHeight() * 0.875f), true); {
ImGui::Text("Teammates");
ImGui::Separator();
if (CONFIGBOOL("Visuals>Players>Teammates>Box")) {
ImGui::ColorEdit4("Box Color", (float*)&CONFIGCOL("Visuals>Players>Teammates>Box Color"), ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_PickerHueWheel);
ImGui::SameLine();
}
ImGui::Checkbox("Box", &CONFIGBOOL("Visuals>Players>Teammates>Box"));
if (CONFIGBOOL("Visuals>Players>Teammates>Skeleton")) {
ImGui::ColorEdit4("Skeleton Color", (float*)&CONFIGCOL("Visuals>Players>Teammates>Skeleton Color"), ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_PickerHueWheel);
ImGui::SameLine();
}
ImGui::Checkbox("Skeleton", &CONFIGBOOL("Visuals>Players>Teammates>Skeleton"));
ImGui::Checkbox("Name", &CONFIGBOOL("Visuals>Players>Teammates>Name"));
ImGui::Checkbox("Health", &CONFIGBOOL("Visuals>Players>Teammates>Health"));
if (CONFIGBOOL("Visuals>Players>Teammates>Health Bar")) {
ImGui::ColorEdit4("Health Bar Color", (float*)&CONFIGCOL("Visuals>Players>Teammates>Health Bar Color"), ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_PickerHueWheel);
ImGui::SameLine();
}
ImGui::Checkbox("Health Bar", &CONFIGBOOL("Visuals>Players>Teammates>Health Bar"));
if (CONFIGBOOL("Visuals>Players>Teammates>Health Bar")) {
ImGui::SameLine();
ImGui::Checkbox("Dynamic Color", &CONFIGBOOL("Visuals>Players>Teammates>Dynamic Color"));
}
ImGui::Checkbox("Money", &CONFIGBOOL("Visuals>Players>Teammates>Money"));
ImGui::Checkbox("Armor", &CONFIGBOOL("Visuals>Players>Teammates>Armor"));
ImGui::Checkbox("Weapon", &CONFIGBOOL("Visuals>Players>Teammates>Weapon"));
ImGui::Checkbox("Only When Dead", &CONFIGBOOL("Visuals>Players>Teammates>Only When Dead"));
drawChamsWidget(
/* label */ "Teammates",
/* material */ &CONFIGINT("Visuals>Players>Teammates>Chams>Visible Material"),
/* color */ &CONFIGCOL("Visuals>Players>Teammates>Chams>Visible Color"),
/* overlayMaterial */ &CONFIGINT("Visuals>Players>Teammates>Chams>Visible Overlay Material"),
/* overlayColor */ &CONFIGCOL("Visuals>Players>Teammates>Chams>Visible Overlay Color"),
/* occludedMaterial */ &CONFIGINT("Visuals>Players>Teammates>Chams>Occluded Material"),
/* occludedColor */ &CONFIGCOL("Visuals>Players>Teammates>Chams>Occluded Color"),
/* ragdollMaterial */ &CONFIGINT("Visuals>Players>Teammates>Chams>Ragdoll Material"),
/* ragdollColor */ &CONFIGCOL("Visuals>Players>Teammates>Chams>Ragdoll Color"),
/* targetMaterial */ nullptr,
/* targetColor */ nullptr,
/* backtrackMaterial */ nullptr,
/* backtrackColor */ nullptr,
/* backtrackTrail */ nullptr,
/* wireframe */ &CONFIGBOOL("Visuals>Players>Teammates>Chams>Visible Wireframe"),
/* overlayWireframe */ &CONFIGBOOL("Visuals>Players>Teammates>Chams>Visible Overlay Wireframe")
);
ImGui::EndChild();
}
ImGui::SameLine();
ImGui::BeginChild("Enemies", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.325f, ImGui::GetWindowHeight() * 0.875f), true); {
ImGui::Text("Enemies");
ImGui::Separator();
if (CONFIGBOOL("Visuals>Players>Enemies>Box")) {
ImGui::ColorEdit4("Box Color", (float*)&CONFIGCOL("Visuals>Players>Enemies>Box Color"), ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_PickerHueWheel);
ImGui::SameLine();
}
ImGui::Checkbox("Box", &CONFIGBOOL("Visuals>Players>Enemies>Box"));
if (CONFIGBOOL("Visuals>Players>Enemies>Skeleton")) {
ImGui::ColorEdit4("Skeleton Color", (float*)&CONFIGCOL("Visuals>Players>Enemies>Skeleton Color"), ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_PickerHueWheel);
ImGui::SameLine();
}
ImGui::Checkbox("Skeleton", &CONFIGBOOL("Visuals>Players>Enemies>Skeleton"));
ImGui::Checkbox("Name", &CONFIGBOOL("Visuals>Players>Enemies>Name"));
ImGui::Checkbox("Health", &CONFIGBOOL("Visuals>Players>Enemies>Health"));
if(CONFIGBOOL("Visuals>Players>Enemies>Health Bar")) {
ImGui::ColorEdit4("Health Bar Color", (float*)&CONFIGCOL("Visuals>Players>Enemies>Health Bar Color"), ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_PickerHueWheel);
ImGui::SameLine();
}
ImGui::Checkbox("Health Bar", &CONFIGBOOL("Visuals>Players>Enemies>Health Bar"));
if(CONFIGBOOL("Visuals>Players>Enemies>Health Bar")) {
ImGui::SameLine();
ImGui::Checkbox("Dynamic Color", &CONFIGBOOL("Visuals>Players>Enemies>Dynamic Color"));
}
ImGui::Checkbox("Money", &CONFIGBOOL("Visuals>Players>Enemies>Money"));
ImGui::Checkbox("Armor", &CONFIGBOOL("Visuals>Players>Enemies>Armor"));
ImGui::Checkbox("Flashed", &CONFIGBOOL("Visuals>Players>Enemies>Flashed"));
ImGui::Checkbox("Weapon", &CONFIGBOOL("Visuals>Players>Enemies>Weapon"));
ImGui::Checkbox("Radar", &CONFIGBOOL("Visuals>Players>Enemies>Radar"));
ImGui::Checkbox("Forwardtrack Dots", &CONFIGBOOL("Visuals>Players>Enemies>Forwardtrack Dots"));
ImGui::Checkbox("Vis Check", &CONFIGBOOL("Visuals>Players>Enemies>Vis Check"));
ImGui::Checkbox("Only When Dead", &CONFIGBOOL("Visuals>Players>Enemies>Only When Dead"));
drawChamsWidget(
/* label */ "Enemies",
/* material */ &CONFIGINT("Visuals>Players>Enemies>Chams>Visible Material"),
/* color */ &CONFIGCOL("Visuals>Players>Enemies>Chams>Visible Color"),
/* overlayMaterial */ &CONFIGINT("Visuals>Players>Enemies>Chams>Visible Overlay Material"),
/* overlayColor */ &CONFIGCOL("Visuals>Players>Enemies>Chams>Visible Overlay Color"),
/* occludedMaterial */ &CONFIGINT("Visuals>Players>Enemies>Chams>Occluded Material"),
/* occludedColor */ &CONFIGCOL("Visuals>Players>Enemies>Chams>Occluded Color"),
/* ragdollMaterial */ &CONFIGINT("Visuals>Players>Enemies>Chams>Ragdoll Material"),
/* ragdollColor */ &CONFIGCOL("Visuals>Players>Enemies>Chams>Ragdoll Color"),
/* targetMaterial */ &CONFIGINT("Visuals>Players>Enemies>Chams>Target Material"),
/* targetColor */ &CONFIGCOL("Visuals>Players>Enemies>Chams>Target Color"),
/* backtrackMaterial */ &CONFIGINT("Visuals>Players>Enemies>Chams>Backtrack Material"),
/* backtrackColor */ &CONFIGCOL("Visuals>Players>Enemies>Chams>Backtrack Color"),
/* backtrackTrail */ &CONFIGBOOL("Visuals>Players>Enemies>Chams>Trail"),
/* wireframe */ &CONFIGBOOL("Visuals>Players>Enemies>Chams>Visible Wireframe"),
/* overlayWireframe */ &CONFIGBOOL("Visuals>Players>Enemies>Chams>Visible Overlay Wireframe")
);
ImGui::EndChild();
}
ImGui::SameLine();
ImGui::BeginChild("LocalPlayer", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.325f, ImGui::GetWindowHeight() * 0.875f), true); {
ImGui::Text("LocalPlayer");
ImGui::Separator();
ImGui::Text("Arms");
drawChamsWidget(
/* label */ "Arms",
/* material */ &CONFIGINT("Visuals>Players>LocalPlayer>Arms Material"),
/* color */ &CONFIGCOL("Visuals>Players>LocalPlayer>Arms Color"),
/* overlayMaterial */ &CONFIGINT("Visuals>Players>LocalPlayer>Arms Overlay Material"),
/* overlayColor */ &CONFIGCOL("Visuals>Players>LocalPlayer>Arms Overlay Color"),
/* occludedMaterial */ nullptr,
/* occludedColor */ nullptr,
/* ragdollMaterial */ nullptr,
/* ragdollColor */ nullptr,
/* targetMaterial */ nullptr,
/* targetColor */ nullptr,
/* backtrackMaterial */ nullptr,
/* backtrackColor */ nullptr,
/* backtrackTrail */ nullptr,
/* wireframe */ &CONFIGBOOL("Visuals>Players>LocalPlayer>Arms Wireframe"),
/* overlayWireframe */ &CONFIGBOOL("Visuals>Players>LocalPlayer>Arms Overlay Wireframe")
);
ImGui::Separator();
ImGui::Text("Sleeves");
drawChamsWidget(
/* label */ "Sleeves",
/* material */ &CONFIGINT("Visuals>Players>LocalPlayer>Sleeve Material"),
/* color */ &CONFIGCOL("Visuals>Players>LocalPlayer>Sleeve Color"),
/* overlayMaterial */ &CONFIGINT("Visuals>Players>LocalPlayer>Sleeve Overlay Material"),
/* overlayColor */ &CONFIGCOL("Visuals>Players>LocalPlayer>Sleeve Overlay Color"),
/* occludedMaterial */ nullptr,
/* occludedColor */ nullptr,
/* ragdollMaterial */ nullptr,
/* ragdollColor */ nullptr,
/* targetMaterial */ nullptr,
/* targetColor */ nullptr,
/* backtrackMaterial */ nullptr,
/* backtrackColor */ nullptr,
/* backtrackTrail */ nullptr,
/* wireframe */ &CONFIGBOOL("Visuals>Players>LocalPlayer>Sleeve Wireframe"),
/* overlayWireframe */ &CONFIGBOOL("Visuals>Players>LocalPlayer>Sleeve Overlay Wireframe")
);
ImGui::Separator();
ImGui::Text("Weapons");
drawChamsWidget(
/* label */ "Weapons",
/* material */ &CONFIGINT("Visuals>Players>LocalPlayer>Weapon Material"),
/* color */ &CONFIGCOL("Visuals>Players>LocalPlayer>Weapon Color"),
/* overlayMaterial */ &CONFIGINT("Visuals>Players>LocalPlayer>Weapon Overlay Material"),
/* overlayColor */ &CONFIGCOL("Visuals>Players>LocalPlayer>Weapon Overlay Color"),
/* occludedMaterial */ nullptr,
/* occludedColor */ nullptr,
/* ragdollMaterial */ nullptr,
/* ragdollColor */ nullptr,
/* targetMaterial */ nullptr,
/* targetColor */ nullptr,
/* backtrackMaterial */ nullptr,
/* backtrackColor */ nullptr,
/* backtrackTrail */ nullptr,
/* wireframe */ &CONFIGBOOL("Visuals>Players>LocalPlayer>Weapon Wireframe"),
/* overlayWireframe */ &CONFIGBOOL("Visuals>Players>LocalPlayer>Weapon Overlay Wireframe")
);
ImGui::Separator();
ImGui::ColorEdit4("Crosshair Color", (float*)&CONFIGCOL("Visuals>Players>LocalPlayer>Crosshair Color"), ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_PickerHueWheel);
ImGui::SameLine();
ImGui::ColorEdit4("Crosshair Border Color", (float*)&CONFIGCOL("Visuals>Players>LocalPlayer>Crosshair Border Color"), ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_PickerHueWheel);
ImGui::SameLine();
ImGui::Checkbox("Spread Crosshair", &CONFIGBOOL("Visuals>Players>LocalPlayer>Spread Crosshair"));
ImGui::Checkbox("Recoil Crosshair", &CONFIGBOOL("Visuals>Players>LocalPlayer>Recoil Crosshair"));
// Make sure they can't both be on at the same time
if (CONFIGBOOL("Visuals>Players>LocalPlayer>Recoil Crosshair") && !CONFIGBOOL("Visuals>Players>LocalPlayer>Spread Crosshair")) {
ImGui::Checkbox("Only When Shooting", &CONFIGBOOL("Visuals>Players>LocalPlayer>Recoil Crosshair>Only When Shooting"));
}
ImGui::Separator();
ImGui::Checkbox("No Aim Punch", &CONFIGBOOL("Visuals>Players>LocalPlayer>No Aim Punch"));
ImGui::Checkbox("No View Punch", &CONFIGBOOL("Visuals>Players>LocalPlayer>No View Punch"));
ImGui::EndChild();
}
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("World")) {
ImGui::BeginChild("World", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.65f, ImGui::GetWindowHeight() * 0.875f), true); {
ImGui::Text("World");
ImGui::Separator();
if (
ImGui::ColorEdit4("World Color Modulation", (float*)&CONFIGCOL("Visuals>World>World>World Color Modulation"), ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_PickerHueWheel) ||
ImGui::ColorEdit4("SkyBox Color Modulation", (float*)&CONFIGCOL("Visuals>World>World>SkyBox Color Modulation"), ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_PickerHueWheel) ||
ImGui::Button("Update Color Modulation")) {
Features::ColorModulation::updateColorModulation();
}
ImGui::Text("NightMode");
ImGui::SetNextItemWidth(ImGui::GetWindowContentRegionWidth());
ImGui::SliderInt("##NightMode", &CONFIGINT("Visuals>World>World>Nightmode"), 0, 100);
ImGui::Text("Bloom");
ImGui::SetNextItemWidth(ImGui::GetWindowContentRegionWidth());
ImGui::SliderInt("##Bloom", &CONFIGINT("Visuals>World>World>Bloom"), 0, 1000);
ImGui::Text("Skybox");
ImGui::SetNextItemWidth(ImGui::GetWindowContentRegionWidth());
ImGui::Combo("##Skybox", &CONFIGINT("Visuals>World>World>Skybox"), skyboxes, IM_ARRAYSIZE(skyboxes));
ImGui::Text("Camera FOV");
ImGui::SetNextItemWidth(ImGui::GetWindowContentRegionWidth());
ImGui::SliderInt("##Camera FOV", &CONFIGINT("Visuals>World>World>FOV"), 70, 120);
ImGui::Text("Viewmodel FOV");
ImGui::SetNextItemWidth(ImGui::GetWindowContentRegionWidth());
ImGui::SliderInt("##Viewmodel FOV", &CONFIGINT("Visuals>World>World>Viewmodel FOV"), 0, 130);
ImGui::Checkbox("Third Person", &CONFIGBOOL("Visuals>World>World>Third Person"));
ImGui::Checkbox("No Sniper Crosshair", &CONFIGBOOL("Visuals>World>World>No Sniper Crosshair"));
ImGui::Checkbox("No Flash", &CONFIGBOOL("Visuals>World>World>No Flash"));
ImGui::Text("Flash Amount");
ImGui::SetNextItemWidth(ImGui::GetWindowContentRegionWidth());
ImGui::SliderInt("##Flash Amount", &CONFIGINT("Visuals>World>World>No Flash Amount"), 0, 255);
ImGui::Checkbox("Fullbright (Applying this setting may lag momentarily)", &CONFIGBOOL("Visuals>World>World>Fullbright"));
ImGui::Checkbox("Draw Gray (Applying this setting may lag momentarily)", &CONFIGBOOL("Visuals>World>World>Gray"));
ImGui::Checkbox("Low-res Image (Applying this setting may lag momentarily)", &CONFIGBOOL("Visuals>World>World>Low-res Image"));
ImGui::Checkbox("Ragdoll Gravity", &CONFIGBOOL("Visuals>World>World>Ragdoll Gravity"));
ImGui::Checkbox("No Shadows (CSM) (Applying this setting may lag momentarily)", &CONFIGBOOL("Visuals>World>World>No Shadows"));
impactsSelectBox("Visuals>World>World>Show Impacts");
if (CONFIGBOOL("Visuals>World>World>Bullet Tracers")) {
ImGui::ColorEdit4("Bullet Tracers Color", (float*)&CONFIGCOL("Visuals>World>World>Bullet Tracers Color"), ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_PickerHueWheel);
ImGui::SameLine();
}
ImGui::Checkbox("Bullet Tracers", &CONFIGBOOL("Visuals>World>World>Bullet Tracers"));
if (CONFIGBOOL("Visuals>World>World>Bullet Tracers")) {
ImGui::SameLine();
ImGui::Checkbox("Laser", &CONFIGBOOL("Visuals>World>World>Bullet Tracers Laser"));
}
ImGui::Separator();
ImGui::Checkbox("Fog", &CONFIGBOOL("Visuals>World>World>Override Fog"));
if (CONFIGBOOL("Visuals>World>World>Override Fog")) {
auto fogStartValue = CONFIGINT("Visuals>World>World>Fog Start");
auto fogEndValue = CONFIGINT("Visuals>World>World>Fog End");
auto fogFarzValue = CONFIGINT("Visuals>World>World>Fog Farz");
ImGui::Text("Fog Start");
ImGui::SetNextItemWidth(ImGui::GetWindowContentRegionWidth());
ImGui::SliderInt("##Fog Start", &fogStartValue, 0, 30000);
ImGui::Text("Fog End");
ImGui::SetNextItemWidth(ImGui::GetWindowContentRegionWidth());
ImGui::SliderInt("##Fog End", &fogEndValue, 0, 30000);
ImGui::Text("Fog Farz (Clip)");
ImGui::SetNextItemWidth(ImGui::GetWindowContentRegionWidth());
ImGui::SliderInt("##Fog Farz", &fogFarzValue, 0, 30000);
ImGui::ColorEdit4("Fog Color", (float*)&CONFIGCOL("Visuals>World>World>Fog Color"), ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_PickerHueWheel);
CONFIGINT("Visuals>World>World>Fog Start") = std::clamp(fogStartValue, 0, fogEndValue);
CONFIGINT("Visuals>World>World>Fog End") = std::clamp(fogEndValue, fogStartValue, fogFarzValue);
CONFIGINT("Visuals>World>World>Fog Farz") = std::clamp(fogFarzValue, fogEndValue, 30000);
}
ImGui::EndChild();
}
ImGui::SameLine();
ImGui::BeginChild("Items", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.34f, ImGui::GetWindowHeight() * 0.875f), true); {
ImGui::Text("Items");
ImGui::Separator();
if (CONFIGBOOL("Visuals>World>Items>Weapon Box")) {
ImGui::ColorEdit4("Weapon Box Color", (float*)&CONFIGCOL("Visuals>World>Items>Weapon Box Color"), ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_PickerHueWheel);
ImGui::SameLine();
}
ImGui::Checkbox("Weapon Box", &CONFIGBOOL("Visuals>World>Items>Weapon Box"));
ImGui::Checkbox("Weapon Label", &CONFIGBOOL("Visuals>World>Items>Weapon Label"));
ImGui::Separator();
if (CONFIGBOOL("Visuals>World>Items>Grenade Box")) {
ImGui::ColorEdit4("Grenade Box Color", (float*)&CONFIGCOL("Visuals>World>Items>Grenade Box Color"), ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_PickerHueWheel);
ImGui::SameLine();
}
ImGui::Checkbox("Grenade Box", &CONFIGBOOL("Visuals>World>Items>Grenade Box"));
if (CONFIGBOOL("Visuals>World>Items>Grenade Box")) {
ImGui::SameLine();
ImGui::Checkbox("Dynamic Color", &CONFIGBOOL("Visuals>World>Items>Grenade Box Dynamic Color"));
}
ImGui::Checkbox("Grenade Label", &CONFIGBOOL("Visuals>World>Items>Grenade Label"));
ImGui::Checkbox("Grenade Owners", &CONFIGBOOL("Visuals>World>Items>Grenade Owners"));
ImGui::Separator();
if (CONFIGBOOL("Visuals>World>Items>Planted C4 Box")) {
ImGui::ColorEdit4("Planted C4 Box Color", (float*)&CONFIGCOL("Visuals>World>Items>Planted C4 Box Color"), ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_PickerHueWheel);
ImGui::SameLine();
}
ImGui::Checkbox("Planted C4 Box", &CONFIGBOOL("Visuals>World>Items>Planted C4 Box"));
ImGui::Checkbox("Planted C4 Label", &CONFIGBOOL("Visuals>World>Items>Planted C4 Label"));
ImGui::Separator();
if (CONFIGBOOL("Visuals>World>Items>Chicken Box")) {
ImGui::ColorEdit4("Chicken Box Color", (float*)&CONFIGCOL("Visuals>World>Items>Chicken Box Color"), ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_PickerHueWheel);
ImGui::SameLine();
}
ImGui::Checkbox("Chicken Box", &CONFIGBOOL("Visuals>World>Items>Chicken Box"));
ImGui::Checkbox("Chicken Label", &CONFIGBOOL("Visuals>World>Items>Chicken Label"));
ImGui::Separator();
if (CONFIGBOOL("Visuals>World>Items>Fish Box")) {
ImGui::ColorEdit4("Fish Box Color", (float*)&CONFIGCOL("Visuals>World>Items>Fish Box Color"), ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_PickerHueWheel);
ImGui::SameLine();
}
ImGui::Checkbox("Fish Box", &CONFIGBOOL("Visuals>World>Items>Fish Box"));
ImGui::Checkbox("Fish Label", &CONFIGBOOL("Visuals>World>Items>Fish Label"));
ImGui::Separator();
ImGui::Checkbox("ESP Quite literally everything", &CONFIGBOOL("Visuals>World>Items>ESP Quite literally everything"));
ImGui::Separator();
ImGui::Text("World Models");
drawChamsWidget(
/* label */ "World Model",
/* material */ &CONFIGINT("Visuals>World>World>Model Material"),
/* color */ &CONFIGCOL("Visuals>World>World>Model Color"),
/* overlayMaterial */ nullptr,
/* overlayColor */ nullptr,
/* occludedMaterial */ nullptr,
/* occludedColor */ nullptr,
/* ragdollMaterial */ nullptr,
/* ragdollColor */ nullptr,
/* targetMaterial */ nullptr,
/* targetColor */ nullptr,
/* backtrackMaterial */ nullptr,
/* backtrackColor */ nullptr,
/* backtrackTrail */ nullptr,
/* wireframe */ nullptr,
/* overlayWireframe */ nullptr
);
drawChamsWidget(
/* label */ "World Overlay Model",
/* material */ &CONFIGINT("Visuals>World>World>Model Overlay Material"),
/* color */ &CONFIGCOL("Visuals>World>World>Model Overlay Color"),
/* overlayMaterial */ nullptr,
/* overlayColor */ nullptr,
/* occludedMaterial */ nullptr,
/* occludedColor */ nullptr,
/* ragdollMaterial */ nullptr,
/* ragdollColor */ nullptr,
/* targetMaterial */ nullptr,
/* targetColor */ nullptr,
/* backtrackMaterial */ nullptr,
/* backtrackColor */ nullptr,
/* backtrackTrail */ nullptr,
/* wireframe */ nullptr,
/* overlayWireframe */ nullptr
);
ImGui::EndChild();
}
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("Menu")) {
ImGui::BeginChild("Menu", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.65f, ImGui::GetWindowHeight() * 0.875f), true); {
ImGui::Text("Menu");
ImGui::Separator();
ImGui::ColorEdit4("Accent", (float *)&CONFIGCOL("Visuals>Menu>Menu>Accent"), ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_PickerHueWheel);
ImGui::SameLine();
ImGui::Text("Accent");
ImGui::ColorEdit4("Background", (float *)&CONFIGCOL("Visuals>Menu>Menu>Background"), ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_PickerHueWheel);
ImGui::SameLine();
ImGui::Text("Background");
ImGui::ColorEdit4("Background Secondary", (float *)&CONFIGCOL("Visuals>Menu>Menu>Background Secondary"), ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_PickerHueWheel);
ImGui::SameLine();
ImGui::Text("Background Secondary");
ImGui::ColorEdit4("Foreground", (float *)&CONFIGCOL("Visuals>Menu>Menu>Foreground"), ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_PickerHueWheel);
ImGui::SameLine();
ImGui::Text("Foreground");
ImGui::EndChild();
}
ImGui::EndTabItem();
}
ImGui::EndTabBar();
}
}
| 57.411978 | 231 | 0.586742 | [
"model"
] |
7ce3b8381fa46483a5b80c026b5ade1ed6b80096 | 216 | cpp | C++ | Server/src/character/enemy/Enemy.cpp | YanaPIIDXer/UnityAnpanMMO | ea1cf79ee344b955d5f423bf2f8a201efaa61f9b | [
"MIT"
] | 2 | 2021-07-07T06:35:59.000Z | 2021-08-07T12:22:48.000Z | Server/src/character/enemy/Enemy.cpp | YanaPIIDXer/UnityAnpanMMO | ea1cf79ee344b955d5f423bf2f8a201efaa61f9b | [
"MIT"
] | null | null | null | Server/src/character/enemy/Enemy.cpp | YanaPIIDXer/UnityAnpanMMO | ea1cf79ee344b955d5f423bf2f8a201efaa61f9b | [
"MIT"
] | null | null | null | #include "Enemy.h"
// コンストラクタ
Enemy::Enemy(uint InId, Area *pInArea, const Vector &InPosition, float InRotation)
: Character(InId, pInArea, InPosition, InRotation)
{
}
// デストラクタ
Enemy::~Enemy()
{
}
| 16.615385 | 83 | 0.652778 | [
"vector"
] |
7ce815300147298ef69fa68e41f7ffcea1fac88b | 602 | hpp | C++ | src/core/lib/core_reflection/interfaces/i_method.hpp | wgsyd/wgtf | d8cacb43e2c5d40080d33c18a8c2f5bd27d21bed | [
"BSD-3-Clause"
] | 28 | 2016-06-03T05:28:25.000Z | 2019-02-14T12:04:31.000Z | src/core/lib/core_reflection/interfaces/i_method.hpp | karajensen/wgtf | 740397bcfdbc02bc574231579d57d7c9cd5cc26d | [
"BSD-3-Clause"
] | null | null | null | src/core/lib/core_reflection/interfaces/i_method.hpp | karajensen/wgtf | 740397bcfdbc02bc574231579d57d7c9cd5cc26d | [
"BSD-3-Clause"
] | 14 | 2016-06-03T05:52:27.000Z | 2019-03-21T09:56:03.000Z | #ifndef I_METHOD_HPP
#define I_METHOD_HPP
#include <cstddef>
#include "core_reflection/reflection_dll.hpp"
namespace wgt
{
class ObjectHandle;
class IDefinitionManager;
class ReflectedMethodParameters;
class Variant;
class REFLECTION_DLL IMethod
{
public:
virtual ~IMethod()
{
}
virtual Variant invoke(const ObjectHandle& object, const IDefinitionManager& definitionManager,
const ReflectedMethodParameters& parameters) = 0;
// TODO return a collection of the arg types
virtual std::size_t parameterCount() const = 0;
};
} // end namespace wgt
#endif // I_METHOD_HPP
| 21.5 | 96 | 0.755814 | [
"object"
] |
7ce90dc309fe6e50cb0702091bc9b8172566f016 | 5,581 | cpp | C++ | Chimera/Source/AnalogInput/AiCore.cpp | zzpwahaha/Chimera-Control-Trim | df1bbf6bea0b87b8c7c9a99dce213fdc249118f2 | [
"MIT"
] | null | null | null | Chimera/Source/AnalogInput/AiCore.cpp | zzpwahaha/Chimera-Control-Trim | df1bbf6bea0b87b8c7c9a99dce213fdc249118f2 | [
"MIT"
] | null | null | null | Chimera/Source/AnalogInput/AiCore.cpp | zzpwahaha/Chimera-Control-Trim | df1bbf6bea0b87b8c7c9a99dce213fdc249118f2 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "AiCore.h"
#include <Windows.h>
#include <sstream>
AiCore::AiCore()
: socket(AI_SAFEMODE, AI_SOCKET_ADDRESS, AI_SOCKET_PORT)
{
//socket.write("mac", terminator);
//QByteArray tmp = socket.read();
}
void AiCore::getSettingsFromConfig(ConfigStream& file)
{
std::string tmp;
for (auto& av : aiValues) {
file >> tmp;
av.status.range = av.status.fromStr(tmp);
}
}
void AiCore::saveSettingsToConfig(ConfigStream& file)
{
file << "\n/*Channel Ranges*/ ";
for (auto& av : aiValues) {
file << AiChannelRange::toStr(av.status.range) << " ";
}
}
void AiCore::updateChannelRange()
{
/*A3-A0,A7-A4,B3-B0,B7-B4*/
unsigned char buff[5] = { 0,0,0,0,0 }; // the last 0 is important to terminate the char*, otherwise it is undefined when append to string, ie might contain junking trailing behind
for (size_t i = 0; i < 4/*range register*/; i++)
{
for (size_t j = 0; j < 4/*2 bit code*/; j++)
{
buff[i] += aiValues[i * 4 + j].status.codes() << (2 * j);
}
}
try {
socket.open();
socket.write(QByteArray::fromStdString(std::string("(rng,") + (char*)buff + ")"), terminator);
std::string rc = socket.read();
socket.close();
if (str(rc, 13, false, true).find("Error") != std::string::npos) {
thrower("Error in updating range in Analoge in. \r\n" + rc);
}
}
catch (ChimeraError& e) {
throwNested(e.what());
}
}
void AiCore::getSingleSnap(unsigned n_to_avg)
{
std::vector<unsigned> onChannel;
char buff[3] = { 0,0,0 };
for (unsigned i = 0; i < size_t(AIGrid::total); i++)
{
if (aiValues[i].status.range != AiChannelRange::which::off) {
onChannel.push_back(i);
buff[i / size_t(AIGrid::numPERunit)] |= 1 << (i % size_t(AIGrid::numPERunit));
}
}
if (buff[0] == 0 && buff[1] == 0) {
thrower("Error: Analog in - No channel is on for acquisition");
return; // no channel to be sampled
}
// make sure when all channels in one bank (A or B) are off, the cmd is not terminated by that 0
std::array<bool, 2> epty = { false,false };
for (short i = 0; i < 2; i++) { if (buff[i] == 0) { buff[i] = 1; epty[i] = true; } }
unsigned n_chnl = onChannel.size() + (epty[0] || epty[1]);
if (epty[0] || epty[1]) { epty[0] ? onChannel.insert(onChannel.begin(), 0) : onChannel.push_back(size_t(AIGrid::numPERunit) - 1); }
//socket.resetConnection();
socket.open();
socket.write(QByteArray("(") + placeholder + QByteArray(buff, 2) + QByteArray(",")
+ QByteArray::fromStdString(str(n_to_avg)) + QByteArray(")"), terminator);
Sleep(5);
socket.resetConnection();
socket.write("(trg, )", terminator);
QByteArray rc;
Sleep(20);
try {
//rc = socket.readAll();
//rc = socket.readAll();
//rc = std::move(socket.readRaw());
rc = std::move(socket.readTillFull(n_chnl * n_to_avg * 2));
socket.close();
}
catch (ChimeraError& e) {
throwNested(e.what());
}
// see if the return start with error
if (std::string(rc.left(10)).find("Error") != std::string::npos) {
thrower(str("Error exception thrown while getting Ai system single snap! \r\n") + rc.data());
return;
}
//std::vector<double> datatmp;
//std::stringstream ss(rc.data());
//while (ss.good())
//{
// std::string substr;
// std::getline(ss, substr, ',');
// if (substr.size() == 0) {
// thrower("Analogin Error: Empty string encountered in converting to int");
// return;
// }
// datatmp.push_back(std::stoi(substr));
//}
//if (datatmp.size() != n_chnl * n_to_avg) {
// thrower("Error in Analog in: the data size is not as expected, data might correupted.\r\n");
// return;
//}
//std::vector<std::vector<double>> data(n_chnl);
//for (unsigned chanCnts = 0; chanCnts < n_chnl; chanCnts++)
//{
// data[chanCnts].resize(n_to_avg);
// for (unsigned i = 0; i < datatmp.size() / n_chnl; i++)
// {
// data[chanCnts][i] = datatmp[(i * n_chnl + chanCnts)];
// }
//}
if (rc.size() != n_chnl * n_to_avg * 2/*byte*/) {
thrower("Error in Analog in: the data size is " + str(rc.size()) + " and is not as expected to be"
+ str(n_chnl * n_to_avg * 2) + ", data might correupted.\r\n");
return;
}
std::vector<std::vector<double>> data(n_chnl);
for (unsigned chanCnts = 0; chanCnts < n_chnl; chanCnts++)
{
data[chanCnts].resize(n_to_avg);
for (unsigned i = 0; i < rc.size() / n_chnl / 2/*byte*/; i++)
{
unsigned short high = (unsigned short(rc[(i * n_chnl + chanCnts) * 2]) << 8) & 0xff00;
unsigned short low = unsigned short(rc[(i * n_chnl + chanCnts) * 2 + 1]) & 0x00ff;
data[chanCnts][i] = signed short(high | low);
}
}
for (unsigned ch = 0; ch < n_chnl; ch++)
{
double sum = std::accumulate(data[ch].begin(), data[ch].end(), 0.0);
double m = sum / n_to_avg;
double accum = 0.0;
std::for_each(data[ch].begin(), data[ch].end(), [&](const double d) {
accum += (d - m) * (d - m); });
double stdev = sqrt(accum / (n_to_avg - 1));
if (aiValues[onChannel[ch]].status.range != AiChannelRange::which::off) {
aiValues[onChannel[ch]].mean = m * aiValues[onChannel[ch]].status.scales() / 0x7fff;
aiValues[onChannel[ch]].std = stdev * aiValues[onChannel[ch]].status.scales() / 0x7fff;
}
}
//auto tmpD = reinterpret_cast<short*>(rc.data());
//std::vector<double> tmpdata = std::vector<double>(tmpD, tmpD + rc.size() / 2);
}
std::array<double, size_t(AIGrid::total)> AiCore::getCurrentValues()
{
std::array<double, size_t(AIGrid::total)> vals;
for (size_t i = 0; i < size_t(AIGrid::total); i++)
{
vals[i] = aiValues[i].mean;
}
return vals;
}
void AiCore::setAiRange(unsigned channel, AiChannelRange::which range)
{
aiValues[channel].status.range = range;
}
| 29.84492 | 180 | 0.627486 | [
"vector"
] |
7ce93dab91108b6f140c95285dd3fcb2b441fab1 | 2,032 | cpp | C++ | WordBalancing/src/main.cpp | dylanrainwater/Daily-Programmer | 2bdeac16ad2d499c41f977f57c254a18fc39efe3 | [
"MIT"
] | null | null | null | WordBalancing/src/main.cpp | dylanrainwater/Daily-Programmer | 2bdeac16ad2d499c41f977f57c254a18fc39efe3 | [
"MIT"
] | null | null | null | WordBalancing/src/main.cpp | dylanrainwater/Daily-Programmer | 2bdeac16ad2d499c41f977f57c254a18fc39efe3 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
/*
* Enter multiple lines of input separated by '\n', when a line is empty stop collecting input.
*/
cout << "Enter input in capital letters, just press enter to stop." << endl;
vector<string> input;
string inputLine;
while (getline(cin, inputLine)) {
if (inputLine != "") {
input.push_back(inputLine);
}
else {
break;
}
}
/*
* :/ there are a lot of for loops ahead.
* This initial for loop is just cycling
* through all of the words from the input.
*/
bool balances = false;
for (string &word : input) {
/*
* This for loop goes through all of
* the letters in the current word.
*/
for (int i = 0; i < word.length(); ++i) {
int leftWeight = 0;
int rightWeight = 0;
/*
* This loop goes through all of the letters to the left
* of the currently selected "balance point" and calculates
* the total "weight" on the left side.
*/
for (int j = 0; j < i; ++j) { // Left of index
leftWeight += (1 + word[j] - 'A') * (i - j);
}
/*
* Same as above, but for the right-side of the "balance point."
*/
for (int j = i; j < word.length(); ++j) {
rightWeight += (1 + word[j] - 'A') * (j - i);
}
balances = leftWeight == rightWeight;
/*
* This exits out as soon as the working "balance point" is found!
*/
if (balances) {
cout << word.substr(0, i) << " " << word[i] << " " << word.substr(i + 1, word.length()) << " - " << leftWeight << endl;
break;
}
}
if (!balances) {
cout << word << " DOES NOT BALANCE." << endl;
}
cout << endl;
}
}
| 30.787879 | 135 | 0.46998 | [
"vector"
] |
7cf730633aa63f2bf21213742cb9fb4ac8c24045 | 12,932 | cpp | C++ | Sources/Elastos/Packages/Apps/Launcher2/src/elastos/droid/launcher2/DragView.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Packages/Apps/Launcher2/src/elastos/droid/launcher2/DragView.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Packages/Apps/Launcher2/src/elastos/droid/launcher2/DragView.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include "elastos/droid/launcher2/DragView.h"
#include "elastos/droid/launcher2/LauncherAnimUtils.h"
#include "elastos/droid/launcher2/DragLayer.h"
#include "elastos/droid/launcher2/CDragLayerLayoutParams.h"
#include "Elastos.Droid.Content.h"
#include "Elastos.Droid.View.h"
#include "Elastos.Droid.Service.h"
#include "R.h"
using Elastos::Droid::Animation::IAnimator;
using Elastos::Droid::Animation::ITimeInterpolator;
using Elastos::Droid::Content::IContext;
using Elastos::Droid::Graphics::PorterDuffMode_SRC_ATOP;
using Elastos::Droid::Graphics::PaintStyle_FILL;
using Elastos::Droid::Graphics::CRect;
using Elastos::Droid::Graphics::CPaint;
using Elastos::Droid::Graphics::IColorFilter;
using Elastos::Droid::Graphics::CBitmapHelper;
using Elastos::Droid::Graphics::IBitmapHelper;
using Elastos::Droid::Graphics::CPorterDuffColorFilter;
using Elastos::Droid::Graphics::IPorterDuffColorFilter;
using Elastos::Droid::View::IView;
using Elastos::Droid::View::IViewGroup;
using Elastos::Droid::View::IViewParent;
using Elastos::Droid::View::Animation::CDecelerateInterpolator;
using Elastos::Droid::View::Animation::IDecelerateInterpolator;
using Elastos::Core::IFloat;
namespace Elastos {
namespace Droid {
namespace Launcher2 {
CAR_INTERFACE_IMPL(DragView::MyListener, Object, IAnimatorUpdateListener);
DragView::MyListener::MyListener(
/* [in] */ DragView* host,
/* [in] */ Float offsetX,
/* [in] */ Float offsetY,
/* [in] */ Float initialScale,
/* [in] */ Float scale)
: mHost(host)
, mOffsetX(offsetX)
, mOffsetY(offsetY)
, mInitialScale(initialScale)
, mScale(scale)
{
}
ECode DragView::MyListener::OnAnimationUpdate(
/* [in] */ IValueAnimator* animation)
{
AutoPtr<IInterface> obj;
animation->GetAnimatedValue((IInterface**)&obj);
AutoPtr<IFloat> fvalue = IFloat::Probe(obj);
Float value;
fvalue->GetValue(&value);
Int32 deltaX = (Int32)((value * mOffsetX) - mHost->mOffsetX);
Int32 deltaY = (Int32)((value * mOffsetY) - mHost->mOffsetY);
mHost->mOffsetX += deltaX;
mHost->mOffsetY += deltaY;
IView::Probe(mHost)->SetScaleX(mInitialScale + (value * (mScale - mInitialScale)));
IView::Probe(mHost)->SetScaleY(mInitialScale + (value * (mScale - mInitialScale)));
if (mHost->sDragAlpha != 1.0f) {
IView::Probe(mHost)->SetAlpha(mHost->sDragAlpha * value + (1.0f - value));
}
AutoPtr<IViewParent> res;
IView::Probe(mHost)->GetParent((IViewParent**)&res);
if (res == NULL) {
IAnimator::Probe(animation)->Cancel();
}
else {
Float tmp;
IView::Probe(mHost)->GetTranslationX(&tmp);
IView::Probe(mHost)->SetTranslationX(tmp + deltaX);
IView::Probe(mHost)->GetTranslationY(&tmp);
IView::Probe(mHost)->SetTranslationY(tmp + deltaY);
}
return NOERROR;
}
CAR_INTERFACE_IMPL(DragView::MyListener2, Object, IAnimatorUpdateListener);
DragView::MyListener2::MyListener2(
/* [in] */ DragView* host)
: mHost(host)
{
}
ECode DragView::MyListener2::OnAnimationUpdate(
/* [in] */ IValueAnimator* animation)
{
return animation->GetAnimatedFraction(&(mHost->mCrossFadeProgress));
}
DragView::MyRunnable::MyRunnable(
/* [in] */ DragView* host)
: mHost(host)
{
}
ECode DragView::MyRunnable::Run()
{
return IAnimator::Probe(mHost->mAnim)->Start();
}
Float DragView::sDragAlpha = 1.0f;
CAR_INTERFACE_IMPL(DragView, View, IDragView);
DragView::DragView()
: mRegistrationX(0)
, mRegistrationY(0)
, mHasDrawn(FALSE)
, mCrossFadeProgress(0.0f)
, mOffsetX(0.0f)
, mOffsetY(0.0f)
, mInitialScale(1.0f)
{
}
ECode DragView::constructor(
/* [in] */ ILauncher* launcher,
/* [in] */ IBitmap* bitmap,
/* [in] */ Int32 registrationX,
/* [in] */ Int32 registrationY,
/* [in] */ Int32 left,
/* [in] */ Int32 top,
/* [in] */ Int32 width,
/* [in] */ Int32 height,
/* [in] */ Float initialScale)
{
View::constructor(IContext::Probe(launcher));
AutoPtr<IDragLayer> dl;
launcher->GetDragLayer((IDragLayer**)&dl);
mDragLayer = dl.Get();
mInitialScale = initialScale;
AutoPtr<IResources> res;
GetResources((IResources**)&res);
Int32 _offsetX;
res->GetDimensionPixelSize(Elastos::Droid::Launcher2::R::dimen::dragViewOffsetX, &_offsetX);
Float offsetX = (Float)_offsetX;
Int32 _offsetY;
res->GetDimensionPixelSize(Elastos::Droid::Launcher2::R::dimen::dragViewOffsetY, &_offsetY);
Float offsetY = (Float)_offsetY;
Int32 _scaleDps;
res->GetDimensionPixelSize(Elastos::Droid::Launcher2::R::dimen::dragViewScale, &_scaleDps);
Float scaleDps = _scaleDps;
Float scale = (width + scaleDps) * 1.0f / width;
// Set the initial scale to avoid any jumps
SetScaleX(initialScale);
SetScaleY(initialScale);
// Animate the view into the correct position
AutoPtr<ArrayOf<Float> > array = ArrayOf<Float>::Alloc(2);
(*array)[0] = 0.0f;
(*array)[1] = 1.0f;
mAnim = LauncherAnimUtils::OfFloat(IView::Probe(this), array);
mAnim->SetDuration(150);
AutoPtr<IAnimatorUpdateListener> listener = new MyListener(this, offsetX, offsetY,
initialScale, scale);
mAnim->AddUpdateListener(listener);
AutoPtr<IBitmapHelper> helper;
CBitmapHelper::AcquireSingleton((IBitmapHelper**)&helper);
helper->CreateBitmap(bitmap, left, top, width, height, (IBitmap**)&mBitmap);
AutoPtr<IRect> rect;
CRect::New(0, 0, width, height, (IRect**)&rect);
SetDragRegion(rect);
// The point in our scaled bitmap that the touch events are located
mRegistrationX = registrationX;
mRegistrationY = registrationY;
// Force a measure, because Workspace uses getMeasuredHeight() before the layout pass
Int32 ms = View::MeasureSpec::MakeMeasureSpec(0, View::MeasureSpec::UNSPECIFIED);
Measure(ms, ms);
CPaint::New(IPaint::FILTER_BITMAP_FLAG, (IPaint**)&mPaint);
return NOERROR;
}
ECode DragView::GetOffsetY(
/* [out] */ Float* y)
{
VALIDATE_NOT_NULL(y);
*y = mOffsetY;
return NOERROR;
}
ECode DragView::GetDragRegionLeft(
/* [out] */ Int32* left)
{
VALIDATE_NOT_NULL(left);
return mDragRegion->GetLeft(left);
}
ECode DragView::GetDragRegionTop(
/* [out] */ Int32* top)
{
VALIDATE_NOT_NULL(top);
return mDragRegion->GetTop(top);
}
ECode DragView::GetDragRegionWidth(
/* [out] */ Int32* width)
{
VALIDATE_NOT_NULL(width);
return mDragRegion->GetWidth(width);
}
ECode DragView::GetDragRegionHeight(
/* [out] */ Int32* height)
{
VALIDATE_NOT_NULL(height);
return mDragRegion->GetHeight(height);
}
ECode DragView::SetDragVisualizeOffset(
/* [in] */ IPoint* p)
{
mDragVisualizeOffset = p;
return NOERROR;
}
ECode DragView::GetDragVisualizeOffset(
/* [out] */ IPoint** point)
{
VALIDATE_NOT_NULL(point);
*point = mDragVisualizeOffset;
REFCOUNT_ADD(*point);
return NOERROR;
}
ECode DragView::SetDragRegion(
/* [in] */ IRect* r)
{
mDragRegion = r;
return NOERROR;
}
ECode DragView::GetDragRegion(
/* [out] */ IRect** rec)
{
VALIDATE_NOT_NULL(rec);
*rec = mDragRegion;
REFCOUNT_ADD(*rec);
return NOERROR;
}
ECode DragView::GetInitialScale(
/* [out] */ Float* scale)
{
VALIDATE_NOT_NULL(scale);
*scale = mInitialScale;
return NOERROR;
}
ECode DragView::UpdateInitialScaleToCurrentScale()
{
return GetScaleX(&mInitialScale);
}
ECode DragView::OnMeasure(
/* [in] */ Int32 widthMeasureSpec,
/* [in] */ Int32 heightMeasureSpec)
{
Int32 width, height;
mBitmap->GetWidth(&width);
mBitmap->GetHeight(&height);
SetMeasuredDimension(width, height);
return NOERROR;
}
void DragView::OnDraw(
/* [in] */ ICanvas* canvas)
{
//@SuppressWarnings("all") // suppress dead code warning
const Boolean debug = FALSE;
if (debug) {
AutoPtr<IPaint> p;
CPaint::New((IPaint**)&p);
p->SetStyle(PaintStyle_FILL);
p->SetColor(0x66ffffff);
Int32 width;
GetWidth(&width);
Int32 height;
GetHeight(&height);
canvas->DrawRect(0, 0, width, height, p);
}
mHasDrawn = TRUE;
Boolean crossFade = mCrossFadeProgress > 0 && mCrossFadeBitmap != NULL;
if (crossFade) {
Int32 alpha = crossFade ? (Int32)(255 * (1 - mCrossFadeProgress)) : 255;
mPaint->SetAlpha(alpha);
}
canvas->DrawBitmap(mBitmap, 0.0f, 0.0f, mPaint);
if (crossFade) {
mPaint->SetAlpha((Int32)(255 * mCrossFadeProgress));
Int32 tmp;
canvas->Save(&tmp);
Int32 width;
mBitmap->GetWidth(&width);
Int32 width2;
mCrossFadeBitmap->GetWidth(&width2);
Float sX = (width * 1.0f) / width2;
Int32 height;
mBitmap->GetHeight(&height);
Int32 height2;
mCrossFadeBitmap->GetHeight(&height2);
Float sY = (height * 1.0f) / height2;
canvas->Scale(sX, sY);
canvas->DrawBitmap(mCrossFadeBitmap, 0.0f, 0.0f, mPaint);
canvas->Restore();
}
}
ECode DragView::SetCrossFadeBitmap(
/* [in] */ IBitmap* crossFadeBitmap)
{
mCrossFadeBitmap = crossFadeBitmap;
return NOERROR;
}
ECode DragView::CrossFade(
/* [in] */ Int32 duration)
{
AutoPtr<ArrayOf<Float> > array = ArrayOf<Float>::Alloc(2);
(*array)[0] = 0.0f;
(*array)[1] = 1.0f;
AutoPtr<IValueAnimator> va = LauncherAnimUtils::OfFloat(IView::Probe(this), array);
va->SetDuration(duration);
AutoPtr<IDecelerateInterpolator> polator;
CDecelerateInterpolator::New(1.5f, (IDecelerateInterpolator**)&polator);
IAnimator::Probe(va)->SetInterpolator(ITimeInterpolator::Probe(polator));
AutoPtr<IAnimatorUpdateListener> listener = new MyListener2(this);
va->AddUpdateListener(listener);
return IAnimator::Probe(va)->Start();
}
ECode DragView::SetColor(
/* [in] */ Int32 color)
{
if (mPaint == NULL) {
CPaint::New(IPaint::FILTER_BITMAP_FLAG, (IPaint**)&mPaint);
}
if (color != 0) {
AutoPtr<IPorterDuffColorFilter> filter;
CPorterDuffColorFilter::New(color, PorterDuffMode_SRC_ATOP, (IPorterDuffColorFilter**)&filter);
mPaint->SetColorFilter(IColorFilter::Probe(filter));
}
else {
mPaint->SetColorFilter(NULL);
}
return Invalidate();
}
ECode DragView::HasDrawn(
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result);
*result = mHasDrawn;
return NOERROR;
}
ECode DragView::SetAlpha(
/* [in] */ Float alpha)
{
View::SetAlpha(alpha);
mPaint->SetAlpha((Int32)(255 * alpha));
return Invalidate();
}
ECode DragView::Show(
/* [in] */ Int32 touchX,
/* [in] */ Int32 touchY)
{
IViewGroup::Probe(mDragLayer)->AddView(this);
// Start the pick-up animation
AutoPtr<CDragLayerLayoutParams> lp;
CDragLayerLayoutParams::NewByFriend(0, 0, (CDragLayerLayoutParams**)&lp);
mBitmap->GetWidth(&(lp->mWidth));
mBitmap->GetHeight(&(lp->mHeight));
lp->mCustomPosition = TRUE;
SetLayoutParams(lp);
SetTranslationX(touchX - mRegistrationX);
SetTranslationY(touchY - mRegistrationY);
// Post the animation to skip other expensive work happening on the first frame
AutoPtr<MyRunnable> run = new MyRunnable(this);
Boolean res;
return Post(run, &res);
}
ECode DragView::CancelAnimation()
{
if (mAnim != NULL) {
Boolean res;
IAnimator::Probe(mAnim)->IsRunning(&res);
if (res) {
return IAnimator::Probe(mAnim)->Cancel();
}
}
return NOERROR;
}
ECode DragView::ResetLayoutParams()
{
mOffsetX = mOffsetY = 0;
return RequestLayout();
}
ECode DragView::Move(
/* [in] */ Int32 touchX,
/* [in] */ Int32 touchY)
{
SetTranslationX(touchX - mRegistrationX + (Int32)mOffsetX);
return SetTranslationY(touchY - mRegistrationY + (Int32)mOffsetY);
}
ECode DragView::Remove()
{
AutoPtr<IViewParent> res;
GetParent((IViewParent**)&res);
if (res != NULL) {
return IViewGroup::Probe(mDragLayer)->RemoveView(this);
}
return NOERROR;
}
} // namespace Launcher2
} // namespace Droid
} // namespace Elastos | 27.87069 | 103 | 0.656434 | [
"object"
] |
7cf97a5af2427222660645782983157a46e8d1a1 | 1,887 | hpp | C++ | api/xui_api.hpp | xxoenoexx/xui | 85b0fb48476e2d52882e300fa52c8e5c3dc2be09 | [
"MIT"
] | 16 | 2020-05-01T21:21:49.000Z | 2022-01-14T11:38:19.000Z | api/xui_api.hpp | xxoenoexx/xui | 85b0fb48476e2d52882e300fa52c8e5c3dc2be09 | [
"MIT"
] | null | null | null | api/xui_api.hpp | xxoenoexx/xui | 85b0fb48476e2d52882e300fa52c8e5c3dc2be09 | [
"MIT"
] | 3 | 2020-07-04T03:19:51.000Z | 2021-12-10T00:28:39.000Z | #ifndef xui_api
#define xui_api
// Utility.
#include <xui/api/objects/xui_object_utility.hpp>
// Object types.
#include <xui/api/objects/xui_object_base.hpp>
#include <xui/api/objects/xui_object_form.hpp>
#include <xui/api/objects/xui_object_page.hpp>
#include <xui/api/objects/xui_object_frame.hpp>
#include <xui/api/objects/xui_object_checkbox.hpp>
#include <xui/api/objects/xui_object_slider.hpp>
namespace xui {
namespace details {
class global_api : public base_api {
private:
// Children objects unique ptrs.
xui::child_vector < xui::object_form > m_Children_ptrs;
// Input distribution.
std::unique_ptr < xui::details::input_distribution > m_Input_distribution_ptr;
// Friendship between Api and Input distribution.
friend class xui::details::input_distribution;
public:
// Deconstructor.
~global_api ( void ) = default;
// Constructor.
global_api ( HWND hwnd ) : base_api ( ) {
// Setup input distribution.
m_Input_distribution_ptr = std::make_unique < xui::details::input_distribution > ( hwnd );
};
// Get input distribution.
auto input_distribution ( void ) {
return m_Input_distribution_ptr.get ( );
};
// Adds form to api.
auto add_form ( std::unique_ptr < xui::object_form > form ) {
m_Children_ptrs.push_back ( std::move ( form ) );
};
};
}; // !!! details
// Api.
extern std::unique_ptr < details::global_api > g_Api;
// Add form to Api.
static auto end_form ( std::unique_ptr < xui::object_form > form ) {
xui::g_Api->add_form ( std::move ( form ) );
};
// Initialize xui api and core components.
template < typename tCompound > requires std::is_compound < tCompound >::value
static auto init ( HWND n , tCompound operation ) {
xui::g_Api = std::make_unique < xui::details::global_api > ( n );
// Populate.
operation ( );
};
}; // !!! xui
#endif // !!! xui_api
| 27.347826 | 94 | 0.687864 | [
"object"
] |
cfb7b97fae7a9f4909367ab7ddddbd12602344f4 | 5,880 | hh | C++ | include/cbrainx/abstractLayer.hh | mansoormemon/cbrainx | 1b7fa699e4470bf5fc39006cb719dcfc48a7688c | [
"Apache-2.0"
] | 1 | 2022-03-02T20:03:49.000Z | 2022-03-02T20:03:49.000Z | include/cbrainx/abstractLayer.hh | mansoormemon/cbrainx | 1b7fa699e4470bf5fc39006cb719dcfc48a7688c | [
"Apache-2.0"
] | null | null | null | include/cbrainx/abstractLayer.hh | mansoormemon/cbrainx | 1b7fa699e4470bf5fc39006cb719dcfc48a7688c | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 CBrainX
// Project URL: https://github.com/mansoormemon/cbrainx
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Copyright (c) 2021 Mansoor Ahmed Memon <mansoorahmed.one@gmail.com>
#ifndef CBRAINX__ABSTRACT_LAYER_HH_
#define CBRAINX__ABSTRACT_LAYER_HH_
#include <string>
#include "shape.hh"
#include "tensor.hh"
#include "typeAliases.hh"
namespace cbx {
// /////////////////////////////////////////////
// Enumerations
// /////////////////////////////////////////////
/// \brief Supported layer types.
enum class LayerType { Dense, Activation, Softmax };
/// \brief The `AbstractLayer` class defines a standard interface for all layers.
///
/// \see LayerType
class AbstractLayer {
public:
using value_type = f32;
using container = Tensor<value_type>;
using size_type = container::size_type;
using difference_type = container::difference_type;
private:
/// \brief Layer ID.
i32 id_ = {};
/// \brief The name of the layer.
std::string name_ = "LYR";
protected:
/// \brief The input layer.
mutable container input_ = {};
/// \brief The output layer.
mutable container output_ = {};
public:
// /////////////////////////////////////////////
// Constructors and Destructors
// /////////////////////////////////////////////
/// \brief Default constructor.
AbstractLayer() = default;
/// \brief Default copy constructor.
/// \param[in] other Source layer.
AbstractLayer(const AbstractLayer &other) = default;
/// \brief Move constructor.
/// \param[in] other Source layer.
AbstractLayer(AbstractLayer &&other) noexcept;
/// \brief Parameterized constructor.
/// \param[in] id Layer ID.
explicit AbstractLayer(i32 id);
/// \brief Parameterized constructor.
/// \param[in] name The name of the layer.
explicit AbstractLayer(std::string_view name);
/// \brief Parameterized constructor.
/// \param[in] id Layer ID.
/// \param[in] name The name of the layer.
AbstractLayer(i32 id, std::string_view name);
/// \brief Default destructor.
virtual ~AbstractLayer() = default;
// /////////////////////////////////////////////
// Assignment Operators
// /////////////////////////////////////////////
/// \brief Default copy assignment operator.
/// \param[in] other Source layer.
/// \return A reference to self.
auto operator=(const AbstractLayer &other) -> AbstractLayer & = default;
/// \brief Move assignment operator.
/// \param[in] other Source layer.
/// \return A reference to self.
auto operator=(AbstractLayer &&other) noexcept -> AbstractLayer &;
// /////////////////////////////////////////////
// Accessors and Mutators
// /////////////////////////////////////////////
/// \brief Returns the ID of the layer.
/// \return Layer ID.
[[nodiscard]] auto id() const -> i32;
/// \brief Sets layer ID.
/// \param[in] id The new ID of the layer.
/// \return A reference to self.
auto set_id(i32 id) -> AbstractLayer &;
/// \brief Returns the name of the layer.
/// \return The name of the layer.
[[nodiscard]] auto name() const -> std::string;
/// \brief Sets the name of the layer.
/// \param[in] name The new name of the layer.
/// \return A reference to self.
auto set_name(std::string_view name) -> AbstractLayer &;
// /////////////////////////////////////////////
// Query Functions
// /////////////////////////////////////////////
/// \brief Returns the number of neurons in the layer.
/// \return The number of neurons in the layer.
[[nodiscard]] virtual auto neurons() const -> size_type = 0;
/// \brief Returns the number of modifiable parameters in the layer.
/// \return The number of modifiable parameters in the layer.
[[nodiscard]] virtual auto parameters() const -> size_type = 0;
/// \brief Returns the type of the layer.
/// \return The type of the layer.
///
/// \see LayerType
[[nodiscard]] virtual auto type() const -> LayerType = 0;
// /////////////////////////////////////////////
// Informative
// /////////////////////////////////////////////
/// \brief Returns a string with information about the layer's properties.
/// \return Information about the layer's properties as a string.
[[nodiscard]] virtual auto property() const -> std::string = 0;
/// \brief Returns a string with the layer's name and ID.
/// \return The layer's name and ID as a string.
[[nodiscard]] virtual auto to_string() const -> std::string;
/// \brief Returns the layer's type as a string.
/// \return The layer's type as a string.
///
/// \see LayerType
[[nodiscard]] virtual auto type_name() const -> std::string;
// /////////////////////////////////////////////
// Core Functionality
// /////////////////////////////////////////////
/// \brief Returns the cached input layer.
/// \return The cached input layer.
[[nodiscard]] auto input() const -> const container &;
/// \brief Returns the cached output layer.
/// \return The cached output layer.
[[nodiscard]] auto output() const -> const container &;
/// \brief Drops the cached input and output layers.
auto drop_caches() const -> void;
/// \brief Forward pass.
/// \param[in] input The input layer.
/// \return A reference to self.
[[nodiscard]] virtual auto forward_pass(const container &input) const -> const AbstractLayer & = 0;
};
}
#endif
| 30.947368 | 101 | 0.602891 | [
"shape"
] |
cfc96d1a6ce26c224738ca96e2fae6f1b069e3ab | 716 | cpp | C++ | LeetCode/ThousandTwo/1695-max_erasure_value.cpp | Ginkgo-Biloba/Cpp-Repo1-VS | 231c68a055e6bf69a3f7c224e7c0182b67ce5b67 | [
"Apache-2.0"
] | null | null | null | LeetCode/ThousandTwo/1695-max_erasure_value.cpp | Ginkgo-Biloba/Cpp-Repo1-VS | 231c68a055e6bf69a3f7c224e7c0182b67ce5b67 | [
"Apache-2.0"
] | null | null | null | LeetCode/ThousandTwo/1695-max_erasure_value.cpp | Ginkgo-Biloba/Cpp-Repo1-VS | 231c68a055e6bf69a3f7c224e7c0182b67ce5b67 | [
"Apache-2.0"
] | null | null | null | #include "leetcode.hpp"
/* 1695. 删除子数组的最大得分
给你一个正整数数组 nums ,请你从中删除一个含有 若干不同元素 的子数组。
删除子数组的 得分 就是子数组各元素之 和 。
返回 只删除一个 子数组可获得的 最大得分 。
如果数组 b 是数组 a 的一个连续子序列,即如果它等于 a[l],a[l+1],...,a[r] ,那么它就是 a 的一个子数组。
示例 1:
输入:nums = [4,2,4,5,6]
输出:17
解释:最优子数组是 [2,4,5,6]
示例 2:
输入:nums = [5,2,1,2,5,2,1,2,5]
输出:8
解释:最优子数组是 [5,2,1] 或 [1,2,5]
提示:
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^4
*/
int maximumUniqueSubarray(vector<int>& A)
{
vector<char> M(100001);
int len = static_cast<int>(A.size());
int ans = 0, sum = 0, i = 0;
for (int k = 0; k < len; ++k)
{
int a = A[k];
for (; M[a]; ++i)
{
M[A[i]] = 0;
sum -= A[i];
}
M[a] = 1;
sum += a;
ans = max(ans, sum);
}
return ans;
}
int main()
{
}
| 14.039216 | 66 | 0.547486 | [
"vector"
] |
cfdc2d20c44418edcd49bcb850c6cdc2916fdd91 | 6,722 | cpp | C++ | src/accelerators/bvh.cpp | jjzhang166/MirageRender | a51c3dff7db6eacaf111b868ad498caa8fe5a3d2 | [
"MIT"
] | 166 | 2015-11-28T21:24:03.000Z | 2022-03-17T12:29:47.000Z | src/accelerators/bvh.cpp | jjzhang166/MirageRender | a51c3dff7db6eacaf111b868ad498caa8fe5a3d2 | [
"MIT"
] | 5 | 2016-09-27T06:18:32.000Z | 2017-05-26T09:31:29.000Z | src/accelerators/bvh.cpp | jjzhang166/MirageRender | a51c3dff7db6eacaf111b868ad498caa8fe5a3d2 | [
"MIT"
] | 16 | 2016-01-24T07:57:27.000Z | 2021-08-04T03:31:40.000Z | #include "bvh.h"
// std includes
#include <iostream>
#include <algorithm>
#include <ctime>
// mirage includes
#include "../macros.h"
namespace mirage
{
// ------------------------------------------------------------------------
// BVH Node Object
// ------------------------------------------------------------------------
BVHNode::BVHNode(int axis, float pos, std::vector<Shape *> data, AABB bbox) :
split_axis(axis),
split_pos(pos),
data(data),
aabb(bbox),
l_child(nullptr),
r_child(nullptr)
{
}
BVHNode::~BVHNode()
{
DELETE(l_child);
DELETE(r_child);
}
bool BVHNode::isLeaf()
{
return (l_child == nullptr) && (r_child == nullptr);
}
// ------------------------------------------------------------------------
// BVH Accelerator Object
// ------------------------------------------------------------------------
BVHAccel::BVHAccel(const std::vector<Shape *> shapes, const float lThreshold) :
Accelerator(shapes),
m_leafThreshold(lThreshold),
m_root(nullptr)
{
LOG("BVHAccel: a New instance was created.");
LOG("BVHAccel: Number of loaded shapes: " << m_shapes.size());
}
BVHAccel::~BVHAccel()
{
DELETE(m_root);
}
void BVHAccel::update() const
{
WRN("Unimplemented function BVHAccel::update was called.");
}
bool BVHAccel::intersect(const Ray & ray, Intersection & iSect)
{
bool result = false;
float tHit = INFINITY;
float tHit0 = 0.0f;
float tHit1 = INFINITY;
traverse(m_root, ray, result, tHit, tHit0, tHit1, iSect);
return result;
}
bool BVHAccel::intersectP(const Ray & ray)
{
bool result = false;
float tHit = ray.maxt;
float tHit0 = ray.mint;
float tHit1 = INFINITY;
traverseP(m_root, ray, result, tHit, tHit0, tHit1);
return result;
}
void BVHAccel::init()
{
LOG("BVHAccel: Started building the hierarchy...");
std::clock_t startTime = std::clock();
m_root = new BVHNode;
buildRecursive(m_root, 0, m_shapes);
std::clock_t endTime = std::clock();
std::clock_t time = endTime - startTime;
float duration = time / (double)CLOCKS_PER_SEC;
m_initialized = true;
LOG("BVHAccel: Build finished! Time taken: " << duration << "s.");
}
void BVHAccel::buildRecursive(BVHNode * node, int depth, std::vector<Shape *> &shapes)
{
// Calculate node axis-aligned bounding box
AABB node_bbox = shapes[0]->worldBound();
for (size_t i = 0; i < shapes.size(); i++)
{
node_bbox = node_bbox.addBox(shapes[i]->worldBound());
}
node->aabb = node_bbox;
// Create a leaf if recursion limit was reached
if (shapes.size() <= m_leafThreshold)
{
node->data.insert(node->data.end(), shapes.begin(), shapes.end());
return;
}
// Split along the longest axis, find it...
const int axis = node_bbox.getMaximumExtent();
node->split_axis = axis;
// Calculate split point & sort the primitives based on pre-set rules
const int median = shapes.size() >> 1;
std::nth_element(shapes.begin(), shapes.begin() + median, shapes.end(), BVHCompareShapes(axis));
node->split_pos = shapes[median]->worldBound().getCentroid()[axis];
// Create branches
node->l_child = new BVHNode;
node->r_child = new BVHNode;
// Create left & right child shape vectors
std::vector<Shape *> lList(median);
std::vector<Shape *> rList(shapes.size() - median);
std::copy(shapes.begin(), shapes.begin() + median, lList.begin());
std::copy(shapes.begin() + median, shapes.end(), rList.begin());
// Recursive call to build the child nodes
buildRecursive(node->l_child, depth + 1, lList);
buildRecursive(node->r_child, depth + 1, rList);
}
void BVHAccel::traverse(BVHNode * node, const Ray & ray, bool & bHit, float & tHit, float & tHit0, float & tHit1, Intersection & iSect)
{
if (node->isLeaf())
{
// Return if our bbox is closer than the triangle
if (tHit0 > tHit)
return;
Intersection iSectInit;
bool bIsectInit = false;
for (auto * s : node->data)
{
bIsectInit = s->intersect(ray, iSectInit);
if (bIsectInit && iSectInit.getT() < tHit && iSectInit.getT() < ray.maxt)
{
bHit = true;
tHit = iSectInit.getT();
iSect = iSectInit;
}
}
}
else
{
if (node->l_child->aabb.intersectP(ray, tHit0, tHit1))
{
traverse(node->l_child, ray, bHit, tHit, tHit0, tHit1, iSect);
}
if (node->r_child->aabb.intersectP(ray, tHit0, tHit1))
{
traverse(node->r_child, ray, bHit, tHit, tHit0, tHit1, iSect);
}
}
// Below is an example optimization, it is not ready yet
/*
else
{
// Capture distances into temp variables
float l_tHit0 = tHit0, l_tHit1 = tHit1, r_tHit0 = tHit0, r_tHit1 = tHit1;
// Attempt to hit both leafs
bool l_hit = node->l_child->aabb.intersectP(ray, l_tHit0, l_tHit1);
bool r_hit = node->r_child->aabb.intersectP(ray, r_tHit0, r_tHit1);
// Traverse the closest hit first, if it hits a shape don't traverse other leaf
if (l_hit && r_hit && (l_tHit0 < r_tHit0))
{
// Capture tHit
float temp_tHit = tHit;
// Traverse to the node
traverse(node->l_child, ray, bHit, tHit, tHit0, tHit1, iSect);
// Only traverse right if we didn't hit a triangle
if (tHit <= temp_tHit)
traverse(node->r_child, ray, bHit, tHit, tHit0, tHit1, iSect);
}
else if (l_hit && r_hit && (l_tHit0 > r_tHit0))
{
// Capture tHit
float temp_tHit = tHit;
// Traverse to the node
traverse(node->r_child, ray, bHit, tHit, tHit0, tHit1, iSect);
// Only traverse left if we didn't hit a triangle
if (tHit <= temp_tHit)
traverse(node->l_child, ray, bHit, tHit, tHit0, tHit1, iSect);
}
else if (l_hit && r_hit)
{
traverse(node->l_child, ray, bHit, tHit, tHit0, tHit1, iSect);
traverse(node->r_child, ray, bHit, tHit, tHit0, tHit1, iSect);
}
else if (l_hit && !r_hit)
{
traverse(node->l_child, ray, bHit, tHit, tHit0, tHit1, iSect);
}
else if (r_hit && !l_hit)
{
traverse(node->r_child, ray, bHit, tHit, tHit0, tHit1, iSect);
}
}
*/
}
// TODO: Figure out how to optimize this. It differs from the regular tree traversion function
void BVHAccel::traverseP(BVHNode * node, const Ray & ray, bool & bHit, float & tHit, float & tHit0, float & tHit1)
{
if (node->isLeaf())
{
Intersection iSectInit;
float tInit = tHit1;
for (auto * s : node->data)
{
if (s->intersectP(ray) && tInit < tHit && tInit < ray.maxt)
{
bHit = true;
tHit = tInit;
}
}
}
else
{
if (node->l_child->aabb.intersectP(ray, tHit0, tHit1))
{
traverseP(node->l_child, ray, bHit, tHit, tHit0, tHit1);
}
if (node->r_child->aabb.intersectP(ray, tHit0, tHit1))
{
traverseP(node->r_child, ray, bHit, tHit, tHit0, tHit1);
}
}
}
}
| 25.853846 | 136 | 0.613062 | [
"object",
"shape",
"vector"
] |
cfdc5657d7fbff174884d7b9ca9efa5f552f811d | 13,606 | cpp | C++ | test/c8_check/c8_check.cpp | hashingitcom/c8 | 3a6c00f5b25bb98cc82b39605d5f14b0f2e820e5 | [
"BSD-3-Clause"
] | 2 | 2018-07-11T10:59:19.000Z | 2020-09-20T08:36:10.000Z | test/c8_check/c8_check.cpp | hashingitcom/c8 | 3a6c00f5b25bb98cc82b39605d5f14b0f2e820e5 | [
"BSD-3-Clause"
] | 25 | 2017-01-09T22:08:39.000Z | 2017-05-29T19:07:31.000Z | test/c8_check/c8_check.cpp | hashingitcom/c8 | 3a6c00f5b25bb98cc82b39605d5f14b0f2e820e5 | [
"BSD-3-Clause"
] | null | null | null | /*
* c8_check.cpp
*/
#include <algorithm>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <vector>
#include <unistd.h>
#include "result.h"
#include "natural_check.h"
#include "integer_check.h"
#include "rational_check.h"
/*
* No-op test used to find timing information.
*/
auto test_nop() -> result {
result r("nop");
r.start_clock();
r.stop_clock();
r.check_pass("");
return r;
}
/*
* Report the usage for this test program.
*/
static auto usage(const char *name) -> void {
std::cerr << "usage: " << name << " [OPTIONS]\n\n";
std::cerr << "Options\n";
std::cerr << " -b Generate benchmark results (optional)\n";
std::cerr << " -v Verbose reporting (optional)\n\n";
}
/*
* List of tests to run.
*/
const test tests[] = {
test_natural_construct_0,
test_natural_construct_1,
test_natural_construct_2,
test_natural_construct_3,
test_natural_construct_4,
test_natural_construct_5,
test_natural_construct_6,
test_natural_construct_7,
test_natural_size_bits_0,
test_natural_size_bits_1,
test_natural_size_bits_2,
test_natural_size_bits_3,
test_natural_add_0a,
test_natural_add_0b,
test_natural_add_1a,
test_natural_add_1b,
test_natural_add_2a,
test_natural_add_2b,
test_natural_add_3a,
test_natural_add_3b,
test_natural_add_4a,
test_natural_add_4b,
test_natural_subtract_0a,
test_natural_subtract_0b,
test_natural_subtract_1a,
test_natural_subtract_1b,
test_natural_subtract_2a,
test_natural_subtract_2b,
test_natural_subtract_3a,
test_natural_subtract_3b,
test_natural_subtract_4a,
test_natural_subtract_4b,
test_natural_subtract_5a,
test_natural_subtract_5b,
test_natural_compare_0a,
test_natural_compare_0b,
test_natural_compare_0c,
test_natural_compare_0d,
test_natural_compare_0e,
test_natural_compare_0f,
test_natural_compare_1a,
test_natural_compare_1b,
test_natural_compare_1c,
test_natural_compare_1d,
test_natural_compare_1e,
test_natural_compare_1f,
test_natural_compare_2a,
test_natural_compare_2b,
test_natural_compare_2c,
test_natural_compare_2d,
test_natural_compare_2e,
test_natural_compare_2f,
test_natural_compare_3a,
test_natural_compare_3b,
test_natural_compare_3c,
test_natural_compare_3d,
test_natural_compare_3e,
test_natural_compare_3f,
test_natural_lshift_0a,
test_natural_lshift_0b,
test_natural_lshift_1a,
test_natural_lshift_1b,
test_natural_lshift_2a,
test_natural_lshift_2b,
test_natural_lshift_3a,
test_natural_lshift_3b,
test_natural_lshift_4a,
test_natural_lshift_4b,
test_natural_lshift_5a,
test_natural_lshift_5b,
test_natural_lshift_6a,
test_natural_lshift_6b,
test_natural_rshift_0a,
test_natural_rshift_0b,
test_natural_rshift_1a,
test_natural_rshift_1b,
test_natural_rshift_2a,
test_natural_rshift_2b,
test_natural_rshift_3a,
test_natural_rshift_3b,
test_natural_rshift_4a,
test_natural_rshift_4b,
test_natural_rshift_5a,
test_natural_rshift_5b,
test_natural_rshift_6a,
test_natural_rshift_6b,
test_natural_multiply_0a,
test_natural_multiply_0b,
test_natural_multiply_1a,
test_natural_multiply_1b,
test_natural_multiply_2a,
test_natural_multiply_2b,
test_natural_multiply_3a,
test_natural_multiply_3b,
test_natural_multiply_4a,
test_natural_multiply_4b,
test_natural_multiply_5a,
test_natural_multiply_5b,
test_natural_divide_0a,
test_natural_divide_0b,
test_natural_divide_0c,
test_natural_divide_1a,
test_natural_divide_1b,
test_natural_divide_1c,
test_natural_divide_2a,
test_natural_divide_2b,
test_natural_divide_2c,
test_natural_divide_3a,
test_natural_divide_3b,
test_natural_divide_3c,
test_natural_divide_4a,
test_natural_divide_4b,
test_natural_divide_4c,
test_natural_divide_5a,
test_natural_divide_5b,
test_natural_divide_5c,
test_natural_divide_6a,
test_natural_divide_6b,
test_natural_divide_6c,
test_natural_divide_7a,
test_natural_divide_7b,
test_natural_divide_7c,
test_natural_divide_8a,
test_natural_divide_8b,
test_natural_divide_8c,
test_natural_gcd_0,
test_natural_gcd_1,
test_natural_gcd_2,
test_natural_gcd_3,
test_natural_gcd_4,
test_natural_to_unsigned_long_long_0,
test_natural_to_unsigned_long_long_1,
test_natural_to_unsigned_long_long_2,
test_natural_to_unsigned_long_long_3,
test_natural_to_unsigned_long_long_4,
test_natural_print_0,
test_natural_print_1,
test_natural_print_2,
test_natural_print_3,
test_natural_print_4,
test_natural_print_5,
test_natural_print_6,
test_natural_print_7,
test_integer_construct_0,
test_integer_construct_1,
test_integer_construct_2,
test_integer_construct_3,
test_integer_construct_4,
test_integer_construct_5,
test_integer_construct_6,
test_integer_construct_7,
test_integer_construct_8,
test_integer_construct_9,
test_integer_construct_10,
test_integer_construct_11,
test_integer_add_0a,
test_integer_add_0b,
test_integer_add_1a,
test_integer_add_1b,
test_integer_add_2a,
test_integer_add_2b,
test_integer_add_3a,
test_integer_add_3b,
test_integer_subtract_0a,
test_integer_subtract_0b,
test_integer_subtract_1a,
test_integer_subtract_1b,
test_integer_subtract_2a,
test_integer_subtract_2b,
test_integer_subtract_3a,
test_integer_subtract_3b,
test_integer_compare_0a,
test_integer_compare_0b,
test_integer_compare_0c,
test_integer_compare_0d,
test_integer_compare_0e,
test_integer_compare_0f,
test_integer_compare_1a,
test_integer_compare_1b,
test_integer_compare_1c,
test_integer_compare_1d,
test_integer_compare_1e,
test_integer_compare_1f,
test_integer_compare_2a,
test_integer_compare_2b,
test_integer_compare_2c,
test_integer_compare_2d,
test_integer_compare_2e,
test_integer_compare_2f,
test_integer_compare_3a,
test_integer_compare_3b,
test_integer_compare_3c,
test_integer_compare_3d,
test_integer_compare_3e,
test_integer_compare_3f,
test_integer_lshift_0a,
test_integer_lshift_0b,
test_integer_lshift_1a,
test_integer_lshift_1b,
test_integer_lshift_2a,
test_integer_lshift_2b,
test_integer_lshift_3a,
test_integer_lshift_3b,
test_integer_lshift_4a,
test_integer_lshift_4b,
test_integer_rshift_0a,
test_integer_rshift_0b,
test_integer_rshift_1a,
test_integer_rshift_1b,
test_integer_rshift_2a,
test_integer_rshift_2b,
test_integer_rshift_3a,
test_integer_rshift_3b,
test_integer_rshift_4a,
test_integer_rshift_4b,
test_integer_multiply_0a,
test_integer_multiply_0b,
test_integer_multiply_1a,
test_integer_multiply_1b,
test_integer_multiply_2a,
test_integer_multiply_2b,
test_integer_multiply_3a,
test_integer_multiply_3b,
test_integer_divide_0a,
test_integer_divide_0b,
test_integer_divide_1a,
test_integer_divide_1b,
test_integer_divide_2a,
test_integer_divide_2b,
test_integer_divide_3a,
test_integer_divide_3b,
test_integer_divide_4a,
test_integer_divide_4b,
test_integer_magnitude_0,
test_integer_magnitude_1,
test_integer_magnitude_2,
test_integer_to_long_long_0,
test_integer_to_long_long_1,
test_integer_to_long_long_2,
test_integer_to_long_long_3,
test_integer_to_long_long_4,
test_integer_print_0,
test_integer_print_1,
test_integer_print_2,
test_integer_print_3,
test_integer_print_4,
test_integer_print_5,
test_integer_print_6,
test_integer_print_7,
test_rational_construct_0,
test_rational_construct_1,
test_rational_construct_2,
test_rational_construct_3,
test_rational_construct_4,
test_rational_construct_5,
test_rational_construct_6,
test_rational_construct_7,
test_rational_construct_8,
test_rational_construct_9,
test_rational_construct_10,
test_rational_add_0a,
test_rational_add_0b,
test_rational_add_1a,
test_rational_add_1b,
test_rational_add_2a,
test_rational_add_2b,
test_rational_add_3a,
test_rational_add_3b,
test_rational_subtract_0a,
test_rational_subtract_0b,
test_rational_subtract_1a,
test_rational_subtract_1b,
test_rational_subtract_2a,
test_rational_subtract_2b,
test_rational_subtract_3a,
test_rational_subtract_3b,
test_rational_compare_0a,
test_rational_compare_0b,
test_rational_compare_0c,
test_rational_compare_0d,
test_rational_compare_0e,
test_rational_compare_0f,
test_rational_compare_1a,
test_rational_compare_1b,
test_rational_compare_1c,
test_rational_compare_1d,
test_rational_compare_1e,
test_rational_compare_1f,
test_rational_compare_2a,
test_rational_compare_2b,
test_rational_compare_2c,
test_rational_compare_2d,
test_rational_compare_2e,
test_rational_compare_2f,
test_rational_compare_3a,
test_rational_compare_3b,
test_rational_compare_3c,
test_rational_compare_3d,
test_rational_compare_3e,
test_rational_compare_3f,
test_rational_multiply_0a,
test_rational_multiply_0b,
test_rational_multiply_1a,
test_rational_multiply_1b,
test_rational_multiply_2a,
test_rational_multiply_2b,
test_rational_multiply_3a,
test_rational_multiply_3b,
test_rational_divide_0a,
test_rational_divide_0b,
test_rational_divide_1a,
test_rational_divide_1b,
test_rational_divide_2a,
test_rational_divide_2b,
test_rational_divide_3a,
test_rational_divide_3b,
test_rational_divide_4a,
test_rational_divide_4b,
test_rational_to_double_0,
test_rational_to_double_1,
test_rational_to_double_2,
test_rational_to_double_3,
test_rational_to_double_4,
test_rational_to_parts_0,
test_rational_to_parts_1,
test_rational_print_0,
test_rational_print_1,
test_rational_print_2,
test_rational_print_3,
test_rational_print_4,
test_rational_print_5,
test_rational_print_6,
test_rational_print_7,
nullptr
};
/*
* Entry point.
*/
auto main(int argc, char **argv) -> int {
bool verbose = false;
std::size_t loops = 1;
/*
* Parse the command line options.
*/
int ch;
while ((ch = getopt(argc, argv, "bv?")) != -1) {
switch (ch) {
case 'b':
loops = 10000;
break;
case 'v':
verbose = true;
break;
case '?':
usage(argv[0]);
exit(-1);
}
}
/*
* Run a prolonged no-op test to warm up any power-saving modes to move
* into a higher performance state. We do this by running the no-op test
* repeatedly for 2 seconds.
*/
std::vector<std::chrono::nanoseconds> nop_durations;
nop_durations.reserve(1000);
std::time_t t = std::time(nullptr);
std::time_t s;
do {
for (std::size_t i = 1; i < 1000; i++) {
result r = test_nop();
nop_durations.push_back(r.get_elapsed());
}
s = std::time(nullptr);
} while ((s - t) < 2);
/*
* Take the 0.01% value - we need to make sure we've picked up one after everything
* is running in a performance state.
*/
std::nth_element(nop_durations.begin(), nop_durations.begin() + (nop_durations.size() / 10000), nop_durations.end());
auto nop_duration = nop_durations[nop_durations.size() / 10000];
/*
* Run the tests.
*/
bool res = true;
const test *p = tests;
while (*p) {
std::vector<std::chrono::nanoseconds> durations;
durations.reserve(loops);
/*
* Run one test every time. This gives the pass/fail status.
*/
result r = (*p)();
bool rp = r.get_pass();
durations.push_back(r.get_elapsed());
/*
* Run more tests if we're running a benchmark.
*/
for (std::size_t i = 1; i < loops; i++) {
result l = (*p)();
durations.push_back(l.get_elapsed());
}
/*
* If we're being verbose then print the results. We print the 20th percentile result if
* this is a benchmark test. Lower than the 10th percentile we can see some rather
* odd timing results and greater than the 50th percentile we can run into problems
* related to scheduling. The 20th percentile number is an empirical choice.
*/
if (verbose) {
std::nth_element(durations.begin(), durations.begin() + (durations.size() / 5), durations.end());
std::cout << std::setw(14) << std::left << r.get_name() << " | ";
auto d = durations[durations.size() / 5] - nop_duration;
std::cout << std::setw(10) << std::right << d.count() << " | " << (rp ? "pass" : "FAIL");
std::cout << " | " << r.get_stream().str();
if (!rp) {
std::cout << " (" << r.get_expected() << ')';
}
std::cout << '\n';
}
res &= rp;
p++;
}
if (!res) {
std::cout << "TESTS FAILED!\n";
exit(-1);
}
std::cout << "All tests passed\n";
return 0;
}
| 27.710794 | 121 | 0.716228 | [
"vector"
] |
cfdc6f1c797f6d2604fcbb61e7c9cf1b28848efc | 5,819 | cpp | C++ | Greedy/659. Split Array into Consecutive Subsequences.cpp | beckswu/Leetcode | 480e8dc276b1f65961166d66efa5497d7ff0bdfd | [
"MIT"
] | 138 | 2020-02-08T05:25:26.000Z | 2021-11-04T11:59:28.000Z | Greedy/659. Split Array into Consecutive Subsequences.cpp | beckswu/Leetcode | 480e8dc276b1f65961166d66efa5497d7ff0bdfd | [
"MIT"
] | null | null | null | Greedy/659. Split Array into Consecutive Subsequences.cpp | beckswu/Leetcode | 480e8dc276b1f65961166d66efa5497d7ff0bdfd | [
"MIT"
] | 24 | 2021-01-02T07:18:43.000Z | 2022-03-20T08:17:54.000Z | /*
659. Split Array into Consecutive Subsequences
/*
pre: 上一个process的数
p1: 以pre结尾长度为1 的数列 pre = 4, seq = 4
p2: 以pre结尾长度为2 的数列 pre = 4, seq = [3,4]
p2: 以pre结尾长度大于等于3 的数列, pre = 4, seq = [1,2,3,4]
cur: 现在将要process 的数
c1: 以cur结尾长度为1 的数列
c2: 以cur结尾长度为2 的数列
c3: 以cur结尾长度大于等于3 的数列
cnt: cur 在数列中出现的个数
遇到cur, 分两种情况讨论,
1. cur != pre + 1, 表示cur 不能加到以pre结尾 consecutive subsequence, 因为之前p1 == 0 && p2 必须为0,
否则return false, 接下来c1 = cnt, c2 = 0, c3 =0; 我们仅有以cur开始的长度为1的subsequence
2. cur == pre + 1; 这时候我们处理的顺序,应该先把cur分给长度为1,再分给长度为2,再分给长度为3个,
我们先看是不是cnt >= p1 + p2, 如果不是的话,代表现在的cur不够分给之前长度为1,长度为2的(之前有的subsequnce长度不够3),return false
此时: 我们已经知道 cur肯定够分给p1, p2
如果分给 p1, p2 , p3之后,还富余,就给新的c1; c1 = max(0, cnt - (p1 + p2 + p3));
c2 = p1, (cnt>p1+ p2)
c3 = p2 + min(p3, cnt-(p1+p2));
min(p3, cnt - (p1 + p2)), 可能cnt - (p1 + p2) 大于p3, 表示p3不能接住所有的剩下的, cnt > p1 + p2 + p3,
所以我们只保留之前已经长度是3的个数, 比如[1,2,3], [1,2,3],[1,2,3], 4,4,4,4
还有可能, cnt - (p1 + p2) < p3, 表示p3, 之前可以在上一位结束一部分,不必所有的p3都延续一位
比如 【1,2,3], [1,2,3], [1,2,3], cur = 4, 4, 只需两个p3接住4,另外一个p3在pre结束,[1,2,3,4], [1,2,3,4], [1,2,3]
*/
class Solution {
public:
bool isPossible(vector<int>& nums) {
int p1 = 0, p2 =0, p3=0, c1 = 0, c2 = 0, c3 = 0, pre=INT_MAX, cur = 0, cnt = 0;
for(int i = 0; i<nums.size(); p1=c1, p2=c2, p3=c3,pre=cur){
for(cur = nums[i], cnt = 0; i<nums.size() && cur == nums[i]; i++, cnt++);
if(cur!=pre+1){
if(p1!=0 || p2!=0 ) return false; // 比如pre = 3 , cur =5, 之前到3为止,长度为1,长度为2的array必须是0
c1 = cnt; c2 = 0; c3 = 0;
}else if(cur == pre+1){
if(cnt < p1 + p2) //有些长度是1,2的array不能填满,返回false
return false;
c1 = max(0, cnt - (p1 + p2 + p3));
c2 = p1;
c3 = p2 + min(p3, cnt-(p1+p2)); //cnt-(p1+p2) 分给p1, p2 之后还剩下 cnt - p1 - p2,
//可以分给p3,但是要保证p3 够多接的住,比如[1,2,3], [1,2,3],[1,2,3], 4,4,4,4 有4个剩余的
// 3 只能接住3个, 多的一个只能给4
}
}
return p1 == 0 && p2 == 0;
}
};
/*
Solution 2:
cnt 表示后面还有几个i还没被使用,tail在i点,以i点为结尾且长度大于等于3的sequence 的个数
当碰到i,
1. 先看cnt是不是大于0,小于0表示i已经被提前透支完了
2. 如果有,看有没有以i-1结尾的且长度大于3等于的, 如果有就继续这个sequence,
- 当然我们也可以用i点再开始新的sequence,但是append old sequence i-1 should always work
比如 [1,2,3,4,5], 在4点,我们可以append 4, 让新的sequence 变成[1,2,3,4], 但是假如我们想开启新的sequence 发现没有4+2
3. 如果没有i-1结尾的, 看能不能以i开头建立新的sequence,建立新的sequence前提是
i+1, i+2 没有预支完, cnt[i+1] > 0 && cnt[i+2] >0
不能调换2,3的顺序,比如例子: [1,2,3,4,5,5,6,7]
正确的sequence是 (1,2,3,4,5), (5,6,7)
如果一碰到点先考虑 建立新的sequence,到4点,建立新的sequence (1,2,3), (4,5,6), 发现只有5,7点了,会return false
*/
class Solution {
public:
bool isPossible(vector<int>& nums) {
unordered_map<int,int>cnt, tail;
for(auto i: nums) cnt[i]++;
for(auto i: nums){
if(cnt[i] == 0) continue; //提起被支付了,已经在sequence里面了,继续
cnt[i]--;
if(tail[i-1]){
tail[i-1]--;
tail[i]++;
}else if(cnt[i+1] && cnt[i+2]){
cnt[i+1]--;
cnt[i+2]--;
tail[i+2]++;
}
else return false;
}
return true;
}
};
/*
Solution 3: check 每三个数构成sequence
*/
class Solution {
public:
bool isPossible(vector<int>& nums) {
int base = nums[0];
for(auto &i: nums) i-=base; //第一个数0,之后跟原来第一个数比
unordered_map<int,int>cnt;
for(auto i: nums) cnt[i]++;
for(int i = 2; i<=nums.back()+2;i++){ //最大的数+2, 因为比如数[0], 1只有到2的时候可以查出来
int cur = cnt[i]; //现在i这个数
int one = max(cnt[i-1] - cnt[i-2], 0);//以i-1 开头数
int two = max(cnt[i-2] - cnt[i-3], 0);//以i-2 开头的数
if(cur < one + two || cnt[i- 1] < two) return false;
// cnt < p1 + p2 (cur<one+two)
//cnt[i- 1] < two 原理上也可以用 cur < one 代替,但是我们从 i = 2开始的,如果用cur < one 代替,比如[0, 2,3,4]的0就查不出了
}
return true;
}
};
/*
priority_queue
Case 1 : num == pq.peek().end, we offer a new interval (num, num) to pq => #1
Case 2 : num == pq.peek().end+ 1, we poll a interval prev, offer a new interval (prev.start, num) => #2
Case 3 : num > p1.peek().end + 1,
we keep abandoning intervals (if the length of the interval to abandon is smaller than 3, return false) until we could reduce to case 1 or case 2 => #3
The order of 3 cases above matters. For easier implementation, Case 3 should be checked first.
In the priority queue, all intervals are sorted by end increasingly, if there is a tie, we sort them by size increasingly.
priority_queue:
1. 如果end 一样,返回长度短的
2. 如果end 不一样,返回end 小的
[1,2,3,3,4,4,5,5],
到第一个4的时候, pq 有 [1,3], [3,3], 先用[3,3]
到第二个4的时候, pq 有[1,3], [3,4], 先用[1,3]
*/
class Solution {
public:
bool isPossible(vector<int>& nums) {
auto cmp = [](vector<int>&a, vector<int>&b){
if(a[1] == b[1] )
return (a[1] - a[0]) > (b[1] - b[0]); //如果end 一样,先return 长度短的
return a[1] > b[1];
};
priority_queue<vector<int>, vector<vector<int>>, decltype(cmp)>pq(cmp);
for(auto num: nums){
while(pq.size() && pq.top()[1] + 1 < num){
if(pq.top()[1] - pq.top()[0] < 2)
return false;
pq.pop();
}
if(pq.empty() || pq.top()[1] == num)
pq.push({num, num});
else{ // pq.top()[1] + 1 = num
vector<int> top = pq.top();
pq.pop();
top[1] = num;
pq.push(top);
}
}
while(pq.size()){
if(pq.top()[1] - pq.top()[0] < 2)
return false;
pq.pop();
}
return true;
}
}; | 31.625 | 151 | 0.522083 | [
"vector"
] |
cfdd4223a167a63f4695d61dd2d86636d947c2ab | 13,623 | cpp | C++ | examples/profile_elements/profile_elements.cpp | rsanfer/tacs | 32cf876d60279d5a448f91ac9a0b35b056865e5d | [
"Apache-2.0"
] | null | null | null | examples/profile_elements/profile_elements.cpp | rsanfer/tacs | 32cf876d60279d5a448f91ac9a0b35b056865e5d | [
"Apache-2.0"
] | null | null | null | examples/profile_elements/profile_elements.cpp | rsanfer/tacs | 32cf876d60279d5a448f91ac9a0b35b056865e5d | [
"Apache-2.0"
] | 2 | 2018-12-14T10:32:49.000Z | 2019-11-24T17:22:55.000Z | // Include the shell element classes
#include "isoFSDTStiffness.h"
#include "MITCShell.h"
#include "MITC9.h"
// Include the plane stress classes
#include "PlaneStressStiffness.h"
#include "PlaneStressQuad.h"
#include "PlaneStressTri6.h"
// Include the solid/3D element classes
#include "SolidStiffness.h"
#include "Solid.h"
// Include the multibody dynamics code
#include "RigidBody.h"
#include "KinematicConstraints.h"
/*
Generate a random array of values
*/
static void generate_random_array( TacsScalar *array, int size,
TacsScalar lower=-1.0,
TacsScalar upper=1.0 ){
for ( int i = 0; i < size; i++ ){
array[i] = (upper - lower)*(rand()/((double)RAND_MAX+1)) + lower;
}
}
/*
Apply all the tests to the element
*/
void test_element( TACSElement *element,
double time,
const TacsScalar Xpts[],
const TacsScalar vars[],
const TacsScalar dvars[],
const TacsScalar ddvars[],
int dvLen ){
TacsScalar *x = new TacsScalar[ dvLen ];
// Get the design variables from the element
element->getDesignVars(x, dvLen);
// Test the element
TACSElement::setStepSize(1e-5);
#ifdef TACS_USE_COMPLEX
TACSElement::setStepSize(1e-30);
#endif
element->testResidual(time, Xpts, vars, dvars, ddvars);
element->testJacobian(time, Xpts, vars, dvars, ddvars);
element->testAdjResProduct(x, dvLen, time, Xpts, vars, dvars, ddvars);
element->testAdjResXptProduct(time, Xpts, vars, dvars, ddvars);
element->testStrainSVSens(Xpts, vars);
element->testStrainXptSens(Xpts, vars);
element->testJacobianXptSens(Xpts);
element->testMatDVSensInnerProduct(STIFFNESS_MATRIX, x, dvLen, Xpts, vars);
element->testMatDVSensInnerProduct(MASS_MATRIX, x, dvLen, Xpts, vars);
delete [] x;
}
/*
The following code tests the element implementation to see if the
computation of the residual is consistent with the energy
formulation, to check if the Jacobian matrix is consistent with the
residual and to test certain design-dependent code.
Useage:
./profile_elements [fd=value]
*/
int main( int argc, char *argv[] ){
// Initialize MPI
MPI_Init(&argc, &argv);
// Test only the input element type - if specified, otherwise
// test everything
const char *ename = NULL;
if (argc > 1){
ename = argv[1];
}
const int MAX_NODES = 27;
const int MAX_VARS_PER_NODE = 8;
const int MAX_VARS = MAX_NODES*MAX_VARS_PER_NODE;
// Set the simulation time
double time = 0.0;
// Set the variable arrays
TacsScalar Xpts[3*MAX_NODES];
TacsScalar vars[MAX_VARS], dvars[MAX_VARS], ddvars[MAX_VARS];
// Generate random arrays
generate_random_array(Xpts, 3*MAX_NODES, 0.0, 1.0);
generate_random_array(vars, MAX_VARS);
generate_random_array(dvars, MAX_VARS);
generate_random_array(ddvars, MAX_VARS);
// Set the tolerances depending on whether we're using complex step
// or not...
#ifdef TACS_USE_COMPLEX
TACSElement::setFailTolerances(1e-1, 1e-12);
#else
TACSElement::setFailTolerances(1e-1, 1e-5);
#endif
// Set the print level
TACSElement::setPrintLevel(2);
// Set up the constitutive relationship
TacsScalar rho = 2700.0, E = 35e4, nu = 0.3, kcorr = 0.8333;
TacsScalar ys = 434.0e6, t = 0.01;
// Set the parameter values from the command line
for ( int i = 0; i < argc; i++ ){
double Ec = 0.0, rhoc = 0.0;
if (sscanf(argv[i], "E=%lf", &Ec)){
if (Ec >= 0.0){
E = Ec;
printf("E = %g\n", TacsRealPart(E));
}
}
if (sscanf(argv[i], "rho=%lf", &rhoc)){
if (rhoc >= 0.0){
rho = rhoc;
printf("rho = %g\n", TacsRealPart(rho));
}
}
}
int dv_num = 14;
int num_design_vars = dv_num+1;
FSDTStiffness *fsdt = new isoFSDTStiffness(rho, E, nu, kcorr, ys, t,
dv_num);
fsdt->incref();
TacsScalar axis[3] = {1.0, -1.0, 0.5};
fsdt->setRefAxis(axis);
// Allocate and test all the different types of shell elements
TACSElement *shell = NULL;
shell = new MITCShell<2>(fsdt, LINEAR); shell->incref();
if (!ename || strcmp(ename, shell->elementName()) == 0){
test_element(shell, time, Xpts, vars, dvars, ddvars, num_design_vars);
}
shell->decref();
shell = new MITCShell<3>(fsdt, LINEAR); shell->incref();
if (!ename || strcmp(ename, shell->elementName()) == 0){
test_element(shell, time, Xpts, vars, dvars, ddvars, num_design_vars);
}
shell->decref();
// Nonlinear elements
shell = new MITCShell<2>(fsdt, NONLINEAR); shell->incref();
if (!ename || strcmp(ename, shell->elementName()) == 0){
test_element(shell, time, Xpts, vars, dvars, ddvars, num_design_vars);
}
shell->decref();
shell = new MITCShell<3>(fsdt, NONLINEAR); shell->incref();
if (!ename || strcmp(ename, shell->elementName()) == 0){
test_element(shell, time, Xpts, vars, dvars, ddvars, num_design_vars);
}
shell->decref();
// Large rotation elements
shell = new MITCShell<2>(fsdt, LARGE_ROTATION); shell->incref();
if (!ename || strcmp(ename, shell->elementName()) == 0){
test_element(shell, time, Xpts, vars, dvars, ddvars, num_design_vars);
}
shell->decref();
shell = new MITCShell<3>(fsdt, LARGE_ROTATION); shell->incref();
if (!ename || strcmp(ename, shell->elementName()) == 0){
test_element(shell, time, Xpts, vars, dvars, ddvars, num_design_vars);
}
shell->decref();
// Normalize the variables for unit quaternions
for ( int i = 0; i < MAX_NODES; i++ ){
vars[8*i+7] = 0.0;
TacsScalar *v = &vars[8*i+3];
TacsScalar fact =
1.0/sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2] + v[3]*v[3]);
for ( int j = 0; j < 4; j++ ){
v[j] *= fact;
}
}
MITC9 *mitc9 = new MITC9(fsdt);
shell = mitc9;
shell->incref();
if (!ename || strcmp(ename, shell->elementName()) == 0){
test_element(shell, time, Xpts, vars, dvars, ddvars, num_design_vars);
// mitc9->testStrain(Xpts);
}
shell->decref();
fsdt->decref();
// Set the variables back to a random array
generate_random_array(dvars, MAX_VARS);
// Allocate the plane stress stiffness object
PlaneStressStiffness *ps = new PlaneStressStiffness(rho, E, nu);
ps->incref();
TACSElement *elem = NULL;
elem = new PlaneStressTri6(ps); elem->incref();
if (!ename || strcmp(ename, elem->elementName()) == 0){
test_element(elem, time, Xpts, vars, dvars, ddvars, num_design_vars);
}
elem->decref();
elem = new PlaneStressQuad<2>(ps); elem->incref();
if (!ename || strcmp(ename, elem->elementName()) == 0){
test_element(elem, time, Xpts, vars, dvars, ddvars, num_design_vars);
}
elem->decref();
elem = new PlaneStressQuad<3>(ps); elem->incref();
if (!ename || strcmp(ename, elem->elementName()) == 0){
test_element(elem, time, Xpts, vars, dvars, ddvars, num_design_vars);
}
elem->decref();
elem = new PlaneStressTri6(ps, NONLINEAR); elem->incref();
if (!ename || strcmp(ename, elem->elementName()) == 0){
test_element(elem, time, Xpts, vars, dvars, ddvars, num_design_vars);
}
elem->decref();
elem = new PlaneStressQuad<2>(ps, NONLINEAR); elem->incref();
if (!ename || strcmp(ename, elem->elementName()) == 0){
test_element(elem, time, Xpts, vars, dvars, ddvars, num_design_vars);
}
elem->decref();
elem = new PlaneStressQuad<3>(ps, NONLINEAR); elem->incref();
if (!ename || strcmp(ename, elem->elementName()) == 0){
test_element(elem, time, Xpts, vars, dvars, ddvars, num_design_vars);
}
elem->decref();
ps->decref();
// Create the solid stiffness classes
SolidStiffness *stiff = new SolidStiffness(rho, E, nu);
stiff->incref();
elem = new Solid<2>(stiff); elem->incref();
if (!ename || strcmp(ename, elem->elementName()) == 0){
test_element(elem, time, Xpts, vars, dvars, ddvars, num_design_vars);
}
elem->decref();
elem = new Solid<3>(stiff); elem->incref();
if (!ename || strcmp(ename, elem->elementName()) == 0){
test_element(elem, time, Xpts, vars, dvars, ddvars, num_design_vars);
}
elem->decref();
elem = new Solid<2>(stiff, NONLINEAR); elem->incref();
if (!ename || strcmp(ename, elem->elementName()) == 0){
test_element(elem, time, Xpts, vars, dvars, ddvars, num_design_vars);
}
elem->decref();
elem = new Solid<3>(stiff, NONLINEAR); elem->incref();
if (!ename || strcmp(ename, elem->elementName()) == 0){
test_element(elem, time, Xpts, vars, dvars, ddvars, num_design_vars);
}
elem->decref();
stiff->decref();
// Test the rigid body code within TACS
if (!ename || strcmp(ename, "Rigid") == 0){
// Generate a random arrary of variables conforming to the
// quaternion constraint
generate_random_array(vars, MAX_VARS);
generate_random_array(dvars, MAX_VARS);
generate_random_array(ddvars, MAX_VARS);
for ( int i = 0; i < MAX_NODES; i++ ){
vars[8*i+7] = 0.0;
TacsScalar *v = &vars[8*i+3];
// Normalize the quaternion constraints
TacsScalar fact =
1.0/sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2] + v[3]*v[3]);
for ( int j = 0; j < 4; j++ ){
v[j] *= fact;
}
}
// The acceleration due to gravity in global frame of reference
TACSGibbsVector *gravVec = new TACSGibbsVector(19.0, 10.0, -9.8);
// Construct the frame of reference
TACSGibbsVector *rAInitVec = new TACSGibbsVector(5.2, 5.3, 5.4);
TACSGibbsVector *rA1Vec = new TACSGibbsVector(5.2+1.0, 5.3, 5.4);
TACSGibbsVector *rA2Vec = new TACSGibbsVector(5.2, 5.3+1.0, 5.4);
TACSRefFrame *refFrameA = new TACSRefFrame(rAInitVec, rA1Vec, rA2Vec);
// Define the inertial properties
const TacsScalar mA = 6.0;
const TacsScalar cA[3] = {20.0, 14.0, 42.0};
const TacsScalar JA[6] = {1.0, 0.8, -0.7,
2.0, 1.4,
3.0};
// Construct a rigid body
TACSRigidBody *bodyA = new TACSRigidBody(refFrameA,
mA, cA, JA,
rAInitVec, rAInitVec, rAInitVec,
gravVec);
bodyA->incref();
test_element(bodyA, time, Xpts, vars, dvars, ddvars, num_design_vars);
// Test the motion driver element
TACSGibbsVector *dir = new TACSGibbsVector(0.0, 0.0, 0.1);
TacsScalar omega = 0.25; // rad/s
TACSMotionDriver *mDriver =
new TACSMotionDriver(dir, omega);
mDriver->incref();
test_element(mDriver, time, Xpts, vars, dvars, ddvars, num_design_vars);
// Test the revolute constraint
TACSGibbsVector *point = new TACSGibbsVector(0.5, 1.0, -2.5);
TACSGibbsVector *eRev = new TACSGibbsVector(1.0, -1.0, 1.0);
TACSRevoluteConstraint *rev =
new TACSRevoluteConstraint(bodyA, point, eRev);
rev->incref();
test_element(rev, time, Xpts, vars, dvars, ddvars, num_design_vars);
// Test the cylindrical constraint
TACSCylindricalConstraint *cyl =
new TACSCylindricalConstraint(bodyA, point, eRev);
cyl->incref();
test_element(cyl, time, Xpts, vars, dvars, ddvars, num_design_vars);
// Test the fixed constraint
TACSFixedConstraint *fix = new TACSFixedConstraint(bodyA, point);
fix->incref();
test_element(fix, time, Xpts, vars, dvars, ddvars, num_design_vars);
// Test the spherical constraint
TACSSphericalConstraint *ball = new TACSSphericalConstraint(bodyA, point);
ball->incref();
test_element(ball, time, Xpts, vars, dvars, ddvars, num_design_vars);
// Test the rigid link code
TACSRigidLink *rlink = new TACSRigidLink(bodyA);
rlink->incref();
// Test the rigid link
test_element(rlink, time, Xpts, vars, dvars, ddvars, num_design_vars);
// Define the inertial properties
const TacsScalar mB = 2.0;
const TacsScalar cB[3] = {2.0, 3.0, 4.0};
const TacsScalar JB[6] = {2.0, 0.60, 0.7,
3.0, 0.80,
4.0};
// Define dynamics properties
TACSGibbsVector *rBInitVec = new TACSGibbsVector(3.2, 3.2, 4.3);
TACSGibbsVector *rB1Vec = new TACSGibbsVector(3.2+1.0, 3.2, 4.3);
TACSGibbsVector *rB2Vec = new TACSGibbsVector(3.2, 3.2+1.0, 4.3);
TACSRefFrame *refFrameB = new TACSRefFrame(rBInitVec, rB1Vec, rB2Vec);
// Construct a rigid body
TACSRigidBody *bodyB = new TACSRigidBody(refFrameB,
mB, cB, JB,
rBInitVec, rBInitVec, rBInitVec,
gravVec);
bodyB->incref();
// Test the revolute constraint
TACSRevoluteConstraint *rev2 =
new TACSRevoluteConstraint(bodyA, bodyB, point, eRev);
rev2->incref();
test_element(rev2, time, Xpts, vars, dvars, ddvars, num_design_vars);
// Test the revolute constraint
TACSCylindricalConstraint *cyl2 =
new TACSCylindricalConstraint(bodyA, bodyB, point, eRev);
cyl2->incref();
test_element(cyl2, time, Xpts, vars, dvars, ddvars, num_design_vars);
// Test the spherical constraint
TACSSphericalConstraint *ball2 =
new TACSSphericalConstraint(bodyA, bodyB, point);
ball2->incref();
test_element(ball2, time, Xpts, vars, dvars, ddvars, num_design_vars);
// Decref everything
cyl->decref();
fix->decref();
rev->decref();
ball->decref();
bodyA->decref();
rev2->decref();
ball2->decref();
bodyB->decref();
rlink->decref();
}
MPI_Finalize();
return (0);
}
| 33.145985 | 78 | 0.628129 | [
"object",
"3d",
"solid"
] |
cfe4ded9a4a3cb7b4bbc69cbd6e52ac61b7778e3 | 4,348 | cpp | C++ | util/partlib/src/Image.cpp | hakonmagnus/ether | 87b772c51a5862ced8feabda4929e0f85d5960a1 | [
"MIT"
] | 2 | 2021-02-05T16:48:41.000Z | 2021-02-05T16:49:48.000Z | util/partlib/src/Image.cpp | hakonmagnus/ether | 87b772c51a5862ced8feabda4929e0f85d5960a1 | [
"MIT"
] | null | null | null | util/partlib/src/Image.cpp | hakonmagnus/ether | 87b772c51a5862ced8feabda4929e0f85d5960a1 | [
"MIT"
] | null | null | null | //============================================================================|
// _______ _________ _______ _______ |
// ( ____ \\__ __/|\ /|( ____ \( ____ ) |
// | ( \/ ) ( | ) ( || ( \/| ( )| |
// | (__ | | | (___) || (__ | (____)| By Hákon Hjaltalín. |
// | __) | | | ___ || __) | __) Licensed under MIT. |
// | ( | | | ( ) || ( | (\ ( |
// | (____/\ | | | ) ( || (____/\| ) \ \__ |
// (_______/ )_( |/ \|(_______/|/ \__/ |
//============================================================================|
#include "partlib/Image.hpp"
#include "partlib/GPT.hpp"
#include "partlib/GUID.hpp"
#include "partlib/CRC32.hpp"
#include "partlib/EBFS.hpp"
#include <cstring>
#include <fstream>
#include <iostream>
Image::Image(const size_t size, const std::string& mbr,
const std::string& loader, const std::string& ebfs) :
m_size{ size }, m_image{ nullptr }, m_mbr{ mbr },
m_loader{ loader }, m_ebfs{ ebfs }
{
m_image = new uint8_t[size];
memset(m_image, 0, size);
}
Image::~Image()
{
delete m_image;
m_image = nullptr;
}
bool Image::write(const std::string& output)
{
size_t biosSize = 64;
size_t ebfsSize = 256;
auto loaderfile = std::fstream(m_loader, std::ios::in | std::ios::binary | std::ios::ate);
auto loadersize = loaderfile.tellg();
loaderfile.seekg(0, std::ios::beg);
loaderfile.read((char*)&m_image[0x200 * 35], loadersize);
loaderfile.close();
EBFS* ebfs = new EBFS(m_ebfs, ebfsSize * 0x200);
uint8_t* ebfsBuf = ebfs->render();
memcpy(&m_image[(35 + biosSize + 1) * 0x200], ebfsBuf, ebfsSize * 0x200);
delete ebfs;
ebfs = nullptr;
uint8_t* entries = new uint8_t[4 * sizeof(GPTEntry)];
memset(entries, 0, 4 * sizeof(GPTEntry));
GPTEntry bios;
memset(&bios, 0, sizeof(bios));
memcpy(bios.typeGUID, biosGUID, 16);
generateGUID(bios.uniqueGUID);
bios.firstLBA = 35;
bios.lastLBA = 35 + biosSize;
memcpy(bios.partitionName, u"BIOS boot partition", 19 * sizeof(char16_t));
memcpy(&entries[0], &bios, sizeof(bios));
GPTEntry ebfsEnt;
memset(&ebfsEnt, 0, sizeof(ebfsEnt));
memcpy(ebfsEnt.typeGUID, ebfsGUID, 16);
generateGUID(ebfsEnt.uniqueGUID);
ebfsEnt.firstLBA = bios.lastLBA + 1;
ebfsEnt.lastLBA = ebfsEnt.firstLBA + ebfsSize;
memcpy(ebfsEnt.partitionName, u"Ether Boot Partition", 20 * sizeof(char16_t));
memcpy(&entries[sizeof(GPTEntry)], &ebfsEnt, sizeof(ebfsEnt));
memcpy(&m_image[0x400], entries, 4 * sizeof(GPTEntry));
memcpy(&m_image[((m_size / 0x200) - 34) * 0x200], entries, 4 * sizeof(GPTEntry));
GPTHeader gpt;
memset(&gpt, 0, sizeof(gpt));
memcpy(gpt.signature, "EFI PART", 8);
gpt.revision = 0x00010000;
gpt.headerSize = 0x5C;
gpt.headerCRC32 = 0;
gpt.currentLBA = 1;
gpt.backupLBA = (m_size / 0x200) - 1;
gpt.firstUsableLBA = 34;
gpt.lastUsableLBA = (m_size / 0x200) - 35;
generateGUID(gpt.diskGUID);
gpt.entriesLBA = 2;
gpt.numEntries = 4;
gpt.entrySize = 0x80;
gpt.entriesCRC32 = crc32(0, entries, 4 * sizeof(GPTEntry));
gpt.headerCRC32 = crc32(0, &gpt, sizeof(gpt));
memcpy(&m_image[0x200], &gpt, sizeof(gpt));
gpt.currentLBA = (m_size / 0x200) - 1;
gpt.backupLBA = 1;
gpt.entriesLBA = (m_size / 0x200) - 34;
gpt.headerCRC32 = 0;
gpt.headerCRC32 = crc32(0, entries, 4 * sizeof(GPTEntry));
memcpy(&m_image[((m_size / 0x200) - 1) * 0x200], &gpt, sizeof(gpt));
delete entries;
entries = nullptr;
auto mbrfile = std::fstream(m_mbr, std::ios::in | std::ios::binary | std::ios::ate);
if (mbrfile.tellg() != 512)
{
std::cout << "\033[1;31mEther Disk Utility: MBR image must be exactly 512 bytes.\033[0m\n";
mbrfile.close();
return false;
}
mbrfile.seekg(0, std::ios::beg);
mbrfile.read((char*)m_image, 512);
mbrfile.close();
auto file = std::fstream(output, std::ios::out | std::ios::binary);
file.write((char*)m_image, m_size);
file.close();
return true;
}
| 35.064516 | 99 | 0.543238 | [
"render"
] |
cfe60c888db0bc70fcb3047046b70dfd7bc3510d | 4,306 | cpp | C++ | external/swak/libraries/simpleFunctionObjects/misc/readAndUpdateFields/readAndUpdateFields.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | external/swak/libraries/simpleFunctionObjects/misc/readAndUpdateFields/readAndUpdateFields.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | external/swak/libraries/simpleFunctionObjects/misc/readAndUpdateFields/readAndUpdateFields.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | /*---------------------------------------------------------------------------*\
Copyright: ICE Stroemungsfoschungs GmbH
Copyright held by original author
-------------------------------------------------------------------------------
License
This file is based on CAELUS.
CAELUS is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CAELUS is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with CAELUS. If not, see <http://www.gnu.org/licenses/>.
Contributors/Copyright:
2012-2014 Bernhard F.W. Gschaider <bgschaid@ice-sf.at>
2013 Bruno Santos <wyldckat@gmail.com>
\*---------------------------------------------------------------------------*/
#include "readAndUpdateFields.hpp"
#include "dictionary.hpp"
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
namespace CML
{
defineTypeNameAndDebug(readAndUpdateFields, 0);
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
CML::readAndUpdateFields::readAndUpdateFields
(
const word& name,
const objectRegistry& obr,
const dictionary& dict,
const bool loadFromFiles
)
:
name_(name),
obr_(obr),
active_(true),
fieldSet_()
{
// Check if the available mesh is an fvMesh otherise deactivate
if (!isA<fvMesh>(obr_))
{
active_ = false;
WarningInFunction
<< "No fvMesh available, deactivating."
<< endl;
}
read(dict);
}
// * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * //
CML::readAndUpdateFields::~readAndUpdateFields()
{}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
void CML::readAndUpdateFields::timeSet()
{
// Do nothing
}
void CML::readAndUpdateFields::read(const dictionary& dict)
{
if (active_)
{
dict.lookup("fields") >> fieldSet_;
//Info<< type() << " " << name_ << ":" << nl;
// Clear out any previously loaded fields
vsf_.clear();
vvf_.clear();
vSpheretf_.clear();
vSymmtf_.clear();
vtf_.clear();
psf_.clear();
pvf_.clear();
pSpheretf_.clear();
pSymmtf_.clear();
ptf_.clear();
forAll(fieldSet_, fieldI)
{
bool found = loadField<scalar>(fieldSet_[fieldI], vsf_, psf_);
found = found || loadField<vector>(fieldSet_[fieldI], vvf_, pvf_);
found = found || loadField<sphericalTensor>(fieldSet_[fieldI], vSpheretf_, pSpheretf_);
found = found || loadField<symmTensor>(fieldSet_[fieldI], vSymmtf_, pSymmtf_);
found = found || loadField<tensor>(fieldSet_[fieldI], vtf_, ptf_);
if(!found)
{
FatalErrorInFunction
<< "Field " << fieldSet_[fieldI] << " does not exist"
<< endl
<< exit(FatalError);
}
}
}
}
const CML::pointMesh &CML::readAndUpdateFields::pMesh(const polyMesh &mesh)
{
if(!pMesh_.valid()) {
pMesh_.set(new pointMesh(mesh));
}
return pMesh_();
}
void CML::readAndUpdateFields::execute()
{
if(active_) {
correctBoundaryConditions(vsf_);
correctBoundaryConditions(vvf_);
correctBoundaryConditions(vtf_);
correctBoundaryConditions(vSymmtf_);
correctBoundaryConditions(vSpheretf_);
correctBoundaryConditions(psf_);
correctBoundaryConditions(pvf_);
correctBoundaryConditions(ptf_);
correctBoundaryConditions(pSymmtf_);
correctBoundaryConditions(pSpheretf_);
}
}
void CML::readAndUpdateFields::end()
{
execute();
}
void CML::readAndUpdateFields::write()
{
// Do nothing
}
// ************************************************************************* //
| 27.081761 | 99 | 0.542963 | [
"mesh",
"vector"
] |
cfe804647717aa596ba09b1b3984e665cc213897 | 1,959 | cpp | C++ | Attic/AtomicEditorReference/Source/UI/Modal/UIMessageModal.cpp | honigbeutler123/AtomicGameEngine | c53425f19b216eb21ecd3bda85052aaa1a6f2aaa | [
"Apache-2.0",
"MIT"
] | null | null | null | Attic/AtomicEditorReference/Source/UI/Modal/UIMessageModal.cpp | honigbeutler123/AtomicGameEngine | c53425f19b216eb21ecd3bda85052aaa1a6f2aaa | [
"Apache-2.0",
"MIT"
] | null | null | null | Attic/AtomicEditorReference/Source/UI/Modal/UIMessageModal.cpp | honigbeutler123/AtomicGameEngine | c53425f19b216eb21ecd3bda85052aaa1a6f2aaa | [
"Apache-2.0",
"MIT"
] | null | null | null | // Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
// Please see LICENSE.md in repository root for license information
// https://github.com/AtomicGameEngine/AtomicGameEngine
#include "AtomicEditor.h"
#include <Atomic/Core/Context.h>
#include "AEEvents.h"
#include "UI/UIMainFrame.h"
#include "UI/Modal/UIMessageModal.h"
#include <TurboBadger/tb_message_window.h>
namespace AtomicEditor
{
/// Construct.
MessageModal::MessageModal(Context* context) :
Object(context)
{
SubscribeToEvent(E_EDITORMODAL, HANDLER(MessageModal, HandleEditorModal));
}
/// Destruct.
MessageModal::~MessageModal()
{
}
void MessageModal::ShowErrorWindow(const String& title, const String& message)
{
MainFrame* mainframe = GetSubsystem<MainFrame>();
TBMessageWindow *msg_win = new TBMessageWindow(mainframe->GetWidgetDelegate(), TBIDC("modal_error"));
TBMessageWindowSettings settings(TB_MSG_OK, TBID(uint32(0)));
settings.dimmer = true;
settings.styling = true;
msg_win->Show(title.CString(), message.CString(), &settings, 640, 360);
}
void MessageModal::ShowInfoWindow(const String& title, const String& message)
{
MainFrame* mainframe = GetSubsystem<MainFrame>();
TBMessageWindow *msg_win = new TBMessageWindow(mainframe->GetWidgetDelegate(), TBIDC("modal_info"));
TBMessageWindowSettings settings(TB_MSG_OK, TBID(uint32(0)));
settings.dimmer = true;
settings.styling = true;
msg_win->Show(title.CString(), message.CString(), &settings, 640, 360);
}
void MessageModal::HandleEditorModal(StringHash eventType, VariantMap& eventData)
{
using namespace EditorModal;
const String& title = eventData[P_TITLE].GetString();
const String& message = eventData[P_MESSAGE].GetString();
if (eventData[P_TYPE].GetUInt() == EDITOR_MODALERROR)
ShowErrorWindow(title, message);
if (eventData[P_TYPE].GetUInt() == EDITOR_MODALINFO)
ShowInfoWindow(title, message);
}
}
| 28.391304 | 105 | 0.737621 | [
"object"
] |
3213524c132f54d5254c98f21e64739c88d658b6 | 9,811 | hpp | C++ | src/mzdb/writer/bb_inserter.hpp | jerkos/pwiz-mzdb | edeaefc4388e7c9c1b48dfa2d69ced3a080a9535 | [
"Apache-2.0"
] | null | null | null | src/mzdb/writer/bb_inserter.hpp | jerkos/pwiz-mzdb | edeaefc4388e7c9c1b48dfa2d69ced3a080a9535 | [
"Apache-2.0"
] | null | null | null | src/mzdb/writer/bb_inserter.hpp | jerkos/pwiz-mzdb | edeaefc4388e7c9c1b48dfa2d69ced3a080a9535 | [
"Apache-2.0"
] | null | null | null | #ifndef MZBBINSERTER_H
#define MZBBINSERTER_H
#include "../lib/sqlite3/include/sqlite3.h"
#include "bb_computer.hpp"
#include "mzDBFile.h"
namespace mzdb {
class mzBBInserter {
private:
MzDBFile& m_mzdbFile;
int m_bbCount, m_lastMinRunSliceIdx, m_lastMaxRunSliceIdx, m_runSliceCount;
map<int, int> m_runSliceIndexByMsLevel;
/// Insert data into sqlite file
template<class h_mz_t, class h_int_t,
class l_mz_t, class l_int_t>
void _insertData(int msLevel,
double& bbheight,
map<int, int>& runSlices,
map<int, vector<std::shared_ptr<Centroid<h_mz_t, h_int_t> > > >& highResPeaks,
map<int, vector<std::shared_ptr<Centroid<l_mz_t, l_int_t> > > >& lowResPeaks,
map<int, DataMode>& dataModes,
double parentMinMz=0,
double parentMaxMz = 0) {
//useful typedef
typedef std::shared_ptr<Centroid<h_mz_t, h_int_t> > HighResCentroidSPtr;
typedef std::shared_ptr<Centroid<l_mz_t, l_int_t> > LowResCentroidSPtr;
typedef unique_ptr<mzBoundingBox<h_mz_t, h_int_t, l_mz_t, l_int_t> > mzBoundingBoxUPtr;
vector<mzBoundingBoxUPtr> bbs;
map<int, unique_ptr<map<int, vector<HighResCentroidSPtr> > > > r1;
map<int, unique_ptr<map<int, vector<LowResCentroidSPtr> > > > r2;
BBComputer::computeBoundingBox<h_mz_t, h_int_t, l_mz_t, l_int_t>(bbheight, highResPeaks, lowResPeaks, bbs, r1, r2);
//special cases leading to failure IMPORTANT SEGFAULT
bool emptyMsLevel = false;
if (bbs.empty()) {
//Too much log in ABI sciex file
//LOG(INFO) << "Found a bounding box empty";
emptyMsLevel = true;
auto bb = mzBoundingBoxUPtr(
new mzBoundingBox<h_mz_t, h_int_t,l_mz_t, l_int_t>(
unique_ptr<map<int, vector<HighResCentroidSPtr> > >(new map<int, vector<HighResCentroidSPtr> >),
unique_ptr<map<int, vector<LowResCentroidSPtr> > >(new map<int, vector<LowResCentroidSPtr> >)));
bb->update(highResPeaks, lowResPeaks);
bbs.push_back(std::move(bb));
}
int refScanIdx, refLastScanId;
if ( ! highResPeaks.empty() && ! lowResPeaks.empty()) {
refScanIdx = min(highResPeaks.begin()->first, lowResPeaks.begin()->first);
refLastScanId = max(highResPeaks.rbegin()->first, lowResPeaks.rbegin()->first);
} else if ( ! highResPeaks.empty() && lowResPeaks.empty()) {
refScanIdx = highResPeaks.begin()->first;
refLastScanId = highResPeaks.rbegin()->first;
} else{
refScanIdx = lowResPeaks.begin()->first;
refLastScanId = lowResPeaks.rbegin()->first;
}
//bbs are sorted by mz and so on by runSliceIdx
auto firstRunSliceIdx = bbs.front()->runSliceIdx();
auto lastRunSliceIdx = bbs.back()->runSliceIdx();
if (m_lastMinRunSliceIdx && firstRunSliceIdx < m_lastMinRunSliceIdx) {
printf("The first spectrum does not contain a low mass contained in the first runSlice.\n");
printf("This is a bug and it will be fixed in a next release of raw2mzdb.\n");
exit(0);
}
const double invBBheight = 1.0 / bbheight;
if (m_lastMaxRunSliceIdx && m_lastMaxRunSliceIdx < firstRunSliceIdx) {
const char* sql = "INSERT INTO run_slice VALUES (?, ?, ?, ?, ?, ?, ?);";
sqlite3_prepare_v2(m_mzdbFile.db, sql, -1, &(m_mzdbFile.stmt), 0);
for (int i = m_lastMaxRunSliceIdx + 1; i <= firstRunSliceIdx; ++i) {
if (runSlices.find(i) == runSlices.end()) {//not found
runSlices[i] = m_runSliceCount;
sqlite3_bind_int(m_mzdbFile.stmt, 1, m_runSliceCount);
sqlite3_bind_int(m_mzdbFile.stmt, 2, msLevel);
sqlite3_bind_int(m_mzdbFile.stmt, 3, m_runSliceCount);
double moz = i * invBBheight;
sqlite3_bind_double(m_mzdbFile.stmt, 4, moz);
sqlite3_bind_double(m_mzdbFile.stmt, 5, moz + invBBheight);
sqlite3_bind_null(m_mzdbFile.stmt, 6);
sqlite3_bind_int(m_mzdbFile.stmt, 7, 1);
sqlite3_step(m_mzdbFile.stmt);
sqlite3_reset(m_mzdbFile.stmt);
m_runSliceCount++;
}
}
sqlite3_finalize(m_mzdbFile.stmt);
m_mzdbFile.stmt = 0; //optional
}
const char* sql = "INSERT INTO run_slice VALUES (?, ?, ?, ?, ?, ?, ?);";
sqlite3_prepare_v2(m_mzdbFile.db, sql, -1, &(m_mzdbFile.stmt), 0);
for (int i = firstRunSliceIdx; i <= lastRunSliceIdx; ++i) {
if (runSlices.find(i) == runSlices.end()) {
//not found
runSlices[i] = m_runSliceCount;
sqlite3_bind_int(m_mzdbFile.stmt, 1, m_runSliceCount);
sqlite3_bind_int(m_mzdbFile.stmt, 2, msLevel);
sqlite3_bind_int(m_mzdbFile.stmt, 3, m_runSliceCount);
double moz = i * invBBheight;
sqlite3_bind_double(m_mzdbFile.stmt, 4, moz);
sqlite3_bind_double(m_mzdbFile.stmt, 5, moz + invBBheight);
sqlite3_bind_null(m_mzdbFile.stmt, 6);
sqlite3_bind_int(m_mzdbFile.stmt, 7, 1);
sqlite3_step(m_mzdbFile.stmt);
sqlite3_reset(m_mzdbFile.stmt);
m_runSliceCount++;
}
}
sqlite3_finalize(m_mzdbFile.stmt);
m_mzdbFile.stmt = 0;
// bounding boxes
const char* sql_2 = "INSERT INTO bounding_box VALUES ( ?, ?, ?, ?, ?);";
const char* sql_3 = "INSERT INTO bounding_box_rtree VALUES (?, ?, ?, ?, ?);";
const char* sql_4 = "INSERT INTO bounding_box_msn_rtree VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?);";
//create a new statement in order to iterate over bounding boxes only once
sqlite3_stmt* stmt = 0;
sqlite3_stmt* stmtHigherLevel = 0;
sqlite3_prepare_v2(m_mzdbFile.db, sql_2, -1, &(m_mzdbFile.stmt), 0);
sqlite3_prepare_v2(m_mzdbFile.db, sql_3, -1, &stmt, 0);
sqlite3_prepare_v2(m_mzdbFile.db, sql_4, -1, &stmtHigherLevel, 0);
for (auto it = bbs.begin(); it != bbs.end(); ++it) {
mzBoundingBox<h_mz_t, h_int_t, l_mz_t, l_int_t>& bb = **it;
vector<byte> data;// output;
bb.asByteArray(data, dataModes);
sqlite3_bind_int(m_mzdbFile.stmt, 1, m_bbCount);
sqlite3_bind_blob(m_mzdbFile.stmt, 2, &data[0], data.size(), SQLITE_STATIC);
sqlite3_bind_int(m_mzdbFile.stmt, 3, runSlices[bb.runSliceIdx()]);
sqlite3_bind_int(m_mzdbFile.stmt, 4, refScanIdx);
sqlite3_bind_int(m_mzdbFile.stmt, 5, refLastScanId);
sqlite3_step(m_mzdbFile.stmt);
sqlite3_reset(m_mzdbFile.stmt);
if (msLevel == 1) {
sqlite3_bind_int(stmt, 1, m_bbCount);
sqlite3_bind_double(stmt, 2, bb.mzmin());
sqlite3_bind_double(stmt, 3, bb.mzmax());
sqlite3_bind_double(stmt, 4, bb.rtmin());
sqlite3_bind_double(stmt, 5, bb.rtmax());
sqlite3_step(stmt);
sqlite3_reset(stmt);
} else {
sqlite3_bind_int(stmtHigherLevel, 1, m_bbCount);
sqlite3_bind_int(stmtHigherLevel, 2, msLevel);
sqlite3_bind_int(stmtHigherLevel, 3, msLevel);
sqlite3_bind_int(stmtHigherLevel, 4, parentMinMz); // parent_min_mz
sqlite3_bind_int(stmtHigherLevel, 5, parentMaxMz); // parent_max_mz
sqlite3_bind_double(stmtHigherLevel, 6, bb.mzmin());
sqlite3_bind_double(stmtHigherLevel, 7, bb.mzmax());
sqlite3_bind_double(stmtHigherLevel, 8, bb.rtmin());
sqlite3_bind_double(stmtHigherLevel, 9, bb.rtmax());
sqlite3_step(stmtHigherLevel);
sqlite3_reset(stmtHigherLevel);
}
++m_bbCount;
}
sqlite3_finalize(m_mzdbFile.stmt);
sqlite3_finalize(stmt);
sqlite3_finalize(stmtHigherLevel);
m_mzdbFile.stmt = stmt = stmtHigherLevel = 0;
}
public:
inline mzBBInserter(MzDBFile& mzdbFile):
m_mzdbFile(mzdbFile), m_bbCount(1), m_lastMinRunSliceIdx(0), m_lastMaxRunSliceIdx(0), m_runSliceCount(1){}
template<class h_mz_t, class h_int_t,
class l_mz_t, class l_int_t>
void buildAndInsertData(int msLevel,
double& bbheight,
vector<std::shared_ptr<mzSpectrum<h_mz_t, h_int_t> > >& highResBuffer,
vector<std::shared_ptr<mzSpectrum<l_mz_t, l_int_t> > >& lowResBuffer,
map<int, int>& runSlices,
double parentMinMz=0,
double parentMaxMz=0) {
map<int, vector<std::shared_ptr<Centroid<h_mz_t, h_int_t> > > >p1;
map<int, vector<std::shared_ptr<Centroid<l_mz_t, l_int_t> > > >p2;
map<int, DataMode> dataModes;
BBComputer::buildCentroidsByScanID<h_mz_t, h_int_t>(p1, highResBuffer, dataModes);
BBComputer::buildCentroidsByScanID<l_mz_t, l_int_t>(p2, lowResBuffer, dataModes);
this->_insertData<h_mz_t, h_int_t, l_mz_t, l_int_t>(msLevel, bbheight, runSlices, p1, p2, dataModes, parentMinMz, parentMaxMz);
}
};
__END_MZDB_NM //end namespace
#endif // MZBBINSERTER_H
| 45.632558 | 135 | 0.585363 | [
"vector"
] |
3219bd8718f4a421706d891aeda75c5de03a53fe | 24,771 | cpp | C++ | engine/src/window/platform/win32/win32window.cpp | TRBFLXR/x808 | d5ab9e96c5a6109283151a591c261e4183628075 | [
"MIT"
] | null | null | null | engine/src/window/platform/win32/win32window.cpp | TRBFLXR/x808 | d5ab9e96c5a6109283151a591c261e4183628075 | [
"MIT"
] | null | null | null | engine/src/window/platform/win32/win32window.cpp | TRBFLXR/x808 | d5ab9e96c5a6109283151a591c261e4183628075 | [
"MIT"
] | null | null | null | //
// Created by FLXR on 7/15/2018.
//
#undef NOGDI
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef WIN32_EXTRA_LEAN
#define WIN32_EXTRA_LEAN
#endif
#include <windows.h>
#define NOGDI
#include <dbt.h>
#include <xe/window/window.hpp>
#include <xe/utils/logger.hpp>
#include <xe/audio/audiomaster.hpp>
#include <xe/core/filesystem.hpp>
#include "win32window.hpp"
namespace {
uint windowCount = 0;
uint handleCount = 0;
const wchar_t *className = L"x808_win32_window";
xe::internal::PlatformWindowWin32 *fullscreenWindow = nullptr;
}
namespace xe::internal {
static PIXELFORMATDESCRIPTOR getPixelFormat() {
PIXELFORMATDESCRIPTOR result = { };
result.nSize = sizeof(PIXELFORMATDESCRIPTOR);
result.nVersion = 1;
result.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
result.iPixelType = PFD_TYPE_RGBA;
result.cColorBits = 32;
result.cDepthBits = 24;
result.cStencilBits = 8;
result.cAuxBuffers = 0;
result.iLayerType = PFD_MAIN_PLANE;
return result;
}
PlatformWindowWin32::PlatformWindowWin32(VideoMode mode, const string &title, uint style) :
handle(nullptr),
callback(0),
cursorVisible(true),
lastCursor(LoadCursor(nullptr, IDC_ARROW)),
icon(nullptr),
keyRepeatEnabled(true),
lastSize(mode.width, mode.height),
resizing(false),
mouseInside(false),
fullscreen((style & WindowStyle::Fullscreen) != 0),
cursorGrabbed(fullscreen) {
//register
if (windowCount == 0) {
registerWindowClass();
}
HDC screenDC = GetDC(nullptr);
int32 left = (GetDeviceCaps(screenDC, HORZRES) - mode.width) / 2;
int32 top = (GetDeviceCaps(screenDC, VERTRES) - mode.height) / 2;
int32 width = mode.width;
int32 height = mode.height;
ReleaseDC(nullptr, screenDC);
DWORD win32Style = WS_VISIBLE;
if (style == WindowStyle::None) {
win32Style |= WS_POPUPWINDOW;
} else {
win32Style |= WS_POPUP;
if (style & WindowStyle::Titlebar) win32Style |= WS_CAPTION | WS_MINIMIZEBOX;
if (style & WindowStyle::Resize) win32Style |= WS_THICKFRAME | WS_MAXIMIZEBOX;
if (style & WindowStyle::Close) win32Style |= WS_SYSMENU;
}
if (!fullscreen) {
RECT rectangle = {0, 0, width, height};
AdjustWindowRect(&rectangle, win32Style, false);
width = rectangle.right - rectangle.left;
height = rectangle.bottom - rectangle.top;
}
handle = CreateWindow(className, toWstring(title).c_str(), win32Style, left, top, width, height,
nullptr, nullptr, GetModuleHandle(nullptr), this);
DEV_BROADCAST_HDR deviceBroadcastHeader = {sizeof(DEV_BROADCAST_HDR), DBT_DEVTYP_DEVICEINTERFACE, 0};
RegisterDeviceNotification(handle, &deviceBroadcastHeader,
DEVICE_NOTIFY_WINDOW_HANDLE | DEVICE_NOTIFY_ALL_INTERFACE_CLASSES);
screenDC = GetDC(handle);
PIXELFORMATDESCRIPTOR pfd = getPixelFormat();
int32 pixelFormat = ChoosePixelFormat(screenDC, &pfd);
if (pixelFormat) {
if (!SetPixelFormat(screenDC, pixelFormat, &pfd)) {
XE_CORE_FATAL("[PlatformWindowWin32]: Failed setting pixel format!");
}
} else {
XE_CORE_FATAL("[PlatformWindowWin32]: Failed choosing pixel format!");
}
ReleaseDC(handle, screenDC);
setSize(vec2(mode.width, mode.height));
if (fullscreen) {
switchToFullscreen(mode);
}
windowCount++;
}
PlatformWindowWin32::~PlatformWindowWin32() {
ShowCursor(true);
SetCursor(LoadCursor(nullptr, IDC_ARROW));
if (icon) {
DestroyIcon(icon);
}
if (handle) {
--handleCount;
}
if (!callback) {
if (handle) {
DestroyWindow(handle);
}
windowCount--;
if (windowCount == 0) {
UnregisterClass(className, GetModuleHandle(nullptr));
}
} else {
SetWindowLongPtr(handle, GWLP_WNDPROC, callback);
}
if (this == fullscreenWindow) {
fullscreenWindow = nullptr;
}
}
void *PlatformWindowWin32::getHandle() const {
return handle;
}
vec2 PlatformWindowWin32::getPosition() const {
RECT rect;
GetWindowRect(handle, &rect);
return vec2(rect.left, rect.top);
}
void PlatformWindowWin32::setPosition(const vec2 &position) const {
SetWindowPos(handle, nullptr,
static_cast<int32>(position.x),
static_cast<int32>(position.y),
0, 0, SWP_NOSIZE | SWP_NOZORDER);
if (cursorGrabbed) {
grabCursor(true);
}
}
vec2 PlatformWindowWin32::getSize() const {
GetClientRect(handle, &rect);
return vec2(rect.right - rect.left, rect.bottom - rect.top);
}
void PlatformWindowWin32::setSize(const vec2 &size) const {
RECT rectangle = {0, 0, static_cast<LONG>(size.x), static_cast<LONG>(size.y)};
AdjustWindowRect(&rectangle, static_cast<DWORD>(GetWindowLong(handle, GWL_STYLE)), false);
const int32 width = rectangle.right - rectangle.left;
const int32 height = rectangle.bottom - rectangle.top;
SetWindowPos(handle, nullptr, 0, 0, width, height, SWP_NOMOVE | SWP_NOZORDER);
}
void PlatformWindowWin32::setTitle(const string &title) const {
SetWindowText(handle, toWstring(title).c_str());
}
string PlatformWindowWin32::getTitle() const {
std::wstring title(128, '\0');
GetWindowText(handle, &title[0], 128);
return toString(title);
}
void PlatformWindowWin32::setIcon(uint width, uint height, const byte *pixels) {
if (icon) {
DestroyIcon(icon);
}
std::vector<byte> iconPixels(width * height * 4);
for (std::size_t i = 0; i < iconPixels.size() / 4; ++i) {
iconPixels[i * 4 + 0] = pixels[i * 4 + 2];
iconPixels[i * 4 + 1] = pixels[i * 4 + 1];
iconPixels[i * 4 + 2] = pixels[i * 4 + 0];
iconPixels[i * 4 + 3] = pixels[i * 4 + 3];
}
icon = CreateIcon(GetModuleHandleW(nullptr), width, height, 1, 32, nullptr, &iconPixels[0]);
if (icon) {
SendMessage(handle, WM_SETICON, ICON_BIG, (LPARAM) icon);
SendMessage(handle, WM_SETICON, ICON_SMALL, (LPARAM) icon);
} else {
XE_CORE_ERROR("[PlatformWindowWin32]: Failed to set the window's icon");
}
}
void PlatformWindowWin32::setVisible(bool visible) const {
ShowWindow(handle, visible ? SW_SHOW : SW_HIDE);
}
void PlatformWindowWin32::setMouseCursorVisible(bool visible) {
if (visible != cursorVisible) {
cursorVisible = visible;
ShowCursor(visible);
}
}
void PlatformWindowWin32::setMouseCursorGrabbed(bool grabbed) {
cursorGrabbed = grabbed;
grabCursor(cursorGrabbed);
}
bool PlatformWindowWin32::isMouseCursorGrabbed() const {
return cursorGrabbed;
}
void PlatformWindowWin32::setMouseCursor(const Cursor &cursor) {
lastCursor = static_cast<HCURSOR>(cursor.raw());
SetCursor(lastCursor);
}
void PlatformWindowWin32::setKeyRepeatEnabled(bool enabled) {
keyRepeatEnabled = enabled;
}
void PlatformWindowWin32::requestFocus() const {
DWORD thisPid = GetWindowThreadProcessId(handle, nullptr);
DWORD foregroundPid = GetWindowThreadProcessId(GetForegroundWindow(), nullptr);
if (thisPid == foregroundPid) {
SetForegroundWindow(handle);
} else {
FLASHWINFO info;
info.cbSize = sizeof(info);
info.hwnd = handle;
info.dwFlags = FLASHW_TRAY;
info.dwTimeout = 0;
info.uCount = 3;
FlashWindowEx(&info);
}
}
bool PlatformWindowWin32::hasFocus() const {
return handle == GetForegroundWindow();
}
void PlatformWindowWin32::processEvents() {
if (!callback) {
MSG message;
while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) {
TranslateMessage(&message);
DispatchMessageW(&message);
}
}
}
void PlatformWindowWin32::registerWindowClass() {
WNDCLASSW windowClass;
windowClass.style = 0;
windowClass.lpfnWndProc = &PlatformWindowWin32::globalOnEvent;
windowClass.cbClsExtra = 0;
windowClass.cbWndExtra = 0;
windowClass.hInstance = GetModuleHandleW(nullptr);
windowClass.hIcon = nullptr;
windowClass.hCursor = nullptr;
windowClass.hbrBackground = nullptr;
windowClass.lpszMenuName = nullptr;
windowClass.lpszClassName = className;
RegisterClass(&windowClass);
}
void PlatformWindowWin32::switchToFullscreen(const VideoMode &mode) {
DEVMODE devMode;
devMode.dmSize = sizeof(DEVMODE);
devMode.dmPelsWidth = mode.width;
devMode.dmPelsHeight = mode.height;
devMode.dmBitsPerPel = mode.bitsPerPixel;
devMode.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL;
if (ChangeDisplaySettingsW(&devMode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) {
XE_CORE_ERROR("[PlatformWindowWin32]: Failed to change display mode for fullscreen");
return;
}
SetWindowLong(handle, GWL_STYLE, WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS);
SetWindowLong(handle, GWL_EXSTYLE, WS_EX_APPWINDOW);
SetWindowPos(handle, HWND_TOP, 0, 0, mode.width, mode.height, SWP_FRAMECHANGED);
ShowWindow(handle, SW_SHOW);
fullscreenWindow = this;
}
void PlatformWindowWin32::cleanup() {
if (fullscreenWindow == this) {
ChangeDisplaySettings(nullptr, 0);
fullscreenWindow = nullptr;
}
setMouseCursorVisible(true);
setTracking(false);
ReleaseCapture();
}
void PlatformWindowWin32::setTracking(bool track) {
TRACKMOUSEEVENT mouseEvent;
mouseEvent.cbSize = sizeof(TRACKMOUSEEVENT);
mouseEvent.dwFlags = track ? TME_LEAVE : TME_CANCEL;
mouseEvent.hwndTrack = handle;
mouseEvent.dwHoverTime = HOVER_DEFAULT;
TrackMouseEvent(&mouseEvent);
}
void PlatformWindowWin32::grabCursor(bool grabbed) const {
if (grabbed) {
RECT rect;
GetClientRect(handle, &rect);
MapWindowPoints(handle, nullptr, reinterpret_cast<LPPOINT>(&rect), 2);
ClipCursor(&rect);
} else {
ClipCursor(nullptr);
}
}
void PlatformWindowWin32::processEvent(UINT message, WPARAM wParam, LPARAM lParam) {
if (!handle) return;
switch (message) {
case WM_DESTROY: {
cleanup();
break;
}
case WM_SETCURSOR: {
if (LOWORD(lParam) == HTCLIENT) {
SetCursor(lastCursor);
}
break;
}
case WM_CLOSE: {
Event event{ };
event.type = Event::Closed;
pushEvent(event);
break;
}
case WM_SIZE: {
if (wParam != SIZE_MINIMIZED && !resizing && lastSize != getSize()) {
lastSize = getSize();
Event event{ };
event.type = Event::Resized;
event.size.width = lastSize.x;
event.size.height = lastSize.y;
pushEvent(event);
grabCursor(cursorGrabbed);
}
break;
}
case WM_ENTERSIZEMOVE: {
resizing = true;
grabCursor(false);
break;
}
case WM_EXITSIZEMOVE: {
resizing = false;
if (lastSize != getSize()) {
lastSize = getSize();
Event event{ };
event.type = Event::Resized;
event.size.width = lastSize.x;
event.size.height = lastSize.y;
pushEvent(event);
}
grabCursor(cursorGrabbed);
break;
}
case WM_GETMINMAXINFO: {
MINMAXINFO *info = reinterpret_cast<MINMAXINFO *>(lParam);
info->ptMaxTrackSize.x = 50000;
info->ptMaxTrackSize.y = 50000;
break;
}
case WM_SETFOCUS: {
grabCursor(cursorGrabbed);
Event event{ };
event.type = Event::GainedFocus;
pushEvent(event);
break;
}
case WM_KILLFOCUS: {
grabCursor(false);
Event event{ };
event.type = Event::LostFocus;
pushEvent(event);
break;
}
case WM_CHAR: {
if (keyRepeatEnabled || ((lParam & (1 << 30)) == 0)) {
uint ch = static_cast<uint>(wParam);
Event event{ };
event.type = Event::TextEntered;
wcharToUTF8(ch, event.text.unicode);
pushEvent(event);
}
break;
}
case WM_KEYDOWN:
case WM_SYSKEYDOWN: {
if (keyRepeatEnabled || ((HIWORD(lParam) & KF_REPEAT) == 0)) {
Event event{ };
event.type = Event::KeyPressed;
event.key.alt = HIWORD(GetKeyState(VK_MENU)) != 0;
event.key.control = HIWORD(GetKeyState(VK_CONTROL)) != 0;
event.key.shift = HIWORD(GetKeyState(VK_SHIFT)) != 0;
event.key.system = HIWORD(GetKeyState(VK_LWIN)) || HIWORD(GetKeyState(VK_RWIN));
event.key.code = virtualKeyCodeToXE(wParam, lParam);
pushEvent(event);
}
break;
}
case WM_KEYUP:
case WM_SYSKEYUP: {
Event event{ };
event.type = Event::KeyReleased;
event.key.alt = HIWORD(GetKeyState(VK_MENU)) != 0;
event.key.control = HIWORD(GetKeyState(VK_CONTROL)) != 0;
event.key.shift = HIWORD(GetKeyState(VK_SHIFT)) != 0;
event.key.system = HIWORD(GetKeyState(VK_LWIN)) || HIWORD(GetKeyState(VK_RWIN));
event.key.code = virtualKeyCodeToXE(wParam, lParam);
pushEvent(event);
break;
}
case WM_MOUSEWHEEL: {
POINT position;
position.x = static_cast<int16>(LOWORD(lParam));
position.y = static_cast<int16>(HIWORD(lParam));
ScreenToClient(handle, &position);
int16 delta = static_cast<int16>(HIWORD(wParam));
Event event{ };
event.type = Event::MouseWheelMoved;
event.mouseWheel.delta = delta / 120;
event.mouseWheel.x = position.x;
event.mouseWheel.y = (rect.bottom - rect.top) - position.y;
pushEvent(event);
break;
}
case WM_LBUTTONDOWN: {
Event event{ };
event.type = Event::MouseButtonPressed;
event.mouseButton.button = Mouse::Left;
event.mouseButton.x = static_cast<float>(LOWORD(lParam));
event.mouseButton.y = (rect.bottom - rect.top) - static_cast<float>(HIWORD(lParam));
pushEvent(event);
break;
}
case WM_LBUTTONUP: {
Event event{ };
event.type = Event::MouseButtonReleased;
event.mouseButton.button = Mouse::Left;
event.mouseButton.x = static_cast<float>(LOWORD(lParam));
event.mouseButton.y = (rect.bottom - rect.top) - static_cast<float>(HIWORD(lParam));
pushEvent(event);
break;
}
case WM_RBUTTONDOWN: {
Event event{ };
event.type = Event::MouseButtonPressed;
event.mouseButton.button = Mouse::Right;
event.mouseButton.x = static_cast<float>(LOWORD(lParam));
event.mouseButton.y = (rect.bottom - rect.top) - static_cast<float>(HIWORD(lParam));
pushEvent(event);
break;
}
case WM_RBUTTONUP: {
Event event{ };
event.type = Event::MouseButtonReleased;
event.mouseButton.button = Mouse::Right;
event.mouseButton.x = static_cast<float>(LOWORD(lParam));
event.mouseButton.y = (rect.bottom - rect.top) - static_cast<float>(HIWORD(lParam));
pushEvent(event);
break;
}
case WM_MBUTTONDOWN: {
Event event{ };
event.type = Event::MouseButtonPressed;
event.mouseButton.button = Mouse::Middle;
event.mouseButton.x = static_cast<float>(LOWORD(lParam));
event.mouseButton.y = (rect.bottom - rect.top) - static_cast<float>(HIWORD(lParam));
pushEvent(event);
break;
}
case WM_MBUTTONUP: {
Event event{ };
event.type = Event::MouseButtonReleased;
event.mouseButton.button = Mouse::Middle;
event.mouseButton.x = static_cast<int16>(LOWORD(lParam));
event.mouseButton.y = (rect.bottom - rect.top) - static_cast<int16>(HIWORD(lParam));
pushEvent(event);
break;
}
case WM_XBUTTONDOWN: {
Event event{ };
event.type = Event::MouseButtonPressed;
event.mouseButton.button = HIWORD(wParam) == XBUTTON1 ? Mouse::XButton1 : Mouse::XButton2;
event.mouseButton.x = static_cast<float>(LOWORD(lParam));
event.mouseButton.y = (rect.bottom - rect.top) - static_cast<float>(HIWORD(lParam));
pushEvent(event);
break;
}
case WM_XBUTTONUP: {
Event event{ };
event.type = Event::MouseButtonReleased;
event.mouseButton.button = HIWORD(wParam) == XBUTTON1 ? Mouse::XButton1 : Mouse::XButton2;
event.mouseButton.x = static_cast<float>(LOWORD(lParam));
event.mouseButton.y = (rect.bottom - rect.top) - static_cast<float>(HIWORD(lParam));
pushEvent(event);
break;
}
case WM_MOUSELEAVE: {
if (mouseInside) {
mouseInside = false;
Event event{ };
event.type = Event::MouseLeft;
pushEvent(event);
}
break;
}
case WM_MOUSEMOVE: {
float x = static_cast<float>(LOWORD(lParam));
float y = static_cast<float>(HIWORD(lParam));
RECT area;
GetClientRect(handle, &area);
if ((wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON | MK_XBUTTON1 | MK_XBUTTON2)) == 0) {
if (GetCapture() == handle) {
ReleaseCapture();
}
} else if (GetCapture() != handle) {
SetCapture(handle);
}
if ((x < area.left) || (x > area.right) || (y < area.top) || (y > area.bottom)) {
if (mouseInside) {
mouseInside = false;
setTracking(false);
Event event{ };
event.type = Event::MouseLeft;
pushEvent(event);
}
} else {
if (!mouseInside) {
mouseInside = true;
setTracking(true);
Event event{ };
event.type = Event::MouseEntered;
pushEvent(event);
}
}
Event event{ };
event.type = Event::MouseMoved;
event.mouseMove.x = x;
event.mouseMove.y = (rect.bottom - rect.top) - y;
pushEvent(event);
break;
}
case WM_DEVICECHANGE : {
if (wParam == DBT_DEVICEARRIVAL) {
auto pDev = reinterpret_cast<PDEV_BROADCAST_HDR>(lParam);
if (pDev) {
if (pDev->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE) {
auto pInter = reinterpret_cast<const PDEV_BROADCAST_DEVICEINTERFACE>(pDev);
static const GUID audioGUID = {1771351300, 37871, 4560,
{163, 204, 0, 160, 201, 34, 49, 150}};
if (pInter->dbcc_classguid == audioGUID) { }
} else if (pDev->dbch_devicetype == DBT_DEVTYP_VOLUME) {
FileSystem::updateVolumes();
}
}
}
if (wParam == DBT_DEVICEREMOVECOMPLETE) {
auto pDev = reinterpret_cast<PDEV_BROADCAST_HDR>(lParam);
if (pDev) {
if (pDev->dbch_devicetype == DBT_DEVTYP_VOLUME) {
FileSystem::updateVolumes();
}
}
}
break;
}
default: break;
}
}
Keyboard::Key PlatformWindowWin32::virtualKeyCodeToXE(WPARAM key, LPARAM flags) {
switch (key) {
case VK_SHIFT: {
static UINT lShift = MapVirtualKeyW(VK_LSHIFT, MAPVK_VK_TO_VSC);
UINT scancode = static_cast<UINT>((flags & (0xFF << 16)) >> 16);
return scancode == lShift ? Keyboard::LShift : Keyboard::RShift;
}
case VK_MENU : return (HIWORD(flags) & KF_EXTENDED) ? Keyboard::RAlt : Keyboard::LAlt;
case VK_CONTROL : return (HIWORD(flags) & KF_EXTENDED) ? Keyboard::RControl : Keyboard::LControl;
case VK_LWIN: return Keyboard::LSystem;
case VK_RWIN: return Keyboard::RSystem;
case VK_APPS: return Keyboard::Menu;
case VK_OEM_1: return Keyboard::SemiColon;
case VK_OEM_2: return Keyboard::Slash;
case VK_OEM_PLUS: return Keyboard::Equal;
case VK_OEM_MINUS: return Keyboard::Dash;
case VK_OEM_4: return Keyboard::LBracket;
case VK_OEM_6: return Keyboard::RBracket;
case VK_OEM_COMMA: return Keyboard::Comma;
case VK_OEM_PERIOD: return Keyboard::Period;
case VK_OEM_7: return Keyboard::Quote;
case VK_OEM_5: return Keyboard::BackSlash;
case VK_OEM_3: return Keyboard::Tilde;
case VK_ESCAPE: return Keyboard::Escape;
case VK_SPACE: return Keyboard::Space;
case VK_RETURN: return Keyboard::Return;
case VK_BACK: return Keyboard::BackSpace;
case VK_TAB: return Keyboard::Tab;
case VK_PRIOR: return Keyboard::PageUp;
case VK_NEXT: return Keyboard::PageDown;
case VK_END: return Keyboard::End;
case VK_HOME: return Keyboard::Home;
case VK_INSERT: return Keyboard::Insert;
case VK_DELETE: return Keyboard::Delete;
case VK_ADD: return Keyboard::Add;
case VK_SUBTRACT: return Keyboard::Subtract;
case VK_MULTIPLY: return Keyboard::Multiply;
case VK_DIVIDE: return Keyboard::Divide;
case VK_PAUSE: return Keyboard::Pause;
case VK_F1: return Keyboard::F1;
case VK_F2: return Keyboard::F2;
case VK_F3: return Keyboard::F3;
case VK_F4: return Keyboard::F4;
case VK_F5: return Keyboard::F5;
case VK_F6: return Keyboard::F6;
case VK_F7: return Keyboard::F7;
case VK_F8: return Keyboard::F8;
case VK_F9: return Keyboard::F9;
case VK_F10: return Keyboard::F10;
case VK_F11: return Keyboard::F11;
case VK_F12: return Keyboard::F12;
case VK_F13: return Keyboard::F13;
case VK_F14: return Keyboard::F14;
case VK_F15: return Keyboard::F15;
case VK_LEFT: return Keyboard::Left;
case VK_RIGHT: return Keyboard::Right;
case VK_UP: return Keyboard::Up;
case VK_DOWN: return Keyboard::Down;
case VK_NUMPAD0: return Keyboard::Numpad0;
case VK_NUMPAD1: return Keyboard::Numpad1;
case VK_NUMPAD2: return Keyboard::Numpad2;
case VK_NUMPAD3: return Keyboard::Numpad3;
case VK_NUMPAD4: return Keyboard::Numpad4;
case VK_NUMPAD5: return Keyboard::Numpad5;
case VK_NUMPAD6: return Keyboard::Numpad6;
case VK_NUMPAD7: return Keyboard::Numpad7;
case VK_NUMPAD8: return Keyboard::Numpad8;
case VK_NUMPAD9: return Keyboard::Numpad9;
case 'A': return Keyboard::A;
case 'Z': return Keyboard::Z;
case 'E': return Keyboard::E;
case 'R': return Keyboard::R;
case 'T': return Keyboard::T;
case 'Y': return Keyboard::Y;
case 'U': return Keyboard::U;
case 'I': return Keyboard::I;
case 'O': return Keyboard::O;
case 'P': return Keyboard::P;
case 'Q': return Keyboard::Q;
case 'S': return Keyboard::S;
case 'D': return Keyboard::D;
case 'F': return Keyboard::F;
case 'G': return Keyboard::G;
case 'H': return Keyboard::H;
case 'J': return Keyboard::J;
case 'K': return Keyboard::K;
case 'L': return Keyboard::L;
case 'M': return Keyboard::M;
case 'W': return Keyboard::W;
case 'X': return Keyboard::X;
case 'C': return Keyboard::C;
case 'V': return Keyboard::V;
case 'B': return Keyboard::B;
case 'N': return Keyboard::N;
case '0': return Keyboard::Num0;
case '1': return Keyboard::Num1;
case '2': return Keyboard::Num2;
case '3': return Keyboard::Num3;
case '4': return Keyboard::Num4;
case '5': return Keyboard::Num5;
case '6': return Keyboard::Num6;
case '7': return Keyboard::Num7;
case '8': return Keyboard::Num8;
case '9': return Keyboard::Num9;
default: return Keyboard::Unknown;
}
}
LRESULT PlatformWindowWin32::globalOnEvent(HWND handle, UINT message, WPARAM wParam, LPARAM lParam) {
if (message == WM_CREATE) {
LONG_PTR window = (LONG_PTR) reinterpret_cast<CREATESTRUCT *>(lParam)->lpCreateParams;
SetWindowLongPtr(handle, GWLP_USERDATA, window);
}
auto *window = handle ? reinterpret_cast<PlatformWindowWin32 *>(GetWindowLongPtr(handle, GWLP_USERDATA))
: nullptr;
if (window) {
window->processEvent(message, wParam, lParam);
if (window->callback) {
return CallWindowProc(reinterpret_cast<WNDPROC>(window->callback),
handle, message, wParam, lParam);
}
}
if (message == WM_CLOSE) {
return 0;
}
if ((message == WM_SYSCOMMAND) && (wParam == SC_KEYMENU)) {
return 0;
}
return DefWindowProcW(handle, message, wParam, lParam);
}
}
| 31.002503 | 108 | 0.621735 | [
"vector"
] |
321f01e540e958aa86450773e7fa39b2b56ea352 | 818 | cpp | C++ | soln/maximum-erasure-value/Solution.cpp | yungweezy/leetcode | 070605351a0a05b80360b9a55326b03224e46bbe | [
"MIT"
] | null | null | null | soln/maximum-erasure-value/Solution.cpp | yungweezy/leetcode | 070605351a0a05b80360b9a55326b03224e46bbe | [
"MIT"
] | null | null | null | soln/maximum-erasure-value/Solution.cpp | yungweezy/leetcode | 070605351a0a05b80360b9a55326b03224e46bbe | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int maximumUniqueSubarray(vector<int>& nums) {
unordered_set<int> s;
int n = nums.size(), curr = 0, max = 0, l = 0, r = 0;
// for (int i : nums) {
// if(s.find(i) == s.end()) {
// s.insert(i);
// sum += i;
// }
// }
while (l <= r && r < n) {
if(s.find(nums[r]) != s.end()) {
curr -= nums[l];
s.erase(nums[l]);
l++;
} else {
s.insert(nums[r]);
curr += nums[r];
r++;
if (curr > max) max = curr;
}
}
return max;
}
};
// https://leetcode.com/problems/maximum-erasure-value/ | 27.266667 | 61 | 0.374083 | [
"vector"
] |
321f27b08272e25dfc3cd5fefa26a5278a4e3e9a | 4,803 | cpp | C++ | AssetManager.cpp | Abscission/abscission-asset-tool | 617f5845a9b366d5a43f3e6ae2a2ecb104464c6b | [
"MIT"
] | 2 | 2015-06-26T07:43:05.000Z | 2015-06-26T12:20:38.000Z | AssetManager.cpp | rilwal/abscission-asset-tool | 617f5845a9b366d5a43f3e6ae2a2ecb104464c6b | [
"MIT"
] | null | null | null | AssetManager.cpp | rilwal/abscission-asset-tool | 617f5845a9b366d5a43f3e6ae2a2ecb104464c6b | [
"MIT"
] | null | null | null |
#include <Windows.h>
#include <iostream>
#include <vector>
#include <string>
#include "include\zlib.h"
struct File {
std::string Filename;
bool shouldCompress;
};
#pragma pack(push, 1)
struct Header {
char FileID[4];
int NumberOfEntries;
int DataLength;
};
struct IndexEntry {
char Name[12];
int Position;
int Length;
bool Compressed;
};
#pragma pack(pop)
typedef unsigned char Byte;
int main(int argc, char* argv[]) {
std::vector<File> Assets;
//parse arguments
bool compressNext = true;
for (int i = 1; i < argc - 1; i++) {
bool compress = compressNext;
if (strcmp(argv[i], "-c") == 0) {
compressNext = true;
}
else if (strcmp(argv[i], "-nc") == 0) {
compressNext = false;
}
else {
File a = { argv[i], compress };
Assets.push_back(a);
compressNext = true;
}
}
const std::string usingCompression = " using compression";
const std::string noCompression = " without compression";
for (auto asset : Assets) {
std::cout << "Adding " << asset.Filename << (asset.shouldCompress ? usingCompression : noCompression) << '\n';
}
int NumberOfAssets = Assets.size();
if (NumberOfAssets < 1) {
std::cout << "Usage: " << argv[0] << " [asset1] [asset2]... [assetN] [AssetFile.aaf]";
return 1;
}
Header FileHeader = {};
*(int*)FileHeader.FileID = 0x41454741;
FileHeader.NumberOfEntries = NumberOfAssets;
//FileHeader.Compressed = true;
IndexEntry* Indexes = (IndexEntry*)VirtualAlloc(0, sizeof(IndexEntry) * NumberOfAssets, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
Byte** CompressedFiles = (Byte**)VirtualAlloc(0, sizeof(char*) * NumberOfAssets, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
int* OriginalSizes= new int[NumberOfAssets];
int* CompressedSizes = new int[NumberOfAssets];
int RunningPosition = 0;
//For each asset
for (int i = 0; i < NumberOfAssets; i++){
//Open the file
HANDLE AssetFile = CreateFileA(Assets[i].Filename.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (AssetFile == INVALID_HANDLE_VALUE) {
std::cout << "Failed to open file: " << argv[i + 1] << '\n';
return 1;
}
//Allocate memory for the read file, and copy the files contents into a buffer
int FileSize = GetFileSize(AssetFile, NULL);
void* UncompressedData = VirtualAlloc(0, FileSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
ReadFile(AssetFile, UncompressedData, FileSize, NULL, NULL);
//Allocate the compression boundary amount of memory. This is the maximum size the file could expand to if it is incompressable data.
int MaxSize = compressBound(FileSize);
CompressedFiles[i] = (Byte*)VirtualAlloc(0, MaxSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
unsigned long CompressedSize;
if (Assets[i].shouldCompress) {
CompressedSize = MaxSize;
compress(CompressedFiles[i], &CompressedSize, (Byte*)UncompressedData, FileSize);
std::cout << "\nFile: " << Assets[i].Filename << "\nOriginalSize: " << FileSize << " bytes\nCompressedSize: " << CompressedSize << " bytes\n\n";
}
else {
CompressedSize = FileSize;
memcpy(CompressedFiles[i], UncompressedData, FileSize);
std::cout << "\nFile: " << Assets[i].Filename << "\nSize: " << FileSize << " bytes\nNot Compressed\n\n";
}
Indexes[i].Length = CompressedSize + 8;
Indexes[i].Position = RunningPosition;
Indexes[i].Compressed = Assets[i].shouldCompress;
RunningPosition += CompressedSize + 8;
OriginalSizes[i] = FileSize;
CompressedSizes[i] = CompressedSize;
}
FileHeader.DataLength = RunningPosition;
//Create the file in memory (inefficient as two copies of most data are created, but good enough for our purposes)
int SizeOfFile = sizeof(Header) + (sizeof(IndexEntry) * NumberOfAssets) + RunningPosition;
void* FileBuffer = VirtualAlloc(0, SizeOfFile, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
memcpy(FileBuffer, &FileHeader, sizeof(FileHeader));
memcpy((void*)((char*)FileBuffer + sizeof(FileHeader)), Indexes, sizeof(IndexEntry) * NumberOfAssets);
for (int i = 0; i < NumberOfAssets; i++) {
if (Assets[i].shouldCompress) {
*(int*)((char*)FileBuffer + sizeof(Header) + (sizeof(IndexEntry) * NumberOfAssets) + Indexes[i].Position) = OriginalSizes[i];
*((int*)((char*)FileBuffer + sizeof(Header) + (sizeof(IndexEntry) * NumberOfAssets) + Indexes[i].Position) + 1) = CompressedSizes[i];
}
memcpy((void*)((int*)((char*)FileBuffer + sizeof(Header) + (sizeof(IndexEntry) * NumberOfAssets) + Indexes[i].Position) + 2), CompressedFiles[i], CompressedSizes[i]);
}
//Write the file
std::cout << "Creating asset file " << argv[argc - 1] << '\n';
HANDLE ArchiveFile = CreateFileA(argv[argc - 1], GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
WriteFile(ArchiveFile, FileBuffer, SizeOfFile, 0, 0);
} | 32.89726 | 168 | 0.696648 | [
"vector"
] |
322182e5448878867b625e715ae85536cbb0e32d | 3,134 | cpp | C++ | Engine/Source/Render/Model/AssimpModelParser/AssimpModelParser.cpp | TzuChieh/XenoGameEngine | 69d7524ee05491c8e6f8c45fdb6a12bfcecb4731 | [
"MIT"
] | 4 | 2016-09-04T12:58:44.000Z | 2020-11-11T15:48:41.000Z | Engine/Source/Render/Model/AssimpModelParser/AssimpModelParser.cpp | TzuChieh/VirtualGameEngine | 69d7524ee05491c8e6f8c45fdb6a12bfcecb4731 | [
"MIT"
] | 1 | 2016-07-16T15:46:32.000Z | 2016-08-05T11:01:16.000Z | Engine/Source/Render/Model/AssimpModelParser/AssimpModelParser.cpp | TzuChieh/VirtualGameEngine | 69d7524ee05491c8e6f8c45fdb6a12bfcecb4731 | [
"MIT"
] | null | null | null | #include "AssimpModelParser.h"
#include "Render/Model/StaticModel.h"
#include "Render/Renderable/StaticRenderable.h"
#include "Render/Material/PhongMaterial.h"
#include "Render/Model/GpuBuffer.h"
#include "Render/Model/GpuMesh.h"
#include "Common/ThirdPartyLib/assimp.h"
#include <iostream>
using namespace ve;
AssimpModelParser::AssimpModelParser()
{
}
AssimpModelParser::~AssimpModelParser()
{
}
bool AssimpModelParser::load(const StaticModel& staticModel, StaticRenderable* out_staticRenderable)
{
const aiScene* assimpScene = m_assimpImporter.ReadFile(staticModel.getFullFilename(), aiProcess_Triangulate);
if(!assimpScene)
{
std::cerr << m_assimpImporter.GetErrorString() << std::endl;
return false;
}
out_staticRenderable->clearAll();
out_staticRenderable->setOriginatedModelName(staticModel.getFullFilename());
out_staticRenderable->setModelMatrix(AssimpModelParser::genModelMatrix(staticModel));
GpuMesh gpuMesh((std::make_shared<GpuMeshRes>()));
GpuBuffer vbo_positions(std::make_shared<GpuBufferRes>(EGpuBufferType::GENERAL_ARRAY, EGpuBufferUsage::STATIC));
GpuBuffer vbo_normals(std::make_shared<GpuBufferRes>(EGpuBufferType::GENERAL_ARRAY, EGpuBufferUsage::STATIC));
GpuBuffer vbo_indices(std::make_shared<GpuBufferRes>(EGpuBufferType::INDEX_ARRAY, EGpuBufferUsage::STATIC));
gpuMesh.setDrawingGenre(EDrawingGenre::TRIANGLES);
std::vector<float32> positions;
std::vector<float32> normals;
std::vector<uint32> indices;
// FIXME: mMeshes[N]
const aiMesh* mesh = assimpScene->mMeshes[0];
// TODO: interleaved buffer data
if(mesh->HasPositions())
{
for(int i = 0; i < mesh->mNumVertices; ++i)
{
positions.push_back(mesh->mVertices[i].x);
positions.push_back(mesh->mVertices[i].y);
positions.push_back(mesh->mVertices[i].z);
}
vbo_positions.loadData(positions, 3);
gpuMesh.addVertexData(vbo_positions, 0);
gpuMesh.setVertexDataLocatorSeparated(0, 0);
}
if(mesh->HasNormals())
{
for(int i = 0; i < mesh->mNumVertices; ++i)
{
normals.push_back(mesh->mNormals[i].x);
normals.push_back(mesh->mNormals[i].y);
normals.push_back(mesh->mNormals[i].z);
}
vbo_normals.loadData(normals, 3);
gpuMesh.addVertexData(vbo_normals, 1);
gpuMesh.setVertexDataLocatorSeparated(1, 1);
}
if(mesh->HasFaces())
{
for(int i = 0; i < mesh->mNumFaces; ++i)
{
indices.push_back(mesh->mFaces[i].mIndices[0]);
indices.push_back(mesh->mFaces[i].mIndices[1]);
indices.push_back(mesh->mFaces[i].mIndices[2]);
}
vbo_indices.loadData(indices, 1);
// size of indices = mesh->mNumFaces * 3
gpuMesh.setIndexData(vbo_indices, indices.size());
}
out_staticRenderable->addMeshMaterialPair(gpuMesh, std::make_shared<PhongMaterial>());
return true;
}
Matrix4f AssimpModelParser::genModelMatrix(const StaticModel& staticModel)
{
Matrix4f translationMatrix;
Matrix4f rotationMatrix;
Matrix4f scaleMatrix;
translationMatrix.initTranslation(staticModel.getPosition());
rotationMatrix.initRotation(staticModel.getOrientation());
scaleMatrix.initScale(staticModel.getScale());
return translationMatrix.mul(rotationMatrix).mul(scaleMatrix);
} | 27.017241 | 113 | 0.75686 | [
"mesh",
"render",
"vector",
"model"
] |
322ab85b6e6480f182c21c2d676f37a57253e27c | 5,869 | cpp | C++ | Sources/Elastos/LibCore/src/elastosx/xml/parsers/DocumentBuilderFactory.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/LibCore/src/elastosx/xml/parsers/DocumentBuilderFactory.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/LibCore/src/elastosx/xml/parsers/DocumentBuilderFactory.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include "DocumentBuilderFactory.h"
#include "utility/logging/Slogger.h"
#include "Thread.h"
#include "CPathClassLoader.h"
// #include "org/apache/harmony/xml/parsers/CDocumentBuilderFactoryImpl.h"
// using Org::Apache::Harmony::Xml::Parsers::CDocumentBuilderFactoryImpl;
using Elastos::Core::Thread;
using Elastos::Core::CPathClassLoader;
namespace Elastosx {
namespace Xml {
namespace Parsers {
CAR_INTERFACE_IMPL(DocumentBuilderFactory, Object, IDocumentBuilderFactory)
DocumentBuilderFactory::DocumentBuilderFactory()
: mValidating(FALSE)
, mNamespaceAware(FALSE)
, mWhitespace(FALSE)
, mExpandEntityRef(TRUE)
, mIgnoreComments(FALSE)
, mCoalescing(FALSE)
{}
ECode DocumentBuilderFactory::SetNamespaceAware(
/* [in] */ Boolean awareness)
{
mNamespaceAware = awareness;
return NOERROR;
}
ECode DocumentBuilderFactory::SetValidating(
/* [in] */ Boolean validating)
{
mValidating = validating;
return NOERROR;
}
ECode DocumentBuilderFactory::SetIgnoringElementContentWhitespace(
/* [in] */ Boolean whitespace)
{
mWhitespace = whitespace;
return NOERROR;
}
ECode DocumentBuilderFactory::SetExpandEntityReferences(
/* [in] */ Boolean expandEntityRef)
{
mExpandEntityRef = expandEntityRef;
return NOERROR;
}
ECode DocumentBuilderFactory::SetIgnoringComments(
/* [in] */ Boolean ignoreComments)
{
mIgnoreComments = ignoreComments;
return NOERROR;
}
ECode DocumentBuilderFactory::SetCoalescing(
/* [in] */ Boolean coalescing)
{
mCoalescing = coalescing;
return NOERROR;
}
ECode DocumentBuilderFactory::IsNamespaceAware(
/* [out] */ Boolean* isAware)
{
*isAware = mNamespaceAware;
return NOERROR;
}
ECode DocumentBuilderFactory::IsValidating(
/* [out] */ Boolean* isValidating)
{
*isValidating = mValidating;
return NOERROR;
}
ECode DocumentBuilderFactory::IsIgnoringElementContentWhitespace(
/* [out] */ Boolean* isIgnoringElementContentWhiteSpace)
{
*isIgnoringElementContentWhiteSpace = mWhitespace;
return NOERROR;
}
ECode DocumentBuilderFactory::IsExpandEntityReferences(
/* [out] */ Boolean* isExpandEntityReferences)
{
*isExpandEntityReferences = mExpandEntityRef;
return NOERROR;
}
ECode DocumentBuilderFactory::IsIgnoringComments(
/* [out] */ Boolean* comments)
{
*comments = mIgnoreComments;
return NOERROR;
}
ECode DocumentBuilderFactory::IsCoalescing(
/* [out] */ Boolean* isCoalescing)
{
*isCoalescing = mCoalescing;
return NOERROR;
}
ECode DocumentBuilderFactory::GetSchema(
/* [out] */ ISchema** schema)
{
return E_UNSUPPORTED_OPERATION_EXCEPTION;
}
ECode DocumentBuilderFactory::SetSchema(
/* [in] */ ISchema* schema)
{
return E_UNSUPPORTED_OPERATION_EXCEPTION;
}
ECode DocumentBuilderFactory::SetXIncludeAware(
/* [in] */ Boolean state)
{
return E_UNSUPPORTED_OPERATION_EXCEPTION;
}
ECode DocumentBuilderFactory::IsXIncludeAware(
/* [out] */ Boolean* isXIncludeAware)
{
return E_UNSUPPORTED_OPERATION_EXCEPTION;
}
ECode DocumentBuilderFactory::NewInstance(
/* [out] */ IDocumentBuilderFactory** instance)
{
// return CDocumentBuilderFactoryImpl::New(instance);
return NOERROR;
}
ECode DocumentBuilderFactory::NewInstance(
/* [in] */ const String& factoryClassName,
/* [in] */ IClassLoader* classLoader,
/* [out] */ IDocumentBuilderFactory** instance)
{
*instance = NULL;
if (factoryClassName == NULL) {
SLOGGERD("DocumentBuilderFactory", "factoryClassName == null");
return E_FACTORY_CONFIGURATION_EXCEPTION;
}
AutoPtr<IClassLoader> pLoader = classLoader;
if (pLoader == NULL) {
FAIL_RETURN(Thread::GetCurrentThread()->GetContextClassLoader((IClassLoader**)&pLoader))
}
// try {
if (pLoader == NULL) {
String path = factoryClassName.Substring(0, factoryClassName.LastIndexOf('.'));
FAIL_RETURN(CPathClassLoader::New(path, NULL, (IClassLoader**)&pLoader))
}
AutoPtr<IClassInfo> clsInfo;
FAIL_RETURN(pLoader->LoadClass(factoryClassName, (IClassInfo**)&clsInfo))
if (clsInfo == NULL) {
return E_CLASS_NOT_FOUND_EXCEPTION;
}
ClassID id;
clsInfo->GetId(&id);
AutoPtr<IInterface> tmp;
FAIL_RETURN(CObject::CreateInstance(id, RGM_SAME_DOMAIN, EIID_IInterface, (IInterface**)&tmp))
*instance = IDocumentBuilderFactory::Probe(tmp);
REFCOUNT_ADD(*instance)
return NOERROR;
// Class<?> type = classLoader != null
// ? classLoader.loadClass(factoryClassName)
// : Class.forName(factoryClassName);
// return (DocumentBuilderFactory) type.newInstance();
// } catch (ClassNotFoundException e) {
// throw new FactoryConfigurationError(e);
// } catch (InstantiationException e) {
// throw new FactoryConfigurationError(e);
// } catch (IllegalAccessException e) {
// throw new FactoryConfigurationError(e);
// }
}
} // namespace Parsers
} // namespace Xml
} // namespace Elastosx | 28.490291 | 102 | 0.684444 | [
"object"
] |
7a86dfde85eb8e5c046c83211edcd49a61152dc3 | 15,646 | cc | C++ | ash/app_list/views/app_list_bubble_apps_page.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | ash/app_list/views/app_list_bubble_apps_page.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | ash/app_list/views/app_list_bubble_apps_page.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/app_list/views/app_list_bubble_apps_page.h"
#include <algorithm>
#include <limits>
#include <memory>
#include <string>
#include <utility>
#include "ash/app_list/app_list_model_provider.h"
#include "ash/app_list/app_list_view_delegate.h"
#include "ash/app_list/model/app_list_model.h"
#include "ash/app_list/views/app_list_reorder_undo_container_view.h"
#include "ash/app_list/views/continue_section_view.h"
#include "ash/app_list/views/recent_apps_view.h"
#include "ash/app_list/views/scrollable_apps_grid_view.h"
#include "ash/bubble/bubble_utils.h"
#include "ash/constants/ash_features.h"
#include "ash/controls/rounded_scroll_bar.h"
#include "ash/controls/scroll_view_gradient_helper.h"
#include "ash/public/cpp/metrics_util.h"
#include "ash/public/cpp/style/color_provider.h"
#include "base/bind.h"
#include "base/check.h"
#include "base/metrics/histogram_functions.h"
#include "base/time/time.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/aura/window.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/compositor/animation_throughput_reporter.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_animator.h"
#include "ui/compositor/layer_type.h"
#include "ui/gfx/text_constants.h"
#include "ui/views/animation/animation_builder.h"
#include "ui/views/border.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/scroll_view.h"
#include "ui/views/controls/separator.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/focus/focus_manager.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/widget/widget.h"
using views::BoxLayout;
namespace ash {
namespace {
constexpr int kContinueColumnCount = 2;
// Insets for the vertical scroll bar.
constexpr gfx::Insets kVerticalScrollInsets(1, 0, 1, 1);
// The padding between different sections within the apps page. Also used for
// interior apps page container margin.
constexpr int kVerticalPaddingBetweenSections = 16;
// The horizontal interior margin for the apps page container - i.e. the margin
// between the apps page bounds and the page content.
constexpr int kHorizontalInteriorMargin = 20;
// Insets for the separator between the continue section and apps.
constexpr gfx::Insets kSeparatorInsets(0, 12);
} // namespace
AppListBubbleAppsPage::AppListBubbleAppsPage(
AppListViewDelegate* view_delegate,
ApplicationDragAndDropHost* drag_and_drop_host,
AppListConfig* app_list_config,
AppListA11yAnnouncer* a11y_announcer,
AppListFolderController* folder_controller) {
DCHECK(view_delegate);
DCHECK(drag_and_drop_host);
DCHECK(a11y_announcer);
DCHECK(folder_controller);
AppListModelProvider::Get()->AddObserver(this);
SetUseDefaultFillLayout(true);
// The entire page scrolls.
scroll_view_ = AddChildView(std::make_unique<views::ScrollView>(
views::ScrollView::ScrollWithLayers::kEnabled));
scroll_view_->ClipHeightTo(0, std::numeric_limits<int>::max());
scroll_view_->SetDrawOverflowIndicator(false);
// Don't paint a background. The bubble already has one.
scroll_view_->SetBackgroundColor(absl::nullopt);
// Arrow keys are used to select app icons.
scroll_view_->SetAllowKeyboardScrolling(false);
// Scroll view will have a gradient mask layer.
scroll_view_->SetPaintToLayer(ui::LAYER_NOT_DRAWN);
// When animations are enabled the gradient helper is created in the animation
// end callback.
if (!features::IsProductivityLauncherAnimationEnabled()) {
gradient_helper_ = std::make_unique<ScrollViewGradientHelper>(scroll_view_);
// Layout() updates the gradient zone, since the gradient helper needs to
// know the bounds of the scroll view and contents view.
}
// Set up scroll bars.
scroll_view_->SetHorizontalScrollBarMode(
views::ScrollView::ScrollBarMode::kDisabled);
auto vertical_scroll =
std::make_unique<RoundedScrollBar>(/*horizontal=*/false);
vertical_scroll->SetInsets(kVerticalScrollInsets);
scroll_view_->SetVerticalScrollBar(std::move(vertical_scroll));
auto scroll_contents = std::make_unique<views::View>();
auto* layout = scroll_contents->SetLayoutManager(std::make_unique<BoxLayout>(
BoxLayout::Orientation::kVertical,
gfx::Insets(kVerticalPaddingBetweenSections, kHorizontalInteriorMargin),
kVerticalPaddingBetweenSections));
layout->set_cross_axis_alignment(BoxLayout::CrossAxisAlignment::kStretch);
// Continue section row.
continue_section_ =
scroll_contents->AddChildView(std::make_unique<ContinueSectionView>(
view_delegate, kContinueColumnCount, /*tablet_mode=*/false));
// Observe changes in continue section visibility, to keep separator
// visibility in sync.
continue_section_->AddObserver(this);
// Recent apps row.
SearchModel* const search_model = AppListModelProvider::Get()->search_model();
AppListModel* const model = AppListModelProvider::Get()->model();
recent_apps_ = scroll_contents->AddChildView(
std::make_unique<RecentAppsView>(this, view_delegate));
recent_apps_->UpdateAppListConfig(app_list_config);
recent_apps_->ShowResults(search_model, model);
// Observe changes in continue section visibility, to keep separator
// visibility in sync.
recent_apps_->AddObserver(this);
// Horizontal separator.
separator_ =
scroll_contents->AddChildView(std::make_unique<views::Separator>());
separator_->SetBorder(views::CreateEmptyBorder(kSeparatorInsets));
separator_->SetColor(ColorProvider::Get()->GetContentLayerColor(
ColorProvider::ContentLayerType::kSeparatorColor));
// Add a empty container view. A toast view should be added to
// `reorder_undo_container_` when the app list starts temporary sorting.
if (features::IsLauncherAppSortEnabled()) {
reorder_undo_container_ = scroll_contents->AddChildView(
std::make_unique<AppListReorderUndoContainerView>());
}
// All apps section.
scrollable_apps_grid_view_ =
scroll_contents->AddChildView(std::make_unique<ScrollableAppsGridView>(
a11y_announcer, view_delegate,
/*folder_delegate=*/nullptr, scroll_view_, folder_controller,
/*focus_delegate=*/this));
scrollable_apps_grid_view_->SetDragAndDropHostOfCurrentAppList(
drag_and_drop_host);
scrollable_apps_grid_view_->Init();
scrollable_apps_grid_view_->UpdateAppListConfig(app_list_config);
scrollable_apps_grid_view_->SetMaxColumns(5);
scrollable_apps_grid_view_->SetModel(model);
scrollable_apps_grid_view_->SetItemList(model->top_level_item_list());
scrollable_apps_grid_view_->ResetForShowApps();
// Ensure the grid fills the remaining space in the bubble so that icons can
// be dropped beneath the last row.
layout->SetFlexForView(scrollable_apps_grid_view_, 1);
scroll_view_->SetContents(std::move(scroll_contents));
continue_section_->UpdateSuggestionTasks();
UpdateSeparatorVisibility();
}
AppListBubbleAppsPage::~AppListBubbleAppsPage() {
AppListModelProvider::Get()->RemoveObserver(this);
continue_section_->RemoveObserver(this);
recent_apps_->RemoveObserver(this);
}
void AppListBubbleAppsPage::StartShowAnimation() {
// The animation relies on the correct positions of views, so force layout.
if (needs_layout())
Layout();
DCHECK(!needs_layout());
// This part of the animation has a longer duration than the bubble part
// handled in AppListBubbleView, so track overall smoothness here.
ui::AnimationThroughputReporter reporter(
scrollable_apps_grid_view_->layer()->GetAnimator(),
metrics_util::ForSmoothness(base::BindRepeating([](int value) {
base::UmaHistogramPercentage(
"Apps.ClamshellLauncher.AnimationSmoothness.OpenAppsPage", value);
})));
// Animate the views. Each section is initially offset down, then slides up
// into its final position. If a section isn't visible, skip it. The further
// down the section, the greater its initial offset. This code uses multiple
// animations because views::AnimationBuilder doesn't have a good way to
// build a single animation with conditional parts. https://crbug.com/1266020
constexpr int kSectionOffset = 20;
int vertical_offset = 0;
if (continue_section_->GetTasksSuggestionsCount() > 0) {
vertical_offset += kSectionOffset;
SlideViewIntoPosition(continue_section_, vertical_offset);
}
if (recent_apps_->GetItemViewCount() > 0) {
vertical_offset += kSectionOffset;
SlideViewIntoPosition(recent_apps_, vertical_offset);
}
if (separator_->GetVisible()) {
// The separator is not offset; it animates next to the view above it.
SlideViewIntoPosition(separator_, vertical_offset);
}
// The apps grid is always visible.
vertical_offset += kSectionOffset;
// Use a special cleanup callback to show the gradient mask at the end of the
// animation. No need to use SlideViewIntoPosition() because this view always
// has a layer.
StartSlideInAnimation(
scrollable_apps_grid_view_, vertical_offset,
base::BindRepeating(&AppListBubbleAppsPage::OnAppsGridViewAnimationEnded,
weak_factory_.GetWeakPtr()));
}
void AppListBubbleAppsPage::SlideViewIntoPosition(views::View* view,
int vertical_offset) {
// Abort any in-progress layer animation. Views might have temporary layers
// during animations that are cleaned up at the end. The code below needs to
// know the final desired layer state.
if (view->layer()) {
DCHECK(view->layer()->GetAnimator());
view->layer()->GetAnimator()->AbortAllAnimations();
}
// Add a layer for the view if it doesn't have one at baseline.
const bool create_layer = !view->layer();
if (create_layer) {
view->SetPaintToLayer();
view->layer()->SetFillsBoundsOpaquely(false);
}
// If we created a layer for the view, undo that when the animation ends.
// The underlying views don't expose weak pointers directly, so use a weak
// pointer to this view, which owns its children.
auto cleanup = create_layer ? base::BindRepeating(
&AppListBubbleAppsPage::DestroyLayerForView,
weak_factory_.GetWeakPtr(), view)
: base::DoNothing();
StartSlideInAnimation(view, vertical_offset, cleanup);
}
void AppListBubbleAppsPage::StartSlideInAnimation(
views::View* view,
int vertical_offset,
base::RepeatingClosure cleanup) {
DCHECK(view->layer());
// Animation spec:
//
// Y Position: Down (offset) → End position
// Duration: 250ms
// Ease: (0.00, 0.00, 0.20, 1.00)
// Set the initial offset via a layer transform.
gfx::Transform translate_down;
translate_down.Translate(0, vertical_offset);
view->layer()->SetTransform(translate_down);
// Animate the transform back to the identity transform.
constexpr gfx::Transform kIdentity;
views::AnimationBuilder()
.OnEnded(cleanup)
.OnAborted(cleanup)
.Once()
.SetDuration(base::Milliseconds(250))
.SetTransform(view, kIdentity, gfx::Tween::LINEAR_OUT_SLOW_IN);
}
void AppListBubbleAppsPage::StartHideAnimation() {
// Remove the gradient mask from the scroll view to improve performance.
gradient_helper_.reset();
}
void AppListBubbleAppsPage::AbortAllAnimations() {
auto abort_animations = [](views::View* view) {
if (view->layer())
view->layer()->GetAnimator()->AbortAllAnimations();
};
abort_animations(continue_section_);
abort_animations(recent_apps_);
abort_animations(separator_);
abort_animations(scrollable_apps_grid_view_);
}
void AppListBubbleAppsPage::DisableFocusForShowingActiveFolder(bool disabled) {
continue_section_->DisableFocusForShowingActiveFolder(disabled);
recent_apps_->DisableFocusForShowingActiveFolder(disabled);
scrollable_apps_grid_view_->DisableFocusForShowingActiveFolder(disabled);
}
void AppListBubbleAppsPage::OnTemporarySortOrderChanged(
const absl::optional<AppListSortOrder>& new_order) {
DCHECK(features::IsLauncherAppSortEnabled());
reorder_undo_container_->OnTemporarySortOrderChanged(new_order);
}
void AppListBubbleAppsPage::Layout() {
views::View::Layout();
if (gradient_helper_)
gradient_helper_->UpdateGradientZone();
}
void AppListBubbleAppsPage::OnActiveAppListModelsChanged(
AppListModel* model,
SearchModel* search_model) {
scrollable_apps_grid_view_->SetModel(model);
scrollable_apps_grid_view_->SetItemList(model->top_level_item_list());
recent_apps_->ShowResults(search_model, model);
}
void AppListBubbleAppsPage::OnViewVisibilityChanged(
views::View* observed_view,
views::View* starting_view) {
if (starting_view == continue_section_ || starting_view == recent_apps_)
UpdateSeparatorVisibility();
}
void AppListBubbleAppsPage::MoveFocusUpFromRecents() {
DCHECK_GT(recent_apps_->GetItemViewCount(), 0);
AppListItemView* first_recent = recent_apps_->GetItemViewAt(0);
// Find the view one step in reverse from the first recent app.
views::View* previous_view = GetFocusManager()->GetNextFocusableView(
first_recent, GetWidget(), /*reverse=*/true, /*dont_loop=*/false);
DCHECK(previous_view);
previous_view->RequestFocus();
}
void AppListBubbleAppsPage::MoveFocusDownFromRecents(int column) {
int top_level_item_count =
scrollable_apps_grid_view_->view_model()->view_size();
if (top_level_item_count <= 0)
return;
// Attempt to focus the item at `column` in the first row, or the last item if
// there aren't enough items. This could happen if the user's apps are in a
// small number of folders.
int index = std::min(column, top_level_item_count - 1);
AppListItemView* item = scrollable_apps_grid_view_->GetItemViewAt(index);
DCHECK(item);
item->RequestFocus();
}
bool AppListBubbleAppsPage::MoveFocusUpFromAppsGrid(int column) {
DVLOG(1) << __FUNCTION__;
const int recent_app_count = recent_apps_->GetItemViewCount();
// If there aren't any recent apps, don't change focus here. Fall back to the
// app grid's default behavior.
if (!recent_apps_->GetVisible() || recent_app_count <= 0)
return false;
// Attempt to focus the item at `column`, or the last item if there aren't
// enough items.
int index = std::min(column, recent_app_count - 1);
AppListItemView* item = recent_apps_->GetItemViewAt(index);
DCHECK(item);
item->RequestFocus();
return true;
}
void AppListBubbleAppsPage::UpdateSeparatorVisibility() {
separator_->SetVisible(recent_apps_->GetItemViewCount() > 0 ||
continue_section_->GetTasksSuggestionsCount() > 0);
}
void AppListBubbleAppsPage::DestroyLayerForView(views::View* view) {
// This function is not static so it can be bound with a weak pointer.
view->DestroyLayer();
}
void AppListBubbleAppsPage::OnAppsGridViewAnimationEnded() {
// If the window is destroyed during an animation the animation will end, but
// there's no need to build the gradient mask layer.
if (GetWidget()->GetNativeWindow()->is_destroying())
return;
// Set up fade in/fade out gradients at top/bottom of scroll view. Wait until
// the end of the show animation because the animation performs better without
// the gradient mask layer.
gradient_helper_ = std::make_unique<ScrollViewGradientHelper>(scroll_view_);
gradient_helper_->UpdateGradientZone();
}
BEGIN_METADATA(AppListBubbleAppsPage, views::View)
END_METADATA
} // namespace ash
| 38.920398 | 80 | 0.750671 | [
"model",
"transform"
] |
7a87dc5c7aace421e36d70943c3784608329ac77 | 532 | cpp | C++ | test/rpc/client.cpp | zgtz/CppNet | 86cceb77bfd3a9b0c0efb38108477aaf477ec058 | [
"BSD-3-Clause"
] | 676 | 2018-07-06T04:31:11.000Z | 2022-03-29T22:05:55.000Z | test/rpc/client.cpp | JiaquanLi/CppNet | 86cceb77bfd3a9b0c0efb38108477aaf477ec058 | [
"BSD-3-Clause"
] | 16 | 2019-06-19T07:20:14.000Z | 2022-01-09T10:41:50.000Z | test/rpc/client.cpp | JiaquanLi/CppNet | 86cceb77bfd3a9b0c0efb38108477aaf477ec058 | [
"BSD-3-Clause"
] | 196 | 2019-08-27T20:01:26.000Z | 2022-03-27T13:15:16.000Z | #include <iostream>
#include "rpc_client.h"
#include "common/util/any.h"
#include "common/util/time.h"
using namespace std;
void Add1CallBack(int code, std::vector<cppnet::Any>& ret) {
if (code == NO_ERROR) {
cout << code << " " << cppnet::any_cast<int>(ret[0]) << endl;
}
}
Call_back func = Add1CallBack;
int main() {
RPCClient client;
client.SetCallBack("Add1", func);
client.Start(8951, "127.0.0.1");
for (;;) {
cppnet::Sleep(1000);
client.CallFunc("Add1", 100, 200);
}
}
| 21.28 | 70 | 0.599624 | [
"vector"
] |
7a8bbb065d727100b54553c6b29802ceef5b7fb0 | 10,737 | cpp | C++ | src/letterboxedsolver.cpp | jeremyephron/letter-boxed-solver | c7d799ca69e8109baf2075e24c82a22b300d6f1c | [
"MIT"
] | null | null | null | src/letterboxedsolver.cpp | jeremyephron/letter-boxed-solver | c7d799ca69e8109baf2075e24c82a22b300d6f1c | [
"MIT"
] | null | null | null | src/letterboxedsolver.cpp | jeremyephron/letter-boxed-solver | c7d799ca69e8109baf2075e24c82a22b300d6f1c | [
"MIT"
] | null | null | null | /*
* File: letterboxedsolver.cpp
* Author: Jeremy Ephron
* ---------------------------
* This is a program to solve the NY Times online puzzle Letter Boxed
* (https://www.nytimes.com/puzzles/letter-boxed).
*
* The NY Times says they use the Oxford English Dictionary, for which I could
* not find a text file with all recognized words. As such I am using a
* Scrabble dictionary text file from
* https://raw.githubusercontent.com/jonbcard/scrabble-bot/master/src/dictionary.txt
*
* This means that not all solutions generated will necessarily be recognized
* as valid, but there certainly will be some valid solutions.
*
* You can modify the dictionary used by editing "dictionary.txt" in the res
* folder, or adding a dictionary of your own and specifying the dictionary
* you would like to use.
*
* This is a multithreaded implementation, where starting from each letter is
* handled by it's own thread.
*
* !!! Important: each letter can only appear *once* in a letter box puzzle
* (this is an assumption this program relies on).
*/
#include <fstream>
#include <thread>
#include "letterbox.h"
#include "word.h"
using WordTable = std::unordered_map<char, std::unordered_set<Word> >;
using Solution = std::vector<std::string>;
static const std::string DEFAULT_DICT = "dictionary.txt";
/* For resetting the input stream */
static inline void reset(std::istream& in) {
in.clear();
in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
/**
* Function: getDictionaryNameFromUser
* -----------------------------------
* Gets a valid dictionary filename from the user.
*
* Uses the default dictionary filename if user input is empty, and reprompts
* if file does not exist.
*
* @returns the filename of the chosen dictionary.
*/
std::string getDictionaryNameFromUser();
/**
* Function: getLettersFromUser
* ----------------------------
* Gets the letters constituting the letter box from the user.
*
* @returns the string of letters representing the letter box.
*/
std::string getLettersFromUser();
/**
* Function: getNumWordsFromUser
* -----------------------------
* Gets the number of words the user wants in a solution.
*
* @param letterBox the LetterBox puzzle object.
* @returns the number of words in a solution.
*/
unsigned int getNumWordsFromUser(const LetterBox &letterBox);
/**
* Function: buildFilteredWordList
* -------------------------------
* Filters words from a dictionary and populates a table with words grouped by
* starting character.
*
* @param dictFilename the filename of the dictionary to use.
* @param letterBox the LetterBox puzzle object.
* @param wordsStartingWith the map from starting character to set of words.
*/
void buildFilteredWordList(const std::string &dictFilename,
const LetterBox &letterBox,
WordTable &wordsStartingWith);
/**
* Function: generateSolutions
* ---------------------------
* Wrapper function to generate all solutions of a fixed number of words.
*
* @param letterBox the LetterBox puzzle object.
* @param nWords the number of words per solution.
* @param wordsStartingWith the map from starting characters to sets of words.
* @param solutions a vector of solutions to be populated.
*/
void generateSolutions(const LetterBox &letterBox, unsigned int nWords,
const WordTable &wordsStartingWith,
std::vector<Solution>& solutions);
/**
* Function: generateSolutionsRec
* ------------------------------
* Generates solutions to a letterBox puzzle with a given number of words
* remaining, a given last character typed, a given set of characters
* remaining, and a given list of already chosen words.
*
* @param letterBox the LetterBox puzzle object.
* @param nWords the number of words left in a possible solution.
* @param last the last character typed that our next word must start with.
* @param remaining the set of characters we haven't used yet.
* @param result the solution being built up.
* @param solutions the vector of all solutions found so far.
* @param solutionsLock a lock acquired before adding to solutions.
* @param wordsStartingWith the map from starting characters to sets of words.
*/
void generateSolutionsRec(const LetterBox &letterBox,
unsigned int nWords,
char last,
std::unordered_set<char> &remaining,
Solution &result,
std::vector<Solution> &solutions,
std::mutex &solutionsLock,
const WordTable &wordsStartingWith);
/**
* Function: writeSolutionsToFile
* ------------------------------
* Writes solutions to a file, specified by the user.
*
* @param filename the name of the output file.
* @param solutions the solutions to the LetterBox puzzle.
*/
void writeSolutionsToFile(const std::string &filename,
const std::vector<Solution> &solutions);
/**
* Function: fileExists
* --------------------
* Checks whether a given file exists.
*
* @param filename the name of the file to check.
* @returns true if the file exists, false otherwise.
*/
bool fileExists(const std::string &filename);
int main() {
std::string dictionaryFilename = getDictionaryNameFromUser();
std::string letters = getLettersFromUser();
LetterBox letterBox(letters);
WordTable wordsStartingWith;
buildFilteredWordList(dictionaryFilename, letterBox, wordsStartingWith);
unsigned int nWords = getNumWordsFromUser(letterBox);
std::cout << "Please be patient, finding all solutions can take a few "
"minutes for n > 2."
<< std::endl;
std::vector<Solution> solutions;
generateSolutions(letterBox, nWords, wordsStartingWith, solutions);
std::cout << solutions.size() << " solution(s) found! Would you like to "
"save them to a file? (y/n): ";
std::string line;
getline(std::cin, line);
if (!line.empty() && tolower(line[0]) == 'y') {
std::cout << "Enter the output filename: ";
getline(std::cin, line);
writeSolutionsToFile(line, solutions);
} else {
std::cout << "Alright, goodbye!" << std::endl;
}
std::cout << "Have a nice day!" << std::endl;
return 0;
}
std::string getDictionaryNameFromUser() {
std::cout << "Enter the filename of the dictionary you want to use "
"(hit enter for \"dictionary.txt\"): ";
std::string dictionaryFilename;
std::getline(std::cin, dictionaryFilename);
while (dictionaryFilename != "" && !fileExists(dictionaryFilename)) {
std::cout << "File \"" << dictionaryFilename << "\" does not exist. "
"Please try again: ";
std::getline(std::cin, dictionaryFilename);
}
return dictionaryFilename != "" ? dictionaryFilename : DEFAULT_DICT;
}
std::string getLettersFromUser() {
std::cout << "Enter each letter such that entire walls "
"are typed in consecutively: ";
std::string input;
std::getline(std::cin, input);
while (input.length() % LetterBox::kNumWalls != 0) {
std::cout << "Please enter a multiple of " << LetterBox::kNumWalls
<< " letters:";
std::getline(std::cin, input);
}
for (size_t i = 0; i < input.length(); i++) {
input[i] = toupper(input[i]);
}
return input;
}
unsigned int getNumWordsFromUser(const LetterBox &letterBox) {
unsigned int minWords = 1;
unsigned int maxWords = letterBox.numLetters() / LetterBox::kMinWordLength;
std::cout << "Please enter the number of words you want in your solution: ";
int n;
std::cin >> n;
while (n < minWords || n > maxWords) {
reset(std::cin);
std::cout << "Please enter a number between " << minWords << " and "
<< maxWords << ": ";
std::cin >> n;
}
reset(std::cin);
return n;
}
void generateSolutions(const LetterBox &letterBox, unsigned int nWords,
const WordTable &wordsStartingWith,
std::vector<Solution>& solutions) {
std::mutex solutionsLock;
std::vector<std::thread> threads;
for (char ch : letterBox.getLetters()) {
threads.push_back(std::thread([&](char ch) {
std::unordered_set<char> remaining = letterBox.getLetters();
Solution result(nWords);
generateSolutionsRec(letterBox, nWords, ch, remaining, result,
solutions, solutionsLock, wordsStartingWith);
}, ch));
}
for (std::thread& t : threads) t.join();
}
void generateSolutionsRec(const LetterBox &letterBox,
unsigned int nWords,
char last,
std::unordered_set<char> &remaining,
Solution &result,
std::vector<Solution> &solutions,
std::mutex &solutionsLock,
const WordTable &wordsStartingWith) {
if (nWords == 0) {
if (remaining.empty()) {
std::lock_guard<std::mutex> lg(solutionsLock);
solutions.push_back(result);
}
return;
}
if (wordsStartingWith.count(last) == 0) return;
for (const auto& word : wordsStartingWith.at(last)) {
if (nWords == 1 && remaining.size() > word.nUniqueLetters) continue;
auto remainingCopy = remaining;
for (char ch : word.content) remainingCopy.erase(ch);
result[result.size() - nWords] = word.content;
generateSolutionsRec(letterBox, nWords - 1, word[word.size() - 1],
remainingCopy, result, solutions,
solutionsLock, wordsStartingWith);
}
}
void buildFilteredWordList(const std::string &dictFilename,
const LetterBox &letterBox,
std::unordered_map<char, std::unordered_set<Word> > &wordsStartingWith) {
std::ifstream file(dictFilename);
std::string word;
while (getline(file, word)) {
if (!letterBox.canMakeWord(word)) continue;
wordsStartingWith[word[0]].insert(Word(word));
}
}
void writeSolutionsToFile(const std::string &filename,
const std::vector<Solution> &solutions) {
std::ofstream out(filename);
for (const auto &solution : solutions) {
for (const auto &word : solution) {
out << word << " ";
}
out << std::endl;
}
}
bool fileExists(const std::string &filename) {
return bool(std::ifstream(filename));
}
| 34.194268 | 84 | 0.621868 | [
"object",
"vector"
] |
7a9b36bfb76acbbeecea3962d393a77f1c1f9ba3 | 6,232 | cpp | C++ | src/texture_frame_buffer.cpp | sweetkristas/anura | 5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd | [
"CC0-1.0"
] | null | null | null | src/texture_frame_buffer.cpp | sweetkristas/anura | 5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd | [
"CC0-1.0"
] | null | null | null | src/texture_frame_buffer.cpp | sweetkristas/anura | 5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd | [
"CC0-1.0"
] | null | null | null | /*
Copyright (C) 2003-2013 by David White <davewx7@gmail.com>
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/>.
*/
#include "graphics.hpp"
#include "asserts.hpp"
#include "preferences.hpp"
#include "texture.hpp"
#include "texture_frame_buffer.hpp"
#if defined(__ANDROID__)
#if defined(USE_SHADERS)
#include <GLES2/gl2ext.h>
#else
#include <GLES/glext.h>
#endif
#endif
#if defined(TARGET_OS_HARMATTAN) || defined(TARGET_PANDORA) || defined(TARGET_TEGRA) || defined(TARGET_BLACKBERRY)
#include <EGL/egl.h>
#define glGenFramebuffersOES preferences::glGenFramebuffersOES
#define glBindFramebufferOES preferences::glBindFramebufferOES
#define glFramebufferTexture2DOES preferences::glFramebufferTexture2DOES
#define glCheckFramebufferStatusOES preferences::glCheckFramebufferStatusOES
#endif
//define macros that make it easy to make the OpenGL calls in this file.
#if defined(USE_SHADERS)
#define EXT_CALL(call) call
#define EXT_MACRO(macro) macro
#elif defined(TARGET_OS_HARMATTAN) || TARGET_OS_IPHONE || defined(TARGET_PANDORA) || defined(TARGET_TEGRA) || defined(TARGET_BLACKBERRY) || defined(__ANDROID__)
#define EXT_CALL(call) call##OES
#define EXT_MACRO(macro) macro##_OES
#elif defined(__APPLE__)
#define EXT_CALL(call) call##EXT
#define EXT_MACRO(macro) macro##_EXT
#else
#define EXT_CALL(call) call##EXT
#define EXT_MACRO(macro) macro##_EXT
#endif
namespace texture_frame_buffer {
namespace {
bool supported = false;
GLuint texture_id = 0, texture_id_back = 0; //ID of the texture which the frame buffer is stored in
GLuint framebuffer_id = 0, framebuffer_id_back = 0; //framebuffer object
GLint video_framebuffer_id = 0; //the original frame buffer object
int frame_buffer_texture_width = 128;
int frame_buffer_texture_height = 128;
void init_internal(int buffer_width, int buffer_height)
{
// Clear any old errors.
glGetError();
frame_buffer_texture_width = buffer_width;
frame_buffer_texture_height = buffer_height;
#if defined(__native_client__)
{
supported = false;
LOG("FRAME BUFFER OBJECT NOT SUPPORTED");
return;
}
#endif
#if defined(TARGET_OS_HARMATTAN) || defined(TARGET_PANDORA) || defined(TARGET_TEGRA) || defined(TARGET_BLACKBERRY)
if (glGenFramebuffersOES != NULL &&
glBindFramebufferOES != NULL &&
glFramebufferTexture2DOES != NULL &&
glCheckFramebufferStatusOES != NULL)
{
supported = true;
}
else
{
fprintf(stderr, "FRAME BUFFER OBJECT NOT SUPPORTED\n");
supported = false;
return;
}
#endif
#if defined(__GLEW_H__)
if(!GLEW_EXT_framebuffer_object)
{
fprintf(stderr, "FRAME BUFFER OBJECT NOT SUPPORTED\n");
supported = false;
return;
}
#endif
fprintf(stderr, "FRAME BUFFER OBJECT IS SUPPORTED\n");
supported = true;
#ifndef TARGET_TEGRA
glGetIntegerv(EXT_MACRO(GL_FRAMEBUFFER_BINDING), &video_framebuffer_id);
#endif
// Clear any current errors.
GLenum err = glGetError();
glGenTextures(1, &texture_id);
glBindTexture(GL_TEXTURE_2D, texture_id);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width(), height(), 0,
GL_RGBA, GL_UNSIGNED_BYTE, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
// create a framebuffer object
EXT_CALL(glGenFramebuffers)(1, &framebuffer_id);
EXT_CALL(glBindFramebuffer)(EXT_MACRO(GL_FRAMEBUFFER), framebuffer_id);
// attach the texture to FBO color attachment point
EXT_CALL(glFramebufferTexture2D)(EXT_MACRO(GL_FRAMEBUFFER), EXT_MACRO(GL_COLOR_ATTACHMENT0),
GL_TEXTURE_2D, texture_id, 0);
// check FBO status
GLenum status = EXT_CALL(glCheckFramebufferStatus)(EXT_MACRO(GL_FRAMEBUFFER));
if(status == EXT_MACRO(GL_FRAMEBUFFER_UNSUPPORTED)) {
std::cerr << "FRAME BUFFER OBJECT NOT SUPPORTED\n";
supported = false;
err = glGetError();
} else {
ASSERT_EQ(status, EXT_MACRO(GL_FRAMEBUFFER_COMPLETE));
}
// switch back to window-system-provided framebuffer
EXT_CALL(glBindFramebuffer)(EXT_MACRO(GL_FRAMEBUFFER), video_framebuffer_id);
err = glGetError();
ASSERT_EQ(err, GL_NO_ERROR);
}
}
void init(int buffer_width, int buffer_height)
{
init_internal(buffer_width, buffer_height);
switch_texture();
init_internal(buffer_width, buffer_height);
}
void set_framebuffer_id(int framebuffer)
{
video_framebuffer_id = framebuffer;
}
void switch_texture()
{
std::swap(texture_id, texture_id_back);
std::swap(framebuffer_id, framebuffer_id_back);
}
int width() { return frame_buffer_texture_width; }
int height() { return frame_buffer_texture_height; }
bool unsupported()
{
return !supported;
}
void set_render_to_texture()
{
EXT_CALL(glBindFramebuffer)(EXT_MACRO(GL_FRAMEBUFFER), framebuffer_id);
glViewport(0, 0, width(), height());
}
void set_render_to_screen()
{
EXT_CALL(glBindFramebuffer)(EXT_MACRO(GL_FRAMEBUFFER), video_framebuffer_id);
glViewport(0, 0, preferences::actual_screen_width(), preferences::actual_screen_height());
}
render_scope::render_scope()
{
set_render_to_texture();
}
render_scope::~render_scope()
{
set_render_to_screen();
}
void set_as_current_texture()
{
graphics::texture::set_current_texture(texture_id);
}
int current_texture_id()
{
return texture_id;
}
void rebuild()
{
if(!supported) {
return;
}
EXT_CALL(glDeleteFramebuffers)(1, &framebuffer_id);
glDeleteTextures(1, &texture_id);
init(preferences::actual_screen_width(), preferences::actual_screen_height());
}
} // namespace texture_frame_buffer
| 28.456621 | 160 | 0.765886 | [
"object"
] |
7aa4b93387b8f918394a90508fd235f64436fd89 | 1,292 | cpp | C++ | main.cpp | priseup/any_json | b304c57968ccea8274748488d49d5f4e074245d4 | [
"MIT"
] | null | null | null | main.cpp | priseup/any_json | b304c57968ccea8274748488d49d5f4e074245d4 | [
"MIT"
] | null | null | null | main.cpp | priseup/any_json | b304c57968ccea8274748488d49d5f4e074245d4 | [
"MIT"
] | null | null | null | #include "any.h"
// #include "types.h"
void test_any()
{
int i = 0;
Any a{5};
Any g{i};
Any f{std::move(i)};
Any b(std::string{"345"});
const Any &c = a;
std::cout << a.cast<int>() << std::endl;
std::cout << c.cast<int>() << std::endl;
Any d{a};
Any e{std::move(a)};
printf("d=f\n");
d = f;
printf("d=c\n");
d = c;
printf("d=move(f)\n");
d = std::move(f);
printf("d=5.6\n");
d = 5.6;
const std::string &dd = std::string{"string"};
printf("d=dd\n");
d = dd;
std::cout << b.cast<std::string>() << std::endl;
Any v = std::vector<int>{1, 2, 3, 4};
std::cout << v.cast<std::vector<int>>().size() << std::endl;
}
int main() {
/*
Friend f1{"my best friend", Singer{"rocker", 18}};
Friend f2{"new friend", "little girl"};
Person p2{"p2", 3, Address{"china", "shanghai", "putuo"}};
Address addr1{"china", "beijing", "wangjing", {p2}};
Person p1{"p1", 4, addr1, {f1, f2}, "the kind!"};
// TODO. 以下是示例代码,需要笔试者具体实现
auto json = dump(p1) // 序列化
std::cout << json << std::endl // 打印序列化结果
std::cout << p1 << std::endl // 打印 Person 对象
auto pp = parse(json); // 反序列化
assert(p1 == pp) // 反序列化的结果是对的
*/
}
| 21.898305 | 64 | 0.48452 | [
"vector"
] |
7aa61ef394cd2d22486826e7e32498b5ef4ffd11 | 2,419 | cpp | C++ | src/main.cpp | Lesbre/csv2mdtable | a4ae31227c3db7f2b026ff8ae0be05158243e45b | [
"MIT"
] | null | null | null | src/main.cpp | Lesbre/csv2mdtable | a4ae31227c3db7f2b026ff8ae0be05158243e45b | [
"MIT"
] | null | null | null | src/main.cpp | Lesbre/csv2mdtable | a4ae31227c3db7f2b026ff8ae0be05158243e45b | [
"MIT"
] | null | null | null | /*
Small utility program to generate markdown table from csv files
Author: Dorian Lesbre
*/
#include "project.hpp"
#include <string>
#include <fstream>
#include <vector>
#include "options.hpp"
#include "io.hpp"
#include "parser.hpp"
#include "formatter.hpp"
int main(int argc, char ** argv) {
// parse command line argumants
settings prgm_settings = {
.use_padding = true,
.ext_pipes = true,
.auto_detect_sep = true,
.col_sep = '\t',
.line_sep = '\n',
.in_path = nullptr,
.out_path = nullptr,
.align = std::vector<char>(),
};
const int cmd_res = parse_cmd(argc, argv, prgm_settings);
if (cmd_res != 0) {
if (cmd_res == -1)
return 0;
return 1; // cmd_res; // bad input error code
}
// read csv input
std::string csv = read(prgm_settings.in_path);
const unsigned int align_len = prgm_settings.align.size();
const unsigned int input_len = csv.length();
if (input_len == 0) {
printf_error("empty input (check path and permissions)\n");
return 2; // invalid file error code
}
if (prgm_settings.auto_detect_sep) {
const char sep = auto_detect_separator(csv, prgm_settings.line_sep);
if (!sep)
return 3; // no suitable separator found
// invalid csv error code
prgm_settings.col_sep = sep;
}
// column sizes for padding
std::vector<unsigned int> widths;
unsigned int col_number;
if (prgm_settings.use_padding) {
widths = columns_width(csv, prgm_settings.col_sep, prgm_settings.line_sep);
#ifdef DEBUG
printf_debug("Column widths\n ");
for (unsigned int i = 0; i < widths.size(); ++i)
std::cout << widths[i] << " ";
std::cout << std::endl;
#endif
// minimum width is three dashes or 5 if align specified
for (unsigned int i = 0; i < widths.size(); ++i) {
if (i < align_len && prgm_settings.align[i] != '_') {
widths[i] = max(widths[i], 5);
}
else {
widths[i] = max(widths[i], 3);
}
}
col_number = widths.size();
} else
col_number = table_width(csv, prgm_settings.col_sep, prgm_settings.line_sep);
while (prgm_settings.align.size() < col_number) {
prgm_settings.align.push_back('_');
}
const std::string output = format(csv, prgm_settings, widths, col_number);
if (write(prgm_settings.out_path, output)) {
printf_error("failed to write to '%s'. Check file path and permissions", prgm_settings.out_path);
return 4; // write failed
}
return 0;
} | 26.010753 | 99 | 0.660604 | [
"vector"
] |
7aa931cff0d1cfdf23b5ce9734cf81e34653d879 | 59,449 | cpp | C++ | FFxtubes onset.cpp | WarwickDumas/FocusFusion2D | 445903f3e9e447985cdfa40444787c108d834e48 | [
"MIT"
] | 1 | 2021-06-21T22:21:57.000Z | 2021-06-21T22:21:57.000Z | FFxtubes onset.cpp | WarwickDumas/FocusFusion2D | 445903f3e9e447985cdfa40444787c108d834e48 | [
"MIT"
] | 2 | 2017-07-16T01:41:11.000Z | 2021-07-05T08:40:01.000Z | FFxtubes onset.cpp | WarwickDumas/FocusFusion2D | 445903f3e9e447985cdfa40444787c108d834e48 | [
"MIT"
] | 1 | 2017-07-16T01:26:51.000Z | 2017-07-16T01:26:51.000Z |
// DropJxy.cpp, qd cpp files, avi_utils.cpp
// meshutil.cpp, mesh.cpp, basics.cpp, surfacegraph_tri.cpp, vector_tensor.cpp
// simulation.cpp, solver.cpp, vetted.cpp, accelerate.cpp, advance.cpp
#include "headers.h"
// #include some cpp files, which should appear here only :
#include "qd/src/fpu.cpp"
#include "qd/src/dd_const.cpp"
#include "qd/src/dd_real.cpp"
#include "qd/src/bits.cpp"
#include "qd/src/c_dd.cpp"
#include "qd/src/util.cpp"
#include "avi_utils.cpp" // for making .avi
#include "cppconst.h"
// Global variables:
// =================
float xzscale;
bool bCullNone = false;
bool bGlobalsave = false;
int GlobalSwitchBox = 0;
int iGlobalScratch;
real GlobalHeightScale;
int GlobalSpeciesToGraph = 1;
int GlobalWhichLabels = 0;
bool GlobalRenderLabels = false;
int GlobalColoursPlanView = 0;
bool GlobalBothSystemsInUse;
bool GlobalCutaway = true;
unsigned int cw; // control word for floating point hardware exception hiding
// Simulation globals :
TriMesh * pX, * pXnew;
TriMesh X1, X2;
long steps_remaining, GlobalStepsCounter;
real evaltime, h;
extern real GlobalIzElasticity;
FILE * massfile,* maxfile;
// Global Variables:
HINSTANCE hInst; // current instance
// window vars:
HWND hWnd;
WNDCLASSEX wcex;
TCHAR szTitle[1024]; // The title bar text
TCHAR szWindowClass[1024]; // the main window class name
char Functionalfilename[1024];
int GlobalGraphSetting[5];
surfacegraph Graph[5]; // why was it 5? // 5th one can be whole thing.
float Historic_max[100][HISTORY]; // if max is falling, use historic maximum for graph.
float Historic_min[100][HISTORY];
int Historic_powermax[200];
int Historic_powermin[200]; // just store previous value only.
bool boolGlobalHistory, GlobalboolDisplayMeshWireframe;
D3DXVECTOR3 GlobalEye,GlobalLookat,GlobalPlanEye,GlobalPlanEye2,GlobalPlanLookat,
GlobalPlanLookat2, GlobalEye2,GlobalLookat2;
// avi file -oriented variables
int const NUMAVI = 1;
HAVI hAvi[NUMAVI];
int const GraphFlags[8] = {SPECIES_NEUTRAL,SPECIES_ION,SPECIES_ELEC,TOTAL,
JZAZBXYEZ, JXYAXYBZEXY, EXY_RHO_PHI_JXY, SIGMA_E_J};
char szAvi[9][128] = {"Plan","Neut","Ion","Elec","Total",
"JzAzBxyEz","JxyAxyBzExy","ExyRhoPhiJxy","SigmaEJ"};
AVICOMPRESSOPTIONS opts;
int counter;
HBITMAP surfbit, dib;
HDC surfdc, dibdc;
LPVOID lpvBits;
BITMAPINFO bitmapinfo;
IDirect3DSurface9* p_backbuffer_surface;
Systdata Systdata_host;
//=======================================================
// Declarations of functions included in this source file
void RefreshGraphs(const TriMesh & X, const int iGraphsFlag);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK SetupBox(HWND, UINT, WPARAM, LPARAM);
void TriMesh::CalculateTotalGraphingData()
{
long iVertex;
Vertex * pVertex = X;
for (iVertex = 0; iVertex < numVertices; iVertex++)
{
if ((pVertex->flags == DOMAIN_VERTEX) || (pVertex->flags == OUTERMOST))
{
pVertex->n = (pVertex->Neut.mass + pVertex->Ion.mass)/pVertex->AreaCell;
pVertex->v = (m_n*pVertex->Neut.mom + m_ion*pVertex->Ion.mom + m_e*pVertex->Elec.mom)/
(m_n*pVertex->Neut.mass+m_ion*pVertex->Ion.mass+m_e*pVertex->Elec.mass);
pVertex->T = (pVertex->Neut.heat + pVertex->Ion.heat + pVertex->Elec.heat)/
(pVertex->Neut.mass + pVertex->Ion.mass + pVertex->Elec.mass);
pVertex->Temp.x = pVertex->Ion.mass/(pVertex->Neut.mass + pVertex->Ion.mass);
};
++pVertex;
}
}
void TriMesh::Setup_J()
{
long iVertex;
Vertex * pVertex = X;
for (iVertex = 0; iVertex < numVertices; iVertex++)
{
if ((pVertex->flags == DOMAIN_VERTEX) || (pVertex->flags == OUTERMOST))
{
pVertex->Temp = q*(pVertex->Ion.mom-pVertex->Elec.mom)/pVertex->AreaCell;
} else {
memset(&(pVertex->Temp),0,sizeof(Vector3));
}
++pVertex;
}
}
void TriMesh::Reset_vertex_nvT(int species)
{
long iVertex;
Vertex * pVertex = X;
switch (species)
{
case SPECIES_NEUT:
for (iVertex = 0; iVertex < numVertices; iVertex++)
{
if ((pVertex->flags == DOMAIN_VERTEX) || (pVertex->flags == OUTERMOST))
{
pVertex->n = pVertex->Neut.mass/pVertex->AreaCell;
pVertex->v = pVertex->Neut.mom/pVertex->Neut.mass;
pVertex->T = pVertex->Neut.heat/pVertex->Neut.mass;
} else {
pVertex->n = 0.0;
memset(&(pVertex->v),0,sizeof(Vector3));
pVertex->T= 0.0;
};
++pVertex;
}
break;
case SPECIES_ION:
for (iVertex = 0; iVertex < numVertices; iVertex++)
{
if ((pVertex->flags == DOMAIN_VERTEX) || (pVertex->flags == OUTERMOST))
{
pVertex->n = pVertex->Ion.mass/pVertex->AreaCell;
pVertex->v = pVertex->Ion.mom/pVertex->Ion.mass;
pVertex->T = pVertex->Ion.heat/pVertex->Ion.mass;
} else {
pVertex->n = 0.0;
memset(&(pVertex->v),0,sizeof(Vector3));
pVertex->T= 0.0;
};
++pVertex;
}
break;
case SPECIES_ELEC:
for (iVertex = 0; iVertex < numVertices; iVertex++)
{
if ((pVertex->flags == DOMAIN_VERTEX) || (pVertex->flags == OUTERMOST))
{
pVertex->n = pVertex->Elec.mass/pVertex->AreaCell;
pVertex->v = pVertex->Elec.mom/pVertex->Elec.mass;
pVertex->T = pVertex->Elec.heat/pVertex->Elec.mass;
} else {
pVertex->n = 0.0;
memset(&(pVertex->v),0,sizeof(Vector3));
pVertex->T= 0.0;
};
++pVertex;
}
break;
}
}
char * report_time(int action)
{
/* action = 0: reset ; action = 1: report */
/* requires timebuffy to be defined as char[255] globally */
static char timebuffer[255];
static clock_t start;
double timenow;
long ops;
if (action == 0)
{
start = clock();
}
else
{
timenow = ((double)(clock()-start)/(double)CLOCKS_PER_SEC);
ops = (long)(clock()-start);
/* create a null-terminated string */
sprintf (timebuffer, "%6.4f sec.",timenow);
};
return &(timebuffer[0]);
};
void surfacegraph::DrawSurface(char szname[],
const int heightflag,
const real * var_ptr_0,
const int colourflag,
const real * var_ptr_c,
const bool bDisplayInner,
const int code, // graph code, to pass to called routines - sometimes useful
const TriMesh * pX // for passing to SetDataWithColour and Render
// and for working out offsets
)
{
// replaced CreateSurfaceGraphs.
// I think this is about the right balance.
char buff[256];
real * temprealptr = (real *)(pX->X);
long offset = var_ptr_0 - temprealptr;
long offset_c = var_ptr_c - temprealptr;
// Does shader always go with colour type?? yes I think.
switch(colourflag) {
case VELOCITY_COLOUR:
this->mhTech = mFX->GetTechniqueByName("VelociTech");
break;
case SEGUE_COLOUR:
this->mhTech = mFX->GetTechniqueByName("SegueTech");
break;
case CURRENT_COLOUR:
this->mhTech = mFX->GetTechniqueByName("XYZTech");
break;
case AZSEGUE_COLOUR:
mhTech = mFX->GetTechniqueByName("AzSegueTech");
break;
case IONISE_COLOUR:
mhTech = mFX->GetTechniqueByName("IoniseTech");
break;
};
// Usual settings:
//if (GlobalGraphSetting[i] != GRAPH_NONE) {
this->boolDisplayMainMesh = true;
this->boolDisplayMeshWireframe = GlobalboolDisplayMeshWireframe;
this->boolClearZBufferBeforeWireframe = false;
// Or try setting true and CULL_CCW to see if this stops it showing "the back of the wireframe"
this->SetEyeAndLookat(GlobalEye, GlobalLookat);
this->boolDisplayScales = true;
this->boolDisplayInnerMesh = bDisplayInner;
// work out whether to display key button:
if (((colourflag == FLAG_VELOCITY_COLOUR) || (colourflag == FLAG_CURRENT_COLOUR))
&& (bDisplayInner == 0))
{
this->boolDisplayKeyButton = true;
} else {
this->boolDisplayKeyButton = false;
};
//int const FLAG_COLOUR_MESH = 0;
//int const FLAG_SEGUE_COLOUR = 1;
//int const FLAG_VELOCITY_COLOUR = 2;
//int const FLAG_CURRENT_COLOUR = 3;
//int const FLAG_AZSEGUE_COLOUR = 4;
//int const FLAG_IONISE_COLOUR = 5;
this->SetDataWithColour(*pX,
colourflag, heightflag, // apparently it's that way round
offset,offset_c,
code);
if (this->bDisplayTimestamp) {
sprintf(buff, "%4.3f ns", evaltime*1.0e9);
this->Render(szname,false,pX,buff);
} else {
this->Render(szname,false,pX);
};
}
// Here we make a function that we can call to tidy up graph calling code:
void PlanViewGraphs1(TriMesh & X)// only not const because of such as Reset_vertex_nvT
{
Vertex * pVertex;
long iVertex;
X.Reset_vertex_nvT(SPECIES_ELECTRON);
D3DXVECTOR3 PlanEye(5.4f,3.2f,70.3f);
for (int i = 0; i < 4; i++)
{
Graph[i].SetEyePlan(PlanEye);
Graph[i].boolDisplayMeshWireframe = false;
Graph[i].boolClearZBufferBeforeWireframe = true;
Graph[i].boolDisplayMainMesh = true;
Graph[i].boolDisplayInnerMesh = false;
Graph[i].boolDisplayScales = false;
};
int offset_v_e = (real *)(&(X.X[0].v)) -(real *)(&(X.X[0]));
int offset_T_e = (real *)(&(X.X[0].T)) -(real *)(&(X.X[0]));
int offset_phi = (real *)(&(X.X[0].phi)) -(real *)(&(X.X[0]));
int offset_ndiff = (real *)(&(X.X[0].Temp.x)) -(real *)(&(X.X[0]));
pVertex = X.X;
for (iVertex = 0; iVertex < X.numVertices; iVertex++)
{
pVertex->Temp.x = (pVertex->Ion.mass-pVertex->Elec.mass)/pVertex->AreaCell;
++pVertex;
}
// phi:
Graph[0].mhTech = Graph[0].mFX->GetTechniqueByName("AzSegueTech");
// n_e-n_i:
Graph[2].mhTech = Graph[2].mFX->GetTechniqueByName("AzSegueTech");
// v_e:
Graph[1].mhTech = Graph[1].mFX->GetTechniqueByName("VelociTech");
// Te:
Graph[3].mhTech = Graph[3].mFX->GetTechniqueByName("SegueTech");
GlobalWhichLabels = 4; // numbers
Graph[0].SetDataWithColour(X,
FLAG_AZSEGUE_COLOUR,FLAG_FLAT_MESH,
offset_phi, offset_phi,
GRAPH_FLAT_WIRE_MESH);// colourmax is being set.
Graph[0].colourmax = 2.5;
Graph[0].Render("phi", true, &X);
GlobalWhichLabels = 5; // numbers
Graph[2].SetDataWithColour(X,
FLAG_AZSEGUE_COLOUR,FLAG_FLAT_MESH,
offset_ndiff, offset_ndiff,
GRAPH_FLAT_WIRE_MESH);
// Where to set colour scale params??
Graph[2].colourmax = 1.0e14;
Graph[2].Render("ni-ne", true, &X);
GlobalWhichLabels = 3;
Graph[1].SetDataWithColour(X,
FLAG_VELOCITY_COLOUR,FLAG_FLAT_MESH,
offset_v_e,offset_v_e,
GRAPH_FLAT_WIRE_MESH); // ?
Graph[1].colourmax = 2.5e8;
Graph[1].Render("ve",true,&X);
GlobalWhichLabels = 2;
// Labels will very shortly be upgraded.
Graph[3].SetDataWithColour(X,
FLAG_SEGUE_COLOUR,FLAG_FLAT_MESH,
offset_T_e, offset_T_e,
GRAPH_FLAT_WIRE_MESH);
//Graph[3].colourmax = 4.0e-11; // colourmax should be left == 1 for T, for whatever reason.
Graph[3].Render("Te",true,&X);
// For now use "Render" -- but create an adjunct routine for adding the
// polygon edges and other details such as velocity arrows..
// Let's see if we can get this to work before continuing.
//Graph[3].DrawSurface("[n_s T_s]/[n_s]",
// DATA_HEIGHT,(real *)(&(X.X[0].T)),
// SEGUE_COLOUR,(real *)(&(X.X[0].T)),
// false,
// GRAPH_TOTAL_T, &X);
//
// Graph 2, in case of species graphs:
//if (GlobalColoursPlanView == 0)
// nothing
//Graph[2].mhTech = Graph[2].mFX->GetTechniqueByName("MeshTech");
//Graph[2].SetDataWithColour(X,FLAG_COLOUR_MESH,FLAG_FLAT_MESH,0,0,
// GRAPH_FLAT_WIRE_MESH);
//Graph[2].Render(buff, GlobalRenderLabels, &X);
// Tell SDWC not to mess with colourmax if it's a flat mesh.
}
void RefreshGraphs(TriMesh & X, // only not const because of such as Reset_vertex_nvT
const int iGraphsFlag)
{
Vertex * pVertex;
long iVertex;
switch(iGraphsFlag) {
case SPECIES_NEUTRAL:
X.Reset_vertex_nvT(SPECIES_NEUTRAL);
Graph[0].DrawSurface("Neutral n",
DATA_HEIGHT,(real *)(&(X.X[0].n)),
VELOCITY_COLOUR,(real *)(&(X.X[0].v)),
false, // no inner mesh display
GRAPH_NEUT_N, &X);
Graph[1].DrawSurface("Neutral v",
VELOCITY_HEIGHT,(real *)(&(X.X[0].v)),
VELOCITY_COLOUR,(real *)(&(X.X[0].v)),
false, // no inner mesh display
GRAPH_NEUT_V, &X);
Graph[3].TickRescaling = 1.0/kB;
Graph[3].DrawSurface("Neutral T",
DATA_HEIGHT,(real *)(&(X.X[0].T)),
SEGUE_COLOUR,(real *)(&(X.X[0].T)),
false, // no inner mesh display
GRAPH_NEUT_T, &X);
Graph[3].TickRescaling = 1.0;
// How to handle Graph[2] ?
break;
case SPECIES_ION:
X.Reset_vertex_nvT(SPECIES_ION);
Graph[3].TickRescaling = 1.0/kB;
Graph[3].DrawSurface("Ion T",
DATA_HEIGHT,(real *)(&(X.X[0].T)),
SEGUE_COLOUR,(real *)(&(X.X[0].T)),
false, // no inner mesh display
GRAPH_ION_T, &X);
Graph[3].TickRescaling = 1.0;
// labels only appear on first 1 called.
Graph[0].DrawSurface("Ion n",
DATA_HEIGHT,(real *)(&(X.X[0].n)),
VELOCITY_COLOUR,(real *)(&(X.X[0].v)),
false, // no inner mesh display
GRAPH_ION_T, &X);
Graph[1].DrawSurface("Ion v",
VELOCITY_HEIGHT,(real *)(&(X.X[0].v)),
VELOCITY_COLOUR,(real *)(&(X.X[0].v)),
false, // no inner mesh display
GRAPH_ION_V, &X);
break;
case SPECIES_ELEC:
X.Reset_vertex_nvT(SPECIES_ELEC);
Graph[0].DrawSurface("Elec n",
DATA_HEIGHT,(real *)(&(X.X[0].n)),
VELOCITY_COLOUR,(real *)(&(X.X[0].v)),
false, // no inner mesh display
GRAPH_ELEC_T, &X);
Graph[1].DrawSurface("Elec v",
VELOCITY_HEIGHT,(real *)(&(X.X[0].v)),
VELOCITY_COLOUR,(real *)(&(X.X[0].v)),
false, // no inner mesh display
GRAPH_ELEC_V, &X);
Graph[3].TickRescaling = 1.0/kB;
Graph[3].DrawSurface("Neutral T",
DATA_HEIGHT,(real *)(&(X.X[0].T)),
SEGUE_COLOUR,(real *)(&(X.X[0].T)),
false, // no inner mesh display
GRAPH_ELEC_T, &X);
Graph[3].TickRescaling = 1.0;
break;
// In other cases, (and even for the above),
// here is a good place to call the
// setup routines for temp variables.
case JZAZBXYEZ:
X.Setup_J(); // the others can already exist.
Graph[0].DrawSurface("Az",
DATA_HEIGHT,(real *)(&(X.X[0].A.z)),
AZSEGUE_COLOUR,(real *)(&(X.X[0].A.z)),
true,
GRAPH_AZ, &X);
Graph[1].DrawSurface("Bxy",
VELOCITY_HEIGHT,(real *)(&(X.X[0].B)),
VELOCITY_COLOUR,(real *)(&(X.X[0].B)),
false, // no inner mesh display: ??
GRAPH_BXY, &X);
Graph[2].DrawSurface("Ez",
DATA_HEIGHT,(real *)(&(X.X[0].E.z)),
FLAG_SEGUE_COLOUR,(real *)(&(X.X[0].E.z)),
false, // ??
GRAPH_EZ, &X);
Graph[3].DrawSurface("Jz",
DATA_HEIGHT,(real *)(&(X.X[0].Temp.z)),
AZSEGUE_COLOUR,(real *)(&(X.X[0].Temp.z)),
false, // no inner mesh display.
GRAPH_JZ, &X);
break;
case JXYAXYBZEXY:
X.Setup_J(); // the others can already exist.
Graph[0].DrawSurface("Axy",
VELOCITY_HEIGHT,(real *)(&(X.X[0].A.x)),
VELOCITY_COLOUR,(real *)(&(X.X[0].A.x)),
true,
GRAPH_AXY, &X);
Graph[1].DrawSurface("Bz",
DATA_HEIGHT,(real *)(&(X.X[0].B.z)),
AZSEGUE_COLOUR,(real *)(&(X.X[0].B.z)),
false, // no inner mesh display: ??
GRAPH_BZ, &X);
Graph[2].DrawSurface("Exy",
VELOCITY_HEIGHT,(real *)(&(X.X[0].E)),
VELOCITY_COLOUR,(real *)(&(X.X[0].E)),
false,
GRAPH_EXY, &X);
Graph[3].DrawSurface("Jxy",
VELOCITY_HEIGHT,(real *)(&(X.X[0].Temp.x)),
VELOCITY_COLOUR,(real *)(&(X.X[0].Temp.x)),
false, // no inner mesh display.
GRAPH_JXY, &X);
break;
case EXY_RHO_PHI_JXY:
// create rho on pVertex->temp2.x ...
pVertex= pX->X;
for (iVertex = 0; iVertex < pX->numVertices; iVertex++)
{
if (pVertex->flags == DOMAIN_VERTEX) {
pVertex->temp2.x = q*(pVertex->Ion.mass-pVertex->Elec.mass)/pVertex->AreaCell;
} else {
pVertex->temp2.x = 0.0;
};
++pVertex;
}
Graph[0].DrawSurface("phi",
DATA_HEIGHT,(real *)(&(X.X[0].phi)),
AZSEGUE_COLOUR,(real *)(&(X.X[0].phi)),
false,
GRAPH_PHI, &X);
Graph[1].DrawSurface("Jxy",
VELOCITY_HEIGHT,(real *)(&(X.X[0].Temp)),
VELOCITY_COLOUR,(real *)(&(X.X[0].Temp)),
false, // no inner mesh display: ??
GRAPH_JXY, &X);
Graph[2].DrawSurface("Exy",
VELOCITY_HEIGHT,(real *)(&(X.X[0].E)),
VELOCITY_COLOUR,(real *)(&(X.X[0].E)),
false,
GRAPH_EXY, &X);
Graph[3].DrawSurface("rho",
DATA_HEIGHT,(real *)(&(X.X[0].temp2.x)),
AZSEGUE_COLOUR,(real *)(&(X.X[0].temp2.x)),
false, // no inner mesh display.
GRAPH_RHO, &X);
break;
case SIGMA_E_J:
X.Setup_J(); // the others can already exist.
Graph[0].DrawSurface("sigma_e_zz",
DATA_HEIGHT,(real *)(&(X.X[0].sigma_e.zz)),
AZSEGUE_COLOUR,(real *)(&(X.X[0].sigma_e.zz)),
true,
GRAPH_SIGMA_E, &X);
//Graph[1].DrawSurface("v_e_0.z",
// DATA_HEIGHT,(real *)(&(X.X[0].v_e_0.z)),
// AZSEGUE_COLOUR,(real *)(&(X.X[0].v_e_0.z)),
//false, // no inner mesh display: ??
// GRAPH_VE0Z, &X);
Graph[1].DrawSurface("nsigma",
DATA_HEIGHT,(real *)(&(X.X[0].xdotdot.x)),
AZSEGUE_COLOUR,(real *)(&(X.X[0].xdotdot.x)),
true, GRAPH_SIGMATEMP, &X);
Graph[2].DrawSurface("Ez",
DATA_HEIGHT,(real *)(&(X.X[0].E.z)),
FLAG_AZSEGUE_COLOUR,(real *)(&(X.X[0].E.z)), // how to make SEGUE_COLOUR work?
false, // ??
GRAPH_EZ, &X);
Graph[3].DrawSurface("Jz",
DATA_HEIGHT,(real *)(&(X.X[0].Temp.z)),
AZSEGUE_COLOUR,(real *)(&(X.X[0].Temp.z)),
false, // no inner mesh display.
GRAPH_JZ, &X);
break;
case TOTAL:
// In this case we have to create data,
// as we go.
// Best put it here so we can see where
// data is being populated.
X.CalculateTotalGraphingData();
// ought to change this to use variables n,v,T !
Graph[0].DrawSurface("n_n+n_ion",
DATA_HEIGHT,(real *)(&(X.X[0].n)),
IONISE_COLOUR,(real *)(&(X.X[0].Temp.y)),
false,
GRAPH_TOTAL_N, &X);
Graph[1].DrawSurface("[n_s v_s m_s]/[n_s m_s]",
VELOCITY_HEIGHT,(real *)(&(X.X[0].v)),
VELOCITY_COLOUR,(real *)(&(X.X[0].v)),
false, // no inner mesh display
GRAPH_TOTAL_V, &X);
Graph[2].DrawSurface("n_n+n_ion",
DATA_HEIGHT,(real *)(&(X.X[0].n)),
VELOCITY_COLOUR,(real *)(&(X.X[0].v)),
false,
GRAPH_TOTAL_N_II, &X);
Graph[3].TickRescaling = 1.0/kB;
Graph[3].DrawSurface("[n_s T_s]/[n_s]",
DATA_HEIGHT,(real *)(&(X.X[0].T)),
SEGUE_COLOUR,(real *)(&(X.X[0].T)),
false,
GRAPH_TOTAL_T, &X);
Graph[3].TickRescaling = 1.0;
break;
};
// Graph 2, in case of species graphs:
char buff[256];
sprintf(buff, "%4.3f ns", evaltime*1.0e9);
switch(iGraphsFlag) {
case SPECIES_NEUTRAL:
case SPECIES_ION:
case SPECIES_ELEC:
Graph[2].SetEyePlan(GlobalPlanEye);
Graph[2].boolDisplayMeshWireframe = true;
Graph[2].boolClearZBufferBeforeWireframe = true;
Graph[2].boolDisplayMainMesh = true;
Graph[2].boolDisplayInnerMesh = false;
Graph[2].boolDisplayScales = false;
if (GlobalColoursPlanView == 0)
{
// nothing
Graph[2].mhTech = Graph[2].mFX->GetTechniqueByName("MeshTech");
Graph[2].SetDataWithColour(X,FLAG_COLOUR_MESH,FLAG_FLAT_MESH,0,0,
GRAPH_FLAT_WIRE_MESH);
Graph[2].Render(buff, GlobalRenderLabels, &X);
} else {
// Tell SDWC not to mess with colourmax if it's a flat mesh.
X.Reset_vertex_nvT(SPECIES_ION);
int offset_v_ion = (real *)(&(X.X[0].v)) -(real *)(&(X.X[0]));
int offset_T_ion = (real *)(&(X.X[0].T)) -(real *)(&(X.X[0]));
if (GlobalColoursPlanView == 1)
{
// velocity
Graph[2].mhTech = Graph[2].mFX->GetTechniqueByName("VelociTech");
Graph[2].colourmax = Graph[0].colourmax; // match colours
Graph[2].SetDataWithColour(X,FLAG_VELOCITY_COLOUR,FLAG_FLAT_MESH,offset_v_ion,offset_v_ion,
GRAPH_FLAT_WIRE_MESH);
Graph[2].Render(buff, GlobalRenderLabels, &X);
} else {
// temperature
Graph[2].mhTech = Graph[2].mFX->GetTechniqueByName("SegueTech");
// SegueVS should take maximum as a parameter;
// at least for colours we should prefer an absolute scale for T
// Is it ever used for anything else? Not so far? eps?
Graph[2].SetDataWithColour(X,FLAG_SEGUE_COLOUR,FLAG_FLAT_MESH,offset_T_ion, offset_T_ion,
GRAPH_FLAT_WIRE_MESH);
Graph[2].Render(buff, GlobalRenderLabels, &X);
};
};
break;
}
}
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
unsigned int old_cw;
// with X86 defined 0 in config.h, this will do nothing:
// fpu_fix_start(&old_cw);
char szInitialFilenameAvi[512];
MSG msg;
HDC hdc;
// HACCEL hAccelTable;
real x,y,temp;
int i,j;
float a1,a2,a3,a4;
HWND hwndConsole;
FILE * fp;
extern char Functionalfilename[1024];
hInst = hInstance;
cw = 0;
_controlfp_s(&cw, 0, 0); // zeroes out control word.
_controlfp_s(0, _EM_INEXACT | _EM_UNDERFLOW, _MCW_EM);
// hide only "inexact" and underflow FP exception
// Why underflow?
AllocConsole(); // for development purposes
freopen( "CONOUT$", "wb", stdout );
SetConsoleTitle("2D 1/16 annulus DPF simulation");
Sleep(40);
hwndConsole = FindWindow(NULL,"2D 1/16 annulus DPF simulation");
MoveWindow(hwndConsole,0,0,SCREEN_WIDTH-VIDEO_WIDTH-10,SCREEN_HEIGHT-30,TRUE);
h = TIMESTEP;
evaltime = 0.0; // gets updated before advance
memset(Historic_powermax, 0,200*sizeof(int));
memset(Historic_powermin, 0,200*sizeof(int));
ZeroMemory(Historic_max,100*HISTORY*sizeof(float));
ZeroMemory(Historic_min,100*HISTORY*sizeof(float));
Vector2 x1,x2,x3,r1,r2,r3;
x1.x = 0.0; x1.y = 0.0;
x2.x = 1.0; x2.y = 1.0;
x3.x = 2.0; x3.y = 0.0;
r1.x = 0.0; r1.y = 0.0;
r2.x = 0.0; r2.y = 1.0;
r3.x = 1.0; r3.y = 0.0;
// so far, appears to work
real area = CalculateTriangleIntersectionArea(x1, x2, x3, r1, r2, r3);
area = CalculateTriangleIntersectionArea(r1, r2, r3,x1, x2, x3);
// what would really give confidence would be if we finish our columns method
// and verify that they give the same answers.
GlobalStepsCounter = 0; steps_remaining = 0;
// Note : atanf gives values in 1st and 4th quadrant - but remember atan2
// Find next available filename for functional output:
int filetag = 0;
do {
filetag++;
sprintf(Functionalfilename,FUNCTIONALFILE_START "%03d.txt",filetag);
} while ((_access( Functionalfilename, 0 )) != -1 );
//if( (_access( "ACCESS.C", 0 )) != -1 )
//{
// printf( "File ACCESS.C exists\n" );
// /* Check for write permission */
// if( (_access( "ACCESS.C", 2 )) != -1 )
// printf( "File ACCESS.C has write permission\n" );
//}
printf("\n\nopening %s \n",Functionalfilename);
fp = fopen(Functionalfilename,"w");
if (fp == 0) {
printf("error with %s \n",Functionalfilename);
getch();
} else {
printf("opened %s \n",Functionalfilename);
};
fprintf(fp,"GSC evaltime Area neut.N ion.N elec.N neut.r ion.r elec.r SDneut.r SDion.r SDelec.r "
" neut.vr neut.vth neut.vz ion.vr ion.vth ion.vz elec.vr elec.vth elec.vz neut.heat ion.heat elec.heat neut.T ion.T elec.T "
" neut.mnvv/3 ion.mnvv/3 elec.mnvv/3 elec.force(vxB)r within3.6 elec.Bth EE BB Heatings and dT changes - see code \n");
fclose(fp);
report_time(0);
printf("Initialising meshes...\n");
if (bScrewPinch) {
//X1.InitialiseScrewPinch();
//X2.InitialiseScrewPinch();
} else {
X1.Initialise(1); // Set evaltime first
X2.Initialise(2);
}
pX = &X1;
pXnew = &X2;
// A,phi seeding relies on both system values
GlobalBothSystemsInUse = 0;
//if (SYSTEM_INITIALISE_VS_LOAD == LOAD)
//{
// if (pX->Load(AUTO_DATA_LOAD_FILENAME))
// {
// printf("File error auto-loading %s",AUTO_DATA_LOAD_FILENAME);
// getch();
// PostQuitMessage(2000);
// } else {
// pXnew->Load(AUTO_DATA_LOAD_FILENAME);
// // lazy way! Do differently.
// };
//};
printf(report_time(1));
printf("\n");
report_time(0);
// Window setup
LoadString(hInstance, IDS_APP_TITLE, szTitle, 1024);
LoadString(hInstance, IDC_F2DVALS, szWindowClass, 1024);
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_F2DVALS));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCE(IDR_MENU1);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
RegisterClassEx(&wcex);
printf("SCREEN_WIDTH %d VIDEO_WIDTH %d VIDEO_HEIGHT %d \n",
SCREEN_WIDTH,VIDEO_WIDTH,VIDEO_HEIGHT);
hWnd = CreateWindowEx(NULL,szWindowClass, szTitle, WS_BORDER | WS_POPUP,
SCREEN_WIDTH-VIDEO_WIDTH-5, 0, VIDEO_WIDTH+5, VIDEO_HEIGHT+20, NULL, NULL, hInstance, NULL);
if (!hWnd) return 3000;
// This fails, although dimensions are sensible.
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
xzscale = 2.0/0.1; // very zoomed in. Now what?
DXChk(Direct3D.Initialise(hWnd,hInstance,VIDEO_WIDTH,VIDEO_HEIGHT));
// With Field Of View = PI/4 used this:
GlobalEye.x = 0.0f;
GlobalEye.y = 12.4f; //7.2f;
GlobalEye.z = -18.0f+2.5*xzscale;//DEVICE_RADIUS_INSULATOR_OUTER*xzscale;//-17.8f+
GlobalLookat.x = 0.4f;
GlobalLookat.y = 3.0f;
GlobalLookat.z = DEVICE_RADIUS_INITIAL_FILAMENT_CENTRE*xzscale;
GlobalPlanEye.x = 0.0f;
GlobalPlanEye.y = 35.0f;
GlobalPlanEye.z = (3.44+4.1)*0.5*xzscale;
GlobalPlanEye2.x = -0.1f;
GlobalPlanEye2.y = 19.5f;
GlobalPlanEye2.z = 2.8*xzscale;
GlobalPlanLookat.x = GlobalPlanEye.x;
GlobalPlanLookat.y = 0.0f;
GlobalPlanLookat.z = GlobalPlanEye.z+0.0001;
GlobalPlanLookat2.x = GlobalPlanEye2.x;
GlobalPlanLookat2.y = 0.0f;
GlobalPlanLookat2.z = GlobalPlanEye2.z+0.0001;
if (DXChk( Graph[3].InitialiseWithoutBuffers(GRAPH_WIDTH,GRAPH_HEIGHT,GRAPH_WIDTH,GRAPH_HEIGHT,GlobalEye,GlobalLookat) ) +
DXChk( Graph[3].InitialiseBuffers(X1) )
)
{ PostQuitMessage(203); };
if (DXChk( Graph[2].InitialiseWithoutBuffers(GRAPH_WIDTH,0,GRAPH_WIDTH,GRAPH_HEIGHT,GlobalPlanEye,GlobalPlanLookat) ) +
DXChk( Graph[2].InitialiseBuffers(X1) )
)
{ PostQuitMessage(202); };
if (DXChk( Graph[1].InitialiseWithoutBuffers(0,GRAPH_HEIGHT,GRAPH_WIDTH,GRAPH_HEIGHT,GlobalEye,GlobalLookat) ) +
DXChk( Graph[1].InitialiseBuffers(X1) )
)
{ PostQuitMessage(201); };
if (DXChk( Graph[0].InitialiseWithoutBuffers(0,0,GRAPH_WIDTH,GRAPH_HEIGHT,GlobalEye, GlobalLookat) ) +
DXChk( Graph[0].InitialiseBuffers(X1) )
)
{ PostQuitMessage(200); };
if (DXChk( Graph[4].InitialiseWithoutBuffers(0,0,GRAPH_WIDTH*2,GRAPH_HEIGHT*2,GlobalPlanEye,GlobalPlanLookat) ) +
DXChk( Graph[4].InitialiseBuffers(X1) )
)
{ PostQuitMessage(204); };
Graph[4].SetEyePlan(GlobalPlanEye);
Graph[4].boolDisplayMeshWireframe = true;
Graph[4].boolClearZBufferBeforeWireframe = true;
Graph[4].boolDisplayMainMesh = true;
Graph[4].boolDisplayInnerMesh = false;
Graph[4].boolDisplayScales = false;
// if (DXChk( Graph[4].InitialiseWithoutBuffers(0,0,2*GRAPH_WIDTH,
// 2*GRAPH_HEIGHT,GlobalPlanEye2,GlobalPlanLookat2) ) +
// DXChk( Graph[4].InitialiseBuffers(X1) )
// )
// { PostQuitMessage(208); };
// ?? -- for doing 1 graph in whole space. ?!
Graph[0].bDisplayTimestamp = false;
Graph[1].bDisplayTimestamp = false;
Graph[2].bDisplayTimestamp = true;
Graph[3].bDisplayTimestamp = false;
Direct3D.pd3dDevice->GetBackBuffer(0,0,D3DBACKBUFFER_TYPE_MONO, &p_backbuffer_surface);
if(DXChk(p_backbuffer_surface->GetDC(&surfdc),1000))
MessageBox(NULL,"GetDC failed","oh dear",MB_OK);
surfbit = CreateCompatibleBitmap(surfdc,VIDEO_WIDTH,VIDEO_HEIGHT); // EXTRAHEIGHT = 90
SelectObject(surfdc,surfbit);
dibdc = CreateCompatibleDC(surfdc);
long VideoWidth = VIDEO_WIDTH;
long VideoHeight = VIDEO_HEIGHT;
// pasted here just to set up format:
bitmapinfo.bmiHeader.biSize = sizeof(BITMAPINFO);
bitmapinfo.bmiHeader.biWidth = VideoWidth;
bitmapinfo.bmiHeader.biHeight = VideoHeight;
bitmapinfo.bmiHeader.biPlanes = 1;
bitmapinfo.bmiHeader.biBitCount = 24;
bitmapinfo.bmiHeader.biCompression = BI_RGB; // uncompressed
bitmapinfo.bmiHeader.biSizeImage = bitmapinfo.bmiHeader.biHeight;
bitmapinfo.bmiHeader.biXPelsPerMeter = 3000;
bitmapinfo.bmiHeader.biYPelsPerMeter = 3000;
bitmapinfo.bmiHeader.biClrUsed = 0;
bitmapinfo.bmiHeader.biClrImportant = 0;
bitmapinfo.bmiColors->rgbBlue = 0;
bitmapinfo.bmiColors->rgbRed = 0;
bitmapinfo.bmiColors->rgbGreen = 0;
bitmapinfo.bmiColors->rgbReserved = 0;
// dimension DIB and set up pointer to bits
dib = CreateDIBSection(dibdc, &bitmapinfo, DIB_RGB_COLORS, &lpvBits, NULL, 0);
SelectObject(dibdc, dib);
BitBlt(dibdc,0,0,VIDEO_WIDTH,VIDEO_HEIGHT,surfdc,0,0,SRCCOPY);
for (i = 0 ; i < NUMAVI; i++)
{
sprintf(szInitialFilenameAvi,"%s%s_%s",FOLDER,szAvi[i],INITIALAVI);
hAvi[i] = CreateAvi(szInitialFilenameAvi, AVIFRAMEPERIOD, NULL);
};
// 1000/25 = 40
ZeroMemory(&opts,sizeof(opts));
opts.fccHandler=mmioFOURCC('D','I','B',' ');//('d','i','v','x');
opts.dwFlags = 8;
for (i = 0 ; i < NUMAVI; i++)
SetAviVideoCompression(hAvi[i],dib,&opts,false,hWnd); // always run this for every avi file but can
// call with false as long as we know opts contains valid information.
counter = 0;
//ReleaseDC(hWnd,surfdc);
p_backbuffer_surface->ReleaseDC(surfdc);
GlobalCutaway = true;
RefreshGraphs(*pX,GlobalSpeciesToGraph);
ZeroMemory( &msg, sizeof( msg ) );
// Main message loop:
while( msg.message != WM_QUIT )
{
if( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
} else {
Direct3D.pd3dDevice->Present( NULL, NULL, NULL, NULL );
};
};
UnregisterClass(szWindowClass, wcex.hInstance );
fclose( stdout );
FreeConsole();
// fpu_fix_end(&old_cw);
return (int) msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int iAntiskips;
int wmId, wmEvent;
int i,j;
PAINTSTRUCT ps;
HDC hdc;
real time_back_for_Adot;
TriMesh * temp;
FILE * file, *fp;
int maxeerr, count,iMin;
char buf1000[1024];
int attempts;
real store_h;
char ch;
int failed;
RECT rect;
Vertex * pVertex;
real TotalArea, TotalCharge;
Triangle * pTri,*pTriSrc;
long iVertex;
real mass_avg, mass_SD, mass_min, mass_max;
OPENFILENAME ofn; // common dialog box structure
char szFile[260]; // buffer for file name
char szFilter[1000]; // buffer for file filter
char szfilter[256];
switch (message)
{
case WM_CREATE:
// Don't ever try doing initialisation here;
// That should be done manually from the menus.
RefreshGraphs(*pX,GlobalSpeciesToGraph);
Direct3D.pd3dDevice->Present( NULL, NULL, NULL, NULL );
break;
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Ensure that display menu items are consecutive IDs.
if ((wmId >= ID_DISPLAY_NEUT) &&
(wmId < ID_DISPLAY_NEUT + NUMAVI))
{
//if (wmId < ID_DISPLAY_NEUT + 4)
GlobalSpeciesToGraph = wmId;
i = wmId-ID_DISPLAY_NEUT;
printf("\nGraph: %d %s",i,szAvi[i]);
RefreshGraphs(*pX,i);
Direct3D.pd3dDevice->Present( NULL, NULL, NULL, NULL );
return 0;
}
// Parse the menu selections:
switch (wmId)
{
case ID_HELP_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case ID_FILE_EXIT:
DestroyWindow(hWnd);
break;
case ID_FILE_SAVECAMERA:
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hWnd;
ofn.lpstrFile = szFile;
// Set lpstrFile[0] to '\0' so that GetOpenFileName does not
// use the contents of szFile to initialize itself.
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(szFile);
memcpy(szfilter, "All\0*.*\0cam\0*.CAM\0\0", 19); // strcpy stops at first null !!
ofn.lpstrFilter = szfilter; //"All\0*.*\0Dat\0*.DAT\0\0"; // summat weird about that example code
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_OVERWRITEPROMPT;
ofn.lpstrTitle = NULL;
if (GetSaveFileName(&ofn)==TRUE)
{
printf("\nsaving camera...");
fp = fopen(ofn.lpstrFile,"wt");
if (fp == 0) {
printf("save failed.\n");
} else {
fprintf(fp,"%f %f %f ",GlobalPlanEye.x,GlobalPlanEye.y,GlobalPlanEye.z);
fprintf(fp,"%f %f %f ",GlobalLookat.x,GlobalLookat.y,GlobalLookat.z);
fprintf(fp,"%f %f %f ",GlobalEye.x,GlobalEye.y,GlobalEye.z);
fprintf(fp,"%f %f %f ",GlobalPlanLookat.x,GlobalPlanLookat.y,GlobalPlanLookat.z);
fclose(fp);
printf("done\n");
};
} else {
printf("there was an issue\n");
};
break;
case ID_FILE_LOADCAMERA:
// Initialize OPENFILENAME
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hWnd;
ofn.lpstrFile = szFile;
// Set lpstrFile[0] to '\0' so that GetOpenFileName does not
// use the contents of szFile to initialize itself.
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(szFile);
memcpy(szfilter, "All\0*.*\0*.cam\0*.Cam\0\0", 21); // strcpy stops at first null !!
ofn.lpstrFilter = szfilter; //"All\0*.*\0*.Dat\0*.DAT\0\0"; // summat weird about that example code
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
// Display the Open dialog box.
if (GetOpenFileName(&ofn)==TRUE)
{
printf("\nloading camera...");
fp = fopen(ofn.lpstrFile,"rt");
if (fp == 0) {
printf("failed.\n");
} else {
rewind(fp);
fscanf(fp,"%f %f %f ",&(GlobalPlanEye.x),&(GlobalPlanEye.y),&(GlobalPlanEye.z));
fscanf(fp,"%f %f %f ",&(GlobalLookat.x),&(GlobalLookat.y),&(GlobalLookat.z));
fscanf(fp,"%f %f %f ",&(GlobalEye.x),&(GlobalEye.y),&(GlobalEye.z));
fscanf(fp,"%f %f %f ",&(GlobalPlanLookat.x),&(GlobalPlanLookat.y),&(GlobalPlanLookat.z));
fclose(fp);
};
RefreshGraphs(*pX,GlobalSpeciesToGraph); // sends data to graphs AND renders them
Direct3D.pd3dDevice->Present( NULL, NULL, NULL, NULL );
} else {
printf("file error camera\n");
};
break;
case ID_FILE_SAVEBINARY:
// Initialize OPENFILENAME
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hWnd;
ofn.lpstrFile = szFile;
// Set lpstrFile[0] to '\0' so that GetOpenFileName does not
// use the contents of szFile to initialize itself.
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(szFile);
memcpy(szfilter, "All\0*.*\0*.dat\0*.Dat\0\0", 21); // strcpy stops at first null !!
ofn.lpstrFilter = szfilter; //"All\0*.*\0Dat\0*.DAT\0\0"; // summat weird about that example code
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_OVERWRITEPROMPT;
ofn.lpstrTitle = NULL;
// Display the Open dialog box.
if (GetSaveFileName(&ofn)==TRUE)
{
printf("\nsaving system...");
pX->Save(ofn.lpstrFile);
printf("done\n");
} else {
printf("there was an issue\n");
};
break;
case ID_FILE_SAVETEXT:
// Initialize OPENFILENAME
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hWnd;
ofn.lpstrFile = szFile;
//
// Set lpstrFile[0] to '\0' so that GetOpenFileName does not
// use the contents of szFile to initialize itself.
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(szFile);
//strcpy(szFilter,"All\0*.*\0Text\0*.TXT\0");
memcpy(szfilter, "All\0*.*\0Dat\0*.DAT\0\0", 19); // strcpy stops at first null !!
ofn.lpstrFilter = szfilter; //"All\0*.*\0Dat\0*.DAT\0\0"; // summat weird about that example code
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_OVERWRITEPROMPT;
ofn.lpstrTitle = NULL;
// Display the Open dialog box.
if (GetSaveFileName(&ofn)==TRUE)
{
printf("\nsaving system...");
pX->SaveText(ofn.lpstrFile);
printf("done\n");
} else {
printf("there was an issue\n");
};
break;
case ID_FILE_LOAD:
// Initialize OPENFILENAME:
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hWnd;
ofn.lpstrFile = szFile;
//
// Set lpstrFile[0] to '\0' so that GetOpenFileName does not
// use the contents of szFile to initialize itself.
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(szFile);
//strcpy(szFilter, "All\0*.*\0Dat\0*.DAT\0\0");
memcpy(szfilter, "All\0*.*\0Dat\0*.DAT\0\0", 19); // strcpy stops at first null !!
ofn.lpstrFilter = szfilter; //"All\0*.*\0Dat\0*.DAT\0\0"; // summat weird about that example code
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
// Display the Open dialog box.
if (GetOpenFileName(&ofn)==TRUE)
{
printf("\nloading system...");
X1.Load(ofn.lpstrFile);
printf("done\n");
RefreshGraphs(*pX,GlobalSpeciesToGraph); // sends data to graphs AND renders them
Direct3D.pd3dDevice->Present( NULL, NULL, NULL, NULL );
GlobalBothSystemsInUse = 0;
} else {
printf("file error loadsyst\n");
};
break;
case ID_RUN_SIMULATIONSTEPS:
GlobalSwitchBox = 0;
DialogBox(hInst, MAKEINTRESOURCE(IDD_DIALOG1), hWnd, SetupBox);
// that will not return with steps_remaining unset.
if (steps_remaining > 0)
SetTimer(hWnd, 1, 10, NULL); // 10 millisecond delay
break;
case ID_RUN_STOP:
steps_remaining = 0;
break;
case ID_INITIALISE_IONISATIONSTEPS:
/*
GlobalSwitchBox = 0;
DialogBox(hInst, MAKEINTRESOURCE(IDD_DIALOG1), hWnd, SetupBox);
// that will not return with steps_remaining unset.
Celldata_host = new fluid3BE[pX->numTriangles];
Cellinfo_host = new structural[pX->numTriangles];
Vertinfo_host = new vertinfo[pX->numTriangles];
Vertdata_host = new vertdata[pX->numTriangles];
pX->Setup_Data_for_CUDA(
Celldata_host, // pointers to receive data
//Vertdata_host,
Cellinfo_host,
Vertinfo_host,
Vertdata_host
) ;
printf("passed data to arrays.\n");
PerformCUDA_Ionisation_Only(
Celldata_host, Cellinfo_host, Vertinfo_host ,
Vertdata_host, pX->numTriangles, pX->numVertices,
1.0e-13, 100);
// 100 repeats of 1e-13 ionisation.
pX->Suck_Data_from_CUDA(Celldata_host);
printf("retrieved data from arrays.\n");
pX->RecalculateVertexVariables(); // needed to affect graphics
RefreshGraphs(*pX); // sends data to graphs AND renders them
Direct3D.pd3dDevice->Present( NULL, NULL, NULL, NULL );
delete[] Celldata_host;
delete[] Cellinfo_host;
delete[] Vertinfo_host;
delete[] Vertdata_host;
*/
break;
case ID_INITIALISE_RUNPOTENTIALSSOLVER:
// Inputs:
// Need to take pressure and grad Te before we call
// to setup matrices.
printf("pX->GetGradTeOnVertices(); \n");
pX->GetGradTeOnVertices(); // shouldn't have to belong here.
pX->Iz_prescribed = pX->GetIzPrescribed(evaltime);
printf("pX->EstimateInitialOhms_zz(); \n");
pX->EstimateInitialOhms_zz(); // set up (zz) Ohm's Law for initial solve.
GlobalIzElasticity = PIOVERPEAKTIME / tan ((evaltime + ZCURRENTBASETIME) * PIOVERPEAKTIME );
store_h = h;
printf("GlobalIzElasticity %1.10E \n",GlobalIzElasticity);
getch();
printf("pX->Solve_A_phi(true); \n");
h = 1.0/c; // for chargeflows
time_back_for_Adot = 0.0; //store_h*0.5; // Assume we want to set A-dot for half a simulation timestep into the past.
printf("Time where Adot was set: %1.5E in the past",time_back_for_Adot);
pX->Solve_Az(time_back_for_Adot);
h = store_h;
pX->GetBFromA(); // MAKE SURE THEN THAT WE ARE PASSING IT.
if (pX == &X1) {
printf("\n\n did for X1\n");
} else {
printf("\n\n did for X2\n");
};
RefreshGraphs(*pX, JZAZBXYEZ);
//GlobalSpeciesToGraph = JZAZBXYEZ;
Direct3D.pd3dDevice->Present( NULL, NULL, NULL, NULL );
/*
pX->CreateVertexAveragingCoefficients(); // used in visc coeff routine and ODE
pX->MakePressureAccelData(SEPARATE_ELECTRON_AND_ION);
pTri = pX->T;
for (iTri = 0; iTri < pX->numTriangles; iTri++)
{
pTri->RecalculateEdgeNormalVectors(false);
pX->GetGradTe(pTri);
++pTri;
};
// Bear in mind we should define e,i params as 0 outside domain.
pX->EstimateInitialSigma_etc();
// defines v_e and v_i parameters
pX->Iz_prescribed = pX->GetIzPrescribed(evaltime);
if (wmId == ID_INITIALISE_RUNASOLVER)
{
if (bScrewPinch) {
store_h = h;
h = 100.0;
printf("h effective for initial solve = %1.12E \n",h);
pX->Solve_AzEz(0);
h = store_h;
} else {
GlobalIzElasticity = PIOVERPEAKTIME / tan ((evaltime + ZCURRENTBASETIME) * PIOVERPEAKTIME );
store_h = h;
h = 1.0/GlobalIzElasticity;
printf("h effective for initial solve = %1.12E \n",h);
pX->Solve_AzEz(0);
h = store_h;
};
} else {
//h = 1.0e-8; // try that.
pX->Solve_AzEz(pXnew);
};
// ??
*/
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
break;
case WM_TIMER:
if (wParam == 1)
{
KillTimer(hWnd, 1);
// Run 1 step:
if (steps_remaining > 0)
{
//HeapValidate(GetProcessHeap(),0,NULL);//printf("heap validated.\n"); //getch();
GlobalStepsCounter++;
failed = 0;
if (pX == &X1) {
printf("Setup from X1 ");
} else {
printf("Setup from X2 ");
};
printf("\n\n16000: elec.mom.z %1.8E \n\n",pX->X[16000].Elec.mom.z);
#ifndef NOCUDA
Systdata_host.InvokeHost(pX->numVertices);
pX->Setup_Data_for_CUDA( &Systdata_host ) ;
PerformCUDA_Advance (
&Systdata_host,
pX->numVertices,
1e-13,
10,
pX->numStartZCurrentRow,
pX->numEndZCurrentRow,
&Systdata_host,
evaltime
);
evaltime += 1.0e-13;
printf("evaltime %1.8E\n",evaltime);
#endif
pX->Suck_Data_from_CUDA(&Systdata_host);
printf("That's it.\n");
// End of test.
// pX->Advance(pXnew);
if (!failed)
{
// Only sucking back to pX.
// temp = pX;
// pX = pXnew;
// pXnew = temp;
steps_remaining--;
//evaltime += h; // this is done during the step
printf("Done step: %d || Remaining this run: %d\n\n",GlobalStepsCounter,steps_remaining);
if (GlobalStepsCounter % GRAPHICS_FREQUENCY == 0)
{
// make video frames:
//for (i = 0; i < NUMAVI; i++)
i = 0;
{
::PlanViewGraphs1(*pX);
//RefreshGraphs(*pX,GraphFlags[i]); // sends data to graphs AND renders them
Direct3D.pd3dDevice->Present( NULL, NULL, NULL, NULL );
if(DXChk(p_backbuffer_surface->GetDC(&surfdc),100))
MessageBox(NULL,"GetDC failed","oh dear",MB_OK);
//SelectObject(surfdc,surfbit);
BitBlt(dibdc,0,0,VIDEO_WIDTH,VIDEO_HEIGHT,surfdc,0,0,SRCCOPY);
p_backbuffer_surface->ReleaseDC(surfdc);
AddAviFrame(hAvi[i], dib);
};
};
// RefreshGraphs(*pX,GlobalSpeciesToGraph); // sends data to graphs AND renders them
// Direct3D.pd3dDevice->Present( NULL, NULL, NULL, NULL );
printf("%s\n",report_time(1));
};
/*
if ((GlobalStepsCounter % SWIM_FREQUENCY == 0))
// Swim involves ~9x8 advections so we may end up spending more time than on steps??
{
count = 0;
do
{
pX->CopyMesh(pXnew);
pXnew->SwimMesh(pX); // Note that SwimMesh does not call redelaunerize
// will need to look carefully into mechanics of what is being populated by what.
pXnew->RefreshVertexNeighboursOfVerticesOrdered();
pXnew->Redelaunerize(true);
pXnew->RefreshVertexNeighboursOfVerticesOrdered();
pX->RepopulateCells(pXnew,ALL_VARS);
pXnew->AverageVertexPositionsAndInterpolate(pX,false);
// Az (A and phi) handling is crucial.
// Every time we rotate systems we should be interpolating Az.
// We should interpolate B as well as A since it is not repopulated on vertices.
// Flip systems
temp = pX;
pX = pXnew;
pXnew = temp;
pX->CreateVertexAveragingCoefficients();
pX->RecalculateVertexVariables();
pX->SurveyCellMassStats(&mass_avg,&mass_SD,&mass_min,&mass_max,&iMin);
printf("\nmass avg: %1.10E SD: %1.10E\n min: %1.10E max: %1.10E iMin: %d \n",
mass_avg, mass_SD, mass_min, mass_max, iMin);
count++;
} while (((mass_SD > 0.2*mass_avg) || (mass_min < 0.2*mass_avg)) && (count < SWIM_COUNT));
RefreshGraphs(*pX); // sends data to graphs AND renders them
Direct3D.pd3dDevice->Present( NULL, NULL, NULL, NULL );
}; // whether % SWIM_FREQ == 0
*/
if (steps_remaining > 0){
SetTimer(hWnd,1,DELAY_MILLISECS,NULL);
printf("Waiting %d milliseconds to allow user input.\n",DELAY_MILLISECS);
} else {
printf("Run completed.\n");
sprintf(buf1000, "autosave%d.dat", GlobalStepsCounter);
pX->Save(buf1000);
printf("saved as %s\n",buf1000);
};
} else {
printf("steps_remaining = 0.\n");
};
if (GlobalStepsCounter % (AVI_FILE_PINCHOFF_FREQUENCY * GRAPHICS_FREQUENCY) == 0)
{
for (i = 0; i < NUMAVI; i++)
{
// now have to pinch out avi file and make a new one
sprintf(buf1000, "%s%s_%d.avi", FOLDER, szAvi[i], GlobalStepsCounter);
CloseAvi(hAvi[i]);
hAvi[i] = CreateAvi(buf1000, AVIFRAMEPERIOD, NULL);
SetAviVideoCompression(hAvi[i],dib,&opts,false,hWnd);
};
};
// Auto-save system:
if (GlobalStepsCounter % DATA_SAVE_FREQUENCY == 0)
{
// now have to save data
sprintf(buf1000, DATAFILENAME "%d.dat", GlobalStepsCounter);
pX->Save(buf1000);
// Do regular text save as well: ?
} else {
pX->Save(AUTOSAVE_FILENAME);
pX->SaveText("autosave.txt");
};
};
break;
case WM_KEYDOWN:
switch(wParam)
{
case 'W':
GlobalEye.z += 1.0f;
printf("GlobalEye %f %f %f \n",
GlobalEye.x,GlobalEye.y,GlobalEye.z);
break;
case 'S':
GlobalEye.z -= 1.0f;
printf("GlobalEye %f %f %f \n",
GlobalEye.x,GlobalEye.y,GlobalEye.z);
break;
case 'A':
GlobalEye.x -= 0.8f;
printf("GlobalEye %f %f %f \n",
GlobalEye.x,GlobalEye.y,GlobalEye.z);
break;
case 'D':
GlobalEye.x += 0.8f;
printf("GlobalEye %f %f %f \n",
GlobalEye.x,GlobalEye.y,GlobalEye.z);
break;
case 'E':
GlobalEye.y += 0.8f;
printf("GlobalEye %f %f %f \n",
GlobalEye.x,GlobalEye.y,GlobalEye.z);
break;
case 'C':
GlobalEye.y -= 0.8f;
printf("GlobalEye %f %f %f \n",
GlobalEye.x,GlobalEye.y,GlobalEye.z);
break;
case 'V':
GlobalLookat.z -= 0.4f;
printf("GlobalEye %f %f %f GlobalLookat %f %f %f\n",
GlobalEye.x,GlobalEye.y,GlobalEye.z,GlobalLookat.x,GlobalLookat.y,GlobalLookat.z);
break;
case 'R':
GlobalLookat.z += 0.4f;
printf("GlobalEye %f %f %f GlobalLookat %f %f %f\n",
GlobalEye.x,GlobalEye.y,GlobalEye.z,GlobalLookat.x,GlobalLookat.y,GlobalLookat.z);
break;
case 'F':
GlobalLookat.x -= 0.4f;
printf("GlobalEye %f %f %f GlobalLookat %f %f %f\n",
GlobalEye.x,GlobalEye.y,GlobalEye.z,GlobalLookat.x,GlobalLookat.y,GlobalLookat.z);
break;
case 'G':
GlobalLookat.x += 0.4f;
printf("GlobalEye %f %f %f GlobalLookat %f %f %f\n",
GlobalEye.x,GlobalEye.y,GlobalEye.z,GlobalLookat.x,GlobalLookat.y,GlobalLookat.z);
break;
case 'T':
GlobalLookat.y += 0.4f;
printf("GlobalLookat %f %f %f\n",
GlobalLookat.x,GlobalLookat.y,GlobalLookat.z);
break;
case 'B':
GlobalLookat.y -= 0.4f;
printf("GlobalLookat %f %f %f\n",
GlobalLookat.x,GlobalLookat.y,GlobalLookat.z);
break;
case 'Q':
GlobalCutaway = !GlobalCutaway;
break;
case 'Y':
case '<':
GlobalEye.x = -10.4; GlobalEye.y = 16.4; GlobalEye.z = 44.0;
GlobalLookat.x = -3.6; GlobalLookat.y = 3.0; GlobalLookat.z = 72.2;
printf("GlobalEye %f %f %f GlobalLookat %f %f %f\n",
GlobalEye.x,GlobalEye.y,GlobalEye.z,GlobalLookat.x,GlobalLookat.y,GlobalLookat.z);
GlobalPlanEye.x = 7.1; GlobalPlanEye.y = 11.5; GlobalPlanEye.z = 71.35;
printf("GlobalPlanEye %f %f %f\n",
GlobalPlanEye.x,GlobalPlanEye.y,GlobalPlanEye.z);
break;
case '_':
case '-':
case '>':
GlobalPlanEye.x = 7.0; GlobalPlanEye.y = 14.0; GlobalPlanEye.z = 71.0;
printf("GlobalPlanEye %f %f %f\n",
GlobalPlanEye.x,GlobalPlanEye.y,GlobalPlanEye.z);
break;
case 'U':
GlobalPlanEye.z += 0.6f;
printf("GlobalPlanEye %f %f %f\n",
GlobalPlanEye.x,GlobalPlanEye.y,GlobalPlanEye.z);
break;
case 'J':
GlobalPlanEye.z -= 0.6f;
printf("GlobalPlanEye %f %f %f\n",
GlobalPlanEye.x,GlobalPlanEye.y,GlobalPlanEye.z);
break;
case 'H':
GlobalPlanEye.x -= 0.6f;
printf("GlobalPlanEye %f %f %f\n",
GlobalPlanEye.x,GlobalPlanEye.y,GlobalPlanEye.z);
break;
case 'K':
GlobalPlanEye.x += 0.6f;
printf("GlobalPlanEye %f %f %f\n",
GlobalPlanEye.x,GlobalPlanEye.y,GlobalPlanEye.z);
break;
case 'I':
GlobalPlanEye.y *= 1.25f;
printf("GlobalPlanEye %f %f %f\n",
GlobalPlanEye.x,GlobalPlanEye.y,GlobalPlanEye.z);
break;
case 'M':
GlobalPlanEye.y *= 0.8f;
printf("GlobalPlanEye %f %f %f\n",
GlobalPlanEye.x,GlobalPlanEye.y,GlobalPlanEye.z);
break;
case 'N':
GlobalboolDisplayMeshWireframe = !GlobalboolDisplayMeshWireframe;
//Graph1.boolDisplayMeshWireframe = (!(Graph1.boolDisplayMeshWireframe));
break;
case '9':
GlobalRenderLabels = false;
break;
case '5':
GlobalRenderLabels = true;
GlobalWhichLabels = 0;// iTri
break;
case '8':
GlobalRenderLabels = true;
GlobalWhichLabels = 1;//T
break;
case '7':
GlobalRenderLabels = true;
GlobalWhichLabels = 2;//v
break;
case '6':
GlobalRenderLabels = true;
GlobalWhichLabels = 3; //n
break;
case '1':
GlobalColoursPlanView = 1;//v
break;
case '4':
GlobalColoursPlanView = 0;//nothing
break;
case '2':
GlobalColoursPlanView = 2;//T
break;
case '0':
steps_remaining = 0;
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
};
PlanViewGraphs1(*pX);
//RefreshGraphs(*pX,GlobalSpeciesToGraph); // sends data to graphs AND renders them
Direct3D.pd3dDevice->Present( NULL, NULL, NULL, NULL );
break;
case WM_PAINT:
// Not sure, do we want to do this?
//RefreshGraphs(*pX); // sends data to graphs AND renders them
GetUpdateRect(hWnd, &rect, FALSE);
Direct3D.pd3dDevice->Present( &rect, &rect, NULL, NULL );
ValidateRect(hWnd, NULL);
break;
case WM_DESTROY:
DeleteObject(dib);
DeleteDC(dibdc);
for (i = 0; i < NUMAVI; i++)
CloseAvi(hAvi[i]);
_controlfp_s(0, cw, _MCW_EM); // Line A
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
INT_PTR CALLBACK SetupBox(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
char buffer[2048];
char string[1024];
real newh;
switch (message)
{
case WM_INITDIALOG:
sprintf(buffer,"New h? (present = %1.10E)",h);
if (GlobalSwitchBox)
SetDlgItemText(hDlg,IDC_STATIC,buffer);
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK)
{
// try to read data from edit control:
GetDlgItemText(hDlg,IDC_EDIT1,buffer,2048);
if (GlobalSwitchBox == 0)
{
//
steps_remaining = atoi(buffer);
if (steps_remaining >= 0)
{
EndDialog(hDlg, LOWORD(wParam));
} else {
MessageBox(NULL,"incorrect value","Enter a nonnegative integer.",MB_OK);
};
} else {
newh = atof(buffer);
if (newh > 0.0)
{
EndDialog(hDlg, LOWORD(wParam));
sprintf(string,"h = %1.10E\n",newh);
h = newh;
MessageBox(NULL,string,"New value of h",MB_OK);
} else {
MessageBox(NULL,"no good","Negative h entered",MB_OK);
};
};
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
#ifndef NOCUDA
void TriMesh::Setup_Data_for_CUDA( Systdata * pSystdata )
{
// The idea is just to repackage TriMesh data into the desired format.
// FOR NOW -- not sure if we initialised or what so who cares
// just to get speed test.
memset(pSystdata->p_phi,0,sizeof(f64)*numVertices);
memset(pSystdata->p_phidot,0,sizeof(f64)*numVertices);
memset(pSystdata->p_A,0,sizeof(f64_vec3)*numVertices);
memset(pSystdata->p_Adot,0,sizeof(f64_vec3)*numVertices);
pSystdata->EzTuning = this->EzTuning.x[0];
long izNeigh[128];
long i;
long iVertex;
Vertex * pVertex = X;
for (iVertex = 0; iVertex < numVertices; iVertex++)
{
// Writing on phi,A
pSystdata->p_phi[iVertex] = pVertex->phi;
pSystdata->p_A[iVertex] = pVertex->A;
pSystdata->p_Adot[iVertex] = pVertex->Adot;
pSystdata->p_B[iVertex] = pVertex->B;
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// phidot IS MISSING from Vertex class !!!!
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
pSystdata->p_nT_neut[iVertex].n = pVertex->Neut.mass/pVertex->AreaCell;
pSystdata->p_nT_neut[iVertex].T = pVertex->Neut.heat/pVertex->Neut.mass;
pSystdata->p_v_neut[iVertex] = pVertex->Neut.mom/pVertex->Neut.mass;
pSystdata->p_nT_ion[iVertex].n = pVertex->Ion.mass/pVertex->AreaCell;
pSystdata->p_nT_ion[iVertex].T = pVertex->Ion.heat/pVertex->Ion.mass;
pSystdata->p_v_ion[iVertex] = pVertex->Ion.mom/pVertex->Ion.mass;
pSystdata->p_nT_elec[iVertex].n = pVertex->Elec.mass/pVertex->AreaCell;
pSystdata->p_nT_elec[iVertex].T = pVertex->Elec.heat/pVertex->Elec.mass;
pSystdata->p_v_elec[iVertex] = pVertex->Elec.mom/pVertex->Elec.mass;
pSystdata->p_area[iVertex] = pVertex->AreaCell;
if (pVertex->AreaCell == 0.0) {
printf(" area=0 %d ",iVertex);
}
long neigh_len = pVertex->GetNeighIndexArray(izNeigh);
pSystdata->p_info[iVertex].flag = (short)(pVertex->flags);
pSystdata->p_info[iVertex].neigh_len = (short)neigh_len;
pSystdata->p_info[iVertex].pos = pVertex->pos;
memcpy(pSystdata->pIndexNeigh + MAXNEIGH_d*iVertex,izNeigh,sizeof(long)*neigh_len);
if (neigh_len > MAXNEIGH_d) {
printf("Too many neighbours iVertex %d : %d \n",iVertex,neigh_len);
getch();
};
for (i = 0; i < neigh_len; i++)
{
// For each neighbour assess its periodic status relative to this.
// A simple test will do initially:
Vertex * pNeigh = X + izNeigh[i];
char PBC = 0;
if ((pNeigh->pos.x/pNeigh->pos.y > GRADIENT_X_PER_Y*0.5)
&&
(pVertex->pos.x/pVertex->pos.y < -0.5*GRADIENT_X_PER_Y))
{
PBC = ANTICLOCKWISE;
// " ANTICLOCKWISE means neigh needs to be rotated anticlockwise "
};
if ((pNeigh->pos.x/pNeigh->pos.y < -GRADIENT_X_PER_Y*0.5)
&&
(pVertex->pos.x/pVertex->pos.y > 0.5*GRADIENT_X_PER_Y))
{
PBC = CLOCKWISE;
};
pSystdata->pPBCneigh[MAXNEIGH_d*iVertex + i] = PBC;
if (iVertex == 14336) {
printf("14336 i %d %d PBC %d pos %1.4E %1.4E \n",
i,izNeigh[i],(int)PBC,pNeigh->pos.x,pNeigh->pos.y);
}
}
// And that's all it wanted.
++pVertex;
};
}
void TriMesh::Suck_Data_from_CUDA( Systdata * pSystdata )
{
this->EzTuning.x[0] = pSystdata->EzTuning;
long izNeigh[128];
long i;
long iVertex;
Vertex * pVertex = X;
for (iVertex = 0; iVertex < numVertices; iVertex++)
{
// Writing on phi,A
pVertex->phi = pSystdata->p_phi[iVertex];
pVertex->A = pSystdata->p_A[iVertex];
pVertex->Adot = pSystdata->p_Adot[iVertex];
pVertex->B = pSystdata->p_B[iVertex];
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// phidot IS MISSING from Vertex class !!!!
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// Can we create graphics directly from Systdata object? Haven't finalised structs yet.
pVertex->Neut.mass = pSystdata->p_nT_neut[iVertex].n*pSystdata->p_area[iVertex];
pVertex->Neut.heat = pVertex->Neut.mass*pSystdata->p_nT_neut[iVertex].T;
pVertex->Neut.mom = pVertex->Neut.mass*pSystdata->p_v_neut[iVertex];
// CAN we do that?
pVertex->Ion.mass = pSystdata->p_nT_ion[iVertex].n*pSystdata->p_area[iVertex];
pVertex->Ion.heat = pVertex->Ion.mass*pSystdata->p_nT_ion[iVertex].T;
pVertex->Ion.mom = pVertex->Ion.mass*pSystdata->p_v_ion[iVertex];
pVertex->Elec.mass = pSystdata->p_nT_elec[iVertex].n*pSystdata->p_area[iVertex];
pVertex->Elec.heat = pVertex->Elec.mass*pSystdata->p_nT_elec[iVertex].T;
pVertex->Elec.mom = pVertex->Elec.mass*pSystdata->p_v_elec[iVertex];
if (iVertex == 13202) {
printf("diff of mass %1.5E \n",
(pVertex->Ion.mass - pVertex->Elec.mass));
};
pVertex->AreaCell = pSystdata->p_area[iVertex];
if (pVertex->AreaCell == 0.0) {
printf(" area=0 %d ",iVertex);
}
pVertex->pos = pSystdata->p_info[iVertex].pos;
++pVertex;
};
}
#endif
| 29.873869 | 130 | 0.6279 | [
"mesh",
"render",
"object"
] |
7aac4325b2666783eb699edffaed9b3ae35eb351 | 1,879 | cpp | C++ | ch10/ex10_14_15_16.cpp | courri/Cpp-Primer | b459698618b876f5d259154f69f81b18ff439aac | [
"CC0-1.0"
] | 2 | 2015-06-11T17:50:41.000Z | 2017-01-23T09:37:56.000Z | ch10/ex10_14_15_16.cpp | courri/Cpp-Primer | b459698618b876f5d259154f69f81b18ff439aac | [
"CC0-1.0"
] | null | null | null | ch10/ex10_14_15_16.cpp | courri/Cpp-Primer | b459698618b876f5d259154f69f81b18ff439aac | [
"CC0-1.0"
] | 1 | 2018-10-23T09:43:12.000Z | 2018-10-23T09:43:12.000Z | //!
//! @author @Yue Wang @shbling @pezy @zzzkl
//! @date 02.12.2014
//!
//! Exercise 10.14:
//! Write a lambda that takes two ints and returns their sum.
//!
//! Exercise 10.15:
//! Write a lambda that captures an int from its enclosing function
//! and takes an int parameter. The lambda should return the sum of
//! the captured int and the int parameter.
//!
//! Exercise 10.16:
//! Write your own version of the biggies function using lambdas.
//!
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
//! from ex 10.9
void elimdups(std::vector<std::string> &vs)
{
std::sort(vs.begin(), vs.end());
auto new_end = std::unique(vs.begin(),vs.end());
vs.erase(new_end, vs.end());
}
void biggies(std::vector<std::string> &vs, std::size_t sz)
{
using std::stable_sort;
using std::string;
using std::find_if;
elimdups(vs);
//! sort by size, but maintain alphabetical order for same size.
stable_sort(vs.begin(), vs.end(),[](string const& lhs, string const& rhs){
return lhs.size() < rhs.size();
});
//! get an iterator to the first one whose size() is >= sz
auto wc = find_if(vs.begin(), vs.end(),[sz](string const& s){
return s.size() > sz;
});
for(auto it = wc; it != vs.cend(); ++it)
std::cout << *it << " ";
}
int main()
{
//! ex10.14
auto add = [](int lhs, int rhs){return lhs+rhs;};
std::cout << "ex10.14: " << add(1,2) << std::endl;
//! ex10.15
int i = 42;
auto lambda = [&i](int num){return i+num;};
std::cout << "ex10.15: " << lambda(99) << std::endl;
//! ex10.16
std::vector<std::string> v
{
"1234","1234","1234","hi~", "alan", "alan"
};
std::cout << "ex10.16: ";
biggies(v,3);
std::cout << std::endl;
return 0;
}
//! output :
//!
//ex10.14: 3
//ex10.15: 141
//ex10.16: 1234 alan
| 22.914634 | 78 | 0.575306 | [
"vector"
] |
7ab1e3645e26c22db24574c3946a2399850d0deb | 16,541 | cc | C++ | src/tracing/traced_proto_unittest.cc | ankit-16/perfetto | 9d372be4d8b1d1dd97452c9646b36d60ecf2487b | [
"Apache-2.0"
] | 3 | 2022-01-27T23:05:58.000Z | 2022-01-28T07:53:34.000Z | src/tracing/traced_proto_unittest.cc | ankit-16/perfetto | 9d372be4d8b1d1dd97452c9646b36d60ecf2487b | [
"Apache-2.0"
] | null | null | null | src/tracing/traced_proto_unittest.cc | ankit-16/perfetto | 9d372be4d8b1d1dd97452c9646b36d60ecf2487b | [
"Apache-2.0"
] | 2 | 2022-03-29T02:58:16.000Z | 2022-03-29T13:19:34.000Z | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "perfetto/tracing/traced_proto.h"
#include "perfetto/test/traced_value_test_support.h"
#include "perfetto/tracing/track_event.h"
#include "protos/perfetto/trace/test_event.gen.h"
#include "protos/perfetto/trace/test_event.pb.h"
#include "protos/perfetto/trace/test_event.pbzero.h"
#include "protos/perfetto/trace/track_event/track_event.gen.h"
#include "protos/perfetto/trace/track_event/track_event.pb.h"
#include "test/gtest_and_gmock.h"
namespace perfetto {
class TracedProtoTest : public ::testing::Test {
public:
TracedProtoTest() : context_(track_event_.get(), &incremental_state_) {}
EventContext& context() { return context_; }
private:
protozero::HeapBuffered<protos::pbzero::TrackEvent> track_event_;
internal::TrackEventIncrementalState incremental_state_;
EventContext context_;
};
using TestPayload = protos::pbzero::TestEvent::TestPayload;
TEST_F(TracedProtoTest, SingleInt_WriteField) {
protozero::HeapBuffered<TestPayload> event;
perfetto::TracedProto<TestPayload> proto = context().Wrap(event.get());
WriteTracedProtoField(proto, TestPayload::kSingleInt, 42);
protos::TestEvent::TestPayload result;
result.ParseFromString(event.SerializeAsString());
EXPECT_TRUE(result.has_single_int());
EXPECT_EQ(result.single_int(), 42);
}
TEST_F(TracedProtoTest, SingleInt_Set) {
protozero::HeapBuffered<TestPayload> event;
perfetto::TracedProto<TestPayload> proto = context().Wrap(event.get());
proto.Set(TestPayload::kSingleInt, 42);
protos::TestEvent::TestPayload result;
result.ParseFromString(event.SerializeAsString());
EXPECT_TRUE(result.has_single_int());
EXPECT_EQ(result.single_int(), 42);
}
TEST_F(TracedProtoTest, RepeatedInt_WriteField) {
protozero::HeapBuffered<TestPayload> event;
perfetto::TracedProto<TestPayload> proto = context().Wrap(event.get());
WriteTracedProtoField(proto, TestPayload::kRepeatedInts,
std::vector<int>{1, 2, 3});
protos::TestEvent::TestPayload result;
result.ParseFromString(event.SerializeAsString());
EXPECT_THAT(result.repeated_ints(), ::testing::ElementsAre(1, 2, 3));
}
TEST_F(TracedProtoTest, RepeatedInt_AppendValue) {
protozero::HeapBuffered<TestPayload> event;
perfetto::TracedProto<TestPayload> proto = context().Wrap(event.get());
proto.AppendValue(TestPayload::kRepeatedInts, 1);
protos::TestEvent::TestPayload result;
result.ParseFromString(event.SerializeAsString());
EXPECT_THAT(result.repeated_ints(), ::testing::ElementsAre(1));
}
TEST_F(TracedProtoTest, RepeatedInt_AppendFrom) {
protozero::HeapBuffered<TestPayload> event;
perfetto::TracedProto<TestPayload> proto = context().Wrap(event.get());
proto.AppendFrom(TestPayload::kRepeatedInts, std::vector<int>{1, 2, 3});
protos::TestEvent::TestPayload result;
result.ParseFromString(event.SerializeAsString());
EXPECT_THAT(result.repeated_ints(), ::testing::ElementsAre(1, 2, 3));
}
TEST_F(TracedProtoTest, SingleString_WriteField) {
protozero::HeapBuffered<TestPayload> event;
perfetto::TracedProto<TestPayload> proto = context().Wrap(event.get());
WriteTracedProtoField(proto, TestPayload::kSingleString, "foo");
protos::TestEvent::TestPayload result;
result.ParseFromString(event.SerializeAsString());
EXPECT_TRUE(result.has_single_string());
EXPECT_EQ(result.single_string(), "foo");
}
TEST_F(TracedProtoTest, SingleString_Set) {
protozero::HeapBuffered<TestPayload> event;
perfetto::TracedProto<TestPayload> proto = context().Wrap(event.get());
proto.Set(TestPayload::kSingleString, "foo");
protos::TestEvent::TestPayload result;
result.ParseFromString(event.SerializeAsString());
EXPECT_TRUE(result.has_single_string());
EXPECT_EQ(result.single_string(), "foo");
}
TEST_F(TracedProtoTest, RepeatedString_WriteField) {
protozero::HeapBuffered<TestPayload> event;
perfetto::TracedProto<TestPayload> proto = context().Wrap(event.get());
WriteTracedProtoField(proto, TestPayload::kStr,
std::vector<std::string>{"foo", "bar"});
protos::TestEvent::TestPayload result;
result.ParseFromString(event.SerializeAsString());
EXPECT_THAT(result.str(), ::testing::ElementsAre("foo", "bar"));
}
TEST_F(TracedProtoTest, RepeatedString_AppendFrom) {
protozero::HeapBuffered<TestPayload> event;
perfetto::TracedProto<TestPayload> proto = context().Wrap(event.get());
proto.AppendFrom(TestPayload::kStr, std::vector<std::string>{"foo", "bar"});
protos::TestEvent::TestPayload result;
result.ParseFromString(event.SerializeAsString());
EXPECT_THAT(result.str(), ::testing::ElementsAre("foo", "bar"));
}
TEST_F(TracedProtoTest, RepeatedString_AppendValue) {
protozero::HeapBuffered<TestPayload> event;
perfetto::TracedProto<TestPayload> proto = context().Wrap(event.get());
proto.AppendValue(TestPayload::kStr, "foo");
protos::TestEvent::TestPayload result;
result.ParseFromString(event.SerializeAsString());
EXPECT_THAT(result.str(), ::testing::ElementsAre("foo"));
}
namespace {
struct Foo {
void WriteIntoTrace(TracedProto<TestPayload> message) const {
message->set_single_int(42);
auto dict = std::move(message).AddDebugAnnotations();
dict.Add("arg", "value");
}
};
struct Bar {};
} // namespace
template <>
struct TraceFormatTraits<Bar> {
static void WriteIntoTrace(
TracedProto<protos::pbzero::TestEvent::TestPayload> message,
const Bar&) {
message->set_single_string("value");
}
};
TEST_F(TracedProtoTest, SingleNestedMessage_Method) {
protozero::HeapBuffered<protos::pbzero::TestEvent> event;
perfetto::TracedProto<protos::pbzero::TestEvent> proto =
context().Wrap(event.get());
WriteTracedProtoField(proto, protos::pbzero::TestEvent::kPayload, Foo());
protos::TestEvent result;
result.ParseFromString(event.SerializeAsString());
EXPECT_EQ(result.payload().single_int(), 42);
}
TEST_F(TracedProtoTest, SingleNestedMessage_TraceFormatTraits) {
protozero::HeapBuffered<protos::pbzero::TestEvent> event;
perfetto::TracedProto<protos::pbzero::TestEvent> proto =
context().Wrap(event.get());
WriteTracedProtoField(proto, protos::pbzero::TestEvent::kPayload, Bar());
protos::TestEvent result;
result.ParseFromString(event.SerializeAsString());
EXPECT_EQ(result.payload().single_string(), "value");
}
TEST_F(TracedProtoTest, SingleNestedMessage_Pointer) {
protozero::HeapBuffered<protos::pbzero::TestEvent> event;
perfetto::TracedProto<protos::pbzero::TestEvent> proto =
context().Wrap(event.get());
Bar bar;
WriteTracedProtoField(proto, protos::pbzero::TestEvent::kPayload, &bar);
protos::TestEvent result;
result.ParseFromString(event.SerializeAsString());
EXPECT_EQ(result.payload().single_string(), "value");
}
TEST_F(TracedProtoTest, SingleNestedMessage_UniquePtr) {
protozero::HeapBuffered<protos::pbzero::TestEvent> event;
perfetto::TracedProto<protos::pbzero::TestEvent> proto =
context().Wrap(event.get());
std::unique_ptr<Bar> bar(new Bar);
WriteTracedProtoField(proto, protos::pbzero::TestEvent::kPayload, bar);
protos::TestEvent result;
result.ParseFromString(event.SerializeAsString());
EXPECT_EQ(result.payload().single_string(), "value");
}
TEST_F(TracedProtoTest, SingleNestedMessage_EmptyUniquePtr) {
protozero::HeapBuffered<protos::pbzero::TestEvent> event;
perfetto::TracedProto<protos::pbzero::TestEvent> proto =
context().Wrap(event.get());
std::unique_ptr<Bar> bar;
WriteTracedProtoField(proto, protos::pbzero::TestEvent::kPayload, bar);
protos::TestEvent result;
result.ParseFromString(event.SerializeAsString());
EXPECT_FALSE(result.payload().has_single_string());
}
TEST_F(TracedProtoTest, SingleNestedMessage_Nullptr) {
protozero::HeapBuffered<protos::pbzero::TestEvent> event;
perfetto::TracedProto<protos::pbzero::TestEvent> proto =
context().Wrap(event.get());
WriteTracedProtoField(proto, protos::pbzero::TestEvent::kPayload, nullptr);
protos::TestEvent result;
result.ParseFromString(event.SerializeAsString());
EXPECT_FALSE(result.payload().has_single_string());
}
TEST_F(TracedProtoTest, SingleNestedMessage_Method_Set) {
protozero::HeapBuffered<protos::pbzero::TestEvent> event;
perfetto::TracedProto<protos::pbzero::TestEvent> proto =
context().Wrap(event.get());
WriteTracedProtoField(proto, protos::pbzero::TestEvent::kPayload, Foo());
protos::TestEvent result;
result.ParseFromString(event.SerializeAsString());
EXPECT_EQ(result.payload().single_int(), 42);
}
TEST_F(TracedProtoTest, SingleNestedMessage_TraceFormatTraits_Set) {
protozero::HeapBuffered<protos::pbzero::TestEvent> event;
perfetto::TracedProto<protos::pbzero::TestEvent> proto =
context().Wrap(event.get());
proto.Set(protos::pbzero::TestEvent::kPayload, Bar());
protos::TestEvent result;
result.ParseFromString(event.SerializeAsString());
EXPECT_EQ(result.payload().single_string(), "value");
}
TEST_F(TracedProtoTest, SingleNestedMessage_Pointer_Set) {
protozero::HeapBuffered<protos::pbzero::TestEvent> event;
perfetto::TracedProto<protos::pbzero::TestEvent> proto =
context().Wrap(event.get());
Bar bar;
proto.Set(protos::pbzero::TestEvent::kPayload, &bar);
protos::TestEvent result;
result.ParseFromString(event.SerializeAsString());
EXPECT_EQ(result.payload().single_string(), "value");
}
TEST_F(TracedProtoTest, SingleNestedMessage_UniquePtr_Set) {
protozero::HeapBuffered<protos::pbzero::TestEvent> event;
perfetto::TracedProto<protos::pbzero::TestEvent> proto =
context().Wrap(event.get());
std::unique_ptr<Bar> bar(new Bar);
proto.Set(protos::pbzero::TestEvent::kPayload, bar);
protos::TestEvent result;
result.ParseFromString(event.SerializeAsString());
EXPECT_EQ(result.payload().single_string(), "value");
}
TEST_F(TracedProtoTest, SingleNestedMessage_EmptyUniquePtr_Set) {
protozero::HeapBuffered<protos::pbzero::TestEvent> event;
perfetto::TracedProto<protos::pbzero::TestEvent> proto =
context().Wrap(event.get());
std::unique_ptr<Bar> bar;
proto.Set(protos::pbzero::TestEvent::kPayload, bar);
protos::TestEvent result;
result.ParseFromString(event.SerializeAsString());
EXPECT_FALSE(result.payload().has_single_string());
}
TEST_F(TracedProtoTest, SingleNestedMessage_Nullptr_Set) {
protozero::HeapBuffered<protos::pbzero::TestEvent> event;
perfetto::TracedProto<protos::pbzero::TestEvent> proto =
context().Wrap(event.get());
proto.Set(protos::pbzero::TestEvent::kPayload, nullptr);
protos::TestEvent result;
result.ParseFromString(event.SerializeAsString());
EXPECT_FALSE(result.payload().has_single_string());
}
TEST_F(TracedProtoTest, RepeatedNestedMessage_Method) {
protozero::HeapBuffered<TestPayload> event;
perfetto::TracedProto<TestPayload> proto = context().Wrap(event.get());
WriteTracedProtoField(proto, TestPayload::kNested,
std::vector<Foo>{Foo(), Foo()});
protos::TestEvent::TestPayload result;
result.ParseFromString(event.SerializeAsString());
EXPECT_EQ(result.nested_size(), 2);
EXPECT_EQ(result.nested(0).single_int(), 42);
EXPECT_EQ(result.nested(1).single_int(), 42);
}
TEST_F(TracedProtoTest, RepeatedNestedMessage_TraceFormatTraits) {
protozero::HeapBuffered<TestPayload> event;
perfetto::TracedProto<TestPayload> proto = context().Wrap(event.get());
WriteTracedProtoField(proto, TestPayload::kNested,
std::vector<Bar>{Bar(), Bar()});
protos::TestEvent::TestPayload result;
result.ParseFromString(event.SerializeAsString());
EXPECT_EQ(result.nested_size(), 2);
EXPECT_EQ(result.nested(0).single_string(), "value");
EXPECT_EQ(result.nested(1).single_string(), "value");
}
TEST_F(TracedProtoTest, RepeatedNestedMessage_Pointer) {
protozero::HeapBuffered<TestPayload> event;
perfetto::TracedProto<TestPayload> proto = context().Wrap(event.get());
Bar bar;
std::vector<Bar*> bars;
bars.push_back(&bar);
bars.push_back(nullptr);
WriteTracedProtoField(proto, TestPayload::kNested, bars);
protos::TestEvent::TestPayload result;
result.ParseFromString(event.SerializeAsString());
EXPECT_EQ(result.nested_size(), 2);
EXPECT_EQ(result.nested(0).single_string(), "value");
EXPECT_FALSE(result.nested(1).has_single_string());
}
TEST_F(TracedProtoTest, RepeatedNestedMessage_Method_AppendValue) {
protozero::HeapBuffered<TestPayload> event;
perfetto::TracedProto<TestPayload> proto = context().Wrap(event.get());
proto.AppendValue(TestPayload::kNested, Foo());
protos::TestEvent::TestPayload result;
result.ParseFromString(event.SerializeAsString());
EXPECT_EQ(result.nested_size(), 1);
EXPECT_EQ(result.nested(0).single_int(), 42);
}
TEST_F(TracedProtoTest, RepeatedNestedMessage_TraceFormatTraits_AppendValue) {
protozero::HeapBuffered<TestPayload> event;
perfetto::TracedProto<TestPayload> proto = context().Wrap(event.get());
proto.AppendValue(TestPayload::kNested, Bar());
protos::TestEvent::TestPayload result;
result.ParseFromString(event.SerializeAsString());
EXPECT_EQ(result.nested_size(), 1);
EXPECT_EQ(result.nested(0).single_string(), "value");
}
TEST_F(TracedProtoTest, RepeatedNestedMessage_Pointer_AppendValue) {
protozero::HeapBuffered<TestPayload> event;
perfetto::TracedProto<TestPayload> proto = context().Wrap(event.get());
Bar bar;
proto.AppendValue(TestPayload::kNested, &bar);
proto.AppendValue(TestPayload::kNested, nullptr);
protos::TestEvent::TestPayload result;
result.ParseFromString(event.SerializeAsString());
EXPECT_EQ(result.nested_size(), 2);
EXPECT_EQ(result.nested(0).single_string(), "value");
EXPECT_FALSE(result.nested(1).has_single_string());
}
TEST_F(TracedProtoTest, RepeatedNestedMessage_Method_AppendFrom) {
protozero::HeapBuffered<TestPayload> event;
perfetto::TracedProto<TestPayload> proto = context().Wrap(event.get());
proto.AppendFrom(TestPayload::kNested, std::vector<Foo>{Foo(), Foo()});
protos::TestEvent::TestPayload result;
result.ParseFromString(event.SerializeAsString());
EXPECT_EQ(result.nested_size(), 2);
EXPECT_EQ(result.nested(0).single_int(), 42);
EXPECT_EQ(result.nested(1).single_int(), 42);
}
TEST_F(TracedProtoTest, RepeatedNestedMessage_TraceFormatTraits_AppendFrom) {
protozero::HeapBuffered<TestPayload> event;
perfetto::TracedProto<TestPayload> proto = context().Wrap(event.get());
proto.AppendFrom(TestPayload::kNested, std::vector<Bar>{Bar(), Bar()});
protos::TestEvent::TestPayload result;
result.ParseFromString(event.SerializeAsString());
EXPECT_EQ(result.nested_size(), 2);
EXPECT_EQ(result.nested(0).single_string(), "value");
EXPECT_EQ(result.nested(1).single_string(), "value");
}
TEST_F(TracedProtoTest, RepeatedNestedMessage_Pointer_AppendFrom) {
protozero::HeapBuffered<TestPayload> event;
perfetto::TracedProto<TestPayload> proto = context().Wrap(event.get());
Bar bar;
std::vector<Bar*> bars;
bars.push_back(&bar);
bars.push_back(nullptr);
proto.AppendFrom(TestPayload::kNested, bars);
protos::TestEvent::TestPayload result;
result.ParseFromString(event.SerializeAsString());
EXPECT_EQ(result.nested_size(), 2);
EXPECT_EQ(result.nested(0).single_string(), "value");
EXPECT_FALSE(result.nested(1).has_single_string());
}
TEST_F(TracedProtoTest, WriteDebugAnnotations) {
protozero::HeapBuffered<protos::pbzero::TestEvent> event;
perfetto::TracedProto<protos::pbzero::TestEvent> proto =
context().Wrap(event.get());
WriteTracedProtoField(proto, protos::pbzero::TestEvent::kPayload, Foo());
protos::TestEvent result;
result.ParseFromString(event.SerializeAsString());
protos::DebugAnnotation dict;
for (const auto& annotation : result.payload().debug_annotations()) {
*dict.add_dict_entries() = annotation;
}
EXPECT_EQ(internal::DebugAnnotationToString(dict.SerializeAsString()),
"{arg:value}");
}
} // namespace perfetto
| 36.839644 | 78 | 0.751829 | [
"vector"
] |
7abaa1b8461123ed61bde15ab38843e4669d7cb0 | 20,754 | cpp | C++ | src/tests/basic-tests.cpp | lanamineh/qsl | 7e339d2345297709ef817d78ae3a52a33b1c8614 | [
"Apache-2.0"
] | null | null | null | src/tests/basic-tests.cpp | lanamineh/qsl | 7e339d2345297709ef817d78ae3a52a33b1c8614 | [
"Apache-2.0"
] | null | null | null | src/tests/basic-tests.cpp | lanamineh/qsl | 7e339d2345297709ef817d78ae3a52a33b1c8614 | [
"Apache-2.0"
] | null | null | null | /*
* Authors: Lana Mineh and John Scott
* Copyright 2021 Phasecraft Ltd. and John Scott
*
* 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.
*
*/
/**
* \file basic-tests.cpp
* \brief Contains catch testing
*/
// This tells Catch to provide a main() - only do this in one cpp file
#define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
#include <qsl/utils/random.hpp>
#include <qsl/utils/quantum.hpp>
#include <qsl/utils/misc.hpp>
#include <qsl/qubits.hpp>
#include <qsl/verify.hpp>
#include <sstream>
TEST_CASE("Check the measureOut function", "[resize]")
{
using Sim = qsl::Qubits<qsl::Type::Resize, double>;
// Make a simulator in computational basis state
Sim q{ 4 };
unsigned outcome = q.measureOut(0);
REQUIRE(outcome == 0);
REQUIRE(q.getNumQubits() == 3);
std::vector<qsl::complex<double>> state = q.getState();
REQUIRE(state.size() == (1 << 3));
REQUIRE(qsl::norm(state) - 1 < 1e-10); // Check correct norm
// Check that measuring out a Bell pair works
Sim q1{ 2 };
const double sqrt2 = std::sqrt(2);
q1.setState({{1/sqrt2,0}, {0,0}, {0,0}, {1/sqrt2,0}}); // Set Bell pair
outcome = q1.measureOut(1); // Measure out qubit 1
state = q1.getState();
REQUIRE(state.size() == 2);
std::vector<qsl::complex<double>> state_correct;
if (outcome == 0) {
state_correct.push_back({1,0});
state_correct.push_back({0,0});
} else {
state_correct.push_back({0,0});
state_correct.push_back({1,0});
}
REQUIRE(distance(state_correct, state) < 1e-10);
// Check that you can add a qubit
q1.addQubit();
REQUIRE(q1.getNumQubits() == 2);
state = q1.getState();
// The correct state has new zeroes at the end
state_correct.push_back({0,0});
state_correct.push_back({0,0});
REQUIRE(distance(state_correct, state) < 1e-10);
REQUIRE(qsl::norm(state) - 1 < 1e-10); // Check correct norm
}
TEST_CASE("Test choose function", "[misc-utils]")
{
REQUIRE(qsl::choose(1,1) == 1);
REQUIRE(qsl::choose(4,3) == 4);
REQUIRE(qsl::choose(10,3) == 120);
REQUIRE(qsl::choose(10,10) == 1);
}
TEST_CASE ("Test overloaded vector substraction function", "[misc-utils]")
{
const unsigned num_qubits{ 5 };
const std::vector<qsl::complex<double>> state1
= qsl::makeRandomState<double>(num_qubits);
const std::vector<qsl::complex<double>> state2
= qsl::makeRandomState<double>(num_qubits + 1);
// Cannot subtract vectors of different sizes
CHECK_THROWS(state1 - state2);
}
TEST_CASE ("Test the convertState function", "[misc-utils]")
{
const unsigned num_qubits{ 5 };
// Make a random state of doubles
const std::vector<qsl::complex<double>> state_double
= qsl::makeRandomState<double>(num_qubits);
// Convert it to floats
const std::vector<qsl::complex<float>> state_float
= qsl::convertState<float>(state_double);
// Check the two states are equal by verifying all
double val = 0;
for (std::size_t n = 0; n < state_float.size(); n++) {
val += std::abs(state_double[n].real - state_float[n].real);
val += std::abs(state_double[n].imag - state_float[n].imag);
}
// What is a reasonable number to put here?
REQUIRE(val < 1e-5);
}
TEST_CASE ("Test the innerProduct function", "[quantum-utils]")
{
const std::vector<qsl::complex<double>> a{ {1,1.2}, {1.2,1}, {1,1.5} };
const std::vector<qsl::complex<double>> b{ {1,0}, {0,-1}, {-1,0} };
const std::vector<qsl::complex<double>> c{
{1.2,0}, {1.2,-2.1}, {1.3,2}, {0,0} };
// Check that inner product throws exception for different sized vectors
CHECK_THROWS(innerProduct(a,c));
}
TEST_CASE ("Test the checkStateSize function", "[quantum-utils]")
{
// Not a valid state size, should throw exception
const std::vector<qsl::complex<double>> pretend_state{ {1,0}, {0,1}, {1,1} };
CHECK_THROWS(checkStateSize(pretend_state));
// Check that the function returns the correct state size
const std::vector<qsl::complex<double>> state{
{1,0}, {0,1}, {1,0}, {0,1} };
REQUIRE( checkStateSize(state) == 2 );
}
TEST_CASE( "Test Fubini Study distance", "[quantum-utils]" )
{
std::vector<qsl::complex<double>> a{ {1,0}, {0,1}, {1,1} };
std::vector<qsl::complex<double>> double_a{ {2,0}, {0,2}, {2,2} };
std::vector<qsl::complex<double>> b{ {1.3,2}, {1,1.3}, {1.5,0.2} };
std::vector<qsl::complex<double>> double_b{ {2.6,4}, {2,2.6}, {3,0.4} };
// Test that distance between equal and scaled vectors is zero
REQUIRE( fubiniStudy(a,a) < 1e-13);
REQUIRE( fubiniStudy(double_a,a) < 1e-13);
double distance_a_b = fubiniStudy(a,b);
double scaled_distance_a_b = fubiniStudy(a,double_b);
REQUIRE( std::abs(distance_a_b - scaled_distance_a_b) < 1e-13);
}
TEST_CASE( "Qubits<Default> basic functions", "[state-functions]" )
{
using Sim = qsl::Qubits<qsl::Type::Default, double>;
const unsigned num_qubits{ 3 };
Sim q{ num_qubits };
// Set q to a random state
const std::vector<qsl::complex<double>> state
= qsl::makeRandomState<double>(num_qubits + 1);
// Can't assign state vector with a different number of qubits
CHECK_THROWS( q.setState(state) );
// Check that the basis states work
std::size_t index = 4; // Should choose a random value
q.setBasisState(index);
std::vector<qsl::complex<double>> basis_state = q.getState();
// Check that the right element is 1
REQUIRE(basis_state[index].real == 1);
REQUIRE(std::abs(norm(basis_state) - 1) < 1e-15);
}
TEST_CASE( "Qubits<Omp> basic functions", "[state-functions]" )
{
using Sim = qsl::Qubits<qsl::Type::Omp, double>;
const unsigned num_qubits{ 3 };
Sim q{ num_qubits };
// Set q to a random state
const std::vector<qsl::complex<double>> state
= qsl::makeRandomState<double>(num_qubits + 1);
// Can't assign state vector with a different number of qubits
CHECK_THROWS( q.setState(state) );
// Check that the basis states work
std::size_t index = 4; // Should choose a random value
q.setBasisState(index);
std::vector<qsl::complex<double>> basis_state = q.getState();
// Check that the right element is 1
REQUIRE(basis_state[index].real == 1);
REQUIRE(std::abs(norm(basis_state) - 1) < 1e-15);
}
TEST_CASE( "Qubits<Resize> basic functions", "[state-functions]" )
{
using Sim = qsl::Qubits<qsl::Type::Resize, double>;
const unsigned num_qubits{ 3 };
Sim q{ num_qubits };
// Set q to a random state
const std::vector<qsl::complex<double>> state
= qsl::makeRandomState<double>(num_qubits + 1);
// Can't assign state vector with a different number of qubits
CHECK_THROWS( q.setState(state) );
// Check that the basis states work
std::size_t index = 4; // Should choose a random value
q.setBasisState(index);
std::vector<qsl::complex<double>> basis_state = q.getState();
// Check that the right element is 1
REQUIRE(basis_state[index].real == 1);
REQUIRE(std::abs(norm(basis_state) - 1) < 1e-15);
}
TEST_CASE( "Qubits<NP> basic functions", "[state-functions]" )
{
using Sim = qsl::Qubits<qsl::Type::NP, double>;
// Try to make an object with more ones than qubits
CHECK_THROWS(Sim(4,5));
const unsigned num_qubits{ 4 };
const unsigned num_ones{ 2 };
Sim q{ num_qubits };
// Can't set number of ones more than number of qubits
CHECK_THROWS(q.setNumOnes(num_qubits + 1));
// Check that the returned number of ones is the same as that set
q.setNumOnes(num_ones);
REQUIRE(q.getNumOnes() == num_ones);
// Set q to a random state
const std::vector<qsl::complex<double>> state
= qsl::makeRandomNPState<double>(num_qubits + 1);
// Can't assign state vector with a different number of qubits
CHECK_THROWS( q.setState(state) );
// Check that the basis states work
std::size_t index = 4; // Should choose a random value
q.setBasisState(index);
std::vector<qsl::complex<double>> basis_state = q.getState();
// Check that the right element is 1
REQUIRE(basis_state[index].real == 1);
REQUIRE(std::abs(norm(basis_state) - 1) < 1e-15);
}
TEST_CASE( "Qubits<Default> object constructors", "[constructors]" )
{
using Sim = qsl::Qubits<qsl::Type::Default, double>;
const unsigned num_qubits{ 5 };
Sim q{ num_qubits };
// Set q to a random state
const std::vector<qsl::complex<double>> state
= qsl::makeRandomState<double>(num_qubits);
q.setState(state);
// Construct another object using the copy constructor
Sim q_copy{ q };
// Check that the other properties are also the same
REQUIRE(q.getNumQubits() == q_copy.getNumQubits());
// Check that both objects have the same internal state
double distance = qsl::distance(q.getState(), q_copy.getState());
REQUIRE(std::abs(distance) < 1e-10);
// Construct another object using initialisation from state vector
Sim q_from_state{ state };
// Check that both objects have the same internal state
distance = qsl::distance(q.getState(), q_from_state.getState());
REQUIRE(std::abs(distance) < 1e-10);
// Check that assignment works
Sim q_new{ num_qubits };
q_new = q; // Perform the test
distance = qsl::distance(q.getState(), q_new.getState());
REQUIRE(std::abs(distance) < 1e-10);
// Check that assignment fails for wrong number of qubits
Sim q_wrong{ num_qubits + 1};
CHECK_THROWS(q_wrong = q); // Perform the test
}
TEST_CASE( "Qubits<OMP> object constructors", "[constructors]" )
{
using Sim = qsl::Qubits<qsl::Type::Omp, double>;
const unsigned num_qubits{ 5 };
Sim q{ num_qubits };
// Set q to a random state
const std::vector<qsl::complex<double>> state
= qsl::makeRandomState<double>(num_qubits);
q.setState(state);
// Construct another object using the copy constructor
Sim q_copy{ q };
// Check that the other properties are also the same
REQUIRE(q.getNumQubits() == q_copy.getNumQubits());
// Check that both objects have the same internal state
double distance = qsl::distance(q.getState(), q_copy.getState());
REQUIRE(std::abs(distance) < 1e-10);
// Construct another object using initialisation from state vector
Sim q_from_state{ state };
// Check that both objects have the same internal state
distance = qsl::distance(q.getState(), q_from_state.getState());
REQUIRE(std::abs(distance) < 1e-10);
// Check that assignment works
Sim q_new{ num_qubits };
q_new = q; // Perform the test
distance = qsl::distance(q.getState(), q_new.getState());
REQUIRE(std::abs(distance) < 1e-10);
// Check that assignment fails for wrong number of qubits
Sim q_wrong{ num_qubits + 1};
CHECK_THROWS(q_wrong = q); // Perform the test
}
TEST_CASE( "Qubits<NP> object constructors", "[constructors]" )
{
using Sim = qsl::Qubits<qsl::Type::NP, double>;
const unsigned num_qubits{ 5 };
Sim q{ num_qubits };
// Set q to a random state (number preserving
const std::vector<qsl::complex<double>> state
= qsl::makeRandomNPState<double>(num_qubits);
q.setState(state);
// Construct another object using the copy constructor
Sim q_copy{ q };
// Check that the other properties are also the same
REQUIRE(q.getNumQubits() == q_copy.getNumQubits());
// Check that both objects have the same internal state
double distance = qsl::distance(q.getState(), q_copy.getState());
REQUIRE(std::abs(distance) < 1e-10);
// Construct another object using initialisation from state vector
Sim q_from_state{ state };
// Check that both objects have the same internal state
distance = qsl::distance(q.getState(), q_from_state.getState());
REQUIRE(std::abs(distance) < 1e-10);
// Check that assignment works
Sim q_new{ num_qubits };
q_new = q; // Perform the test
distance = qsl::distance(q.getState(), q_new.getState());
REQUIRE(std::abs(distance) < 1e-10);
// Check that assignment fails for wrong number of qubits
Sim q_wrong{ num_qubits + 1};
CHECK_THROWS(q_wrong = q); // Perform the test
}
/// NOT TESTING ANYTHING YET
TEST_CASE( "Qubits<Default> against Qubits<OMP>", "[compare]" )
{
using Sim1 = qsl::Qubits<qsl::Type::Default, double>;
using Sim2 = qsl::Qubits<qsl::Type::Omp, double>;
qsl::Verify<Sim1, Sim2, qsl::DefaultStateGen<double>,
qsl::MeasureChecker,
qsl::PostselectChecker,
qsl::SampleChecker,
qsl::SampleAllChecker,
qsl::ProbChecker,
qsl::DefaultGateChecker> verify;
verify.configureState(8);
verify.configureChecker<qsl::SampleAllChecker>(1000000, 0.99);
//verify.checkAll();
auto prob_result = verify.check<qsl::ProbChecker>();
// Check that the probabilities are equal
REQUIRE(std::abs(prob_result.mean<double>(1)) < 1e-10);
REQUIRE(prob_result.variance<double>(1) < 1e-10);
REQUIRE(std::abs(prob_result.mean<double>(2)) < 1e-10);
REQUIRE(prob_result.variance<double>(2) < 1e-10);
// Check the measurement
auto measure_result = verify.check<qsl::MeasureChecker>();
// Check that all the intervals overlap
REQUIRE(std::abs(measure_result.mean<double>(1) - 1) < 1e-10);
REQUIRE(measure_result.variance<double>(1) < 1e-10);
auto postselect_result = verify.check<qsl::PostselectChecker>();
// Check that all the probability differences are zero for both outcomes
REQUIRE(std::abs(postselect_result.mean<double>(1)) < 1e-10);
REQUIRE(postselect_result.variance<double>(1) < 1e-10);
REQUIRE(std::abs(postselect_result.mean<double>(2)) < 1e-10);
REQUIRE(postselect_result.variance<double>(2) < 1e-10);
// Check that all the state distances are zero for both outcomes
REQUIRE(std::abs(postselect_result.mean<double>(3)) < 1e-7);
REQUIRE(postselect_result.variance<double>(3) < 1e-7);
REQUIRE(std::abs(postselect_result.mean<double>(4)) < 1e-7);
REQUIRE(postselect_result.variance<double>(4) < 1e-7);
auto sample_result = verify.check<qsl::SampleChecker>();
// Check that all the confidence intervals overlap
REQUIRE(std::abs(sample_result.mean<double>(1) - 1) < 1e-10);
auto sample_all_result = verify.check<qsl::SampleAllChecker>();
// Check that all the confidence intervals overlap
REQUIRE(std::abs(sample_all_result.overlap_rate - 1) < 1e-10);
// Check the mean relative error is less than 15%
REQUIRE(std::abs(sample_all_result.mean_relative_error) < 0.15);
auto gate_result = verify.check<qsl::DefaultGateChecker>();
for (const auto & [gate,table] : gate_result) {
// Check that all the distances are zero
REQUIRE(std::abs(table.mean<double>("distance")) < 1e-9);
REQUIRE(std::abs(table.variance<double>("distance")) < 1e-9);
}
}
TEST_CASE( "Qubits<Default> against Qubits<NP>", "[compare]" )
{
using Sim1 = qsl::Qubits<qsl::Type::Default, double>;
using Sim2 = qsl::Qubits<qsl::Type::NP, double>;
qsl::Verify<Sim1, Sim2, qsl::NPStateGen<double>,
qsl::MeasureChecker,
qsl::PostselectChecker,
qsl::SampleChecker,
qsl::SampleAllChecker,
qsl::ProbChecker,
qsl::NPGateChecker> verify;
verify.configureState(8, 5); // Pass number of ones as second argument
verify.configureChecker<qsl::SampleAllChecker>(1000000, 0.99);
//verify.checkAll();
// Check the measurement
auto measure_result = verify.check<qsl::MeasureChecker>();
// Check that all the intervals overlap
REQUIRE(std::abs(measure_result.mean<double>(1) - 1) < 1e-10);
REQUIRE(measure_result.variance<double>(1) < 1e-10);
auto postselect_result = verify.check<qsl::PostselectChecker>();
// Check that all the probability differences are zero for both outcomes
REQUIRE(std::abs(postselect_result.mean<double>(1)) < 1e-10);
REQUIRE(postselect_result.variance<double>(1) < 1e-10);
REQUIRE(std::abs(postselect_result.mean<double>(2)) < 1e-10);
REQUIRE(postselect_result.variance<double>(2) < 1e-10);
// Check that all the state distances are zero for both outcomes
REQUIRE(std::abs(postselect_result.mean<double>(3)) < 1e-10);
REQUIRE(postselect_result.variance<double>(3) < 1e-10);
REQUIRE(std::abs(postselect_result.mean<double>(4)) < 1e-10);
REQUIRE(postselect_result.variance<double>(4) < 1e-10);
auto sample_result = verify.check<qsl::SampleChecker>();
// Check that all the confidence intervals overlap
REQUIRE(std::abs(sample_result.mean<double>(1) - 1) < 1e-10);
auto sample_all_result = verify.check<qsl::SampleAllChecker>();
// Check that all the confidence intervals overlap
REQUIRE(std::abs(sample_all_result.overlap_rate - 1) < 1e-10);
// Check the mean relative error is less than 15%
REQUIRE(std::abs(sample_all_result.mean_relative_error) < 0.15);
auto prob_result = verify.check<qsl::ProbChecker>();
// Check that the probabilities are equal
REQUIRE(std::abs(prob_result.mean<double>(1)) < 1e-10);
REQUIRE(prob_result.variance<double>(1) < 1e-10);
REQUIRE(std::abs(prob_result.mean<double>(2)) < 1e-10);
REQUIRE(prob_result.variance<double>(2) < 1e-10);
auto gate_result = verify.check<qsl::NPGateChecker>();
for (const auto & [gate,table] : gate_result) {
// Check that all the distances are zero
REQUIRE(std::abs(table.mean<double>("distance")) < 1e-9);
REQUIRE(std::abs(table.variance<double>("distance")) < 1e-9);
}
}
TEST_CASE( "Qubits<Default> against Qubits<Resize>", "[compare]" )
{
using Sim1 = qsl::Qubits<qsl::Type::Default, double>;
using Sim2 = qsl::Qubits<qsl::Type::Resize, double>;
qsl::Verify<Sim1, Sim2, qsl::DefaultStateGen<double>,
qsl::MeasureChecker,
qsl::PostselectChecker,
qsl::SampleChecker,
qsl::SampleAllChecker,
qsl::ProbChecker,
qsl::DefaultGateChecker> verify;
verify.configureState(8);
verify.configureChecker<qsl::SampleAllChecker>(1000000, 0.99);
//verify.checkAll();
// Check the measurement
auto measure_result = verify.check<qsl::MeasureChecker>();
// Check that all the intervals overlap
REQUIRE(std::abs(measure_result.mean<double>(1) - 1) < 1e-10);
REQUIRE(measure_result.variance<double>(1) < 1e-10);
auto postselect_result = verify.check<qsl::PostselectChecker>();
// Check that all the probability differences are zero for both outcomes
REQUIRE(std::abs(postselect_result.mean<double>(1)) < 1e-10);
REQUIRE(postselect_result.variance<double>(1) < 1e-10);
REQUIRE(std::abs(postselect_result.mean<double>(2)) < 1e-10);
REQUIRE(postselect_result.variance<double>(2) < 1e-10);
// Check that all the state distances are zero for both outcomes
REQUIRE(std::abs(postselect_result.mean<double>(3)) < 1e-10);
REQUIRE(postselect_result.variance<double>(3) < 1e-10);
REQUIRE(std::abs(postselect_result.mean<double>(4)) < 1e-10);
REQUIRE(postselect_result.variance<double>(4) < 1e-10);
auto sample_result = verify.check<qsl::SampleChecker>();
// Check that all the confidence intervals overlap
REQUIRE(std::abs(sample_result.mean<double>(1) - 1) < 1e-10);
auto sample_all_result = verify.check<qsl::SampleAllChecker>();
// Check that all the confidence intervals overlap
REQUIRE(std::abs(sample_all_result.overlap_rate - 1) < 1e-10);
// Check the mean relative error is less than 15%
REQUIRE(std::abs(sample_all_result.mean_relative_error) < 0.15);
auto prob_result = verify.check<qsl::ProbChecker>();
// Check that the probabilities are equal
REQUIRE(std::abs(prob_result.mean<double>(1)) < 1e-10);
REQUIRE(prob_result.variance<double>(1) < 1e-10);
REQUIRE(std::abs(prob_result.mean<double>(2)) < 1e-10);
REQUIRE(prob_result.variance<double>(2) < 1e-10);
auto gate_result = verify.check<qsl::DefaultGateChecker>();
for (const auto & [gate,table] : gate_result) {
// Check that all the distances are zero
REQUIRE(std::abs(table.mean<double>("distance")) < 1e-9);
REQUIRE(std::abs(table.variance<double>("distance")) < 1e-9);
}
}
| 35.598628 | 81 | 0.670184 | [
"object",
"vector"
] |
7ac914ecf3545f4bd0fee5aee3caebcf1073d878 | 165,664 | hpp | C++ | BECTI_RHS_USA_RUSA.Takistan/Rsc/Dialogs.hpp | RSpeekenbrink/ArmA-3-BECTI | 29650d3937150443ff9c7e639c7d44770254d399 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1 | 2021-08-01T16:33:15.000Z | 2021-08-01T16:33:15.000Z | BECTI_RHS_USA_RUSA.Takistan/Rsc/Dialogs.hpp | RSpeekenbrink/ArmA-3-BECTI | 29650d3937150443ff9c7e639c7d44770254d399 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 18 | 2017-03-21T09:52:50.000Z | 2021-08-31T22:35:37.000Z | BECTI_RHS_USA_RUSA.Tanoa/Rsc/Dialogs.hpp | RSpeekenbrink/ArmA-3-BECTI | 29650d3937150443ff9c7e639c7d44770254d399 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 5 | 2017-06-02T07:42:39.000Z | 2021-08-30T16:15:55.000Z | #include "Styles.hpp"
class CTI_RscBuildMenu {
movingEnable = 0;
idd = 100000;
onLoad = "uiNamespace setVariable ['cti_dialog_ui_buildmenu', _this select 0];['onLoad'] execVM 'Client\Events\Events_UI_BuildMenu.sqf'";
onUnload = "uiNamespace setVariable ['cti_dialog_ui_buildmenu', nil]; ['onUnload'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_BuildMenu.sqf'";
class controlsBackground {
class CTI_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.21)";
y = "SafeZoneY + (SafezoneH * 0.175)";
w = "SafeZoneW * 0.615";
h = "SafeZoneH * 0.6825";
colorBackground[] = {0, 0, 0, 0.7};
moving = 1;
};
class CTI_Background_Header : CTI_Background {
x = "SafeZoneX + (SafeZoneW * 0.21)";
y = "SafeZoneY + (SafezoneH * 0.175)";
w = "SafeZoneW * 0.615";
h = "SafeZoneH * 0.05"; //0.06 stock
colorBackground[] = {0, 0, 0, 0.4};
};
class CTI_Menu_Title : RscText {
style = ST_LEFT;
x = "SafeZoneX + (SafeZoneW * 0.23)";
y = "SafeZoneY + (SafezoneH * 0.180)";
w = "SafeZoneW * 0.595";
h = "SafeZoneH * 0.037";
text = "Building Construction";
colorText[] = {0.258823529, 0.713725490, 1, 1};
sizeEx = "( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_BuildingListFrame : RscFrame {
x = "SafeZoneX + (SafeZoneW * 0.225)";
y = "SafeZoneY + (SafezoneH * 0.4475)";
w = "SafeZoneW * 0.280";
h = "SafeZoneH * 0.34";
};
class CTI_Menu_DefenseListFrame : CTI_Menu_BuildingListFrame {
x = "SafeZoneX + (SafeZoneW * 0.535)";
};
class CTI_Menu_Info : CTI_Menu_BuildingListFrame {
y = "SafeZoneY + (SafezoneH * 0.235)";
h = "SafeZoneH * 0.0925";
};
class CTI_Menu_Info_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.225)";
y = "SafeZoneY + (SafezoneH * 0.235)";
w = "SafeZoneW * 0.280";
h = "SafeZoneH * 0.0925";
colorBackground[] = {0.5, 0.5, 0.5, 0.25};
};
};
class controls {
class CTI_Menu_Control_Undo : RscButton {
idc = 100001;
x = "SafeZoneX + (SafeZoneW * 0.225)";
y = "SafeZoneY + (SafeZoneH * 0.8025)";
w = "SafeZoneW * 0.280";
h = "SafeZoneH * 0.04";
text = "Undo Structure";
action = "['onUndoStructure'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_BuildMenu.sqf'";
};
class CTI_Menu_Control_UndoDefense : CTI_Menu_Control_Undo {
idc = 100010;
x = "SafeZoneX + (SafeZoneW * 0.535)";
text = "Undo Defense";
action = "['onUndoDefense'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_BuildMenu.sqf'";
};
class CTI_Menu_Control_BuildStructure : CTI_Menu_Control_Undo {
idc = 100002;
y = "SafeZoneY + (SafeZoneH * 0.3925)";
text = "Build Structure";
action = "['onBuildStructure', lnbCurSelRow 100006] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_BuildMenu.sqf'";
};
class CTI_Menu_Control_AutoAlign : CTI_Menu_Control_Undo {
idc = 100003;
x = "SafeZoneX + (SafeZoneW * 0.6775)";
y = "SafeZoneY + (SafeZoneH * 0.34)";
w = "SafeZoneW * 0.1375";
text = "";
action = "['onAutoAlign'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_BuildMenu.sqf'";
};
class CTI_Menu_Control_AutoManning : CTI_Menu_Control_AutoAlign {
idc = 100011;
x = "SafeZoneX + (SafeZoneW * 0.535)";
text = "";
action = "['onAutoManning'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_BuildMenu.sqf'";
};
class CTI_Menu_Control_BuildDefense : CTI_Menu_Control_Undo {
idc = 100004;
x = "SafeZoneX + (SafeZoneW * 0.535)";
y = "SafeZoneY + (SafeZoneH * 0.3925)";
text = "Build Defense";
action = "['onBuildDefense', lnbCurSelRow 100007] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_BuildMenu.sqf'";
};
class CTI_Menu_Control_AddWorker : CTI_Menu_Control_Undo {
idc = 100005;
y = "SafeZoneY + (SafeZoneH * 0.34)";
text = "Add Worker";
action = "['onAddWorker'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_BuildMenu.sqf'";
};
class CTI_Menu_Control_BuildingList : RscListNBox {
idc = 100006;
x = "SafeZoneX + (SafeZoneW * 0.225)";
y = "SafeZoneY + (SafezoneH * 0.4475)";
w = "SafeZoneW * 0.280";
h = "SafeZoneH * 0.34";
rowHeight = "1.3 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
sizeEx = "0.78 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
colorText[] = {1,1,1,1};
colorBackground[] = {0,0,0,0};
itemBackground[] = {1,1,1,0.1};
// columns[] = {0.001, 0.26};
columns[] = {0.001, 0.18};
onLBDblClick = "['onBuildStructure', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_BuildMenu.sqf'";
};
class CTI_Menu_Control_DefenseList : CTI_Menu_Control_BuildingList {
idc = 100007;
x = "SafeZoneX + (SafeZoneW * 0.535)";
onLBDblClick = "['onBuildDefense', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_BuildMenu.sqf'";
};
class CTI_Menu_Control_Info : RscStructuredText {
idc = 100008;
x = "SafeZoneX + (SafeZoneW * 0.225)";
y = "SafeZoneY + (SafezoneH * 0.235)";
w = "SafeZoneW * 0.280";
h = "SafeZoneH * 0.03";
size = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_Control_InfoSupply : CTI_Menu_Control_Info {
idc = 100009;
y = "SafeZoneY + (SafezoneH * 0.2625)";
};
class CTI_Menu_Control_InfoWorkers : CTI_Menu_Control_Info {
idc = 100013;
y = "SafeZoneY + (SafezoneH * 0.29)";
};
class CTI_Control_HQ_Deploy : RscButton_Lesser {
idc = 100014;
x = "SafeZoneX + (SafeZoneW * 0.535)";
y = "SafeZoneY + (SafeZoneH * 0.235)";
w = "SafeZoneW * 0.280";
h = "SafeZoneH * 0.04";
text = "Deploy HQ";
action = "['onHQDeployment'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_BuildMenu.sqf'";
};
class CTI_Menu_Control_NVMode : CTI_Menu_Control_Undo {
idc = 100015;
x = "SafeZoneX + (SafeZoneW * 0.535)";
y = "SafeZoneY + (SafeZoneH * 0.2875)";
text = "Normal";
action = "['onViewModeChanged'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_BuildMenu.sqf'";
};
class CTI_Control_Exit : RscButton {
idc = 22557;
x = "SafeZoneX + (SafeZoneW * 0.77)";
y = "SafeZoneY + (SafezoneH * 0.18)";
w = "SafeZoneW * 0.04";
h = "SafeZoneH * 0.04";
text = "X";
action = "closeDialog 0";
};
};
};
class CTI_RscPurchaseMenu {
movingEnable = 0;
idd = 110000;
onLoad = "uiNamespace setVariable ['cti_dialog_ui_purchasemenu', _this select 0];['onLoad'] execVM 'Client\Events\Events_UI_PurchaseMenu.sqf'";
onUnload = "uiNamespace setVariable ['cti_dialog_ui_purchasemenu', nil]; ['onUnload'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_PurchaseMenu.sqf'";
class controlsBackground {
class CTI_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.21)";
y = "SafeZoneY + (SafezoneH * 0.175)";
w = "SafeZoneW * 0.615";
h = "SafeZoneH * 0.705";
colorBackground[] = {0, 0, 0, 0.7};
moving = 1;
};
class CTI_Background_Header : CTI_Background {
x = "SafeZoneX + (SafeZoneW * 0.21)";
y = "SafeZoneY + (SafezoneH * 0.175)";
w = "SafeZoneW * 0.615";
h = "SafeZoneH * 0.05"; //0.06 stock
colorBackground[] = {0, 0, 0, 0.4};
};
class CTI_Menu_Title : RscText {
style = ST_LEFT;
x = "SafeZoneX + (SafeZoneW * 0.23)";
y = "SafeZoneY + (SafezoneH * 0.180)";
w = "SafeZoneW * 0.595";
h = "SafeZoneH * 0.037";
text = "Factory Menu";
colorText[] = {0.258823529, 0.713725490, 1, 1};
sizeEx = "( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_UnitsListFrame : RscFrame {
x = "SafeZoneX + (SafeZoneW * 0.225)";
y = "SafeZoneY + (SafezoneH * 0.419)";
w = "SafeZoneW * 0.280";
h = "SafeZoneH * 0.391";
};
class CTI_Menu_Info : CTI_Menu_UnitsListFrame {
y = "SafeZoneY + (SafezoneH * 0.245)";
h = "SafeZoneH * 0.064";
};
class CTI_Menu_Info_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.225)";
y = "SafeZoneY + (SafezoneH * 0.245)";
w = "SafeZoneW * 0.280";
h = "SafeZoneH * 0.064";
colorBackground[] = {0.5, 0.5, 0.5, 0.25};
};
class CTI_Menu_ResourcesInfo_Background : CTI_Menu_Info_Background {
y = "SafeZoneY + (SafezoneH * 0.373)";
h = "SafeZoneH * 0.030";
};
class CTI_Menu_SubInfo : CTI_Menu_Info {
y = "SafeZoneY + (SafezoneH * 0.325)";
h = "SafeZoneH * 0.078";
};
class CTI_Menu_ComboFrame : CTI_Menu_Info {
x = "SafeZoneX + (SafeZoneW * 0.535)";
h = "SafeZoneH * 0.1";
};
class CTI_Menu_TeamComboLabel : RscText {
x = "SafeZoneX + (SafeZoneW * 0.54)";
y = "SafeZoneY + (SafezoneH * 0.257)";
w = "SafeZoneW * 0.1";
h = "SafeZoneH * 0.035";
text = "Team :";
// colorText[] = {0.258823529, 0.713725490, 1, 1};
sizeEx = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_FactoryComboLabel : CTI_Menu_TeamComboLabel {
y = "SafeZoneY + (SafezoneH * 0.3)";
text = "Factory :";
};
class CTI_Menu_MapFrame : CTI_Menu_ComboFrame {
y = "SafeZoneY + (SafezoneH * 0.361)";
h = "SafeZoneH * 0.235";
};
class CTI_Menu_Info_MapIntel : RscText {
x = "SafeZoneX + (SafeZoneW * 0.535)";
y = "SafeZoneY + (SafezoneH * 0.361)";
w = "SafeZoneW * 0.280";
h = "SafeZoneH * 0.2";
colorBackground[] = {0.5, 0.5, 0.5, 0.25};
};
class CTI_Menu_QueueFrame : CTI_Menu_MapFrame {
y = "SafeZoneY + (SafezoneH * 0.612)";
h = "SafeZoneH * 0.143";
};
};
class controls {
class CTI_Menu_Map : RscMapControl {
idc = 110010;
x = "SafeZoneX + (SafeZoneW * 0.535)";
y = "SafeZoneY + (SafezoneH * 0.391)";
w = "SafeZoneW * 0.280";
h = "SafeZoneH * 0.205";
showCountourInterval = 1;
};
class CTI_Menu_Map_Info : RscStructuredText {
idc = 110901;
x = "SafeZoneX + (SafeZoneW * 0.535)";
y = "SafeZoneY + (SafezoneH * 0.361)";
w = "SafeZoneW * 0.1375";
h = "SafeZoneH * 0.03";
size = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
class Attributes {
font = "PuristaMedium";
color = "#ffffff";
align = "left";
shadow = 1;
};
};
class CTI_Menu_Group_Info : CTI_Menu_Map_Info {
idc = 110902;
x = "SafeZoneX + (SafeZoneW * 0.6725)";
};
class CTI_Icon_Barracks : RscActiveText {
idc = 110001;
style = ST_KEEP_ASPECT_RATIO;
x = "SafeZoneX + (SafeZoneW * 0.225)";
y = "SafeZoneY + (SafezoneH * 0.245)";
w = "SafeZoneW * 0.035";
h = "SafeZoneH * 0.064";
color[] = {0.75,0.75,0.75,0.7};
colorActive[] = {1,1,1,0.7};
colorDisabled[] = {1,1,1,0.3};
colorBackground[] = {0.6, 0.8392, 0.4706, 0.7};
colorBackgroundSelected[] = {0.6, 0.8392, 0.4706, 0.7};
colorFocused[] = {0.0, 0.0, 0.0, 0};
text = "Rsc\Pictures\icon_wf_building_barracks.paa";
action = "['onIconSet', 0, CTI_BARRACKS] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_PurchaseMenu.sqf'";
};
class CTI_Icon_Light : CTI_Icon_Barracks {
idc = 110002;
x = "SafeZoneX + (SafeZoneW * 0.26)";
text = "Rsc\Pictures\icon_wf_building_lvs.paa";
action = "['onIconSet', 1, CTI_LIGHT] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_PurchaseMenu.sqf'";
};
class CTI_Icon_Heavy : CTI_Icon_Barracks {
idc = 110003;
x = "SafeZoneX + (SafeZoneW * 0.295)";
text = "Rsc\Pictures\icon_wf_building_hvs.paa";
action = "['onIconSet', 2, CTI_HEAVY] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_PurchaseMenu.sqf'";
};
class CTI_Icon_Air : CTI_Icon_Barracks {
idc = 110004;
x = "SafeZoneX + (SafeZoneW * 0.33)";
text = "Rsc\Pictures\icon_wf_building_air.paa";
action = "['onIconSet', 3, CTI_AIR] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_PurchaseMenu.sqf'";
};
class CTI_Icon_Repair : CTI_Icon_Barracks {
idc = 110005;
x = "SafeZoneX + (SafeZoneW * 0.365)";
text = "Rsc\Pictures\icon_wf_building_repair.paa";
action = "['onIconSet', 4, CTI_REPAIR] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_PurchaseMenu.sqf'";
};
class CTI_Icon_Ammo : CTI_Icon_Barracks {
idc = 110006;
x = "SafeZoneX + (SafeZoneW * 0.4)";
text = "Rsc\Pictures\icon_wf_building_ammo.paa";
action = "['onIconSet', 5, CTI_AMMO] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_PurchaseMenu.sqf'";
};
class CTI_Icon_Naval : CTI_Icon_Barracks {
idc = 110007;
x = "SafeZoneX + (SafeZoneW * 0.435)";
text = "Rsc\Pictures\icon_wf_building_naval.paa";
action = "['onIconSet', 6, CTI_NAVAL] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_PurchaseMenu.sqf'";
};
class CTI_Icon_Depot : CTI_Icon_Barracks {
idc = 110011;
x = "SafeZoneX + (SafeZoneW * 0.470)";
text = "Rsc\Pictures\icon_wf_building_depot.paa";
action = "['onIconSet', 7, CTI_DEPOT] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_PurchaseMenu.sqf'";
};
class CTI_Icon_Driver : CTI_Icon_Barracks {
idc = 110100;
x = "SafeZoneX + (SafeZoneW * 0.25)";
y = "SafeZoneY + (SafezoneH * 0.325)";
w = "SafeZoneW * 0.03";
h = "SafeZoneH * 0.048";
color[] = {0.258823529, 0.713725490, 1, 1};
colorDisabled[] = {1,1,1,0.3};
colorActive[] = {1,1,1,0.7};
colorBackground[] = {0.6, 0.8392, 0.4706, 0.7};
colorBackgroundSelected[] = {0.6, 0.8392, 0.4706, 0.7};
colorFocused[] = {0.0, 0.0, 0.0, 0};
text = "Rsc\Pictures\i_driver.paa";
action = "['onVehicleIconClicked', 'driver', 110100] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_PurchaseMenu.sqf'";
};
class CTI_Icon_Gunner : CTI_Icon_Driver {
idc = 110101;
x = "SafeZoneX + (SafeZoneW * 0.28)";
text = "Rsc\Pictures\i_gunner.paa";
action = "['onVehicleIconClicked', 'gunner', 110101] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_PurchaseMenu.sqf'";
};
class CTI_Icon_Commander : CTI_Icon_Driver {
idc = 110102;
x = "SafeZoneX + (SafeZoneW * 0.31)";
text = "Rsc\Pictures\i_commander.paa";
action = "['onVehicleIconClicked', 'commander', 110102] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_PurchaseMenu.sqf'";
};
class CTI_Icon_Turrets : CTI_Icon_Driver {
idc = 110103;
x = "SafeZoneX + (SafeZoneW * 0.34)";
text = "Rsc\Pictures\i_turrets.paa";
action = "['onVehicleIconClicked', 'turrets', 110103] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_PurchaseMenu.sqf'";
};
class CTI_Icon_Camo : RscCombo {
idc = 110104;
x = "SafeZoneX + (SafeZoneW * 0.372)";
y = "SafeZoneY + (SafezoneH * 0.3315)";
w = "SafeZoneW * 0.1";
h = "SafeZoneH * 0.035";
sizeEx = "0.8 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
onLBSelChanged = "['onCamoLBSelChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_PurchaseMenu.sqf'";
};
class CTI_Icon_Lock : CTI_Icon_Driver {
idc = 110105;
x = "SafeZoneX + (SafeZoneW * 0.47)";
color[] = {1, 0.22745098, 0.22745098, 1};
colorDisabled[] = {1,1,1,0.3};
text = "Rsc\Pictures\i_lock.paa";
action = "['onVehicleLockClicked'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_PurchaseMenu.sqf'";
};
class CTI_Menu_Control_UnitsList : RscListNBox {
idc = 111007;
x = "SafeZoneX + (SafeZoneW * 0.225)";
y = "SafeZoneY + (SafezoneH * 0.419)";
w = "SafeZoneW * 0.280";
h = "SafeZoneH * 0.391";
// rowHeight = "1.5 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
rowHeight = "1.35 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
sizeEx = "0.78 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
colorText[] = {1,1,1,1};
colorBackground[] = {0,0,0,0};
colorPicture[] = {1, 1, 1, 1};
itemBackground[] = {1,1,1,0.1};
// columns[] = {0.001, 0.26};
columns[] = {0.001, 0.35};
onLBSelChanged = "['onUnitsLBSelChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_PurchaseMenu.sqf'";
onLBDblClick = "['onPurchase', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_PurchaseMenu.sqf'";
};
class CTI_Menu_ComboTeam : RscCombo {
idc = 110008;
x = "SafeZoneX + (SafeZoneW * 0.6075)";
y = "SafeZoneY + (SafezoneH * 0.257)";
w = "SafeZoneW * 0.195";
h = "SafeZoneH * 0.035";
sizeEx = "0.8 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
onLBSelChanged = "['onGroupLBSelChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_PurchaseMenu.sqf'";
};
class CTI_Menu_ComboFactory : CTI_Menu_ComboTeam {
idc = 110009;
y = "SafeZoneY + (SafezoneH * 0.3)";
onLBSelChanged = "['onFactoryLBSelChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_PurchaseMenu.sqf'";
};
class CTI_Menu_Control_Purchase : RscButton {
idc = 100011;
// x = "SafeZoneX + (SafeZoneW * 0.535)";
x = "SafeZoneX + (SafeZoneW * 0.225)";
y = "SafeZoneY + (SafeZoneH * 0.825)";
w = "SafeZoneW * 0.280";
h = "SafeZoneH * 0.04";
text = "Purchase";
action = "['onPurchase', lnbCurSelRow 111007] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_PurchaseMenu.sqf'";
};
class CTI_Menu_Control_CancelQueu : CTI_Menu_Control_Purchase {
idc = 100012;
x = "SafeZoneX + (SafeZoneW * 0.535)";
y = "SafeZoneY + (SafeZoneH * 0.77)";
text = "Cancel Queue";
action = "['onQueueCancel', lbCurSel 110013] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_PurchaseMenu.sqf'";
};
class CTI_Menu_Control_IndependentSalvager : CTI_Menu_Control_CancelQueu {
idc = 100016;
y = "SafeZoneY + (SafeZoneH * 3.825)";
text = "Buy Independent Salvager";
action = "['onIndependentSalvagerPressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_PurchaseMenu.sqf'";
};
class CTI_Menu_Control_QueueList : RscListBox {
idc = 110013;
x = "SafeZoneX + (SafeZoneW * 0.535)";
y = "SafeZoneY + (SafezoneH * 0.612)";
h = "SafeZoneH * 0.143";
w = "SafeZoneW * 0.280";
rowHeight = "1.5 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
sizeEx = "0.78 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
colorText[] = {1,1,1,1};
colorBackground[] = {0,0,0,0};
// onLBSelChanged = "['onUnitsLBSelChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_PurchaseMenu.sqf'";
onLBDblClick = "['onQueueCancel', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_PurchaseMenu.sqf'";
};
class CTI_Menu_Control_Cost : RscStructuredText {
idc = 110014;
x = "SafeZoneX + (SafeZoneW * 0.225)";
y = "SafeZoneY + (SafezoneH * 0.373)";
w = "SafeZoneW * 0.1375";
h = "SafeZoneH * 0.03";
size = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_Control_Resources : CTI_Menu_Control_Cost {
idc = 110015;
x = "SafeZoneX + (SafeZoneW * 0.3625)";
size = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Control_Exit : RscButton {
idc = 22555;
x = "SafeZoneX + (SafeZoneW * 0.77)";
y = "SafeZoneY + (SafezoneH * 0.18)";
w = "SafeZoneW * 0.04";
h = "SafeZoneH * 0.04";
text = "X";
action = "closeDialog 0";
};
};
};
class CTI_RscGearMenu {
movingEnable = 0;
idd = 70000;
onLoad = "uiNamespace setVariable ['cti_dialog_ui_gear', _this select 0];['onLoad'] execVM 'Client\Events\Events_UI_GearMenu.sqf'";
onUnload = "uiNamespace setVariable ['cti_dialog_ui_gear', nil]; ['onUnload'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
class controlsBackground {
class CTI_Background : RscText {
x = "SafeZoneX";
y = "SafeZoneY";
w = "SafeZoneW";
h = "SafeZoneH";
colorBackground[] = {0, 0, 0, 0.7};
moving = 0;
};
class CTI_Background_Header : CTI_Background {
x = "SafeZoneX";
y = "SafeZoneY";
w = "SafeZoneW";
h = "SafeZoneH * 0.06";
colorBackground[] = {0, 0, 0, 0.4};
};
class CTI_Background_Footer : CTI_Background {
x = "SafeZoneX";
y = "SafeZoneY + (SafezoneH * 0.96)";
w = "SafeZoneW";
h = "SafeZoneH * 0.04";
colorBackground[] = {0, 0, 0, 0.3};
};
class CTI_Menu_Title : RscText {
x = "SafeZoneX + (SafeZoneW * 0.007)";
y = "SafeZoneY + (SafezoneH * 0.01)";
w = "SafeZoneW * 0.5";
h = "SafeZoneH * 0.037";
text = "Gear Purchase Menu :";
colorText[] = {0.258823529, 0.713725490, 1, 1};
sizeEx = "( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Background_Gear : RscText {
x = "SafeZoneX + (SafeZoneW * 0.4)";
y = "SafeZoneY + (SafezoneH * 0.06)";
w = "SafeZoneW * 0.6";
h = "SafeZoneH * 0.9";
colorBackground[] = {0.5, 0.5, 0.5, 0.15};
};
class CTI_Menu_Icons_Frame : RscFrame {
x = "SafeZoneX + (SafeZoneW * 0.01)";
// x = "SafeZoneX + (SafeZoneW * 0.028)";
y = "SafeZoneY + (SafezoneH * 0.07)";
// w = "SafeZoneW * 0.344";
w = "SafeZoneW * 0.38";
h = "SafeZoneH * 0.08";
};
class CTI_Menu_Icons_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.01)";
y = "SafeZoneY + (SafezoneH * 0.07)";
w = "SafeZoneW * 0.38";
h = "SafeZoneH * 0.08";
colorBackground[] = {0.5, 0.5, 0.5, 0.25};
};
class CTI_Menu_ComboTarget_Frame : RscFrame {//unit target frame
x = "SafeZoneX + (SafeZoneW * 0.01)";
y = "SafeZoneY + (SafezoneH * 0.17)";
w = "SafeZoneW * 0.38";
h = "SafeZoneH * 0.055";
};
class CTI_Menu_ComboTarget_Background : CTI_Menu_Icons_Background {//unit target background
y = "SafeZoneY + (SafezoneH * 0.17)";
h = "SafeZoneH * 0.055";
};
class CTI_Menu_ComboTarget_Label : RscText {//unit target text
x = "SafeZoneX + (SafeZoneW * 0.02)";
y = "SafeZoneY + (SafezoneH * 0.18)";
w = "SafeZoneW * 0.1";
h = "SafeZoneH * 0.035";
text = "Target :";
sizeEx = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_ShopList_Frame : RscFrame { //main gear frame
x = "SafeZoneX + (SafeZoneW * 0.01)";
y = "SafeZoneY + (SafezoneH * 0.245)";
w = "SafeZoneW * 0.38";
h = "SafeZoneH * 0.48";
};
class CTI_Menu_LinkedList_Frame : RscFrame { //box below main gear box frame
x = "SafeZoneX + (SafeZoneW * 0.01)";
y = "SafeZoneY + (SafezoneH * 0.745)";
w = "SafeZoneW * 0.38";
h = "SafeZoneH * 0.2";
};
class CTI_Menu_ShopList_Background : CTI_Menu_ComboTarget_Background {//main gear background
y = "SafeZoneY + (SafezoneH * 0.245)";
h = "SafeZoneH * 0.48";
};
class CTI_Menu_MagsList_Background : CTI_Menu_ComboTarget_Background {//box below main gear box background
y = "SafeZoneY + (SafezoneH * 0.745)";
h = "SafeZoneH * 0.2";
};
};
class controls {
//--- Interactive background controls
class CTI_Gear_Container_Uniform : RscText {
idc = 77001;
x = "SafeZoneX + (SafeZoneW * 0.41)";
y = "SafeZoneY + (SafezoneH * 0.07)";
w = "SafeZoneW * 0.09";
h = "SafeZoneH * 0.112";
colorBackground[] = {1, 1, 1, 0.15};
};
class CTI_Gear_Container_Vest : CTI_Gear_Container_Uniform {
idc = 77002;
x = "SafeZoneX + (SafeZoneW * 0.505)";
};
class CTI_Gear_Container_Backpack : CTI_Gear_Container_Uniform {
idc = 77003;
x = "SafeZoneX + (SafeZoneW * 0.60)";
};
class CTI_Gear_Container_Helm : CTI_Gear_Container_Uniform {
idc = 77004;
x = "SafeZoneX + (SafeZoneW * 0.70)";
w = "SafeZoneW * 0.07";
h = "SafeZoneH * 0.09";
};
class CTI_Gear_Container_Glasses : CTI_Gear_Container_Helm {
idc = 77005;
x = "SafeZoneX + (SafeZoneW * 0.774)";
};
class CTI_Gear_Container_NVGoggles : CTI_Gear_Container_Helm {
idc = 77006;
x = "SafeZoneX + (SafeZoneW * 0.847)";
};
class CTI_Gear_Container_Binoculars : CTI_Gear_Container_Helm {
idc = 77007;
x = "SafeZoneX + (SafeZoneW * 0.921)";
};
class CTI_Gear_Container_Map : CTI_Gear_Container_Uniform {
idc = 77008;
x = "SafeZoneX + (SafeZoneW * 0.70)";
y = "SafeZoneY + (SafezoneH * 0.17)";
w = "SafeZoneW * 0.056";
h = "SafeZoneH * 0.07";
};
class CTI_Gear_Container_GPS : CTI_Gear_Container_Map {
idc = 77009;
x = "SafeZoneX + (SafeZoneW * 0.759)";
};
class CTI_Gear_Container_Radio : CTI_Gear_Container_Map {
idc = 77010;
x = "SafeZoneX + (SafeZoneW * 0.818)";
};
class CTI_Gear_Container_Compass : CTI_Gear_Container_Map {
idc = 77011;
x = "SafeZoneX + (SafeZoneW * 0.877)";
};
class CTI_Gear_Container_Clock : CTI_Gear_Container_Map {
idc = 77012;
x = "SafeZoneX + (SafeZoneW * 0.936)";
};
class CTI_Gear_Container_Primary : CTI_Gear_Container_Uniform {
idc = 77013;
x = "SafeZoneX + (SafeZoneW * 0.41)";
y = "SafeZoneY + (SafezoneH * 0.54)";
w = "SafeZoneW * 0.28";
h = "SafeZoneH * 0.112";
};
class CTI_Gear_Container_Primary_Muzzle : CTI_Gear_Container_Map {
idc = 77014;
x = "SafeZoneX + (SafeZoneW * 0.41)";
y = "SafeZoneY + (SafezoneH * 0.657)";
w = "SafeZoneW * 0.055";
};
class CTI_Gear_Container_Primary_Flashlight : CTI_Gear_Container_Primary_Muzzle {
idc = 77015;
x = "SafeZoneX + (SafeZoneW * 0.5223)";
};
class CTI_Gear_Container_Primary_Optics : CTI_Gear_Container_Primary_Muzzle {
idc = 77016;
x = "SafeZoneX + (SafeZoneW * 0.57845)";
};
class CTI_Gear_Container_Primary_CurrentMagazine : CTI_Gear_Container_Primary_Muzzle {
idc = 77901;
x = "SafeZoneX + (SafeZoneW * 0.6346)";
};
class CTI_Gear_Container_Primary_Bipod : CTI_Gear_Container_Primary_Muzzle {
idc = 77017;
x = "SafeZoneX + (SafeZoneW * 0.46615)";
};
class CTI_Gear_Container_Secondary : CTI_Gear_Container_Primary {
idc = 77018;
x = "SafeZoneX + (SafeZoneW * 0.71)";
};
class CTI_Gear_Container_Secondary_Muzzle : CTI_Gear_Container_Map {
idc = 77019;
x = "SafeZoneX + (SafeZoneW * 0.71)";
y = "SafeZoneY + (SafezoneH * 0.657)";
w = "SafeZoneW * 0.055";
};
class CTI_Gear_Container_Secondary_Flashlight : CTI_Gear_Container_Secondary_Muzzle {
idc = 77020;
x = "SafeZoneX + (SafeZoneW * 0.8223)";
}
class CTI_Gear_Container_Secondary_Optics : CTI_Gear_Container_Secondary_Muzzle {
idc = 77021;
x = "SafeZoneX + (SafeZoneW * 0.87845)";
};
class CTI_Gear_Container_Secondary_Bipod : CTI_Gear_Container_Secondary_Muzzle {
idc = 77022;
x = "SafeZoneX + (SafeZoneW * 0.76615)";
};
class CTI_Gear_Container_Secondary_CurrentMagazine : CTI_Gear_Container_Secondary_Muzzle {
idc = 77902;
x = "SafeZoneX + (SafeZoneW * 0.9346)";
};
class CTI_Gear_Container_Pistol : CTI_Gear_Container_Primary {
idc = 77023;
y = "SafeZoneY + (SafeZoneH * 0.756)";
};
class CTI_Gear_Container_Pistol_Muzzle : CTI_Gear_Container_Map {
idc = 77024;
x = "SafeZoneX + (SafeZoneW * 0.41)";
y = "SafeZoneY + (SafezoneH * 0.873)";
w = "SafeZoneW * 0.055";
};
class CTI_Gear_Container_Pistol_Flashlight : CTI_Gear_Container_Pistol_Muzzle {
idc = 77025;
x = "SafeZoneX + (SafeZoneW * 0.5223)";
};
class CTI_Gear_Container_Pistol_Optics : CTI_Gear_Container_Pistol_Muzzle {
idc = 77026;
x = "SafeZoneX + (SafeZoneW * 0.57845)";
};
class CTI_Gear_Container_Pistol_Bipod : CTI_Gear_Container_Pistol_Muzzle {
idc = 77027;
x = "SafeZoneX + (SafeZoneW * 0.46615)";
};
class CTI_Gear_Container_Pistol_CurrentMagazine : CTI_Gear_Container_Pistol_Muzzle {
idc = 77903;
x = "SafeZoneX + (SafeZoneW * 0.6346)";
};
class CTI_Gear_Container_Items_Unit : CTI_Gear_Container_Pistol_Muzzle {
idc = 77109;
x = "SafeZoneX + (SafeZoneW * 0.41)";
y = "SafeZoneY + (SafezoneH * 0.25)";
w = "SafeZoneW * 0.58";
h = "SafeZoneH * 0.28";
};
//--- Actual controls
class CTI_Gear_Control_Items_Purchase : RscListNBox { //Actual gear list
idc = 70108;
x = "SafeZoneX + (SafeZoneW * 0.01)";
y = "SafeZoneY + (SafezoneH * 0.245)";
w = "SafeZoneW * 0.38";
h = "SafeZoneH * 0.48";
rowHeight = "1.5 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
sizeEx = "0.78 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
colorText[] = {1,1,1,1};
colorBackground[] = {0,0,0,0};
colorPicture[] = {1, 1, 1, 1};
colorPictureSelected[] = {1, 1, 1, 1};
itemBackground[] = {1,1,1,0.1};
columns[] = {0.25, 0.001, 0.75, 0.85};
canDrag = 1;
onLBDblClick = "['onShoppingListLBDblClick', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrag = "['onShoppingListLBDrag', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBSelChanged = "['onShoppingListLBSelChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_Linked_Items : CTI_Gear_Control_Items_Purchase {
idc = 70601;
y = "SafeZoneY + (SafezoneH * 0.745)";
h = "SafeZoneH * 0.2";
onLBDblClick = "['onLinkedListLBDblClick', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrag = "['onShoppingListLBDrag', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBSelChanged = "";
};
class CTI_Gear_Control_Items_Unit : RscListNBox {
idc = 70109;
x = "SafeZoneX + (SafeZoneW * 0.41)";
y = "SafeZoneY + (SafezoneH * 0.25)";
w = "SafeZoneW * 0.58";
h = "SafeZoneH * 0.28";
rowHeight = "1.65 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
sizeEx = "0.8 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
colorText[] = {1,1,1,1};
colorBackground[] = {0,0,0,0};
colorPicture[] = {1, 1, 1, 1};
colorPictureSelected[] = {1, 1, 1, 1};
itemBackground[] = {1,1,1,0.1};
itemSpacing = 0.001;
columns[] = {0.01, 0.2};
onLBDblClick = "['onUnitItemsLBDblClick', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'ListItems', 77109, ((_this select 4) select 0) select 2, -1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_Uniform: RscActiveText {
idc = 70001;
style = ST_KEEP_ASPECT_RATIO;
soundDoubleClick[] = {"",0.1,1};
colorBackground[] = {0.6, 0.83, 0.47, 1};
colorBackgroundSelected[] = {0.6, 0.83, 0.47, 1};
colorFocused[] = {0, 0, 0, 0};
color[] = {0.85, 0.85, 0.85, 1};
colorText[] = {0.85, 0.85, 0.85, 1};
colorActive[] = {1, 1, 1, 1};
colorDisabled[] = {1,1,1,0.3};
canDrag = 1;
x = "SafeZoneX + (SafeZoneW * 0.41)";
y = "SafeZoneY + (SafezoneH * 0.07)";
w = "SafeZoneW * 0.09";
h = "SafeZoneH * 0.112";
text = "\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_uniform_gs.paa";
action = "['onItemContainerClicked', 0, 77001] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onMouseButtonDown = "['onItemContainerMouseClicked', 0, 70001, _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onMouseButtonDblClick = "['onItemContainerMouseDblClicked', 0] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'Container', 77001, ((_this select 4) select 0) select 2, 0] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_Vest: CTI_Gear_Control_Uniform {
idc = 70002;
x = "SafeZoneX + (SafeZoneW * 0.505)";
text = "\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_vest_gs.paa";
action = "['onItemContainerClicked', 1, 77002] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onMouseButtonDown = "['onItemContainerMouseClicked', 1, 70002, _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onMouseButtonDblClick = "['onItemContainerMouseDblClicked', 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'Container', 77002, ((_this select 4) select 0) select 2, 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_Backpack: CTI_Gear_Control_Uniform {
idc = 70003;
x = "SafeZoneX + (SafeZoneW * 0.60)";
text = "\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_backpack_gs.paa";
action = "['onItemContainerClicked', 2, 77003] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onMouseButtonDown = "['onItemContainerMouseClicked', 2, 70003, _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onMouseButtonDblClick = "['onItemContainerMouseDblClicked', 2] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'Container', 77003, ((_this select 4) select 0) select 2, 2] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_Helm: CTI_Gear_Control_Uniform {
idc = 70004;
x = "SafeZoneX + (SafeZoneW * 0.70)";
w = "SafeZoneW * 0.07";
h = "SafeZoneH * 0.09";
text = "\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_helmet_gs.paa";
action = "['onAccessoryClicked', 0, 70004, '\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_helmet_gs.paa'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'HeadAsset', 77004, ((_this select 4) select 0) select 2, [2,0]] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onMouseButtonDown = "";
onMouseButtonDblClick = "";
};
class CTI_Gear_Control_Glasses: CTI_Gear_Control_Helm {
idc = 70005;
x = "SafeZoneX + (SafeZoneW * 0.774)";
text = "\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_glasses_gs.paa";
action = "['onAccessoryClicked', 1, 70005, '\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_glasses_gs.paa'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'HeadAsset', 77005, ((_this select 4) select 0) select 2, [2,1]] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_NVGoggles: CTI_Gear_Control_Helm {
idc = 70006;
x = "SafeZoneX + (SafeZoneW * 0.847)";
text = "\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_nvg_gs.paa";
action = "['onItemClicked', [0,0], 70006, '\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_nvg_gs.paa'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'Item', 77006, ((_this select 4) select 0) select 2, [3,0,0]] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_Binoculars: CTI_Gear_Control_Helm {
idc = 70007;
x = "SafeZoneX + (SafeZoneW * 0.921)";
text = "\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_binocular_gs.paa";
action = "['onItemClicked', [0,1], 70007, '\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_binocular_gs.paa', [3,1]] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'Item', 77007, ((_this select 4) select 0) select 2, [3,0,1]] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_Map: CTI_Gear_Control_Uniform {
idc = 70008;
x = "SafeZoneX + (SafeZoneW * 0.70)";
y = "SafeZoneY + (SafezoneH * 0.17)";
w = "SafeZoneW * 0.056";
h = "SafeZoneH * 0.07";
text = "\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_map_gs.paa";
action = "['onItemClicked', [1,0], 70008, '\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_map_gs.paa'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'Item', 77008, ((_this select 4) select 0) select 2, [3,1,0]] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onMouseButtonDown = "";
onMouseButtonDblClick = "";
};
class CTI_Gear_Control_GPS: CTI_Gear_Control_Map {
idc = 70009;
x = "SafeZoneX + (SafeZoneW * 0.759)";
text = "\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_gps_gs.paa";
action = "['onItemClicked', [1,1], 70009, '\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_gps_gs.paa'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'Item', 77009, ((_this select 4) select 0) select 2, [3,1,1]] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_Radio: CTI_Gear_Control_Map {
idc = 70010;
x = "SafeZoneX + (SafeZoneW * 0.818)";
text = "\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_radio_gs.paa";
action = "['onItemClicked', [1,2], 70010, '\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_radio_gs.paa'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'Item', 77010, ((_this select 4) select 0) select 2, [3,1,2]] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_Compass: CTI_Gear_Control_Map {
idc = 70011;
x = "SafeZoneX + (SafeZoneW * 0.877)";
text = "\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_compass_gs.paa";
action = "['onItemClicked', [1,3], 70011, '\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_compass_gs.paa'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'Item', 77011, ((_this select 4) select 0) select 2, [3,1,3]] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_Clock: CTI_Gear_Control_Map {
idc = 70012;
x = "SafeZoneX + (SafeZoneW * 0.936)";
text = "\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_watch_gs.paa";
action = "['onItemClicked', [1,4], 70012, '\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_watch_gs.paa'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'Item', 77012, ((_this select 4) select 0) select 2, [3,1,4]] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_Primary: CTI_Gear_Control_Uniform {
idc = 70013;
x = "SafeZoneX + (SafeZoneW * 0.41)";
y = "SafeZoneY + (SafezoneH * 0.54)";
w = "SafeZoneW * 0.28";
h = "SafeZoneH * 0.112";
text = "\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_primary_gs.paa";
action = "['onWeaponClicked', 0] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'Weapon', 77013, ((_this select 4) select 0) select 2, 0] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onMouseButtonDown = "";
onMouseButtonDblClick = "";
};
class CTI_Gear_Control_Primary_Muzzle: CTI_Gear_Control_Map {
idc = 70014;
x = "SafeZoneX + (SafeZoneW * 0.41)";
y = "SafeZoneY + (SafezoneH * 0.657)";
w = "SafeZoneW * 0.056";
text = "\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_muzzle_gs.paa";
action = "['onWeaponAccessoryClicked', 0, 0, 70014, '\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_muzzle_gs.paa'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'Accessory', 77014, ((_this select 4) select 0) select 2, [0,0,1,0]] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_Primary_Side: CTI_Gear_Control_Primary_Muzzle {
idc = 70015;
x = "SafeZoneX + (SafeZoneW * 0.5223)";
text = "\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_side_gs.paa";
action = "['onWeaponAccessoryClicked', 0, 1, 70015, '\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_side_gs.paa'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'Accessory', 77015, ((_this select 4) select 0) select 2, [0,0,1,1]] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_Primary_Optics: CTI_Gear_Control_Primary_Muzzle {
idc = 70016;
x = "SafeZoneX + (SafeZoneW * 0.57845)";
text = "\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_top_gs.paa";
action = "['onWeaponAccessoryClicked', 0, 2, 70016, '\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_top_gs.paa'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'Accessory', 77016, ((_this select 4) select 0) select 2, [0,0,1,2]] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_Primary_Bipod: CTI_Gear_Control_Primary_Muzzle {
idc = 70017;
x = "SafeZoneX + (SafeZoneW * 0.46615)";
text = "\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_bipod_gs.paa";
action = "['onWeaponAccessoryClicked', 0, 3, 70017, '\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_bipod_gs.paa'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'Accessory', 77017, ((_this select 4) select 0) select 2, [0,0,1,3]] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_Primary_CurrentMagazine: CTI_Gear_Control_Primary_Muzzle {
idc = 70901;
x = "SafeZoneX + (SafeZoneW * 0.6346)";
text = "\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_magazine_gs.paa";
action = "['onWeaponCurrentMagazineClicked', 0, 70901] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'CurrentMagazine', 77901, ((_this select 4) select 0) select 2, 0] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_Secondary: CTI_Gear_Control_Primary {
idc = 70018;
x = "SafeZoneX + (SafeZoneW * 0.71)";
text = "\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_secondary_gs.paa";
action = "['onWeaponClicked', 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'Weapon', 77018, ((_this select 4) select 0) select 2, 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_Secondary_Muzzle: CTI_Gear_Control_Map {
idc = 70019;
x = "SafeZoneX + (SafeZoneW * 0.71)";
y = "SafeZoneY + (SafezoneH * 0.657)";
w = "SafeZoneW * 0.055";
text = "\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_muzzle_gs.paa";
action = "['onWeaponAccessoryClicked', 1, 0, 70019, '\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_muzzle_gs.paa'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'Accessory', 77019, ((_this select 4) select 0) select 2, [0,1,1,0]] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_Secondary_Side: CTI_Gear_Control_Secondary_Muzzle {
idc = 70020;
x = "SafeZoneX + (SafeZoneW * 0.8223)";
text = "\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_side_gs.paa";
action = "['onWeaponAccessoryClicked', 1, 1, 70020, '\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_side_gs.paa'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'Accessory', 77020, ((_this select 4) select 0) select 2, [0,1,1,1]] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_Secondary_Optics: CTI_Gear_Control_Secondary_Muzzle {
idc = 70021;
x = "SafeZoneX + (SafeZoneW * 0.87845)";
text = "\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_top_gs.paa";
action = "['onWeaponAccessoryClicked', 1, 2, 70021, '\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_top_gs.paa'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'Accessory', 77021, ((_this select 4) select 0) select 2, [0,1,1,2]] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_Secondary_Bipod: CTI_Gear_Control_Secondary_Muzzle {
idc = 70022;
x = "SafeZoneX + (SafeZoneW * 0.76615)";
text = "\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_bipod_gs.paa";
action = "['onWeaponAccessoryClicked', 1, 3, 70022, '\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_ui_gear_bipod_gs_gs.paa'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'CurrentMagazine', 77022, ((_this select 4) select 0) select 2, [0,1,1,3]] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_Secondary_CurrentMagazine: CTI_Gear_Control_Secondary_Muzzle {
idc = 70902;
x = "SafeZoneX + (SafeZoneW * 0.9346)";
text = "\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_magazine_gs.paa";
action = "['onWeaponCurrentMagazineClicked', 1, 70902] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'CurrentMagazine', 77902, ((_this select 4) select 0) select 2, 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_Pistol: CTI_Gear_Control_Primary {
idc = 70023;
y = "SafeZoneY + (SafeZoneH * 0.756)";
text = "\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_hgun_gs.paa";
action = "['onWeaponClicked', 2] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'Weapon', 77023, ((_this select 4) select 0) select 2, 2] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_Pistol_Muzzle: CTI_Gear_Control_Map {
idc = 70024;
x = "SafeZoneX + (SafeZoneW * 0.41)";
y = "SafeZoneY + (SafezoneH * 0.873)";
w = "SafeZoneW * 0.056";
text = "\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_muzzle_gs.paa";
action = "['onWeaponAccessoryClicked', 2, 0, 70024, '\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_muzzle_gs.paa'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'Accessory', 77024, ((_this select 4) select 0) select 2, [0,2,1,0]] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_Pistol_Side: CTI_Gear_Control_Pistol_Muzzle {
idc = 70025;
x = "SafeZoneX + (SafeZoneW * 0.5223)";
text = "\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_side_gs.paa";
action = "['onWeaponAccessoryClicked', 2, 1, 70025, '\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_side_gs.paa'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'Accessory', 77025, ((_this select 4) select 0) select 2, [0,2,1,1]] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_Pistol_Optics: CTI_Gear_Control_Pistol_Muzzle {
idc = 70026;
x = "SafeZoneX + (SafeZoneW * 0.57845)";
text = "\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_top_gs.paa";
action = "['onWeaponAccessoryClicked', 2, 2, 70026, '\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_top_gs.paa'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'Accessory', 77026, ((_this select 4) select 0) select 2, [0,2,1,2]] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_Pistol_Bipod: CTI_Gear_Control_Pistol_Muzzle {
idc = 70027;
x = "SafeZoneX + (SafeZoneW * 0.46615)";
text = "\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_bipod_gs.paa";
action = "['onWeaponAccessoryClicked', 2, 3, 70027, '\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_bipod_gs.paa'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'Accessory', 77027, ((_this select 4) select 0) select 2, [0,2,1,3]] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_Pistol_CurrentMagazine: CTI_Gear_Control_Pistol_Muzzle {
idc = 70903;
x = "SafeZoneX + (SafeZoneW * 0.6346)";
text = "\A3\Ui_f\data\GUI\Rsc\RscDisplayGear\ui_gear_magazine_gs.paa";
action = "['onWeaponCurrentMagazineClicked', 2, 70903] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
onLBDrop = "['onShoppingListLBDrop', 'CurrentMagazine', 77903, ((_this select 4) select 0) select 2, 2] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_Combo_Target : RscCombo { //Target drop box
idc = 70201;
x = "SafeZoneX + (SafeZoneW * 0.15)";
y = "SafeZoneY + (SafezoneH * 0.18)";
w = "SafeZoneW * 0.235";
h = "SafeZoneH * 0.037";
onLBSelChanged = "['onUnitLBSelChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Uniform_Progress_Load : RscProgress {
idc = 70301;
style = 0;
texture = "";
textureExt = "";
colorBar[] = {0.9,0.9,0.9,0.9};
colorExtBar[] = {1,1,1,1};
colorFrame[] = {1,1,1,1};
x = "SafeZoneX + (SafeZoneW * 0.41)";
y = "SafeZoneY + (SafezoneH * 0.183)";
w = "SafeZoneW * 0.09";
h = "SafeZoneH * 0.016";
};
class CTI_Gear_Vest_Progress_Load : CTI_Gear_Uniform_Progress_Load {
idc = 70302;
x = "SafeZoneX + (SafeZoneW * 0.505)";
};
class CTI_Gear_Backpack_Progress_Load : CTI_Gear_Uniform_Progress_Load {
idc = 70303;
x = "SafeZoneX + (SafeZoneW * 0.60)";
};
class CTI_Icon_Primary : RscActiveText {
idc = 70501;
style = ST_KEEP_ASPECT_RATIO;
x = "SafeZoneX + (SafeZoneW * 0.028)";
y = "SafeZoneY + (SafezoneH * 0.07)";
w = "SafeZoneW * 0.043";
h = "SafeZoneH * 0.08";
color[] = {0.75,0.75,0.75,0.7};
colorActive[] = {1,1,1,0.7};
colorDisabled[] = {1,1,1,0.3};
colorBackground[] = {0.6, 0.8392, 0.4706, 0.7};
colorBackgroundSelected[] = {0.6, 0.8392, 0.4706, 0.7};
colorFocused[] = {0.0, 0.0, 0.0, 0};
text = "Rsc\Pictures\icon_wf_gear_primary.paa";
action = "['onShoppingTabClicked', CTI_GEAR_TAB_PRIMARY] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Icon_Secondary : CTI_Icon_Primary {
idc = 70502;
x = "SafeZoneX + (SafeZoneW * 0.071)";
text = "Rsc\Pictures\icon_wf_gear_secondary.paa";
action = "['onShoppingTabClicked', CTI_GEAR_TAB_SECONDARY] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Icon_Handgun : CTI_Icon_Primary {
idc = 70503;
x = "SafeZoneX + (SafeZoneW * 0.114)";
text = "Rsc\Pictures\icon_wf_gear_handgun.paa";
action = "['onShoppingTabClicked', CTI_GEAR_TAB_HANDGUN] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Icon_Accessories : CTI_Icon_Primary {
idc = 70504;
x = "SafeZoneX + (SafeZoneW * 0.157)";
text = "Rsc\Pictures\icon_wf_gear_accessories.paa";
action = "['onShoppingTabClicked', CTI_GEAR_TAB_ACCESSORIES] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Icon_Ammunitions : CTI_Icon_Primary {
idc = 70505;
x = "SafeZoneX + (SafeZoneW * 0.2)";
text = "Rsc\Pictures\icon_wf_gear_ammunition.paa";
action = "['onShoppingTabClicked', CTI_GEAR_TAB_AMMO] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Icon_Misc : CTI_Icon_Primary {
idc = 70506;
x = "SafeZoneX + (SafeZoneW * 0.243)";
text = "Rsc\Pictures\icon_wf_gear_miscellaneous.paa";
action = "['onShoppingTabClicked', CTI_GEAR_TAB_MISC] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Icon_Equipment : CTI_Icon_Primary {
idc = 70507;
x = "SafeZoneX + (SafeZoneW * 0.286)";
text = "Rsc\Pictures\icon_wf_gear_equipment.paa";
action = "['onShoppingTabClicked', CTI_GEAR_TAB_EQUIPMENT] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Icon_Template : CTI_Icon_Primary {
idc = 70508;
x = "SafeZoneX + (SafeZoneW * 0.329)";
text = "Rsc\Pictures\icon_wf_building_barracks.paa";
action = "['onShoppingTabClicked', CTI_GEAR_TAB_TEMPLATES] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_CreateTemplate : RscButton {
idc = 70401;
x = "SafeZoneX + (SafeZoneW * 0.71)";
y = "SafeZoneY + (SafezoneH * 0.756)";
w = "SafeZoneW * 0.28";
h = "SafeZoneH * 0.04";
text = "Create Template";
tooltip = "Create a template of the current gear setup";
action = "['onTemplateCreation'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_DeleteTemplate : CTI_Gear_Control_CreateTemplate {
idc = 70402;
y = "SafeZoneY + (SafezoneH * 0.806)";
text = "Delete Template";
tooltip = "Remove an existing template";
action = "['onTemplateDeletion', lnbCurSelRow 70108] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_Buy : CTI_Gear_Control_CreateTemplate {
idc = 70403;
y = "SafeZoneY + (SafezoneH * 0.903)";
text = "Buy";
tooltip = "Purchase the current gear setup";
action = "['onPurchase'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Menu_Control_Info : RscStructuredText {
idc = 70028;
x = "SafeZoneX + (SafeZoneW * 0.41)";
y = "SafeZoneY + (SafezoneH * 0.21)";
w = "SafeZoneW * 0.28";
h = "SafeZoneH * 0.06";
size = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Gear_Control_Clear : RscButton_Lesser {
idc = 70029;
x = "SafeZoneX + (SafeZoneW * 0.01)";
y = "SafeZoneY + (SafezoneH * 0.96)";
w = "SafeZoneW * 0.185";
h = "SafeZoneH * 0.04";
text = "Clear";
tooltip = "Clear the gear of the existing target";
action = "['onInventoryClear'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Gear_Control_Reload : CTI_Gear_Control_Clear {
idc = 70030;
x = "SafeZoneX + (SafeZoneW * 0.205)";
text = "Reload";
tooltip = "Reload the last purchased gear for this target";
action = "['onInventoryReload'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_GearMenu.sqf'";
};
class CTI_Control_Exit : RscButton {
idc = 22555;
x = "SafeZoneX + (SafeZoneW * 0.95)";
y = "SafeZoneY + (SafezoneH * 0.01)";
w = "SafeZoneW * 0.04";
h = "SafeZoneH * 0.04";
text = "X";
action = "closeDialog 0";
};
};
};
class CTI_RscRespawnMenu {
movingEnable = 0;
idd = 120000;
onLoad = "uiNamespace setVariable ['cti_dialog_ui_respawnmenu', _this select 0];['onLoad'] execVM 'Client\Events\Events_UI_RespawnMenu.sqf'";
onUnload = "uiNamespace setVariable ['cti_dialog_ui_respawnmenu', nil]; ['onUnload'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_RespawnMenu.sqf'";
class controlsBackground {
class CTI_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.15)";
y = "SafeZoneY + (SafezoneH * 0.15)";
w = "SafeZoneW * 0.7";
h = "SafeZoneH * 0.7";
colorBackground[] = {0, 0, 0, 0.7};
moving = 1;
};
class CTI_Background_Header : CTI_Background {
x = "SafeZoneX + (SafeZoneW * 0.15)";
y = "SafeZoneY + (SafezoneH * 0.15)";
w = "SafeZoneW * 0.7";
h = "SafeZoneH * 0.05"; //0.06 stock
colorBackground[] = {0, 0, 0, 0.4};
};
class CTI_Menu_Title : RscText {
style = ST_LEFT;
x = "SafeZoneX + (SafeZoneW * 0.17)";
y = "SafeZoneY + (SafezoneH * 0.155)";
w = "SafeZoneW * 0.68";
h = "SafeZoneH * 0.037";
text = "Respawn Menu";
colorText[] = {0.258823529, 0.713725490, 1, 1};
sizeEx = "( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_MapFrame : RscFrame {
x = "SafeZoneX + (SafeZoneW * 0.16)";
y = "SafeZoneY + (SafezoneH * 0.21)";
w = "SafeZoneW * 0.40";
h = "SafeZoneH * 0.58";
};
class CTI_Menu_InfoFrame : CTI_Menu_MapFrame {
y = "SafeZoneY + (SafezoneH * 0.8)";
w = "SafeZoneW * 0.40";
h = "SafeZoneH * 0.04";
};
class CTI_Menu_ListLabelFrame : CTI_Menu_MapFrame {
x = "SafeZoneX + (SafeZoneW * 0.57)";
w = "SafeZoneW * 0.27";
h = "SafeZoneH * 0.04";
};
class CTI_Menu_ListFrame : CTI_Menu_ListLabelFrame {
y = "SafeZoneY + (SafezoneH * 0.26)";
h = "SafeZoneH * 0.58";
};
class CTI_Menu_ListInfo_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.57)";
y = "SafeZoneY + (SafezoneH * 0.21)";
w = "SafeZoneW * 0.27";
h = "SafeZoneH * 0.04";
colorBackground[] = {0.5, 0.5, 0.5, 0.25};
};
class CTI_Menu_ListInfo_Text : RscText {
style = ST_CENTER;
x = "SafeZoneX + (SafeZoneW * 0.57)";
y = "SafeZoneY + (SafezoneH * 0.21)";
w = "SafeZoneW * 0.27";
h = "SafeZoneH * 0.04";
text = "Available locations";
sizeEx = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
};
class controls {
class CTI_Menu_Map : RscMapControl {
idc = 120001;
x = "SafeZoneX + (SafeZoneW * 0.16)";
y = "SafeZoneY + (SafezoneH * 0.21)";
w = "SafeZoneW * 0.40";
h = "SafeZoneH * 0.58";
showCountourInterval = 1;
onMouseMoving = "mouseX = (_this select 1);mouseY = (_this select 2)";
onMouseButtonDown = "mouseButtonDown = _this select 1;";
onMouseButtonUp = "mouseButtonUp = _this select 1;";
};
class CTI_Menu_Control_LocationList : RscListBox {
idc = 120002;
x = "SafeZoneX + (SafeZoneW * 0.57)";
w = "SafeZoneW * 0.27";
y = "SafeZoneY + (SafezoneH * 0.26)";
h = "SafeZoneH * 0.58";
rowHeight = "1.5 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
sizeEx = "0.78 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
colorText[] = {1,1,1,1};
colorBackground[] = {0,0,0,0};
onLBSelChanged = "['onSpawnLBSelChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_RespawnMenu.sqf'";
// onLBDblClick = "['onBuildStructureLBDblClick', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_BuildMenu.sqf'";
};
class CTI_Menu_Respawn_Info : RscStructuredText {
idc = 120003;
x = "SafeZoneX + (SafeZoneW * 0.16)";
y = "SafeZoneY + (SafezoneH * 0.805)";
w = "SafeZoneW * 0.40";
h = "SafeZoneH * 0.035";
size = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class LineMarker
{
lineDistanceMin = 3e-005;
lineLengthMin = 5;
lineWidthThick = 0.014;
lineWidthThin = 0.008;
textureComboBoxColor = "#(argb,8,8,3)color(1,1,1,1)";
};
};
};
class CTI_RscOptionsMenu {
movingEnable = 0;
idd = 130000;
onLoad = "uiNamespace setVariable ['cti_dialog_ui_optionsmenu', _this select 0];['onLoad'] execVM 'Client\Events\Events_UI_OptionsMenu.sqf'";
onUnload = "uiNamespace setVariable ['cti_dialog_ui_optionsmenu', nil]; ['onUnload'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_OptionsMenu.sqf'";
class controlsBackground {
class CTI_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.2)";
y = "SafeZoneY + (SafezoneH * 0.175)";
w = "SafeZoneW * 0.3";
h = "SafeZoneH * 0.73";
colorBackground[] = {0, 0, 0, 0.7};
moving = 1;
};
class CTI_Background_Header : CTI_Background {
x = "SafeZoneX + (SafeZoneW * 0.2)";
y = "SafeZoneY + (SafezoneH * 0.175)";
w = "SafeZoneW * 0.3";
h = "SafeZoneH * 0.05"; //0.06 stock
colorBackground[] = {0, 0, 0, 0.4};
};
class CTI_Menu_Title : RscText {
style = ST_LEFT;
x = "SafeZoneX + (SafeZoneW * 0.22)";
y = "SafeZoneY + (SafezoneH * 0.18)";
w = "SafeZoneW * 0.28";
h = "SafeZoneH * 0.037";
text = "Options & Info";
colorText[] = {0.258823529, 0.713725490, 1, 1};
sizeEx = "( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_InfoListFrame : RscFrame {
x = "SafeZoneX + (SafeZoneW * 0.21)";
y = "SafeZoneY + (SafezoneH * 0.245)";
w = "SafeZoneW * 0.28";
h = "SafeZoneH * 0.18";
};
class CTI_Menu_Info_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.21)";
y = "SafeZoneY + (SafezoneH * 0.245)";
w = "SafeZoneW * 0.28";
h = "SafeZoneH * 0.18";
colorBackground[] = {0.5, 0.5, 0.5, 0.25};
};
};
class controls {
class CTI_Menu_Options_Info1 : RscStructuredText {
idc = 130001;
x = "SafeZoneX + (SafeZoneW * 0.21)";
y = "SafeZoneY + (SafezoneH * 0.245)";
w = "SafeZoneW * 0.28";
h = "SafeZoneH * 0.03";
size = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
// text = "Victory: Destroy Enemy";
};
class CTI_Menu_Options_Info2 : CTI_Menu_Options_Info1 {
idc = 130002;
y = "SafeZoneY + (SafezoneH * 0.275)";
// text = "Victory: Destroy Enemy";
};
class CTI_Menu_Options_Info3 : CTI_Menu_Options_Info1 {
idc = 130003;
y = "SafeZoneY + (SafezoneH * 0.305)";
// text = "Player Pool: 30%";
};
class CTI_Menu_Options_Info4 : CTI_Menu_Options_Info1 {
idc = 130004;
y = "SafeZoneY + (SafezoneH * 0.335)";
// text = "Award Pool: 30%";
};
class CTI_Menu_Options_Info5 : CTI_Menu_Options_Info1 {
idc = 130005;
y = "SafeZoneY + (SafezoneH * 0.365)";
// text = "Resources: $23125 (+$510/min)";
};
class CTI_Menu_Options_Info6 : CTI_Menu_Options_Info1 {
idc = 130006;
y = "SafeZoneY + (SafezoneH * 0.395)";
// text = "Towns Held: 0/23";
};
class CTI_Menu_Options_OnlineHelp : RscButton {
idc = 130006;
x = "SafeZoneX + (SafeZoneW * 0.21)";
y = "SafeZoneY + (SafezoneH * 0.445)";
w = "SafeZoneW * 0.28";
h = "SafeZoneH * 0.04";
text = "Help";
action = "['onOnlineHelpPressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_OptionsMenu.sqf'";
};
class CTI_Menu_Options_Video : CTI_Menu_Options_OnlineHelp {
idc = 130007;
y = "SafeZoneY + (SafezoneH * 0.495)";
text = "Video Settings";
action = "['onVideoSettingsPressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_OptionsMenu.sqf'";
};
class CTI_Menu_Options_Music : CTI_Menu_Options_OnlineHelp {
idc = 130008;
y = "SafeZoneY + (SafezoneH * 0.545)";
text = "Play Music: Off";
action = "['onMusicPressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_OptionsMenu.sqf'";
};
class CTI_Menu_Options_TransferFunds : CTI_Menu_Options_OnlineHelp {
idc = 130009;
y = "SafeZoneY + (SafezoneH * 0.595)";
text = "Transfer Resources";
action = "['onTransferResourcesPressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_OptionsMenu.sqf'";
};
class CTI_Menu_Options_Unflip : CTI_Menu_Options_OnlineHelp {
idc = 130010;
y = "SafeZoneY + (SafezoneH * 0.645)";
text = "Unflip Nearest Vehicle";
action = "['onUnflipPressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_OptionsMenu.sqf'";
};
class CTI_Menu_Options_Service : CTI_Menu_Options_OnlineHelp {
idc = 130011;
y = "SafeZoneY + (SafezoneH * 0.695)";
text = "Service Menu";
action = "['onServicePressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_OptionsMenu.sqf'";
};
class CTI_Menu_Options_AIMicro : CTI_Menu_Options_OnlineHelp {
idc = 130014;
y = "SafeZoneY + (SafezoneH * 0.745)";
text = "AI Management";
action = "['onAIMicroPressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_OptionsMenu.sqf'";
};
class CTI_Menu_Options_UnitsCam : CTI_Menu_Options_OnlineHelp { //--- Render out
idc = 130012;
y = "SafeZoneY + (SafezoneH * 3.795)";
text = "Units Camera";
action = "['onUnitsCamPressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_OptionsMenu.sqf'";
};
class CTI_Menu_Options_SatCam : CTI_Menu_Options_OnlineHelp { //--- Render out
idc = 130013;
y = "SafeZoneY + (SafezoneH * 3.845)";
text = "Satellite Camera";
action = "['onSatCamPressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_OptionsMenu.sqf'";
};
class CTI_Control_Exit : RscButton {
idc = 22555;
x = "SafeZoneX + (SafeZoneW * 0.45)";
y = "SafeZoneY + (SafezoneH * 0.18)";
w = "SafeZoneW * 0.04";
h = "SafeZoneH * 0.04";
text = "X";
action = "closeDialog 0";
};
};
};
class CTI_RscTransferResourcesMenu {
movingEnable = 0;
idd = 140000;
onLoad = "uiNamespace setVariable ['cti_dialog_ui_transferresourcesmenu', _this select 0];['onLoad'] execVM 'Client\Events\Events_UI_TransferResourcesMenu.sqf'";
onUnload = "uiNamespace setVariable ['cti_dialog_ui_transferresourcesmenu', nil]; ['onUnload'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_TransferResourcesMenu.sqf'";
class controlsBackground {
class CTI_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.2)";
y = "SafeZoneY + (SafezoneH * 0.205)";
w = "SafeZoneW * 0.6";
h = "SafeZoneH * 0.47";
colorBackground[] = {0, 0, 0, 0.7};
moving = 1;
};
class CTI_Background_Header : CTI_Background {
x = "SafeZoneX + (SafeZoneW * 0.2)";
y = "SafeZoneY + (SafezoneH * 0.205)";
w = "SafeZoneW * 0.6";
h = "SafeZoneH * 0.05"; //0.06 stock
colorBackground[] = {0, 0, 0, 0.4};
};
class CTI_Menu_Title : RscText {
style = ST_LEFT;
x = "SafeZoneX + (SafeZoneW * 0.22)";
y = "SafeZoneY + (SafezoneH * 0.21)";
w = "SafeZoneW * 0.58";
h = "SafeZoneH * 0.037";
text = "Resources Menu";
colorText[] = {0.258823529, 0.713725490, 1, 1};
sizeEx = "( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_InfoListFrame : RscFrame {
x = "SafeZoneX + (SafeZoneW * 0.22)";
y = "SafeZoneY + (SafezoneH * 0.275)";
w = "SafeZoneW * 0.29";
h = "SafeZoneH * 0.38";
};
class CTI_Menu_InfoResourcesFrame : RscFrame {
x = "SafeZoneX + (SafeZoneW * 0.52)";
y = "SafeZoneY + (SafezoneH * 0.275)";
w = "SafeZoneW * 0.26";
h = "SafeZoneH * 0.06";
};
class CTI_Menu_TransferFrame : RscFrame {
x = "SafeZoneX + (SafeZoneW * 0.52)";
y = "SafeZoneY + (SafezoneH * 0.35)";
w = "SafeZoneW * 0.26";
h = "SafeZoneH * 0.1";
};
class CTI_Menu_IncomeFrame : RscFrame {
x = "SafeZoneX + (SafeZoneW * 0.52)";
y = "SafeZoneY + (SafezoneH * 0.465)";
w = "SafeZoneW * 0.26";
h = "SafeZoneH * 0.06";
};
class CTI_Menu_Info_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.52)";
y = "SafeZoneY + (SafezoneH * 0.275)";
w = "SafeZoneW * 0.26";
h = "SafeZoneH * 0.06";
colorBackground[] = {0.5, 0.5, 0.5, 0.25};
};
class CTI_Menu_CommanderFrame : CTI_Menu_InfoResourcesFrame {
y = "SafeZoneY + (SafezoneH * 0.54)";
h = "SafeZoneH * 0.115";
};
class CTI_Menu_Commander_Background : CTI_Menu_Info_Background {
y = "SafeZoneY + (SafezoneH * 0.54)";
h = "SafeZoneH * 0.115";
};
class CTI_Menu_Transfer_Background : CTI_Menu_Info_Background {
y = "SafeZoneY + (SafezoneH * 0.35)";
h = "SafeZoneH * 0.1";
};
class CTI_Menu_Income_Background : CTI_Menu_Info_Background {
y = "SafeZoneY + (SafezoneH * 0.465)";
h = "SafeZoneH * 0.06";
};
class CTI_Menu_Info_EditBackground : RscText {
x = "SafeZoneX + (SafeZoneW * 0.71)";
y = "SafeZoneY + (SafezoneH * 0.36)";
w = "SafeZoneW * 0.065";
h = "SafeZoneH * 0.03";
colorBackground[] = {0, 0, 0, 0.8};
};
class CTI_Menu_Players_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.22)";
y = "SafeZoneY + (SafezoneH * 0.275)";
w = "SafeZoneW * 0.29";
h = "SafeZoneH * 0.38";
colorBackground[] = {0.5, 0.5, 0.5, 0.10};
};
class CTI_Menu_PlayerPoolLabel : RscText {
x = "SafeZoneX + (SafeZoneW * 0.52)";
y = "SafeZoneY + (SafezoneH * 0.55)";
w = "SafeZoneW * 0.16";
h = "SafeZoneH * 0.035";
text = "Player Resources %";
sizeEx = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_AwardPoolLabel : CTI_Menu_PlayerPoolLabel {
y = "SafeZoneY + (SafezoneH * 0.605)";
text = "Award Pool %";
};
};
class controls {
class CTI_Menu_Funds_GroupsList : RscListNBox {
idc = 140001;
x = "SafeZoneX + (SafeZoneW * 0.22)";
y = "SafeZoneY + (SafezoneH * 0.275)";
w = "SafeZoneW * 0.29";
h = "SafeZoneH * 0.38";
rowHeight = "1.22 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
sizeEx = "0.78 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
colorText[] = {1,1,1,1};
colorBackground[] = {0,0,0,0};
itemBackground[] = {1,1,1,0.1};
// columns[] = {0.001, 0.26};
columns[] = {0.001, 0.3};
onLBDblClick = "['onGivePlayerPressed', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_TransferResourcesMenu.sqf'";
onLBSelChanged = "['onGroupLBSelChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_TransferResourcesMenu.sqf'";
};
class CTI_Menu_Funds_MyResources : RscStructuredText {
idc = 140002;
x = "SafeZoneX + (SafeZoneW * 0.52)";
y = "SafeZoneY + (SafezoneH * 0.275)";
w = "SafeZoneW * 0.26";
h = "SafeZoneH * 0.03";
size = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
// text = "Your Resources: $8000";
};
class CTI_Menu_Funds_TargetResources : CTI_Menu_Funds_MyResources {
idc = 140003;
y = "SafeZoneY + (SafezoneH * 0.305)";
size = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
// text = "Player Resources: $8000";
};
class CTI_Menu_Funds_Slider : RscXSliderH {
idc = 140008;
x = "SafeZoneX + (SafeZoneW * 0.525)";
y = "SafeZoneY + (SafezoneH * 0.36)";
w = "SafeZoneW * 0.18";
h = "SafeZoneH * 0.03";
onSliderPosChanged = "['onFundSliderChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_TransferResourcesMenu.sqf'";
};
class CTI_Menu_Funds_Box : RscEdit {
idc = 140009;
x = "SafeZoneX + (SafeZoneW * 0.71)";
y = "SafeZoneY + (SafezoneH * 0.36)";
w = "SafeZoneW * 0.065";
h = "SafeZoneH * 0.03";
sizeEx = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
text = "0";
};
class CTI_Menu_Funds_GivePlayer : RscButton {
idc = 140004;
x = "SafeZoneX + (SafeZoneW * 0.525)";
y = "SafeZoneY + (SafezoneH * 0.4)";
w = "SafeZoneW * 0.25";
h = "SafeZoneH * 0.04";
text = "Give Player";
action = "['onGivePlayerPressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_TransferResourcesMenu.sqf'";
};
class CTI_Menu_Funds_Commander : RscStructuredText {
idc = 140010;
x = "SafeZoneX + (SafeZoneW * 0.52)";
y = "SafeZoneY + (SafezoneH * 0.465)";
w = "SafeZoneW * 0.26";
h = "SafeZoneH * 0.03";
size = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_Funds_Players : CTI_Menu_Funds_Commander {
idc = 140011;
y = "SafeZoneY + (SafezoneH * 0.495)";
size = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_Funds_ResourcesPool : RscCombo {
idc = 140006;
x = "SafeZoneX + (SafeZoneW * 0.7)";
y = "SafeZoneY + (SafezoneH * 0.55)";
w = "SafeZoneW * 0.07";
h = "SafeZoneH * 0.04";
onLBSelChanged = "['onResourcesPoolLBSelChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_TransferResourcesMenu.sqf'";
sizeEx = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_Funds_AwardPool : CTI_Menu_Funds_ResourcesPool {
idc = 140007;
y = "SafeZoneY + (SafezoneH * 0.605)";
onLBSelChanged = "['onAwardPoolLBSelChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_TransferResourcesMenu.sqf'";
};
class CTI_Control_Exit : RscButton {
idc = 22555;
x = "SafeZoneX + (SafeZoneW * 0.74)";
y = "SafeZoneY + (SafezoneH * 0.21)";
w = "SafeZoneW * 0.04";
h = "SafeZoneH * 0.04";
text = "X";
action = "closeDialog 0";
};
class CTI_Control_Back : CTI_Control_Exit {
idc = 22555;
x = "SafeZoneX + (SafeZoneW * 0.695)";
text = "<<";
action = "['onGoBack'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_TransferResourcesMenu.sqf'";
};
};
};
class CTI_RscVideoSettingsMenu {
movingEnable = 0;
idd = 150000;
onLoad = "uiNamespace setVariable ['cti_dialog_ui_videosettingsmenu', _this select 0];['onLoad'] execVM 'Client\Events\Events_UI_VideoSettingsMenu.sqf'";
onUnload = "uiNamespace setVariable ['cti_dialog_ui_videosettingsmenu', nil]; ['onUnload'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_VideoSettingsMenu.sqf'";
class controlsBackground {
class CTI_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.2)";
y = "SafeZoneY + (SafezoneH * 0.205)";
w = "SafeZoneW * 0.3";
h = "SafeZoneH * 0.426";
colorBackground[] = {0, 0, 0, 0.7};
moving = 1;
};
class CTI_Background_Header : CTI_Background {
x = "SafeZoneX + (SafeZoneW * 0.2)";
y = "SafeZoneY + (SafezoneH * 0.205)";
w = "SafeZoneW * 0.3";
h = "SafeZoneH * 0.05";
colorBackground[] = {0, 0, 0, 0.4};
};
class CTI_Menu_Title : RscText {
style = ST_LEFT;
x = "SafeZoneX + (SafeZoneW * 0.22)";
y = "SafeZoneY + (SafezoneH * 0.21)";
w = "SafeZoneW * 0.28";
h = "SafeZoneH * 0.037";
text = "Video Settings";
colorText[] = {0.258823529, 0.713725490, 1, 1};
sizeEx = "( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_InfoListFrame : RscFrame {
x = "SafeZoneX + (SafeZoneW * 0.21)";
y = "SafeZoneY + (SafezoneH * 0.275)";
w = "SafeZoneW * 0.28";
h = "SafeZoneH * 0.2";
};
class CTI_Menu_Info_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.21)";
y = "SafeZoneY + (SafezoneH * 0.275)";
w = "SafeZoneW * 0.28";
h = "SafeZoneH * 0.2";
colorBackground[] = {0.5, 0.5, 0.5, 0.25};
};
class CTI_Menu_GridFrame : CTI_Menu_InfoListFrame {
y = "SafeZoneY + (SafezoneH * 0.491)";
h = "SafeZoneH * 0.07";
};
class CTI_Menu_Grid_Background : CTI_Menu_Info_Background {
y = "SafeZoneY + (SafezoneH * 0.491)";
h = "SafeZoneH * 0.07";
};
};
class controls {
class CTI_Menu_Video_ViewDistanceLabel : RscText {
idc = 150001;
x = "SafeZoneX + (SafeZoneW * 0.21)";
y = "SafeZoneY + (SafezoneH * 0.275)";
w = "SafeZoneW * 0.28";
h = "SafeZoneH * 0.035";
text = "View Distance: 1000m";
sizeEx = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_Video_ViewDistance : RscXSliderH {
idc = 150002;
x = "SafeZoneX + (SafeZoneW * 0.22)";
y = "SafeZoneY + (SafezoneH * 0.31)";
w = "SafeZoneW * 0.26";
h = "SafeZoneH * 0.025";
onSliderPosChanged = "['onViewSliderChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_VideoSettingsMenu.sqf'";
};
class CTI_Menu_Video_ObjectDistanceLabel : CTI_Menu_Video_ViewDistanceLabel {
idc = 150003;
y = "SafeZoneY + (SafezoneH * 0.34)";
text = "Objects Distance: 1000m";
};
class CTI_Menu_Video_ObjectDistance : CTI_Menu_Video_ViewDistance {
idc = 150004;
y = "SafeZoneY + (SafezoneH * 0.375)";
onSliderPosChanged = "['onObjectSliderChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_VideoSettingsMenu.sqf'";
};
class CTI_Menu_Video_ShadowsDistanceLabel : CTI_Menu_Video_ViewDistanceLabel {
idc = 150005;
y = "SafeZoneY + (SafezoneH * 0.405)";
// text = "Shadows Distance: 200m";
};
class CTI_Menu_Video_ShadowsDistance : CTI_Menu_Video_ViewDistance {
idc = 150006;
y = "SafeZoneY + (SafezoneH * 0.44)";
onSliderPosChanged = "['onShadowsSliderChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_VideoSettingsMenu.sqf'";
};
class CTI_Menu_Video_GridLabel : CTI_Menu_Video_ViewDistanceLabel {
idc = 150007;
y = "SafeZoneY + (SafezoneH * 0.491)";
// text = "Terrain Grid: 25";
};
class CTI_Menu_Video_GridLevel : CTI_Menu_Video_ViewDistance {
idc = 150008;
y = "SafeZoneY + (SafezoneH * 0.526)";
onSliderPosChanged = "['onGridSliderChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_VideoSettingsMenu.sqf'";
};
class CTI_Menu_Hints : RscButton {
idc = 150009;
x = "SafeZoneX + (SafeZoneW * 0.21)";
y = "SafeZoneY + (SafezoneH * 0.576)";
w = "SafeZoneW * 0.28";
h = "SafeZoneH * 0.04";
text = "";
action = "['onHintsPressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_VideoSettingsMenu.sqf'";
};
class CTI_Control_Exit : RscButton {
idc = 22555;
x = "SafeZoneX + (SafeZoneW * 0.45)";
y = "SafeZoneY + (SafezoneH * 0.21)";
w = "SafeZoneW * 0.04";
h = "SafeZoneH * 0.04";
text = "X";
action = "closeDialog 0";
};
class CTI_Control_Back : CTI_Control_Exit {
idc = 22555;
x = "SafeZoneX + (SafeZoneW * 0.405)";
text = "<<";
action = "closeDialog 0; createDialog 'CTI_RscOptionsMenu';";
};
};
};
class CTI_RscOnlineHelpMenu {
movingEnable = 0;
idd = 160000;
onLoad = "uiNamespace setVariable ['cti_dialog_ui_onlinehelpmenu', _this select 0];['onLoad'] execVM 'Client\Events\Events_UI_OnlineHelpMenu.sqf'";
onUnload = "uiNamespace setVariable ['cti_dialog_ui_onlinehelpmenu', nil]; ['onUnload'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_OnlineHelpMenu.sqf'";
class controlsBackground {
class CTI_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.1)";
y = "SafeZoneY + (SafezoneH * 0.105)";
w = "SafeZoneW * 0.8";
h = "SafeZoneH * 0.8";
colorBackground[] = {0, 0, 0, 0.7};
moving = 1;
};
class CTI_Background_Header : CTI_Background {
x = "SafeZoneX + (SafeZoneW * 0.1)";
y = "SafeZoneY + (SafezoneH * 0.105)";
w = "SafeZoneW * 0.8";
h = "SafeZoneH * 0.05"; //0.06 stock
colorBackground[] = {0, 0, 0, 0.4};
};
class CTI_Menu_Title : RscText {
style = ST_LEFT;
x = "SafeZoneX + (SafeZoneW * 0.12)";
y = "SafeZoneY + (SafezoneH * 0.11)";
w = "SafeZoneW * 0.78";
h = "SafeZoneH * 0.037";
text = "Help";
colorText[] = {0.258823529, 0.713725490, 1, 1};
sizeEx = "( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_InfoListFrame : RscFrame {
x = "SafeZoneX + (SafeZoneW * 0.12)";
y = "SafeZoneY + (SafezoneH * 0.175)";
w = "SafeZoneW * 0.2";
h = "SafeZoneH * 0.71";
};
class CTI_Menu_InfoResourcesFrame : RscFrame {
x = "SafeZoneX + (SafeZoneW * 0.34)";
y = "SafeZoneY + (SafezoneH * 0.175)";
w = "SafeZoneW * 0.54";
h = "SafeZoneH * 0.71";
};
class CTI_Menu_Info_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.34)";
y = "SafeZoneY + (SafezoneH * 0.175)";
w = "SafeZoneW * 0.54";
h = "SafeZoneH * 0.71";
colorBackground[] = {0.5, 0.5, 0.5, 0.25};
};
class CTI_Control_Exit : RscButton {
idc = 22555;
x = "SafeZoneX + (SafeZoneW * 0.84)";
y = "SafeZoneY + (SafezoneH * 0.11)";
w = "SafeZoneW * 0.04";
h = "SafeZoneH * 0.04";
text = "X";
action = "closeDialog 0";
};
class CTI_Control_Back : CTI_Control_Exit {
idc = 22555;
x = "SafeZoneX + (SafeZoneW * 0.795)";
text = "<<";
action = "closeDialog 0; createDialog 'CTI_RscOptionsMenu';";
};
};
class controls {
class CTI_Menu_Help_Topics : RscListBox {
idc = 160001;
x = "SafeZoneX + (SafeZoneW * 0.12)";
y = "SafeZoneY + (SafezoneH * 0.175)";
w = "SafeZoneW * 0.2";
h = "SafeZoneH * 0.71";
rowHeight = "1.5 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
sizeEx = "0.78 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
colorText[] = {1,1,1,1};
colorBackground[] = {0,0,0,0};
onLBSelChanged = "['onHelpLBSelChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_OnlineHelpMenu.sqf'";
};
class CTI_Menu_Help_ControlsGroup : RscControlsGroup {
x = "SafeZoneX + (SafeZoneW * 0.34)";
y = "SafeZoneY + (SafezoneH * 0.175)";
w = "SafeZoneW * 0.54";
h = "SafeZoneH * 0.71";
class controls {
class CTI_Menu_Help_Explanation : RscStructuredText {
idc = 160002;
x = "0";
y = "0";
w = "SafeZoneW * 0.53";
h = "SafeZoneH * 2.71";
size = "0.85 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
// text = "Your Resources: $8000";
};
};
};
};
};
class CTI_RscSatelitteCamera {
movingEnable = 0;
idd = 170000;
onLoad = "uiNamespace setVariable ['cti_dialog_ui_satcam', _this select 0];['onLoad'] execVM 'Client\Events\Events_UI_SatelitteCamera.sqf'";
onUnload = "uiNamespace setVariable ['cti_dialog_ui_satcam', nil]; ['onUnload'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_SatelitteCamera.sqf'";
class controlsBackground {
class CTI_MouseArea : RscText {
idc = 170001;
style = ST_MULTI;
x = "safezoneX";
y = "safezoneY";
w = "safezoneW";
h = "safezoneH";
text = "";
};
};
class controls {
class CTI_Background : RscText { //--- Render out.
idc = 170002;
x = "SafeZoneX + (SafeZoneW * 0.8)";
y = "SafeZoneY + (SafezoneH * 3.06)";
w = "SafeZoneW * 0.19";
h = "SafeZoneH * 0.55";
colorBackground[] = {0, 0, 0, 0.5};
};
class CTI_Menu_Control_UnitsList_Label : RscText { //--- Render out.
idc = 170003;
x = "SafeZoneX + (SafeZoneW * 0.805)";
y = "SafeZoneY + (SafezoneH * 3.0605)";
w = "SafeZoneW * 0.19";
h = "SafeZoneH * 0.03";
text = "Teams :";
colorText[] = {0.231372549, 0.580392157, 0.929411765, 1};
sizeEx = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_Control_UnitsList_Frame : RscFrame { //--- Render out.
idc = 170004;
x = "SafeZoneX + (SafeZoneW * 0.805)";
y = "SafeZoneY + (SafeZoneH * 3.10)";
h = "SafeZoneH * 0.3";
w = "SafeZoneW * 0.18";
};
class CTI_Menu_Control_UnitsAIList_Label : CTI_Menu_Control_UnitsList_Label { //--- Render out.
idc = 170005;
x = "SafeZoneX + (SafeZoneW * 0.805)";
y = "SafeZoneY + (SafezoneH * 3.41)";
w = "SafeZoneW * 0.19";
h = "SafeZoneH * 0.03";
text = "AI Members :";
};
class CTI_Menu_Control_UnitsAIList_Frame : CTI_Menu_Control_UnitsList_Frame { //--- Render out.
idc = 170006;
x = "SafeZoneX + (SafeZoneW * 0.805)";
y = "SafeZoneY + (SafeZoneH * 3.45)";
h = "SafeZoneH * 0.15";
w = "SafeZoneW * 0.18";
};
class CTI_Menu_Control_ToggleGroups : RscButton_Opac {
idc = 170007;
x = "SafeZoneX + (SafeZoneW * 0.8)";
y = "SafeZoneY + (SafeZoneH * 0.01)";
h = "SafeZoneH * 0.04";
w = "SafeZoneW * 0.19";
text = "";
action = "['onToggleGroup'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_SatelitteCamera.sqf'";
};
class CTI_Menu_Control_ToggleMap : CTI_Menu_Control_ToggleGroups {
idc = 170008;
y = "SafeZoneY + (SafeZoneH * 0.95)";
text = "";
action = "['onToggleMap'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_SatelitteCamera.sqf'";
};
class CTI_Background_Map : CTI_Background { //--- Render out.
idc = 170009;
y = "SafeZoneY + (SafezoneH * 3.62)";
h = "SafeZoneH * 0.32";
};
class CTI_Menu_Map : RscMapControl { //--- Render out.
idc = 170010;
x = "SafeZoneX + (SafeZoneW * 0.805)";
y = "SafeZoneY + (SafezoneH * 3.63)";
w = "SafeZoneW * 0.18";
h = "SafeZoneH * 0.30";
showCountourInterval = 1;
onMouseButtonDown = "nullReturn = _this call CTI_UI_SatelitteCamera_MapClicked";
};
class CTI_Background_Top : CTI_Background {
idc = 170011;
style = ST_CENTER;
x = "SafeZoneX + (SafeZoneW * 0.33)";
y = "SafeZoneY + (SafezoneH * 0.01)";
w = "SafeZoneW * 0.34";
h = "SafeZoneH * 0.04";
text = "";
sizeEx = "0.94 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_Control_Exit : RscButton_Opac {
idc = 170012;
x = "SafeZoneX + (SafeZoneW * 0.01)";
y = "SafeZoneY + (SafeZoneH * 0.95)";
h = "SafeZoneH * 0.04";
w = "SafeZoneW * 0.14";
text = "Exit";
action = "closeDialog 0";
};
class CTI_Menu_Control_Mode : CTI_Menu_Control_Exit {
idc = 170013;
x = "SafeZoneX + (SafeZoneW * 0.16)";
text = "";
action = "['onViewModeChanged'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_SatelitteCamera.sqf'";
};
class CTI_Menu_UnitCamJump : CTI_Menu_Control_Exit {
idc = 170014;
x = "SafeZoneX + (SafeZoneW * 0.31)";
text = "Unit Camera";
action = "['onUnitCameraJump'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_SatelitteCamera.sqf'";
};
class CTI_Menu_Control_ToggleInfo : CTI_Menu_Control_ToggleGroups {
idc = 170015;
x = "SafeZoneX + (SafeZoneW * 0.01)";
y = "SafeZoneY + (SafeZoneH * 0.01)";
text = "";
action = "['onToggleInfo'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_SatelitteCamera.sqf'";
};
class CTI_Background_Info : CTI_Background { //--- Render out.
idc = 170016;
x = "SafeZoneX + (SafeZoneW * 0.01)";
y = "SafeZoneY + (SafezoneH * 3.06)";
w = "SafeZoneW * 0.31";
h = "SafeZoneH * 0.6";
};
class CTI_Menu_Help_ControlsGroup : RscControlsGroup { //--- Render out.
idc = 170019;
x = "SafeZoneX + (SafeZoneW * 0.01)";
y = "SafeZoneY + (SafezoneH * 3.06)";
w = "SafeZoneW * 0.31";
h = "SafeZoneH * 0.6";
class controls {
class CTI_Menu_Control_Info : RscStructuredText {
idc = 170018;
x = 0;
y = 0;
w = "SafeZoneW * 0.31";
h = "SafeZoneH * 1";
size = "0.75 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
};
};
class CTI_Menu_Control_UnitsList : RscListBox { //--- Render out.
idc = 170100;
x = "SafeZoneX + (SafeZoneW * 0.805)";
y = "SafeZoneY + (SafeZoneH * 3.10)";
h = "SafeZoneH * 0.3";
w = "SafeZoneW * 0.18";
rowHeight = "1 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
sizeEx = "0.78 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
colorText[] = {1,1,1,1};
colorBackground[] = {0,0,0,0};
onLBSelChanged = "['onUnitsLBSelChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_SatelitteCamera.sqf'";
};
class CTI_Menu_Control_UnitsAIList : CTI_Menu_Control_UnitsList { //--- Render out.
idc = 170101;
y = "SafeZoneY + (SafeZoneH * 3.45)";
h = "SafeZoneH * 0.15";
onLBSelChanged = "['onUnitsAILBSelChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_SatelitteCamera.sqf'";
};
};
};
class CTI_RscUnitsCamera {
movingEnable = 0;
idd = 180000;
onLoad = "uiNamespace setVariable ['cti_dialog_ui_unitscam', _this select 0];['onLoad'] execVM 'Client\Events\Events_UI_UnitsCamera.sqf'";
onUnload = "uiNamespace setVariable ['cti_dialog_ui_unitscam', nil]; ['onUnload'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_UnitsCamera.sqf'";
class controlsBackground {
class CTI_MouseArea : RscText {
idc = 180001;
style = ST_MULTI;
x = "safezoneX";
y = "safezoneY";
w = "safezoneW";
h = "safezoneH";
text = "";
};
};
class controls {
class CTI_Background : RscText { //--- Render out.
idc = 180002;
x = "SafeZoneX + (SafeZoneW * 0.8)";
y = "SafeZoneY + (SafezoneH * 3.06)";
w = "SafeZoneW * 0.19";
h = "SafeZoneH * 0.55";
colorBackground[] = {0, 0, 0, 0.5};
};
class CTI_Menu_Control_UnitsList_Label : RscText { //--- Render out.
idc = 180003;
x = "SafeZoneX + (SafeZoneW * 0.805)";
y = "SafeZoneY + (SafezoneH * 3.0605)";
w = "SafeZoneW * 0.19";
h = "SafeZoneH * 0.03";
text = "Teams :";
colorText[] = {0.231372549, 0.580392157, 0.929411765, 1};
sizeEx = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_Control_UnitsList_Frame : RscFrame { //--- Render out.
idc = 180004;
x = "SafeZoneX + (SafeZoneW * 0.805)";
y = "SafeZoneY + (SafeZoneH * 3.10)";
h = "SafeZoneH * 0.3";
w = "SafeZoneW * 0.18";
};
class CTI_Menu_Control_UnitsAIList_Label : CTI_Menu_Control_UnitsList_Label { //--- Render out.
idc = 180005;
x = "SafeZoneX + (SafeZoneW * 0.805)";
y = "SafeZoneY + (SafezoneH * 3.41)";
w = "SafeZoneW * 0.19";
h = "SafeZoneH * 0.03";
text = "AI Members :";
};
class CTI_Menu_Control_UnitsAIList_Frame : CTI_Menu_Control_UnitsList_Frame { //--- Render out.
idc = 180006;
x = "SafeZoneX + (SafeZoneW * 0.805)";
y = "SafeZoneY + (SafeZoneH * 3.45)";
h = "SafeZoneH * 0.15";
w = "SafeZoneW * 0.18";
};
class CTI_Menu_Control_ToggleGroups : RscButton_Opac {
idc = 180007;
x = "SafeZoneX + (SafeZoneW * 0.8)";
y = "SafeZoneY + (SafeZoneH * 0.01)";
h = "SafeZoneH * 0.04";
w = "SafeZoneW * 0.19";
text = "";
action = "['onToggleGroup'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_UnitsCamera.sqf'";
};
class CTI_Menu_Control_ToggleMap : CTI_Menu_Control_ToggleGroups {
idc = 180008;
y = "SafeZoneY + (SafeZoneH * 0.95)";
text = "";
action = "['onToggleMap'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_UnitsCamera.sqf'";
};
class CTI_Background_Map : CTI_Background { //--- Render out.
idc = 180009;
y = "SafeZoneY + (SafezoneH * 3.62)";
h = "SafeZoneH * 0.32";
};
class CTI_Menu_Map : RscMapControl { //--- Render out.
idc = 180010;
x = "SafeZoneX + (SafeZoneW * 0.805)";
y = "SafeZoneY + (SafezoneH * 3.63)";
w = "SafeZoneW * 0.18";
h = "SafeZoneH * 0.30";
showCountourInterval = 1;
};
class CTI_Background_Top : CTI_Background {
idc = 180011;
style = ST_CENTER;
x = "SafeZoneX + (SafeZoneW * 0.33)";
y = "SafeZoneY + (SafezoneH * 0.01)";
w = "SafeZoneW * 0.34";
h = "SafeZoneH * 0.04";
text = "";
sizeEx = "0.94 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_Control_Exit : RscButton_Opac {
idc = 180012;
x = "SafeZoneX + (SafeZoneW * 0.01)";
y = "SafeZoneY + (SafeZoneH * 0.95)";
h = "SafeZoneH * 0.04";
w = "SafeZoneW * 0.14";
text = "Exit";
action = "closeDialog 0";
};
class CTI_Menu_Control_Mode : CTI_Menu_Control_Exit {
idc = 180013;
x = "SafeZoneX + (SafeZoneW * 0.16)";
text = "";
action = "['onViewModeChanged'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_UnitsCamera.sqf'";
};
class CTI_Menu_UnitCamJump : CTI_Menu_Control_Exit { //--- Render out
idc = 180014;
x = "SafeZoneX + (SafeZoneW * 3.31)";
text = "Satellite Camera";
action = "['onSatelliteCameraJump'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_UnitsCamera.sqf'";
};
class CTI_Menu_Control_ToggleInfo : CTI_Menu_Control_ToggleGroups {
idc = 180015;
x = "SafeZoneX + (SafeZoneW * 0.01)";
y = "SafeZoneY + (SafeZoneH * 0.01)";
text = "";
action = "['onToggleInfo'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_UnitsCamera.sqf'";
};
class CTI_Background_Info : CTI_Background { //--- Render out.
idc = 180016;
x = "SafeZoneX + (SafeZoneW * 0.01)";
y = "SafeZoneY + (SafezoneH * 3.06)";
w = "SafeZoneW * 0.31";
h = "SafeZoneH * 0.6";
};
class CTI_Menu_Help_ControlsGroup : RscControlsGroup { //--- Render out.
idc = 180018;
x = "SafeZoneX + (SafeZoneW * 0.01)";
y = "SafeZoneY + (SafezoneH * 3.06)";
w = "SafeZoneW * 0.31";
h = "SafeZoneH * 0.6";
class controls {
class CTI_Menu_Control_Info : RscStructuredText {
idc = 180017;
x = 0;
y = 0;
w = "SafeZoneW * 0.31";
h = "SafeZoneH * 1";
size = "0.75 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
};
};
class CTI_Menu_Control_IronSight : RscButton_Opac {
idc = 180019;
x = "SafeZoneX + (SafeZoneW * 0.01)";
y = "SafeZoneY + (SafeZoneH * 0.90)";
h = "SafeZoneH * 0.04";
w = "SafeZoneW * 0.14";
text = "Iron Sight";
action = "['onCamChange', 'ironsight'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_UnitsCamera.sqf'";
};
class CTI_Menu_Control_Internal : CTI_Menu_Control_IronSight {
idc = 180020;
y = "SafeZoneY + (SafeZoneH * 0.85)";
text = "Internal";
action = "['onCamChange', 'internal'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_UnitsCamera.sqf'";
};
class CTI_Menu_Control_External : CTI_Menu_Control_IronSight { //--- Render out.
idc = 180021;
y = "SafeZoneY + (SafeZoneH * 3.80)";
text = "External";
action = "['onCamChange', 'external'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_UnitsCamera.sqf'";
};
class CTI_Menu_Control_Unflip : CTI_Menu_Control_IronSight {
idc = 180022;
y = "SafeZoneY + (SafeZoneH * 0.75)";
text = "Unflip Unit";
action = "['onUnitUnflip'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_UnitsCamera.sqf'";
};
class CTI_Menu_Control_Disband : CTI_Menu_Control_IronSight { //--- Render out.
idc = 180023;
y = "SafeZoneY + (SafeZoneH * 3.70)";
text = "Disband Unit";
action = "['onUnitDisband'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_UnitsCamera.sqf'";
};
class CTI_Menu_Control_UnitsList : RscListBox { //--- Render out.
idc = 180100;
x = "SafeZoneX + (SafeZoneW * 0.805)";
y = "SafeZoneY + (SafeZoneH * 3.10)";
h = "SafeZoneH * 0.3";
w = "SafeZoneW * 0.18";
rowHeight = "1 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
sizeEx = "0.78 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
colorText[] = {1,1,1,1};
colorBackground[] = {0,0,0,0};
onLBSelChanged = "['onUnitsLBSelChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_UnitsCamera.sqf'";
};
class CTI_Menu_Control_UnitsAIList : CTI_Menu_Control_UnitsList { //--- Render out.
idc = 180101;
y = "SafeZoneY + (SafeZoneH * 3.45)";
h = "SafeZoneH * 0.15";
onLBSelChanged = "['onUnitsAILBSelChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_UnitsCamera.sqf'";
};
};
};
class CTI_RscTeamsMenu {
movingEnable = 0;
idd = 190000;
onLoad = "uiNamespace setVariable ['cti_dialog_ui_teamsmenu', _this select 0];['onLoad'] execVM 'Client\Events\Events_UI_TeamsMenu.sqf'";
onUnload = "uiNamespace setVariable ['cti_dialog_ui_teamsmenu', nil]; ['onUnload'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_TeamsMenu.sqf'";
class controlsBackground {
class CTI_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.025)";//0.1
y = "SafeZoneY + (SafezoneH * 0.025)";//0.105
w = "SafeZoneW * 0.95";
h = "SafeZoneH * 0.95";
colorBackground[] = {0, 0, 0, 0.7};
moving = 1;
};
class CTI_Background_Header : CTI_Background {
x = "SafeZoneX + (SafeZoneW * 0.025)";
y = "SafeZoneY + (SafezoneH * 0.025)";
w = "SafeZoneW * 0.95";
h = "SafeZoneH * 0.05"; //0.06 stock
colorBackground[] = {0, 0, 0, 0.4};
};
class CTI_Menu_Title : RscText {
style = ST_LEFT;
x = "SafeZoneX + (SafeZoneW * 0.045)";
y = "SafeZoneY + (SafezoneH * 0.03)";
w = "SafeZoneW * 0.93";
h = "SafeZoneH * 0.037";
text = "Teams";
colorText[] = {0.258823529, 0.713725490, 1, 1};
sizeEx = "( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_InfoListFrame : RscFrame {
// x = "SafeZoneX + (SafeZoneW * 0.11)";
x = "SafeZoneX + (SafeZoneW * 0.035)";
// y = "SafeZoneY + (SafezoneH * 0.175)";
y = "SafeZoneY + (SafezoneH * 0.09)";
w = "SafeZoneW * 0.93";
h = "SafeZoneH * 0.625";
};
class CTI_Menu_ActionListFrame : CTI_Menu_InfoListFrame {
y = "SafeZoneY + (SafezoneH * 0.73)";
w = "SafeZoneW * 0.22";
h = "SafeZoneH * 0.23";
};
class CTI_Menu_ActionTeamListFrame : CTI_Menu_ActionListFrame {
x = "SafeZoneX + (SafeZoneW * 0.265)";
// x = "SafeZoneX + (SafeZoneW * 0.34)";
w = "SafeZoneW * 0.7";
};
class CTI_Menu_Info_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.035)";
y = "SafeZoneY + (SafezoneH * 0.09)";
w = "SafeZoneW * 0.93";
h = "SafeZoneH * 0.04";
colorBackground[] = {0.5, 0.5, 0.5, 0.25};
};
class CTI_Menu_Header_Team : RscText {
x = "SafeZoneX + (SafeZoneW * 0.04)";
y = "SafeZoneY + (SafezoneH * 0.09)";
w = "SafeZoneW * 0.1";
h = "SafeZoneH * 0.04";
colorText[] = {0.678431373, 0.815686275, 1};
text = "Team";
sizeEx = "0.78 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
};
class CTI_Menu_Header_Size : CTI_Menu_Header_Team {
x = "SafeZoneX + (SafeZoneW * 0.271)";
text = "Size";
};
class CTI_Menu_Header_Funds : CTI_Menu_Header_Team {
x = "SafeZoneX + (SafeZoneW * 0.366)";
text = "Resources";
};
class CTI_Menu_Header_Independent : CTI_Menu_Header_Team {
x = "SafeZoneX + (SafeZoneW * 0.485)";
text = "Independent";
};
class CTI_Menu_Header_Role : CTI_Menu_Header_Team {
x = "SafeZoneX + (SafeZoneW * 0.597)";
text = "Role";
};
class CTI_Menu_Header_Order : CTI_Menu_Header_Team {
x = "SafeZoneX + (SafeZoneW * 0.782)";
text = "Order";
};
class CTI_Menu_Action_Independent : RscText {
x = "SafeZoneX + (SafeZoneW * 0.27)";//.345
y = "SafeZoneY + (SafezoneH * 0.75)";
w = "SafeZoneW * 0.1";
h = "SafeZoneH * 0.04";
text = "Independent:";
sizeEx = "0.84 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
};
class CTI_Menu_Action_Role : CTI_Menu_Action_Independent {
y = "SafeZoneY + (SafezoneH * 0.8)";
text = "Role:";
};
class CTI_Menu_Action_Order : CTI_Menu_Action_Independent {
y = "SafeZoneY + (SafezoneH * 0.85)";
text = "Order:";
};
class CTI_Menu_Action_Transfer : CTI_Menu_Action_Independent {
y = "SafeZoneY + (SafezoneH * 0.9)";
text = "Transfer:";
};
class CTI_Control_Exit : RscButton {
idc = 22555;
x = "SafeZoneX + (SafeZoneW * 0.925)";
y = "SafeZoneY + (SafezoneH * 0.03)";
w = "SafeZoneW * 0.04";
h = "SafeZoneH * 0.04";
text = "X";
action = "closeDialog 0";
};
class CTI_Control_Back : CTI_Control_Exit {
idc = 22555;
x = "SafeZoneX + (SafeZoneW * 0.88)";
text = "<<";
action = "closeDialog 0; createDialog 'CTI_RscCommandMenu';";
};
};
class controls {
class CTI_Menu_Control_TeamsList : RscListNBox {
idc = 190001;
x = "SafeZoneX + (SafeZoneW * 0.035)";
y = "SafeZoneY + (SafezoneH * 0.13)";
w = "SafeZoneW * 0.93";
h = "SafeZoneH * 0.585";
rowHeight = "1.3 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
sizeEx = "0.78 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
colorText[] = {1,1,1,1};
colorBackground[] = {0,0,0,0};
itemBackground[] = {1,1,1,0.1};
columns[] = {0.001, 0.25, 0.35, 0.48, 0.6, 0.8};
onLBSelChanged = "['onTeamListLBSelChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_TeamsMenu.sqf'";
// onLBDblClick = "['onBuildStructure', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_BuildMenu.sqf'";
};
class CTI_Control_Button_AIIndependent : RscButton {
idc = 190002;
x = "SafeZoneX + (SafeZoneW * 0.045)";
y = "SafeZoneY + (SafezoneH * 0.74)";
w = "SafeZoneW * 0.2";
h = "SafeZoneH * 0.04";
text = "All AI Independent";
action = "['onAllAIIndependentPressed', 0] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_TeamsMenu.sqf'";
};
class CTI_Control_Button_AINotIndependent : CTI_Control_Button_AIIndependent {
idc = 190003;
y = "SafeZoneY + (SafezoneH * 0.79)";
text = "No AI Independent";
action = "['onAllAIIndependentPressed', 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_TeamsMenu.sqf'";
};
class CTI_Menu_Control_Info : RscStructuredText {
idc = 190004;
x = "SafeZoneX + (SafeZoneW * 0.045)";
y = "SafeZoneY + (SafezoneH * 0.85)";
w = "SafeZoneW * 0.2";
h = "SafeZoneH * 0.03";
// text = "Resources: $900000";
size = "0.85 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_Combo_Independent : RscCombo {
idc = 190005;
x = "SafeZoneX + (SafeZoneW * 0.37)";//.445
y = "SafeZoneY + (SafezoneH * 0.75)";
w = "SafeZoneW * 0.15";
h = "SafeZoneH * 0.04";
sizeEx = "0.78 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_Combo_Role : CTI_Menu_Combo_Independent {
idc = 190006;
y = "SafeZoneY + (SafezoneH * 0.8)";
sizeEx = "0.78 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_Combo_Order : CTI_Menu_Combo_Independent {
idc = 190016;
y = "SafeZoneY + (SafezoneH * 0.85)";
sizeEx = "0.78 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_Combo_Funds : CTI_Menu_Combo_Independent {
idc = 190007;
y = "SafeZoneY + (SafezoneH * 0.9)";
sizeEx = "0.78 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Control_Button_SetIndependent : RscButton {
idc = 190008;
x = "SafeZoneX + (SafeZoneW * 0.53)";//.605
y = "SafeZoneY + (SafezoneH * 0.75)";
w = "SafeZoneW * 0.21";//.12
h = "SafeZoneH * 0.04";
text = "Set";
action = "['onSetTeamIndependentPressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_TeamsMenu.sqf'";
};
class CTI_Control_Button_SetRole : CTI_Control_Button_SetIndependent {
idc = 190009;
y = "SafeZoneY + (SafezoneH * 0.8)";
text = "Set";
action = "['onSetRolePressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_TeamsMenu.sqf'";
};
class CTI_Control_Button_Order : CTI_Control_Button_SetIndependent {
idc = 190010;
y = "SafeZoneY + (SafezoneH * 0.85)";
text = "Order";
action = "['onOrderPressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_TeamsMenu.sqf'";
};
class CTI_Control_Button_SendFunds : CTI_Control_Button_SetIndependent {
idc = 190014;
y = "SafeZoneY + (SafezoneH * 0.9)";
text = "Transfer";
action = "['onTransferFundsPressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_TeamsMenu.sqf'";
};
class CTI_Control_Button_SetIndependentAll : CTI_Control_Button_SetIndependent {
idc = 190011;
x = "SafeZoneX + (SafeZoneW * 0.75)";
y = "SafeZoneY + (SafezoneH * 0.75)";
w = "SafeZoneW * 0.205";
h = "SafeZoneH * 0.04";
text = "Set to All";
action = "['onSetAllTeamIndependentPressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_TeamsMenu.sqf'";
};
class CTI_Control_Button_SetRoleAll : CTI_Control_Button_SetIndependentAll {
idc = 190012;
y = "SafeZoneY + (SafezoneH * 0.8)";
text = "Set to All";
action = "['onSetAllRolePressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_TeamsMenu.sqf'";
};
class CTI_Control_Button_OrderAll : CTI_Control_Button_SetIndependentAll {
idc = 190015;
y = "SafeZoneY + (SafezoneH * 0.85)";
text = "Order to All";
action = "['onOrderAllPressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_TeamsMenu.sqf'";
};
class CTI_Control_Button_TransferAll : CTI_Control_Button_SetIndependentAll {
idc = 190013;
y = "SafeZoneY + (SafezoneH * 0.9)";
text = "Transfer to All";
action = "['onTransferAllPressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_TeamsMenu.sqf'";
};
class CTI_Control_Button_Disbands : RscButton_Lesser {
idc = 190017;
x = "SafeZoneX + (SafeZoneW * 0.045)";
y = "SafeZoneY + (SafezoneH * 0.9)";
w = "SafeZoneW * 0.2";
h = "SafeZoneH * 0.04";
text = "Disband Team";
action = "['onTeamDisband', lnbCurSelRow 190001] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_TeamsMenu.sqf'";
};
};
};
class CTI_RscDefenseMenu {
movingEnable = 0;
idd = 200000;
onLoad = "uiNamespace setVariable ['cti_dialog_ui_defensemenu', _this select 0];['onLoad'] execVM 'Client\Events\Events_UI_DefenseMenu.sqf'";
onUnload = "uiNamespace setVariable ['cti_dialog_ui_defensemenu', nil]; ['onUnload'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_DefenseMenu.sqf'";
class controlsBackground {
class CTI_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.21)";
y = "SafeZoneY + (SafezoneH * 0.175)";
w = "SafeZoneW * 0.305";
h = "SafeZoneH * 0.65";
colorBackground[] = {0, 0, 0, 0.7};
moving = 1;
};
class CTI_Background_Header : CTI_Background {
x = "SafeZoneX + (SafeZoneW * 0.21)";
y = "SafeZoneY + (SafezoneH * 0.175)";
w = "SafeZoneW * 0.305";
h = "SafeZoneH * 0.05"; //0.06 stock
colorBackground[] = {0, 0, 0, 0.4};
};
class CTI_Menu_Title : RscText {
style = ST_LEFT;
x = "SafeZoneX + (SafeZoneW * 0.23)";
y = "SafeZoneY + (SafezoneH * 0.180)";
w = "SafeZoneW * 0.295";
h = "SafeZoneH * 0.037";
text = "Defense Construction";
colorText[] = {0.258823529, 0.713725490, 1, 1};
sizeEx = "( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_DefenseListFrame : RscFrame {
x = "SafeZoneX + (SafeZoneW * 0.225)";
y = "SafeZoneY + (SafezoneH * 0.4675)";
w = "SafeZoneW * 0.275";
h = "SafeZoneH * 0.2875";
};
class CTI_Menu_Info : CTI_Menu_DefenseListFrame {
y = "SafeZoneY + (SafezoneH * 0.235)";
h = "SafeZoneH * 0.06";
};
class CTI_Menu_Info_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.225)";
y = "SafeZoneY + (SafezoneH * 0.235)";
w = "SafeZoneW * 0.275";
h = "SafeZoneH * 0.06";
colorBackground[] = {0.5, 0.5, 0.5, 0.25};
};
};
class controls {
class CTI_Menu_Control_Undo : RscButton {
idc = 200001;
x = "SafeZoneX + (SafeZoneW * 0.225)";
y = "SafeZoneY + (SafeZoneH * 0.77)";
w = "SafeZoneW * 0.275";
h = "SafeZoneH * 0.04";
text = "Undo Defense";
action = "['onUndoDefense'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_DefenseMenu.sqf'";
};
class CTI_Menu_Control_BuildStructure : CTI_Menu_Control_Undo {
idc = 200002;
y = "SafeZoneY + (SafeZoneH * 0.36)";
text = "Build Defense";
action = "['onBuildDefense', lnbCurSelRow 200007] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_DefenseMenu.sqf'";
};
class CTI_Menu_Control_AutoAlign : CTI_Menu_Control_Undo {
idc = 200003;
y = "SafeZoneY + (SafeZoneH * 0.3075)";
text = "";
action = "['onAutoAlign'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_DefenseMenu.sqf'";
};
class CTI_Menu_Control_NVMode : CTI_Menu_Control_Undo {
idc = 200004;
y = "SafeZoneY + (SafeZoneH * 0.4125)";
text = "Normal";
action = "['onViewModeChanged'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_DefenseMenu.sqf'";
};
class CTI_Menu_Control_BuildingList : RscListNBox {
idc = 200007;
x = "SafeZoneX + (SafeZoneW * 0.225)";
y = "SafeZoneY + (SafezoneH * 0.4675)";
w = "SafeZoneW * 0.275";
h = "SafeZoneH * 0.2875";
rowHeight = "1.3 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
sizeEx = "0.78 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
colorText[] = {1,1,1,1};
colorBackground[] = {0,0,0,0};
itemBackground[] = {1,1,1,0.1};
// columns[] = {0.001, 0.26};
columns[] = {0.001, 0.18};
onLBDblClick = "['onBuildDefense', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_DefenseMenu.sqf'";
};
class CTI_Menu_Control_Info : RscStructuredText {
idc = 200008;
x = "SafeZoneX + (SafeZoneW * 0.225)";
y = "SafeZoneY + (SafezoneH * 0.235)";
w = "SafeZoneW * 0.275";
h = "SafeZoneH * 0.03";
size = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_Control_InfoWorkers : CTI_Menu_Control_Info {
idc = 200009;
y = "SafeZoneY + (SafezoneH * 0.265)";
};
class CTI_Control_Exit : RscButton {
idc = 22555;
x = "SafeZoneX + (SafeZoneW * 0.46)";
y = "SafeZoneY + (SafezoneH * 0.18)";
w = "SafeZoneW * 0.04";
h = "SafeZoneH * 0.04";
text = "X";
action = "closeDialog 0";
};
};
};
class CTI_RscCommandMenu {
movingEnable = 0;
idd = 210000;
onLoad = "uiNamespace setVariable ['cti_dialog_ui_commandmenu', _this select 0];['onLoad'] execVM 'Client\Events\Events_UI_CommandMenu.sqf'";
onUnload = "uiNamespace setVariable ['cti_dialog_ui_commandmenu', nil]; ['onUnload'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_CommandMenu.sqf'";
class controlsBackground {
class CTI_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.2)";
y = "SafeZoneY + (SafezoneH * 0.205)";
w = "SafeZoneW * 0.3";
h = "SafeZoneH * 0.47";
colorBackground[] = {0, 0, 0, 0.7};
moving = 1;
};
class CTI_Background_Header : CTI_Background {
x = "SafeZoneX + (SafeZoneW * 0.2)";
y = "SafeZoneY + (SafezoneH * 0.205)";
w = "SafeZoneW * 0.3";
h = "SafeZoneH * 0.05"; //0.06 stock
colorBackground[] = {0, 0, 0, 0.4};
};
class CTI_Menu_Title : RscText {
style = ST_LEFT;
x = "SafeZoneX + (SafeZoneW * 0.22)";
y = "SafeZoneY + (SafezoneH * 0.21)";
w = "SafeZoneW * 0.28";
h = "SafeZoneH * 0.037";
text = "Command Menu";
colorText[] = {0.258823529, 0.713725490, 1, 1};
sizeEx = "( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
};
class controls {
class CTI_Control_Resources : RscButton {
idc = 210002;
x = "SafeZoneX + (SafeZoneW * 0.21)";
y = "SafeZoneY + (SafezoneH * 0.27)";
w = "SafeZoneW * 0.28";
h = "SafeZoneH * 0.04";
text = "Resources";
action = "['onResourcesPressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_CommandMenu.sqf'";
};
class CTI_Control_Teams : CTI_Control_Resources {
idc = 210003;
y = "SafeZoneY + (SafezoneH * 3.32)"; //--- Render out
text = "Teams";
action = "['onTeamsPressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_CommandMenu.sqf'";
};
class CTI_Control_Map : CTI_Control_Resources {
idc = 210004;
y = "SafeZoneY + (SafezoneH * 3.37)"; //--- Render out
text = "Map Commanding";
action = "['onMapPressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_CommandMenu.sqf'";
};
class CTI_Control_Upgrades : CTI_Control_Resources {
idc = 210005;
y = "SafeZoneY + (SafezoneH * 3.42)"; //--- Render out
text = "Upgrades";
action = "['onUpgradesPressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_CommandMenu.sqf'";
};
class CTI_Control_Workers : CTI_Control_Resources {
idc = 210006;
y = "SafeZoneY + (SafezoneH * 3.47)"; //--- Render out
text = "Base Management";
action = "['onWorkersPressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_CommandMenu.sqf'";
};
class CTI_Control_RequestMenu : CTI_Control_Resources {
idc = 210008;
y = "SafeZoneY + (SafezoneH * 3.52)"; //--- Render out
text = "Team Requests";
action = "['onRequestMenuPressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_CommandMenu.sqf'";
};
class CTI_Control_ArtilleryMenu : CTI_Control_Resources {
idc = 210009;
y = "SafeZoneY + (SafezoneH * 3.57)"; //--- Render out
text = "Artillery (To be Implemented)";
action = "['onArtilleryMenuPressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_CommandMenu.sqf'";
};
class CTI_Control_VoteMenu : CTI_Control_Resources {
idc = 210010;
y = "SafeZoneY + (SafezoneH * 3.62)"; //--- Render out
text = "Voting";
action = "['onVoteMenuPressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_CommandMenu.sqf'";
};
class CTI_Control_Exit : RscButton {
idc = 22555;
x = "SafeZoneX + (SafeZoneW * 0.45)";
y = "SafeZoneY + (SafezoneH * 0.21)";
w = "SafeZoneW * 0.04";
h = "SafeZoneH * 0.04";
text = "X";
action = "closeDialog 0";
};
};
};
class CTI_RscMapCommandMenu {
movingEnable = 0;
idd = 220000;
onLoad = "uiNamespace setVariable ['cti_dialog_ui_mapcommandmenu', _this select 0];['onLoad'] execVM 'Client\Events\Events_UI_MapCommandMenu.sqf'";
onUnload = "uiNamespace setVariable ['cti_dialog_ui_mapcommandmenu', nil]; ['onUnload'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_MapCommandMenu.sqf'";
class controlsBackground {
class CTI_Background : RscText {
x = "SafeZoneX";
y = "SafeZoneY";
w = "SafeZoneW";
h = "SafeZoneH";
colorBackground[] = {0, 0, 0, 0.7};
};
class CTI_Background_Header : CTI_Background {
x = "SafeZoneX";
y = "SafeZoneY";
w = "SafeZoneW";
h = "SafeZoneH * 0.05";
colorBackground[] = {0, 0, 0, 0.4};
};
class CTI_Menu_Title : RscText {
style = ST_LEFT;
x = "SafeZoneX + (SafezoneH * 0.02)";
y = "SafeZoneY + (SafezoneH * 0.005)";
w = "SafeZoneW * 0.98";
h = "SafeZoneH * 0.037";
text = "Map Commanding";
colorText[] = {0.258823529, 0.713725490, 1, 1};
sizeEx = "( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_Map : RscMapControl {
idc = 220001;
x = "SafeZoneX";
y = "SafeZoneY + (SafezoneH * 0.05)";
w = "SafeZoneW";
h = "SafeZoneH * 0.95";
// showCountourInterval = 1;
onMouseButtonDown = "['onMapButtonDown', _this] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_MapCommandMenu.sqf'";
};
};
class controls {
class CTI_Background_List : RscText {
idc = 220701;
x = "SafeZoneX + (SafeZoneW * 0.78)";
y = "SafeZoneY + (SafezoneH * 0.06)";
w = "SafeZoneW * 0.21";
h = "SafeZoneH * 0.9";
colorBackground[] = {0, 0, 0, 0.7};
};
class CTI_Menu_UnitsListFrame : RscFrame {
idc = 220702;
x = "SafeZoneX + (SafeZoneW * 0.785)";
y = "SafeZoneY + (SafezoneH * 0.095)";
w = "SafeZoneW * 0.2";
h = "SafeZoneH * 0.30";
};
class CTI_Menu_List_Background : RscText {
idc = 220708;
x = "SafeZoneX + (SafeZoneW * 0.785)";
y = "SafeZoneY + (SafezoneH * 0.095)";
w = "SafeZoneW * 0.2";
h = "SafeZoneH * 0.30";
colorBackground[] = {0.5, 0.5, 0.5, 0.25};
};
class CTI_Menu_Control_UnitsList_Label : RscText { //--- Render out.
idc = 220703;
x = "SafeZoneX + (SafeZoneW * 0.785)";
y = "SafeZoneY + (SafezoneH * 0.06)";
w = "SafeZoneW * 0.19";
h = "SafeZoneH * 0.03";
text = "Teams :";
colorText[] = {0.231372549, 0.580392157, 0.929411765, 1};
sizeEx = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_Control_OrdersList_Label : CTI_Menu_Control_UnitsList_Label { //--- Render out.
idc = 220704;
y = "SafeZoneY + (SafezoneH * 0.405)";
h = "SafeZoneH * 0.03";
text = "Orders :";
};
class CTI_Menu_OrdersListFrame : CTI_Menu_UnitsListFrame {
idc = 220705;
y = "SafeZoneY + (SafezoneH * 0.44)";
h = "SafeZoneH * 0.16";
};
class CTI_Menu_Orders_Background : CTI_Menu_List_Background {
idc = 220709;
y = "SafeZoneY + (SafezoneH * 0.44)";
h = "SafeZoneH * 0.16";
};
class CTI_Menu_Control_OrdersParamList_Label : CTI_Menu_Control_UnitsList_Label { //--- Render out.
idc = 220706;
y = "SafeZoneY + (SafezoneH * 0.61)";
h = "SafeZoneH * 0.03";
text = "Order Parameters :";
};
class CTI_Menu_OrdersParamListFrame : CTI_Menu_UnitsListFrame {
idc = 220707;
y = "SafeZoneY + (SafezoneH * 0.645)";
h = "SafeZoneH * 0.2";
};
class CTI_Menu_OrdersParam_Background : CTI_Menu_List_Background {
idc = 220710;
y = "SafeZoneY + (SafezoneH * 0.645)";
h = "SafeZoneH * 0.2";
};
class CTI_Background_Intel : RscText {
idc = 220711;
x = "SafeZoneX + (SafeZoneW * 0.26)";
y = "SafeZoneY + (SafezoneH * 0.06)";
w = "SafeZoneW * 0.48";
h = "SafeZoneH * 0.03";
colorBackground[] = {0, 0, 0, 0.7};
};
class CTI_Menu_Control_UnitsList : RscListNBox {
idc = 220002;
x = "SafeZoneX + (SafeZoneW * 0.785)";
y = "SafeZoneY + (SafezoneH * 0.095)";
w = "SafeZoneW * 0.2";
h = "SafeZoneH * 0.30";
rowHeight = "1 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
sizeEx = "0.75 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
colorText[] = {1,1,1,1};
colorBackground[] = {0,0,0,0};
itemBackground[] = {1,1,1,0.1};
columns[] = {0.001, 0.4};
onLBDblClick = "['onUnitListLBDblClick', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_MapCommandMenu.sqf'";
onLBSelChanged = "['onUnitListLBSelChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_MapCommandMenu.sqf'";
};
class CTI_Menu_Control_OrdersList : RscListBox {
idc = 220009;
x = "SafeZoneX + (SafeZoneW * 0.785)";
y = "SafeZoneY + (SafezoneH * 0.44)";
w = "SafeZoneW * 0.2";
h = "SafeZoneH * 0.16";
rowHeight = "1 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
sizeEx = "0.75 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
colorText[] = {1,1,1,1};
colorBackground[] = {0,0,0,0};
onLBSelChanged = "['onOrdersListLBSelChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_MapCommandMenu.sqf'";
onLBDblClick = "['onOrdersListLBDblClick', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_MapCommandMenu.sqf'";
};
class CTI_Menu_Control_OrdersParamList : CTI_Menu_Control_OrdersList {
idc = 220010;
y = "SafeZoneY + (SafezoneH * 0.645)";
h = "SafeZoneH * 0.2";
onLBDblClick = "['onOrdersParamLBDblClick', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_MapCommandMenu.sqf'";
onLBSelChanged = "";
};
class CTI_Menu_Control_SetOrder : RscButton_Opac {
idc = 220011;
x = "SafeZoneX + (SafeZoneW * 0.785)";
y = "SafeZoneY + (SafeZoneH * 0.86)";
h = "SafeZoneH * 0.04";
w = "SafeZoneW * 0.2";
sizeEx = "0.85 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
text = "Set Order";
action = "['onSetOrderPressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_MapCommandMenu.sqf'";
};
class CTI_Menu_Control_SetMapOrder : CTI_Menu_Control_SetOrder {
idc = 220012;
y = "SafeZoneY + (SafeZoneH * 0.91)";
text = "Set Order (Map Click)";
action = "['onSetMapOrderPressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_MapCommandMenu.sqf'";
};
class CTI_Menu_Control_IntelText : RscStructuredText {
idc = 220013;
x = "SafeZoneX + (SafeZoneW * 0.26)";
y = "SafeZoneY + (SafezoneH * 0.06)";
w = "SafeZoneW * 0.48";
h = "SafeZoneH * 0.03";
size = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Control_Exit : RscButton {
idc = 22555;
x = "SafeZoneX + (SafeZoneW * 0.95)";
y = "SafeZoneY + (SafezoneH * 0.005)";
w = "SafeZoneW * 0.04";
h = "SafeZoneH * 0.04";
text = "X";
action = "closeDialog 0";
};
class CTI_Control_Back : CTI_Control_Exit {
idc = 22555;
x = "SafeZoneX + (SafeZoneW * 0.905)";
text = "<<";
action = "closeDialog 0; createDialog 'CTI_RscCommandMenu';";
};
};
};
class CTI_RscServiceMenu {
movingEnable = 0;
idd = 230000;
onLoad = "uiNamespace setVariable ['cti_dialog_ui_servicemenu', _this select 0];['onLoad'] execVM 'Client\Events\Events_UI_ServiceMenu.sqf'";
onUnload = "uiNamespace setVariable ['cti_dialog_ui_servicemenu', nil]; ['onUnload'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_ServiceMenu.sqf'";
class controlsBackground {
class CTI_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.2)";
y = "SafeZoneY + (SafezoneH * 0.205)";
w = "SafeZoneW * 0.55";
h = "SafeZoneH * 0.48";
colorBackground[] = {0, 0, 0, 0.7};
moving = 1;
};
class CTI_Background_Header : CTI_Background {
x = "SafeZoneX + (SafeZoneW * 0.2)";
y = "SafeZoneY + (SafezoneH * 0.205)";
w = "SafeZoneW * 0.55";
h = "SafeZoneH * 0.05"; //0.06 stock
colorBackground[] = {0, 0, 0, 0.4};
};
class CTI_Menu_Title : RscText {
style = ST_LEFT;
x = "SafeZoneX + (SafeZoneW * 0.22)";
y = "SafeZoneY + (SafezoneH * 0.21)";
w = "SafeZoneW * 0.53";
h = "SafeZoneH * 0.037";
text = "Service Menu";
colorText[] = {0.258823529, 0.713725490, 1, 1};
sizeEx = "( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_ListFrame : RscFrame {
x = "SafeZoneX + (SafeZoneW * 0.21)";
y = "SafeZoneY + (SafezoneH * 0.27)";
w = "SafeZoneW * 0.53";
h = "SafeZoneH * 0.3";
};
class CTI_Menu_ListHeaders_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.21)";
y = "SafeZoneY + (SafezoneH * 0.27)";
w = "SafeZoneW * 0.53";
h = "SafeZoneH * 0.04";
colorBackground[] = {0.5, 0.5, 0.5, 0.25};
};
class CTI_Menu_Repair_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.21)";
y = "SafeZoneY + (SafeZoneH * 0.58)";
h = "SafeZoneH * 0.04";
w = "SafeZoneW * 0.26";
colorBackground[] = {0.5, 0.5, 0.5, 0.25};
};
class CTI_Menu_Rearm_Background : CTI_Menu_Repair_Background {
y = "SafeZoneY + (SafeZoneH * 0.63)";
};
class CTI_Menu_Refuel_Background : CTI_Menu_Repair_Background {
x = "SafeZoneX + (SafeZoneW * 0.48)";
y = "SafeZoneY + (SafeZoneH * 0.58)";
};
class CTI_Menu_Heal_Background : CTI_Menu_Refuel_Background {
y = "SafeZoneY + (SafeZoneH * 0.63)";
};
class CTI_Menu_Header_Unit : RscText {
x = "SafeZoneX + (SafeZoneW * 0.215)";
y = "SafeZoneY + (SafezoneH * 0.27)";
w = "SafeZoneW * 0.1";
h = "SafeZoneH * 0.04";
colorText[] = {0.678431373, 0.815686275, 1};
text = "Unit";
sizeEx = "0.78 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
};
class CTI_Menu_Header_Damage : CTI_Menu_Header_Unit {
x = "SafeZoneX + (SafeZoneW * 0.48)";
text = "Damage";
};
class CTI_Menu_Header_Fuel : CTI_Menu_Header_Unit {
x = "SafeZoneX + (SafeZoneW * 0.558)";
text = "Fuel";
};
class CTI_Menu_Header_Health : CTI_Menu_Header_Unit {
x = "SafeZoneX + (SafeZoneW * 0.638)";
text = "Health";
};
};
class controls {
class CTI_Menu_Control_Repair : RscButton {
idc = 230001;
x = "SafeZoneX + (SafeZoneW * 0.21)";
y = "SafeZoneY + (SafeZoneH * 0.58)";
h = "SafeZoneH * 0.04";
w = "SafeZoneW * 0.16";
text = "Repair";
action = "['onRepairPressed', lnbCurSelRow 230005] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_ServiceMenu.sqf'";
};
class CTI_Menu_Control_Rearm : CTI_Menu_Control_Repair {
idc = 230002;
y = "SafeZoneY + (SafeZoneH * 0.63)";
text = "Rearm";
action = "['onRearmPressed', lnbCurSelRow 230005] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_ServiceMenu.sqf'";
};
class CTI_Menu_Control_Refuel : CTI_Menu_Control_Repair {
idc = 230003;
x = "SafeZoneX + (SafeZoneW * 0.48)";
y = "SafeZoneY + (SafeZoneH * 0.58)";
text = "Refuel";
action = "['onRefuelPressed', lnbCurSelRow 230005] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_ServiceMenu.sqf'";
};
class CTI_Menu_Control_Heal : CTI_Menu_Control_Refuel {
idc = 230004;
y = "SafeZoneY + (SafeZoneH * 0.63)";
text = "Heal";
action = "['onHealPressed', lnbCurSelRow 230005] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_ServiceMenu.sqf'";
};
class CTI_Menu_RepairCost : RscStructuredText {
idc = 230011;
x = "SafeZoneX + (SafeZoneW * 0.37)";
y = "SafeZoneY + (SafeZoneH * 0.585)";
h = "SafeZoneH * 0.03";
w = "SafeZoneW * 0.1";
text = "";
sizeEx = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_Rearm : CTI_Menu_RepairCost {
idc = 230012;
y = "SafeZoneY + (SafeZoneH * 0.635)";
sizeEx = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_Refuel : CTI_Menu_RepairCost {
idc = 230013;
x = "SafeZoneX + (SafeZoneW * 0.64)";
sizeEx = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_Heal : CTI_Menu_RepairCost {
idc = 230014;
y = "SafeZoneY + (SafeZoneH * 0.635)";
x = "SafeZoneX + (SafeZoneW * 0.64)";
sizeEx = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_Control_EntityList : RscListNBox {
idc = 230005;
x = "SafeZoneX + (SafeZoneW * 0.21)";
y = "SafeZoneY + (SafezoneH * 0.31)";
w = "SafeZoneW * 0.53";
h = "SafeZoneH * 0.26";
rowHeight = "1.3 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
sizeEx = "0.78 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
colorText[] = {1,1,1,1};
colorBackground[] = {0,0,0,0};
itemBackground[] = {1,1,1,0.1};
columns[] = {0.001, 0.50, 0.65, 0.80};
onLBSelChanged = "['onEntityListLBSelChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_ServiceMenu.sqf'";
// onLBDblClick = "['onBuildStructure', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_BuildMenu.sqf'";
};
class CTI_Control_Exit : RscButton {
idc = 22555;
x = "SafeZoneX + (SafeZoneW * 0.7)";
y = "SafeZoneY + (SafeZoneH * 0.21)";
w = "SafeZoneW * 0.04";
h = "SafeZoneH * 0.04";
text = "X";
action = "closeDialog 0";
};
class CTI_Control_Back : CTI_Control_Exit {
idc = 22555;
x = "SafeZoneX + (SafeZoneW * 0.655)";
text = "<<";
action = "closeDialog 0; createDialog 'CTI_RscOptionsMenu';";
};
};
};
class CTI_RscHookMenu {
movingEnable = 0;
idd = 240000;
onLoad = "uiNamespace setVariable ['cti_dialog_ui_hookmenu', _this select 0];['onLoad'] execVM 'Client\Events\Events_UI_HookMenu.sqf'";
onUnload = "uiNamespace setVariable ['cti_dialog_ui_hookmenu', nil]; ['onUnload'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_HookMenu.sqf'";
class controlsBackground {
class CTI_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.2)";
y = "SafeZoneY + (SafezoneH * 0.205)";
w = "SafeZoneW * 0.3";
h = "SafeZoneH * 0.56";
colorBackground[] = {0, 0, 0, 0.7};
moving = 1;
};
class CTI_Background_Header : CTI_Background {
x = "SafeZoneX + (SafeZoneW * 0.2)";
y = "SafeZoneY + (SafezoneH * 0.205)";
w = "SafeZoneW * 0.3";
h = "SafeZoneH * 0.05"; //0.06 stock
colorBackground[] = {0, 0, 0, 0.4};
};
class CTI_Menu_Title : RscText {
style = ST_LEFT;
x = "SafeZoneX + (SafeZoneW * 0.22)";
y = "SafeZoneY + (SafezoneH * 0.21)";
w = "SafeZoneW * 0.28";
h = "SafeZoneH * 0.037";
text = "Hook Menu";
colorText[] = {0.258823529, 0.713725490, 1, 1};
sizeEx = "( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_InfoListFrame : RscFrame {
x = "SafeZoneX + (SafeZoneW * 0.21)";
y = "SafeZoneY + (SafezoneH * 0.275)";
w = "SafeZoneW * 0.28";
h = "SafeZoneH * 0.3";
};
class CTI_Menu_HookInfoFrame : RscFrame {
x = "SafeZoneX + (SafeZoneW * 0.21)";
y = "SafeZoneY + (SafezoneH * 0.64)";
w = "SafeZoneW * 0.28";
h = "SafeZoneH * 0.06";
};
class CTI_Menu_HookInfo_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.21)";
y = "SafeZoneY + (SafezoneH * 0.64)";
w = "SafeZoneW * 0.28";
h = "SafeZoneH * 0.06";
colorBackground[] = {0.5, 0.5, 0.5, 0.25};
};
};
class controls {
class CTI_Menu_Options_Hook : RscButton {
idc = 240001;
x = "SafeZoneX + (SafeZoneW * 0.21)";
y = "SafeZoneY + (SafezoneH * 0.585)";
w = "SafeZoneW * 0.28";
h = "SafeZoneH * 0.04";
text = "Hook";
action = "['onHookPressed', lbCurSel 240004] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_HookMenu.sqf'";
};
class CTI_Menu_Vehicle : RscText {
idc = 240002;
x = "SafeZoneX + (SafeZoneW * 0.21)";
y = "SafeZoneY + (SafezoneH * 0.64)";
h = "SafeZoneH * 0.03";
w = "SafeZoneW * 0.28";
text = "";
sizeEx = "0.82 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_Vehicle_Hooked : CTI_Menu_Vehicle {
idc = 240003;
y = "SafeZoneY + (SafezoneH * 0.67)";
};
class CTI_Menu_Control_TargetList : RscListBox { //--- Render out.
idc = 240004;
x = "SafeZoneX + (SafeZoneW * 0.21)";
y = "SafeZoneY + (SafezoneH * 0.275)";
w = "SafeZoneW * 0.28";
h = "SafeZoneH * 0.3";
rowHeight = "1.2 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
sizeEx = "0.78 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
colorText[] = {1,1,1,1};
colorBackground[] = {0,0,0,0};
onLBDblClick = "['onHookPressed', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_HookMenu.sqf'";
};
class CTI_Menu_Options_Detach : CTI_Menu_Options_Hook {
idc = 240005;
y = "SafeZoneY + (SafezoneH * 0.71)";
text = "Detach";
action = "['onHookDetach'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_HookMenu.sqf'";
};
class CTI_Control_Exit : RscButton {
idc = 22555;
x = "SafeZoneX + (SafeZoneW * 0.45)";
y = "SafeZoneY + (SafezoneH * 0.21)";
w = "SafeZoneW * 0.04";
h = "SafeZoneH * 0.04";
text = "X";
action = "closeDialog 0";
};
};
};
class CTI_RscUpgradeMenu {
movingEnable = 0;
idd = 250000;
onLoad = "uiNamespace setVariable ['cti_dialog_ui_upgrademenu', _this select 0];['onLoad'] execVM 'Client\Events\Events_UI_UpgradeMenu.sqf'";
onUnload = "uiNamespace setVariable ['cti_dialog_ui_upgrademenu', nil]; ['onUnload'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_UpgradeMenu.sqf'";
class controlsBackground {
class CTI_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.21)";
y = "SafeZoneY + (SafezoneH * 0.175)";
w = "SafeZoneW * 0.615";
h = "SafeZoneH * 0.705";
colorBackground[] = {0, 0, 0, 0.7};
moving = 1;
};
class CTI_Background_Header : CTI_Background {
x = "SafeZoneX + (SafeZoneW * 0.21)";
y = "SafeZoneY + (SafezoneH * 0.175)";
w = "SafeZoneW * 0.615";
h = "SafeZoneH * 0.05"; //0.06 stock
colorBackground[] = {0, 0, 0, 0.4};
};
class CTI_Menu_Title : RscText {
style = ST_LEFT;
x = "SafeZoneX + (SafeZoneW * 0.23)";
y = "SafeZoneY + (SafezoneH * 0.180)";
w = "SafeZoneW * 0.595";
h = "SafeZoneH * 0.037";
text = "Upgrade Menu";
colorText[] = {0.258823529, 0.713725490, 1, 1};
sizeEx = "( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_UpgradeListFrame : RscFrame {
x = "SafeZoneX + (SafeZoneW * 0.22)";
y = "SafeZoneY + (SafezoneH * 0.24)";
w = "SafeZoneW * 0.2925";
h = "SafeZoneH * 0.625";
};
class CTI_Menu_UpgradeInfoFrame : RscFrame {
x = "SafeZoneX + (SafeZoneW * 0.5225)";
y = "SafeZoneY + (SafezoneH * 0.24)";
w = "SafeZoneW * 0.2925";
h = "SafeZoneH * 0.525";
};
class CTI_Menu_UpgradeRunningFrame : CTI_Menu_UpgradeInfoFrame {
y = "SafeZoneY + (SafezoneH * 0.78)";
h = "SafeZoneH * 0.03";
};
class CTI_Menu_UpgradeInfo_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.5225)";
y = "SafeZoneY + (SafezoneH * 0.24)";
w = "SafeZoneW * 0.2925";
h = "SafeZoneH * 0.525";
colorBackground[] = {0.5, 0.5, 0.5, 0.25};
};
class CTI_Menu_UpgradeRunning_Background : CTI_Menu_UpgradeInfo_Background {
y = "SafeZoneY + (SafezoneH * 0.78)";
h = "SafeZoneH * 0.03";
};
}
class controls {
class CTI_Control_Upgrade : RscButton {
idc = 250001;
x = "SafeZoneX + (SafeZoneW * 0.5225)";
y = "SafeZoneY + (SafezoneH * 0.825)";
w = "SafeZoneW * 0.2925";
h = "SafeZoneH * 0.04";
text = "Upgrade";
action = "['onUpgradePressed', lnbCurSelRow 250002] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_UpgradeMenu.sqf'";
};
class CTI_Menu_Control_UpgradeList : RscListNBox {
idc = 250002;
x = "SafeZoneX + (SafeZoneW * 0.22)";
y = "SafeZoneY + (SafezoneH * 0.24)";
w = "SafeZoneW * 0.2925";
h = "SafeZoneH * 0.625";
rowHeight = "1.3 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
sizeEx = "0.78 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
colorText[] = {1,1,1,1};
colorBackground[] = {0,0,0,0};
itemBackground[] = {1,1,1,0.1};
// columns[] = {0.001, 0.26};
columns[] = {0.001, 0.18};
onLBDblClick = "['onUpgradePressed', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_UpgradeMenu.sqf'";
onLBSelChanged = "['onUpgradeListSelChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_UpgradeMenu.sqf'";
};
class CTI_Menu_Upgrade_Label : RscText {
idc = 250003;
x = "SafeZoneX + (SafeZoneW * 0.5375)";
y = "SafeZoneY + (SafezoneH * 0.24)";
w = "SafeZoneW * 0.2775";
h = "SafeZoneH * 0.05";
colorText[] = {0.258823529, 0.713725490, 1, 1};
size = "1.2 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_Upgrade_Info : RscStructuredText {
idc = 250004;
x = "SafeZoneX + (SafeZoneW * 0.5275)";
y = "SafeZoneY + (SafezoneH * 0.29)";
w = "SafeZoneW * 0.2825";
h = "SafeZoneH * 0.10";
size = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_Upgrade_DepLabel : CTI_Menu_Upgrade_Label {
idc = 250005;
y = "SafeZoneY + (SafezoneH * 0.39)";
};
class CTI_Menu_Upgrade_DepInfo : CTI_Menu_Upgrade_Info {
idc = 250006;
y = "SafeZoneY + (SafezoneH * 0.44)";
h = "SafeZoneH * 0.10";
};
class CTI_Menu_Upgrade_DescLabel : CTI_Menu_Upgrade_Label {
idc = 250007;
y = "SafeZoneY + (SafezoneH * 0.54)";
};
class CTI_Menu_Upgrade_DescInfo : CTI_Menu_Upgrade_Info {
idc = 250008;
y = "SafeZoneY + (SafezoneH * 0.59)";
h = "SafeZoneH * 0.175";
};
class CTI_Menu_Upgrade_RunInfo : RscStructuredText {
idc = 250009;
x = "SafeZoneX + (SafeZoneW * 0.5225)";
y = "SafeZoneY + (SafezoneH * 0.78)";
w = "SafeZoneW * 0.2925";
h = "SafeZoneH * 0.03";
size = "0.85 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Control_Exit : RscButton {
idc = 22555;
x = "SafeZoneX + (SafeZoneW * 0.775)";
y = "SafeZoneY + (SafezoneH * 0.18)";
w = "SafeZoneW * 0.04";
h = "SafeZoneH * 0.04";
text = "X";
action = "closeDialog 0";
};
class CTI_Control_Back : CTI_Control_Exit {
idc = 22555;
x = "SafeZoneX + (SafeZoneW * 0.73)";
text = "<<";
action = "closeDialog 0; createDialog 'CTI_RscCommandMenu';";
};
};
};
class CTI_RscWorkersMenu {
movingEnable = 0;
idd = 260000;
onLoad = "uiNamespace setVariable ['cti_dialog_ui_workersmenu', _this select 0];['onLoad'] execVM 'Client\Events\Events_UI_WorkersMenu.sqf'";
onUnload = "uiNamespace setVariable ['cti_dialog_ui_workersmenu', nil]; ['onUnload'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_WorkersMenu.sqf'";
class controlsBackground {
class CTI_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.2)";
y = "SafeZoneY + (SafezoneH * 0.205)";
w = "SafeZoneW * 0.6";
h = "SafeZoneH * 0.47";
colorBackground[] = {0, 0, 0, 0.7};
moving = 1;
};
class CTI_Background_Header : CTI_Background {
x = "SafeZoneX + (SafeZoneW * 0.2)";
y = "SafeZoneY + (SafezoneH * 0.205)";
w = "SafeZoneW * 0.6";
h = "SafeZoneH * 0.05"; //0.06 stock
colorBackground[] = {0, 0, 0, 0.4};
};
class CTI_Menu_Title : RscText {
style = ST_LEFT;
x = "SafeZoneX + (SafeZoneW * 0.22)";
y = "SafeZoneY + (SafezoneH * 0.21)";
w = "SafeZoneW * 0.58";
h = "SafeZoneH * 0.037";
text = "Base Management";
colorText[] = {0.258823529, 0.713725490, 1, 1};
sizeEx = "( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_InfoListFrame : RscFrame {
x = "SafeZoneX + (SafeZoneW * 0.22)";
y = "SafeZoneY + (SafezoneH * 0.275)";
w = "SafeZoneW * 0.27";
h = "SafeZoneH * 0.38";
};
class CTI_Menu_SalvagerResourcesFrame : CTI_Menu_InfoListFrame {
x = "SafeZoneX + (SafeZoneW * 0.51)";
y = "SafeZoneY + (SafezoneH * 0.275)";
w = "SafeZoneW * 0.13";
h = "SafeZoneH * 0.205";
};
class CTI_Menu_Salvager_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.51)";
y = "SafeZoneY + (SafezoneH * 0.275)";
w = "SafeZoneW * 0.13";
h = "SafeZoneH * 0.205";
colorBackground[] = {0.5, 0.5, 0.5, 0.25};
};
class CTI_Menu_WorkerResourcesFrame : CTI_Menu_SalvagerResourcesFrame {
x = "SafeZoneX + (SafeZoneW * 0.65)";
y = "SafeZoneY + (SafezoneH * 0.275)";
w = "SafeZoneW * 0.13";
h = "SafeZoneH * 0.205";
};
class CTI_Menu_Worker_Background : CTI_Menu_Salvager_Background {
x = "SafeZoneX + (SafeZoneW * 0.65)";
y = "SafeZoneY + (SafezoneH * 0.275)";
w = "SafeZoneW * 0.13";
h = "SafeZoneH * 0.205";
colorBackground[] = {0.5, 0.5, 0.5, 0.25};
};
class CTI_Menu_CommanderFrame : CTI_Menu_WorkerResourcesFrame {
x = "SafeZoneX + (SafeZoneW * 0.51)";
y = "SafeZoneY + (SafezoneH * 0.495)";
w = "SafeZoneW * 0.27";
h = "SafeZoneH * 0.16";
};
class CTI_Menu_Commander_Background : CTI_Menu_Worker_Background {
x = "SafeZoneX + (SafeZoneW * 0.51)";
y = "SafeZoneY + (SafezoneH * 0.495)";
w = "SafeZoneW * 0.27";
h = "SafeZoneH * 0.16";
};
};
class controls {
class CTI_Menu_Map : RscMapControl {
idc = 260001;
x = "SafeZoneX + (SafeZoneW * 0.22)";
y = "SafeZoneY + (SafezoneH * 0.275)";
w = "SafeZoneW * 0.27";
h = "SafeZoneH * 0.38";
showCountourInterval = 0;
onMouseButtonDown = "['onMapButtonDown', _this] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_WorkersMenu.sqf'";
};
class CTI_Menu_Control_SalvagersList : RscListNBox {
idc = 260002;
x = "SafeZoneX + (SafeZoneW * 0.51)";
y = "SafeZoneY + (SafezoneH * 0.275)";
w = "SafeZoneW * 0.13";
h = "SafeZoneH * 0.1825";
rowHeight = "1.3 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
sizeEx = "0.78 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
colorText[] = {1,1,1,1};
colorBackground[] = {0,0,0,0};
itemBackground[] = {1,1,1,0.1};
columns[] = {0.001, 0.35};
onLBSelChanged = "['onSalvagersListLBSelChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_WorkersMenu.sqf'";
};
class CTI_Menu_Control_WorkersList : CTI_Menu_Control_SalvagersList {
idc = 260003;
x = "SafeZoneX + (SafeZoneW * 0.65)";
onLBSelChanged = "['onWorkersListLBSelChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_WorkersMenu.sqf'";
// onLBDblClick = "['onBuildStructure', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_BuildMenu.sqf'";
};
class CTI_Menu_Control_Salvager_Disband : RscButton {
idc = 260004;
x = "SafeZoneX + (SafeZoneW * 0.52)";
y = "SafeZoneY + (SafezoneH * 0.505)";
w = "SafeZoneW * 0.25";
h = "SafeZoneH * 0.04";
text = "Disband Independant Salvager";
action = "['onSalvagerDisbandPressed', lnbCurSelRow 260002] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_WorkersMenu.sqf'";
};
class CTI_Menu_Control_Worker_Disband : CTI_Menu_Control_Salvager_Disband {
idc = 260005;
y = "SafeZoneY + (SafezoneH * 0.555)";
text = "Disband Worker";
action = "['onWorkerDisbandPressed', lnbCurSelRow 260003] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_WorkersMenu.sqf'";
};
class CTI_Menu_Control_Sell : CTI_Menu_Control_Worker_Disband {
idc = 260006;
y = "SafeZoneY + (SafezoneH * 0.605)";
text = "Sell Structure";
action = "['onStructureSellPressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_WorkersMenu.sqf'";
};
class CTI_Control_Exit : RscButton {
idc = 22555;
x = "SafeZoneX + (SafeZoneW * 0.74)";
y = "SafeZoneY + (SafezoneH * 0.21)";
w = "SafeZoneW * 0.04";
h = "SafeZoneH * 0.04";
text = "X";
action = "closeDialog 0";
};
class CTI_Control_Back : CTI_Control_Exit {
idc = 22555;
x = "SafeZoneX + (SafeZoneW * 0.695)";
text = "<<";
action = "closeDialog 0; createDialog 'CTI_RscCommandMenu';";
};
};
};
class CTI_RscAIMicromanagementMenu {
movingEnable = 0;
idd = 270000;
onLoad = "uiNamespace setVariable ['cti_dialog_ui_aimicromenu', _this select 0];['onLoad'] execVM 'Client\Events\Events_UI_AIMicromanagementMenu.sqf'";
onUnload = "uiNamespace setVariable ['cti_dialog_ui_aimicromenu', nil]; ['onUnload'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_AIMicromanagementMenu.sqf'";
class controlsBackground {
class CTI_Background : RscText {
x = "SafeZoneX";
y = "SafeZoneY";
w = "SafeZoneW";
h = "SafeZoneH";
colorBackground[] = {0, 0, 0, 0.7};
};
class CTI_Background_Header : CTI_Background {
x = "SafeZoneX";
y = "SafeZoneY";
w = "SafeZoneW";
h = "SafeZoneH * 0.05";
colorBackground[] = {0, 0, 0, 0.4};
};
class CTI_Menu_Title : RscText {
style = ST_LEFT;
x = "SafeZoneX + (SafezoneH * 0.02)";
y = "SafeZoneY + (SafezoneH * 0.005)";
w = "SafeZoneW * 0.98";
h = "SafeZoneH * 0.037";
text = "AI Micromanagement";
colorText[] = {0.258823529, 0.713725490, 1, 1};
sizeEx = "( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_Map : RscMapControl {
idc = 270001;
x = "SafeZoneX";
y = "SafeZoneY + (SafezoneH * 0.05)";
w = "SafeZoneW";
h = "SafeZoneH * 0.95";
// showCountourInterval = 1;
onMouseButtonDown = "['onMapButtonDown', _this] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_AIMicromanagementMenu.sqf'";
};
};
class controls {
class CTI_Background_List : RscText {
idc = 270701;
x = "SafeZoneX + (SafeZoneW * 0.78)";
y = "SafeZoneY + (SafezoneH * 0.06)";
w = "SafeZoneW * 0.21";
h = "SafeZoneH * 0.9";
colorBackground[] = {0, 0, 0, 0.7};
};
class CTI_Menu_UnitsListFrame : RscFrame {
idc = 270702;
x = "SafeZoneX + (SafeZoneW * 0.785)";
y = "SafeZoneY + (SafezoneH * 0.095)";
w = "SafeZoneW * 0.2";
h = "SafeZoneH * 0.25";
};
class CTI_Menu_List_Background : RscText {
idc = 270708;
x = "SafeZoneX + (SafeZoneW * 0.785)";
y = "SafeZoneY + (SafezoneH * 0.095)";
w = "SafeZoneW * 0.2";
h = "SafeZoneH * 0.25";
colorBackground[] = {0.5, 0.5, 0.5, 0.25};
};
class CTI_Menu_Control_UnitsList_Label : RscText {
idc = 270703;
x = "SafeZoneX + (SafeZoneW * 0.785)";
y = "SafeZoneY + (SafezoneH * 0.06)";
w = "SafeZoneW * 0.19";
h = "SafeZoneH * 0.03";
text = "AI :";
colorText[] = {0.231372549, 0.580392157, 0.929411765, 1};
sizeEx = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_Control_OrdersList_Label : CTI_Menu_Control_UnitsList_Label {
idc = 270704;
y = "SafeZoneY + (SafezoneH * 0.405)";
h = "SafeZoneH * 0.03";
text = "Orders :";
};
class CTI_Menu_OrdersListFrame : CTI_Menu_UnitsListFrame {
idc = 270705;
y = "SafeZoneY + (SafezoneH * 0.44)";
h = "SafeZoneH * 0.16";
};
class CTI_Menu_Orders_Background : CTI_Menu_List_Background {
idc = 270709;
y = "SafeZoneY + (SafezoneH * 0.44)";
h = "SafeZoneH * 0.16";
};
class CTI_Menu_Control_OrdersParamList_Label : CTI_Menu_Control_UnitsList_Label { //--- Render out.
idc = 270706;
y = "SafeZoneY + (SafezoneH * 0.61)";
h = "SafeZoneH * 0.03";
text = "Order Parameters :";
};
class CTI_Menu_OrdersParamListFrame : CTI_Menu_UnitsListFrame {
idc = 270707;
y = "SafeZoneY + (SafezoneH * 0.645)";
h = "SafeZoneH * 0.2";
};
class CTI_Menu_OrdersParam_Background : CTI_Menu_List_Background {
idc = 270710;
y = "SafeZoneY + (SafezoneH * 0.645)";
h = "SafeZoneH * 0.2";
};
class CTI_Background_Intel : RscText {
idc = 270711;
x = "SafeZoneX + (SafeZoneW * 0.26)";
y = "SafeZoneY + (SafezoneH * 0.06)";
w = "SafeZoneW * 0.48";
h = "SafeZoneH * 0.03";
colorBackground[] = {0, 0, 0, 0.7};
};
class CTI_Menu_Control_UnitsList : RscListBox {
idc = 270002;
style = LB_MULTI;
x = "SafeZoneX + (SafeZoneW * 0.785)";
y = "SafeZoneY + (SafezoneH * 0.095)";
w = "SafeZoneW * 0.2";
h = "SafeZoneH * 0.25";
rowHeight = "1 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
sizeEx = "0.75 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
colorText[] = {1,1,1,1};
colorBackground[] = {0,0,0,0};
onLBDblClick = "['onUnitListLBDblClick', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_AIMicromanagementMenu.sqf'";
// onLBSelChanged = "['onUnitListLBSelChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_AIMicromanagementMenu.sqf'";
};
class CTI_Menu_Control_OrdersList : RscListBox {
idc = 270009;
x = "SafeZoneX + (SafeZoneW * 0.785)";
y = "SafeZoneY + (SafezoneH * 0.44)";
w = "SafeZoneW * 0.2";
h = "SafeZoneH * 0.16";
rowHeight = "1 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
sizeEx = "0.75 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
colorText[] = {1,1,1,1};
colorBackground[] = {0,0,0,0};
onLBSelChanged = "['onOrdersListLBSelChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_AIMicromanagementMenu.sqf'";
onLBDblClick = "['onOrdersListLBDblClick', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_AIMicromanagementMenu.sqf'";
};
class CTI_Menu_Control_OrdersParamList : CTI_Menu_Control_OrdersList {
idc = 270010;
y = "SafeZoneY + (SafezoneH * 0.645)";
h = "SafeZoneH * 0.2";
// onLBDblClick = "['onOrdersParamLBDblClick', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_AIMicromanagementMenu.sqf'";
onLBSelChanged = "";
};
class CTI_Menu_Control_SetOrder : RscButton_Opac {
idc = 270011;
x = "SafeZoneX + (SafeZoneW * 0.785)";
y = "SafeZoneY + (SafeZoneH * 0.86)";
h = "SafeZoneH * 0.04";
w = "SafeZoneW * 0.2";
sizeEx = "0.85 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
text = "Set Order";
action = "['onSetOrderPressed', lbCurSel 270009] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_AIMicromanagementMenu.sqf'";
};
class CTI_Menu_Control_SetMapOrder : CTI_Menu_Control_SetOrder {
idc = 270012;
y = "SafeZoneY + (SafeZoneH * 0.91)";
text = "Set Order (Map Click)";
action = "['onSetMapOrderPressed'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_AIMicromanagementMenu.sqf'";
};
class CTI_Menu_Control_Disband : CTI_Menu_Control_SetOrder {
idc = 270014;
y = "SafeZoneY + (SafeZoneH * 0.355)";
text = "Disband";
action = "['onUnitDisbandPressed', lbSelection ((uiNamespace getVariable 'cti_dialog_ui_aimicromenu') displayCtrl 270002)] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_AIMicromanagementMenu.sqf'";
};
class CTI_Menu_Control_IntelText : RscStructuredText {
idc = 270013;
x = "SafeZoneX + (SafeZoneW * 0.26)";
y = "SafeZoneY + (SafezoneH * 0.06)";
w = "SafeZoneW * 0.48";
h = "SafeZoneH * 0.03";
size = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_Control_SelectAll : RscButton {
idc = 270015;
x = "SafeZoneX + (SafeZoneW * 0.935)";
y = "SafeZoneY + (SafezoneH * 0.0625)";
w = "SafeZoneW * 0.05";
h = "SafeZoneH * 0.0275";
text = "All";
action = "['onSelectAll'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_AIMicromanagementMenu.sqf'";
};
class CTI_Control_Exit : RscButton {
idc = 22555;
x = "SafeZoneX + (SafeZoneW * 0.95)";
y = "SafeZoneY + (SafezoneH * 0.005)";
w = "SafeZoneW * 0.04";
h = "SafeZoneH * 0.04";
text = "X";
action = "closeDialog 0";
};
class CTI_Control_Back : CTI_Control_Exit {
idc = 22555;
x = "SafeZoneX + (SafeZoneW * 0.905)";
text = "<<";
action = "closeDialog 0; createDialog 'CTI_RscOptionsMenu';";
};
};
};
class CTI_RscRequestMenu {
movingEnable = 0;
idd = 280000;
onLoad = "uiNamespace setVariable ['cti_dialog_ui_requestmenu', _this select 0];['onLoad'] execVM 'Client\Events\Events_UI_RequestMenu.sqf'";
onUnload = "uiNamespace setVariable ['cti_dialog_ui_requestmenu', nil]; ['onUnload'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_RequestMenu.sqf'";
class controlsBackground {
class CTI_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.21)";
y = "SafeZoneY + (SafezoneH * 0.175)";
w = "SafeZoneW * 0.615";
h = "SafeZoneH * 0.65";
colorBackground[] = {0, 0, 0, 0.7};
moving = 1;
};
class CTI_Background_Header : CTI_Background {
x = "SafeZoneX + (SafeZoneW * 0.21)";
y = "SafeZoneY + (SafezoneH * 0.175)";
w = "SafeZoneW * 0.615";
h = "SafeZoneH * 0.05"; //0.06 stock
colorBackground[] = {0, 0, 0, 0.4};
};
class CTI_Menu_Title : RscText {
style = ST_LEFT;
x = "SafeZoneX + (SafeZoneW * 0.23)";
y = "SafeZoneY + (SafezoneH * 0.180)";
w = "SafeZoneW * 0.595";
h = "SafeZoneH * 0.037";
text = "Team Requests";
colorText[] = {0.258823529, 0.713725490, 1, 1};
sizeEx = "( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_RequestsListFrame : RscFrame {
x = "SafeZoneX + (SafeZoneW * 0.225)";
y = "SafeZoneY + (SafezoneH * 0.245)";
w = "SafeZoneW * 0.285";
h = "SafeZoneH * 0.505";
};
class CTI_Menu_MapListFrame : CTI_Menu_RequestsListFrame {
x = "SafeZoneX + (SafeZoneW * 0.525)";
h = "SafeZoneH * 0.28";
};
class CTI_Menu_RequestInfoFrame : CTI_Menu_MapListFrame {
y = "SafeZoneY + (SafezoneH * 0.54)";
h = "SafeZoneH * 0.21";
};
class CTI_Menu_RequestInfo_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.525)";
y = "SafeZoneY + (SafezoneH * 0.54)";
w = "SafeZoneW * 0.285";
h = "SafeZoneH * 0.21";
colorBackground[] = {0.5, 0.5, 0.5, 0.25};
};
};
class controls {
class CTI_Menu_Control_Accept : RscButton {
idc = 280001;
x = "SafeZoneX + (SafeZoneW * 0.225)";
y = "SafeZoneY + (SafezoneH * 0.765)";
w = "SafeZoneW * 0.285";
h = "SafeZoneH * 0.04";
text = "Accept";
action = "['onRequestAccept', lnbCurSelRow 280005] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_RequestMenu.sqf'";
};
class CTI_Menu_Control_Deny : CTI_Menu_Control_Accept {
idc = 280002;
x = "SafeZoneX + (SafeZoneW * 0.525)";
text = "Deny";
action = "['onRequestDeny', lnbCurSelRow 280005] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_RequestMenu.sqf'";
};
class CTI_Menu_Map : RscMapControl {
idc = 280003;
x = "SafeZoneX + (SafeZoneW * 0.525)";
y = "SafeZoneY + (SafezoneH * 0.245)";
w = "SafeZoneW * 0.285";
h = "SafeZoneH * 0.28";
showCountourInterval = 0;
};
class CTI_Menu_Control_Info : RscStructuredText {
idc = 280004;
x = "SafeZoneX + (SafeZoneW * 0.525)";
y = "SafeZoneY + (SafezoneH * 0.54)";
w = "SafeZoneW * 0.285";
h = "SafeZoneH * 0.21";
size = "0.85 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_Control_RequestsList : RscListNBox {
idc = 280005;
x = "SafeZoneX + (SafeZoneW * 0.225)";
y = "SafeZoneY + (SafezoneH * 0.245)";
w = "SafeZoneW * 0.285";
h = "SafeZoneH * 0.505";
rowHeight = "1.3 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
sizeEx = "0.78 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
colorText[] = {1,1,1,1};
colorBackground[] = {0,0,0,0};
itemBackground[] = {1,1,1,0.1};
// columns[] = {0.001, 0.26};
columns[] = {0.001, 0.26};
onLBDblClick = "['onRequestAccept', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_RequestMenu.sqf'";
onLBSelChanged = "['onRequestSelChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_RequestMenu.sqf'";
};
class CTI_Control_Exit : RscButton {
idc = 22555;
x = "SafeZoneX + (SafeZoneW * 0.77)";
y = "SafeZoneY + (SafezoneH * 0.18)";
w = "SafeZoneW * 0.04";
h = "SafeZoneH * 0.04";
text = "X";
action = "closeDialog 0";
};
class CTI_Control_Back : CTI_Control_Exit {
idc = 22555;
x = "SafeZoneX + (SafeZoneW * 0.725)";
text = "<<";
action = "closeDialog 0; createDialog 'CTI_RscCommandMenu';";
};
// class CTI_Control_Exit : RscButton {
// idc = 22555;
// x = "SafeZoneX + (SafeZoneW * 0.74)";
// y = "SafeZoneY + (SafezoneH * 0.21)";
// w = "SafeZoneW * 0.04";
// h = "SafeZoneH * 0.04";
// text = "X";
// action = "closeDialog 0";
// };
// class CTI_Control_Back : CTI_Control_Exit {
// idc = 22555;
// x = "SafeZoneX + (SafeZoneW * 0.695)";
// text = "<<";
// action = "['onGoBack'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_TransferResourcesMenu.sqf'";
// };
};
};
class CTI_RscArtilleryMenu {
movingEnable = 0;
idd = 290000;
onLoad = "uiNamespace setVariable ['cti_dialog_ui_artillerymenu', _this select 0];['onLoad'] execVM 'Client\Events\Events_UI_ArtilleryMenu.sqf'";
onUnload = "uiNamespace setVariable ['cti_dialog_ui_artillerymenu', nil];['onUnload'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_ArtilleryMenu.sqf'";
class controlsBackground {
class CTI_Background : RscText {
x = "SafeZoneX";
y = "SafeZoneY";
w = "SafeZoneW";
h = "SafeZoneH";
colorBackground[] = {0, 0, 0, 0.7};
};
class CTI_Background_Header : CTI_Background {
x = "SafeZoneX";
y = "SafeZoneY";
w = "SafeZoneW";
h = "SafeZoneH * 0.05";
colorBackground[] = {0, 0, 0, 0.4};
};
class CTI_Menu_Title : RscText {
style = ST_LEFT;
x = "SafeZoneX + (SafezoneH * 0.02)";
y = "SafeZoneY + (SafezoneH * 0.005)";
w = "SafeZoneW * 0.98";
h = "SafeZoneH * 0.037";
text = "Artillery";
colorText[] = {0.258823529, 0.713725490, 1, 1};
sizeEx = "( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_Map : RscMapControl {
idc = 290001;
x = "SafeZoneX";
y = "SafeZoneY + (SafezoneH * 0.05)";
w = "SafeZoneW";
h = "SafeZoneH * 0.95";
showCountourInterval = 1;
onMouseButtonDown = "['onMapButtonDown', _this] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_ArtilleryMenu.sqf'";
};
};
class controls {
class CTI_Background_List : RscText {
idc = 290002;
x = "SafeZoneX + (SafeZoneW * 0.78)";
y = "SafeZoneY + (SafezoneH * 0.06)";
w = "SafeZoneW * 0.21";
h = "SafeZoneH * 0.68";
colorBackground[] = {0, 0, 0, 0.7};
};
class CTI_Menu_FireMission_Frame : RscFrame {
idc = 290003;
x = "SafeZoneX + (SafeZoneW * 0.785)";
y = "SafeZoneY + (SafezoneH * 0.095)";
w = "SafeZoneW * 0.2";
h = "SafeZoneH * 0.215";
};
class CTI_Menu_FireMission_Background : RscText {
idc = 290004;
x = "SafeZoneX + (SafeZoneW * 0.785)";
y = "SafeZoneY + (SafezoneH * 0.095)";
w = "SafeZoneW * 0.2";
h = "SafeZoneH * 0.215";
colorBackground[] = {0.5, 0.5, 0.5, 0.25};
};
class CTI_Menu_FireMission_Label : RscText {
idc = 290005;
x = "SafeZoneX + (SafeZoneW * 0.785)";
y = "SafeZoneY + (SafezoneH * 0.06)";
w = "SafeZoneW * 0.19";
h = "SafeZoneH * 0.03";
text = "Fire Mission :";
colorText[] = {0.231372549, 0.580392157, 0.929411765, 1};
sizeEx = "0.9 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_FireMission_Type_Label : CTI_Menu_FireMission_Label {
idc = 290006;
x = "SafeZoneX + (SafeZoneW * 0.788)";
y = "SafeZoneY + (SafezoneH * 0.095)";
w = "SafeZoneW * 0.18";
h = "SafeZoneH * 0.03";
text = "Artillery Type :";
colorText[] = {0.537254902, 0.843137255, 1, 1};
sizeEx = "0.8 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
};
class CTI_Menu_FireMission_Type_Combo : RscCombo {
idc = 290007;
x = "SafeZoneX + (SafeZoneW * 0.79)";
y = "SafeZoneY + (SafezoneH * 0.125)";
w = "SafeZoneW * 0.19";
h = "SafeZoneH * 0.035";
sizeEx = "0.8 * ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
onLBSelChanged = "['onArtilleryTypeChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_ArtilleryMenu.sqf'";
};
class CTI_Menu_FireMission_Magazine_Label : CTI_Menu_FireMission_Type_Label {
idc = 290008;
y = "SafeZoneY + (SafezoneH * 0.165)";
text = "Artillery Magazine :";
};
class CTI_Menu_FireMission_Magazine_Combo : CTI_Menu_FireMission_Type_Combo {
idc = 290009;
y = "SafeZoneY + (SafezoneH * 0.195)";
onLBSelChanged = "['onArtilleryMagazineChanged', _this select 1] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_ArtilleryMenu.sqf'";
};
class CTI_Menu_FireMission_Burst_Label : CTI_Menu_FireMission_Type_Label {
idc = 290010;
y = "SafeZoneY + (SafezoneH * 0.235)";
text = "Artillery Burst :";
};
class CTI_Menu_FireMission_Burst_Combo : CTI_Menu_FireMission_Type_Combo {
idc = 290011;
y = "SafeZoneY + (SafezoneH * 0.265)";
onLBSelChanged = "";
};
class CTI_Menu_Units_Frame : RscFrame {
idc = 290012;
x = "SafeZoneX + (SafeZoneW * 0.785)";
y = "SafeZoneY + (SafezoneH * 0.325)";
w = "SafeZoneW * 0.2";
h = "SafeZoneH * 0.3";
};
class CTI_Menu_Units_Background : RscText {
idc = 290013;
x = "SafeZoneX + (SafeZoneW * 0.785)";
y = "SafeZoneY + (SafezoneH * 0.325)";
w = "SafeZoneW * 0.2";
h = "SafeZoneH * 0.3";
colorBackground[] = {0.5, 0.5, 0.5, 0.25};
};
class CTI_Menu_Units_List : RscListBox {
idc = 290014;
style = LB_MULTI;
x = "SafeZoneX + (SafeZoneW * 0.785)";
y = "SafeZoneY + (SafezoneH * 0.325)";
w = "SafeZoneW * 0.2";
h = "SafeZoneH * 0.3";
rowHeight = "1 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
sizeEx = "0.75 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
colorText[] = {1,1,1,1};
colorBackground[] = {0,0,0,0};
};
class CTI_Menu_FireMission_Call : RscButton {
idc = 290015;
x = "SafeZoneX + (SafeZoneW * 0.785)";
y = "SafeZoneY + (SafeZoneH * 3.69)"; //--- Render out
h = "SafeZoneH * 0.04";
w = "SafeZoneW * 0.2";
sizeEx = "0.85 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
text = "Call Fire Mission";
action = "['onFireMissionCall'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_ArtilleryMenu.sqf'";
};
class CTI_Menu_FireMission_SelectAll : CTI_Menu_FireMission_Call {
idc = 290016;
y = "SafeZoneY + (SafeZoneH * 0.64)";
text = "Select All";
action = "['onSelectAll'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_ArtilleryMenu.sqf'";
};
class CTI_Control_Exit : RscButton {
idc = 22555;
x = "SafeZoneX + (SafeZoneW * 0.95)";
y = "SafeZoneY + (SafezoneH * 0.005)";
w = "SafeZoneW * 0.04";
h = "SafeZoneH * 0.04";
text = "X";
action = "closeDialog 0";
};
class CTI_Control_Back : CTI_Control_Exit {
idc = 22555;
x = "SafeZoneX + (SafeZoneW * 0.905)";
text = "<<";
action = "closeDialog 0; createDialog 'CTI_RscCommandMenu';";
};
};
};
//--- Vote Menu (ported from WFBE by Sari).
class CTI_RscVoteMenu {
movingEnable = 1;
idd = 500000;
onLoad = "uiNamespace setVariable ['cti_dialog_ui_votemenu', _this select 0]; ['onLoad'] execVM 'Client\Events\Events_UI_VoteMenu.sqf'";
onUnload = "uiNamespace setVariable ['cti_dialog_ui_votemenu', nil]; ['onUnload'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_VoteMenu.sqf'";
class controlsBackground {
class CTI_Background : RscText {
x = "SafeZoneX + (SafeZoneW * 0.325)";
y = "SafeZoneY + (SafezoneH * 0.155)";
w = "SafeZoneW * 0.3";
h = "SafeZoneH * 0.7";
colorBackground[] = {0, 0, 0, 0.7};
moving = 1;
};
class CTI_Background_Header : CTI_Background {
x = "SafeZoneX + (SafeZoneW * 0.325)";
y = "SafeZoneY + (SafezoneH * 0.155)";
w = "SafeZoneW * 0.3";
h = "SafeZoneH * 0.05";
colorBackground[] = {0, 0, 0, 0.4};
};
class CTI_Background_Footer : CTI_Background {
x = "SafeZoneX + (SafeZoneW * 0.325)";
y = "SafeZoneY + (SafezoneH * 0.805)";
w = "SafeZoneW * 0.3";
h = "SafeZoneH * 0.05";
colorBackground[] = {0, 0, 0, 0.4};
};
class CTI_Menu_Title : RscText {
x = "SafeZoneX + (SafeZoneW * 0.33)";
y = "SafeZoneY + (SafezoneH * 0.16)";
w = "SafeZoneW * 0.595";
text = "Commander Vote :";
colorText[] = {1,1,1,1};
};
};
class controls {
class CTI_Vote_List : RscListnBox {
idc = 500100;
x = "SafeZoneX + (SafeZoneW * 0.325)";
y = "SafeZoneY + (SafezoneH * 0.205)";
w = "SafeZoneW * 0.3";
h = "SafeZoneH * 0.6";
rowHeight = "1.3 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
sizeEx = "0.78 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
colorBackground[] = {0,0,0,0};
colorSelectBackground2[] = {0.258823529, 0.713725490, 1, 1};
columns[] = {0.01, 0.75};
onLBSelChanged = "['onUnitsLBSelChanged'] call compile preprocessFileLineNumbers 'Client\Events\Events_UI_VoteMenu.sqf'";
};
class CTI_Menu_Elected : RscText {
idc = 500101;
x = "SafeZoneX + (SafeZoneW * 0.33)";
y = "SafeZoneY + (SafezoneH * 0.81)";
w = 0.23;
sizeEx = 0.03;
text = "";
colorText[] = {1,1,1,1};
shadow = 2;
};
class CTI_Menu_TimeLeft : CTI_Menu_Elected {
idc = 500102;
x = "SafeZoneX + (SafeZoneW * 0.47)";
style = ST_RIGHT;
text = "";
};
class CTI_Menu_Time_Static : CTI_Menu_Elected {
idc = 500103;
x = "SafeZoneX + (SafeZoneW * 0.45)";
style = ST_RIGHT;
text = "Time :";
};
class CTI_Control_Exit : RscButton {
idc = 500104;
x = "SafeZoneX + (SafeZoneW * 0.58)";
y = "SafeZoneY + (SafezoneH * 0.16)";
w = "SafeZoneW * 0.04";
h = "SafeZoneH * 0.04";
text = "X";
action = "closeDialog 0";
};
};
}; | 33.885048 | 218 | 0.63138 | [
"render"
] |
7acbd11bc5db1d3606b762c0304011724278edd9 | 24,536 | cpp | C++ | android/android_9/frameworks/native/services/surfaceflinger/DispSync.cpp | yakuizhao/intel-vaapi-driver | b2bb0383352694941826543a171b557efac2219b | [
"MIT"
] | null | null | null | android/android_9/frameworks/native/services/surfaceflinger/DispSync.cpp | yakuizhao/intel-vaapi-driver | b2bb0383352694941826543a171b557efac2219b | [
"MIT"
] | null | null | null | android/android_9/frameworks/native/services/surfaceflinger/DispSync.cpp | yakuizhao/intel-vaapi-driver | b2bb0383352694941826543a171b557efac2219b | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define ATRACE_TAG ATRACE_TAG_GRAPHICS
//#define LOG_NDEBUG 0
// This is needed for stdint.h to define INT64_MAX in C++
#define __STDC_LIMIT_MACROS
#include <math.h>
#include <algorithm>
#include <log/log.h>
#include <utils/String8.h>
#include <utils/Thread.h>
#include <utils/Trace.h>
#include <utils/Vector.h>
#include <ui/FenceTime.h>
#include "DispSync.h"
#include "EventLog/EventLog.h"
#include "SurfaceFlinger.h"
using std::max;
using std::min;
namespace android {
// Setting this to true enables verbose tracing that can be used to debug
// vsync event model or phase issues.
static const bool kTraceDetailedInfo = false;
// Setting this to true adds a zero-phase tracer for correlating with hardware
// vsync events
static const bool kEnableZeroPhaseTracer = false;
// This is the threshold used to determine when hardware vsync events are
// needed to re-synchronize the software vsync model with the hardware. The
// error metric used is the mean of the squared difference between each
// present time and the nearest software-predicted vsync.
static const nsecs_t kErrorThreshold = 160000000000; // 400 usec squared
#undef LOG_TAG
#define LOG_TAG "DispSyncThread"
class DispSyncThread : public Thread {
public:
explicit DispSyncThread(const char* name)
: mName(name),
mStop(false),
mPeriod(0),
mPhase(0),
mReferenceTime(0),
mWakeupLatency(0),
mFrameNumber(0) {}
virtual ~DispSyncThread() {}
void updateModel(nsecs_t period, nsecs_t phase, nsecs_t referenceTime) {
if (kTraceDetailedInfo) ATRACE_CALL();
Mutex::Autolock lock(mMutex);
mPeriod = period;
mPhase = phase;
mReferenceTime = referenceTime;
ALOGV("[%s] updateModel: mPeriod = %" PRId64 ", mPhase = %" PRId64
" mReferenceTime = %" PRId64,
mName, ns2us(mPeriod), ns2us(mPhase), ns2us(mReferenceTime));
mCond.signal();
}
void stop() {
if (kTraceDetailedInfo) ATRACE_CALL();
Mutex::Autolock lock(mMutex);
mStop = true;
mCond.signal();
}
virtual bool threadLoop() {
status_t err;
nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
while (true) {
Vector<CallbackInvocation> callbackInvocations;
nsecs_t targetTime = 0;
{ // Scope for lock
Mutex::Autolock lock(mMutex);
if (kTraceDetailedInfo) {
ATRACE_INT64("DispSync:Frame", mFrameNumber);
}
ALOGV("[%s] Frame %" PRId64, mName, mFrameNumber);
++mFrameNumber;
if (mStop) {
return false;
}
if (mPeriod == 0) {
err = mCond.wait(mMutex);
if (err != NO_ERROR) {
ALOGE("error waiting for new events: %s (%d)", strerror(-err), err);
return false;
}
continue;
}
targetTime = computeNextEventTimeLocked(now);
bool isWakeup = false;
if (now < targetTime) {
if (kTraceDetailedInfo) ATRACE_NAME("DispSync waiting");
if (targetTime == INT64_MAX) {
ALOGV("[%s] Waiting forever", mName);
err = mCond.wait(mMutex);
} else {
ALOGV("[%s] Waiting until %" PRId64, mName, ns2us(targetTime));
err = mCond.waitRelative(mMutex, targetTime - now);
}
if (err == TIMED_OUT) {
isWakeup = true;
} else if (err != NO_ERROR) {
ALOGE("error waiting for next event: %s (%d)", strerror(-err), err);
return false;
}
}
now = systemTime(SYSTEM_TIME_MONOTONIC);
// Don't correct by more than 1.5 ms
static const nsecs_t kMaxWakeupLatency = us2ns(1500);
if (isWakeup) {
mWakeupLatency = ((mWakeupLatency * 63) + (now - targetTime)) / 64;
mWakeupLatency = min(mWakeupLatency, kMaxWakeupLatency);
if (kTraceDetailedInfo) {
ATRACE_INT64("DispSync:WakeupLat", now - targetTime);
ATRACE_INT64("DispSync:AvgWakeupLat", mWakeupLatency);
}
}
callbackInvocations = gatherCallbackInvocationsLocked(now);
}
if (callbackInvocations.size() > 0) {
fireCallbackInvocations(callbackInvocations);
}
}
return false;
}
status_t addEventListener(const char* name, nsecs_t phase, DispSync::Callback* callback) {
if (kTraceDetailedInfo) ATRACE_CALL();
Mutex::Autolock lock(mMutex);
for (size_t i = 0; i < mEventListeners.size(); i++) {
if (mEventListeners[i].mCallback == callback) {
return BAD_VALUE;
}
}
EventListener listener;
listener.mName = name;
listener.mPhase = phase;
listener.mCallback = callback;
// We want to allow the firstmost future event to fire without
// allowing any past events to fire
listener.mLastEventTime = systemTime() - mPeriod / 2 + mPhase - mWakeupLatency;
mEventListeners.push(listener);
mCond.signal();
return NO_ERROR;
}
status_t removeEventListener(DispSync::Callback* callback) {
if (kTraceDetailedInfo) ATRACE_CALL();
Mutex::Autolock lock(mMutex);
for (size_t i = 0; i < mEventListeners.size(); i++) {
if (mEventListeners[i].mCallback == callback) {
mEventListeners.removeAt(i);
mCond.signal();
return NO_ERROR;
}
}
return BAD_VALUE;
}
status_t changePhaseOffset(DispSync::Callback* callback, nsecs_t phase) {
if (kTraceDetailedInfo) ATRACE_CALL();
Mutex::Autolock lock(mMutex);
for (size_t i = 0; i < mEventListeners.size(); i++) {
if (mEventListeners[i].mCallback == callback) {
EventListener& listener = mEventListeners.editItemAt(i);
const nsecs_t oldPhase = listener.mPhase;
listener.mPhase = phase;
// Pretend that the last time this event was handled at the same frame but with the
// new offset to allow for a seamless offset change without double-firing or
// skipping.
listener.mLastEventTime -= (oldPhase - phase);
mCond.signal();
return NO_ERROR;
}
}
return BAD_VALUE;
}
// This method is only here to handle the !SurfaceFlinger::hasSyncFramework
// case.
bool hasAnyEventListeners() {
if (kTraceDetailedInfo) ATRACE_CALL();
Mutex::Autolock lock(mMutex);
return !mEventListeners.empty();
}
private:
struct EventListener {
const char* mName;
nsecs_t mPhase;
nsecs_t mLastEventTime;
DispSync::Callback* mCallback;
};
struct CallbackInvocation {
DispSync::Callback* mCallback;
nsecs_t mEventTime;
};
nsecs_t computeNextEventTimeLocked(nsecs_t now) {
if (kTraceDetailedInfo) ATRACE_CALL();
ALOGV("[%s] computeNextEventTimeLocked", mName);
nsecs_t nextEventTime = INT64_MAX;
for (size_t i = 0; i < mEventListeners.size(); i++) {
nsecs_t t = computeListenerNextEventTimeLocked(mEventListeners[i], now);
if (t < nextEventTime) {
nextEventTime = t;
}
}
ALOGV("[%s] nextEventTime = %" PRId64, mName, ns2us(nextEventTime));
return nextEventTime;
}
Vector<CallbackInvocation> gatherCallbackInvocationsLocked(nsecs_t now) {
if (kTraceDetailedInfo) ATRACE_CALL();
ALOGV("[%s] gatherCallbackInvocationsLocked @ %" PRId64, mName, ns2us(now));
Vector<CallbackInvocation> callbackInvocations;
nsecs_t onePeriodAgo = now - mPeriod;
for (size_t i = 0; i < mEventListeners.size(); i++) {
nsecs_t t = computeListenerNextEventTimeLocked(mEventListeners[i], onePeriodAgo);
if (t < now) {
CallbackInvocation ci;
ci.mCallback = mEventListeners[i].mCallback;
ci.mEventTime = t;
ALOGV("[%s] [%s] Preparing to fire", mName, mEventListeners[i].mName);
callbackInvocations.push(ci);
mEventListeners.editItemAt(i).mLastEventTime = t;
}
}
return callbackInvocations;
}
nsecs_t computeListenerNextEventTimeLocked(const EventListener& listener, nsecs_t baseTime) {
if (kTraceDetailedInfo) ATRACE_CALL();
ALOGV("[%s] [%s] computeListenerNextEventTimeLocked(%" PRId64 ")", mName, listener.mName,
ns2us(baseTime));
nsecs_t lastEventTime = listener.mLastEventTime + mWakeupLatency;
ALOGV("[%s] lastEventTime: %" PRId64, mName, ns2us(lastEventTime));
if (baseTime < lastEventTime) {
baseTime = lastEventTime;
ALOGV("[%s] Clamping baseTime to lastEventTime -> %" PRId64, mName, ns2us(baseTime));
}
baseTime -= mReferenceTime;
ALOGV("[%s] Relative baseTime = %" PRId64, mName, ns2us(baseTime));
nsecs_t phase = mPhase + listener.mPhase;
ALOGV("[%s] Phase = %" PRId64, mName, ns2us(phase));
baseTime -= phase;
ALOGV("[%s] baseTime - phase = %" PRId64, mName, ns2us(baseTime));
// If our previous time is before the reference (because the reference
// has since been updated), the division by mPeriod will truncate
// towards zero instead of computing the floor. Since in all cases
// before the reference we want the next time to be effectively now, we
// set baseTime to -mPeriod so that numPeriods will be -1.
// When we add 1 and the phase, we will be at the correct event time for
// this period.
if (baseTime < 0) {
ALOGV("[%s] Correcting negative baseTime", mName);
baseTime = -mPeriod;
}
nsecs_t numPeriods = baseTime / mPeriod;
ALOGV("[%s] numPeriods = %" PRId64, mName, numPeriods);
nsecs_t t = (numPeriods + 1) * mPeriod + phase;
ALOGV("[%s] t = %" PRId64, mName, ns2us(t));
t += mReferenceTime;
ALOGV("[%s] Absolute t = %" PRId64, mName, ns2us(t));
// Check that it's been slightly more than half a period since the last
// event so that we don't accidentally fall into double-rate vsyncs
if (t - listener.mLastEventTime < (3 * mPeriod / 5)) {
t += mPeriod;
ALOGV("[%s] Modifying t -> %" PRId64, mName, ns2us(t));
}
t -= mWakeupLatency;
ALOGV("[%s] Corrected for wakeup latency -> %" PRId64, mName, ns2us(t));
return t;
}
void fireCallbackInvocations(const Vector<CallbackInvocation>& callbacks) {
if (kTraceDetailedInfo) ATRACE_CALL();
for (size_t i = 0; i < callbacks.size(); i++) {
callbacks[i].mCallback->onDispSyncEvent(callbacks[i].mEventTime);
}
}
const char* const mName;
bool mStop;
nsecs_t mPeriod;
nsecs_t mPhase;
nsecs_t mReferenceTime;
nsecs_t mWakeupLatency;
int64_t mFrameNumber;
Vector<EventListener> mEventListeners;
Mutex mMutex;
Condition mCond;
};
#undef LOG_TAG
#define LOG_TAG "DispSync"
class ZeroPhaseTracer : public DispSync::Callback {
public:
ZeroPhaseTracer() : mParity(false) {}
virtual void onDispSyncEvent(nsecs_t /*when*/) {
mParity = !mParity;
ATRACE_INT("ZERO_PHASE_VSYNC", mParity ? 1 : 0);
}
private:
bool mParity;
};
DispSync::DispSync(const char* name)
: mName(name), mRefreshSkipCount(0), mThread(new DispSyncThread(name)) {}
DispSync::~DispSync() {}
void DispSync::init(bool hasSyncFramework, int64_t dispSyncPresentTimeOffset) {
mIgnorePresentFences = !hasSyncFramework;
mPresentTimeOffset = dispSyncPresentTimeOffset;
mThread->run("DispSync", PRIORITY_URGENT_DISPLAY + PRIORITY_MORE_FAVORABLE);
// set DispSync to SCHED_FIFO to minimize jitter
struct sched_param param = {0};
param.sched_priority = 2;
if (sched_setscheduler(mThread->getTid(), SCHED_FIFO, ¶m) != 0) {
ALOGE("Couldn't set SCHED_FIFO for DispSyncThread");
}
reset();
beginResync();
if (kTraceDetailedInfo) {
// If we're not getting present fences then the ZeroPhaseTracer
// would prevent HW vsync event from ever being turned off.
// Even if we're just ignoring the fences, the zero-phase tracing is
// not needed because any time there is an event registered we will
// turn on the HW vsync events.
if (!mIgnorePresentFences && kEnableZeroPhaseTracer) {
mZeroPhaseTracer = std::make_unique<ZeroPhaseTracer>();
addEventListener("ZeroPhaseTracer", 0, mZeroPhaseTracer.get());
}
}
}
void DispSync::reset() {
Mutex::Autolock lock(mMutex);
mPhase = 0;
mReferenceTime = 0;
mModelUpdated = false;
mNumResyncSamples = 0;
mFirstResyncSample = 0;
mNumResyncSamplesSincePresent = 0;
resetErrorLocked();
}
bool DispSync::addPresentFence(const std::shared_ptr<FenceTime>& fenceTime) {
Mutex::Autolock lock(mMutex);
mPresentFences[mPresentSampleOffset] = fenceTime;
mPresentSampleOffset = (mPresentSampleOffset + 1) % NUM_PRESENT_SAMPLES;
mNumResyncSamplesSincePresent = 0;
updateErrorLocked();
return !mModelUpdated || mError > kErrorThreshold;
}
void DispSync::beginResync() {
Mutex::Autolock lock(mMutex);
ALOGV("[%s] beginResync", mName);
mModelUpdated = false;
mNumResyncSamples = 0;
}
bool DispSync::addResyncSample(nsecs_t timestamp) {
Mutex::Autolock lock(mMutex);
ALOGV("[%s] addResyncSample(%" PRId64 ")", mName, ns2us(timestamp));
size_t idx = (mFirstResyncSample + mNumResyncSamples) % MAX_RESYNC_SAMPLES;
mResyncSamples[idx] = timestamp;
if (mNumResyncSamples == 0) {
mPhase = 0;
mReferenceTime = timestamp;
ALOGV("[%s] First resync sample: mPeriod = %" PRId64 ", mPhase = 0, "
"mReferenceTime = %" PRId64,
mName, ns2us(mPeriod), ns2us(mReferenceTime));
mThread->updateModel(mPeriod, mPhase, mReferenceTime);
}
if (mNumResyncSamples < MAX_RESYNC_SAMPLES) {
mNumResyncSamples++;
} else {
mFirstResyncSample = (mFirstResyncSample + 1) % MAX_RESYNC_SAMPLES;
}
updateModelLocked();
if (mNumResyncSamplesSincePresent++ > MAX_RESYNC_SAMPLES_WITHOUT_PRESENT) {
resetErrorLocked();
}
if (mIgnorePresentFences) {
// If we don't have the sync framework we will never have
// addPresentFence called. This means we have no way to know whether
// or not we're synchronized with the HW vsyncs, so we just request
// that the HW vsync events be turned on whenever we need to generate
// SW vsync events.
return mThread->hasAnyEventListeners();
}
// Check against kErrorThreshold / 2 to add some hysteresis before having to
// resync again
bool modelLocked = mModelUpdated && mError < (kErrorThreshold / 2);
ALOGV("[%s] addResyncSample returning %s", mName, modelLocked ? "locked" : "unlocked");
return !modelLocked;
}
void DispSync::endResync() {}
status_t DispSync::addEventListener(const char* name, nsecs_t phase, Callback* callback) {
Mutex::Autolock lock(mMutex);
return mThread->addEventListener(name, phase, callback);
}
void DispSync::setRefreshSkipCount(int count) {
Mutex::Autolock lock(mMutex);
ALOGD("setRefreshSkipCount(%d)", count);
mRefreshSkipCount = count;
updateModelLocked();
}
status_t DispSync::removeEventListener(Callback* callback) {
Mutex::Autolock lock(mMutex);
return mThread->removeEventListener(callback);
}
status_t DispSync::changePhaseOffset(Callback* callback, nsecs_t phase) {
Mutex::Autolock lock(mMutex);
return mThread->changePhaseOffset(callback, phase);
}
void DispSync::setPeriod(nsecs_t period) {
Mutex::Autolock lock(mMutex);
mPeriod = period;
mPhase = 0;
mReferenceTime = 0;
mThread->updateModel(mPeriod, mPhase, mReferenceTime);
}
nsecs_t DispSync::getPeriod() {
// lock mutex as mPeriod changes multiple times in updateModelLocked
Mutex::Autolock lock(mMutex);
return mPeriod;
}
void DispSync::updateModelLocked() {
ALOGV("[%s] updateModelLocked %zu", mName, mNumResyncSamples);
if (mNumResyncSamples >= MIN_RESYNC_SAMPLES_FOR_UPDATE) {
ALOGV("[%s] Computing...", mName);
nsecs_t durationSum = 0;
nsecs_t minDuration = INT64_MAX;
nsecs_t maxDuration = 0;
for (size_t i = 1; i < mNumResyncSamples; i++) {
size_t idx = (mFirstResyncSample + i) % MAX_RESYNC_SAMPLES;
size_t prev = (idx + MAX_RESYNC_SAMPLES - 1) % MAX_RESYNC_SAMPLES;
nsecs_t duration = mResyncSamples[idx] - mResyncSamples[prev];
durationSum += duration;
minDuration = min(minDuration, duration);
maxDuration = max(maxDuration, duration);
}
// Exclude the min and max from the average
durationSum -= minDuration + maxDuration;
mPeriod = durationSum / (mNumResyncSamples - 3);
ALOGV("[%s] mPeriod = %" PRId64, mName, ns2us(mPeriod));
double sampleAvgX = 0;
double sampleAvgY = 0;
double scale = 2.0 * M_PI / double(mPeriod);
// Intentionally skip the first sample
for (size_t i = 1; i < mNumResyncSamples; i++) {
size_t idx = (mFirstResyncSample + i) % MAX_RESYNC_SAMPLES;
nsecs_t sample = mResyncSamples[idx] - mReferenceTime;
double samplePhase = double(sample % mPeriod) * scale;
sampleAvgX += cos(samplePhase);
sampleAvgY += sin(samplePhase);
}
sampleAvgX /= double(mNumResyncSamples - 1);
sampleAvgY /= double(mNumResyncSamples - 1);
mPhase = nsecs_t(atan2(sampleAvgY, sampleAvgX) / scale);
ALOGV("[%s] mPhase = %" PRId64, mName, ns2us(mPhase));
if (mPhase < -(mPeriod / 2)) {
mPhase += mPeriod;
ALOGV("[%s] Adjusting mPhase -> %" PRId64, mName, ns2us(mPhase));
}
if (kTraceDetailedInfo) {
ATRACE_INT64("DispSync:Period", mPeriod);
ATRACE_INT64("DispSync:Phase", mPhase + mPeriod / 2);
}
// Artificially inflate the period if requested.
mPeriod += mPeriod * mRefreshSkipCount;
mThread->updateModel(mPeriod, mPhase, mReferenceTime);
mModelUpdated = true;
}
}
void DispSync::updateErrorLocked() {
if (!mModelUpdated) {
return;
}
// Need to compare present fences against the un-adjusted refresh period,
// since they might arrive between two events.
nsecs_t period = mPeriod / (1 + mRefreshSkipCount);
int numErrSamples = 0;
nsecs_t sqErrSum = 0;
for (size_t i = 0; i < NUM_PRESENT_SAMPLES; i++) {
// Only check for the cached value of signal time to avoid unecessary
// syscalls. It is the responsibility of the DispSync owner to
// call getSignalTime() periodically so the cache is updated when the
// fence signals.
nsecs_t time = mPresentFences[i]->getCachedSignalTime();
if (time == Fence::SIGNAL_TIME_PENDING || time == Fence::SIGNAL_TIME_INVALID) {
continue;
}
nsecs_t sample = time - mReferenceTime;
if (sample <= mPhase) {
continue;
}
nsecs_t sampleErr = (sample - mPhase) % period;
if (sampleErr > period / 2) {
sampleErr -= period;
}
sqErrSum += sampleErr * sampleErr;
numErrSamples++;
}
if (numErrSamples > 0) {
mError = sqErrSum / numErrSamples;
mZeroErrSamplesCount = 0;
} else {
mError = 0;
// Use mod ACCEPTABLE_ZERO_ERR_SAMPLES_COUNT to avoid log spam.
mZeroErrSamplesCount++;
ALOGE_IF((mZeroErrSamplesCount % ACCEPTABLE_ZERO_ERR_SAMPLES_COUNT) == 0,
"No present times for model error.");
}
if (kTraceDetailedInfo) {
ATRACE_INT64("DispSync:Error", mError);
}
}
void DispSync::resetErrorLocked() {
mPresentSampleOffset = 0;
mError = 0;
mZeroErrSamplesCount = 0;
for (size_t i = 0; i < NUM_PRESENT_SAMPLES; i++) {
mPresentFences[i] = FenceTime::NO_FENCE;
}
}
nsecs_t DispSync::computeNextRefresh(int periodOffset) const {
Mutex::Autolock lock(mMutex);
nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
nsecs_t phase = mReferenceTime + mPhase;
return (((now - phase) / mPeriod) + periodOffset + 1) * mPeriod + phase;
}
void DispSync::dump(String8& result) const {
Mutex::Autolock lock(mMutex);
result.appendFormat("present fences are %s\n", mIgnorePresentFences ? "ignored" : "used");
result.appendFormat("mPeriod: %" PRId64 " ns (%.3f fps; skipCount=%d)\n", mPeriod,
1000000000.0 / mPeriod, mRefreshSkipCount);
result.appendFormat("mPhase: %" PRId64 " ns\n", mPhase);
result.appendFormat("mError: %" PRId64 " ns (sqrt=%.1f)\n", mError, sqrt(mError));
result.appendFormat("mNumResyncSamplesSincePresent: %d (limit %d)\n",
mNumResyncSamplesSincePresent, MAX_RESYNC_SAMPLES_WITHOUT_PRESENT);
result.appendFormat("mNumResyncSamples: %zd (max %d)\n", mNumResyncSamples, MAX_RESYNC_SAMPLES);
result.appendFormat("mResyncSamples:\n");
nsecs_t previous = -1;
for (size_t i = 0; i < mNumResyncSamples; i++) {
size_t idx = (mFirstResyncSample + i) % MAX_RESYNC_SAMPLES;
nsecs_t sampleTime = mResyncSamples[idx];
if (i == 0) {
result.appendFormat(" %" PRId64 "\n", sampleTime);
} else {
result.appendFormat(" %" PRId64 " (+%" PRId64 ")\n", sampleTime,
sampleTime - previous);
}
previous = sampleTime;
}
result.appendFormat("mPresentFences [%d]:\n", NUM_PRESENT_SAMPLES);
nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
previous = Fence::SIGNAL_TIME_INVALID;
for (size_t i = 0; i < NUM_PRESENT_SAMPLES; i++) {
size_t idx = (i + mPresentSampleOffset) % NUM_PRESENT_SAMPLES;
nsecs_t presentTime = mPresentFences[idx]->getSignalTime();
if (presentTime == Fence::SIGNAL_TIME_PENDING) {
result.appendFormat(" [unsignaled fence]\n");
} else if (presentTime == Fence::SIGNAL_TIME_INVALID) {
result.appendFormat(" [invalid fence]\n");
} else if (previous == Fence::SIGNAL_TIME_PENDING ||
previous == Fence::SIGNAL_TIME_INVALID) {
result.appendFormat(" %" PRId64 " (%.3f ms ago)\n", presentTime,
(now - presentTime) / 1000000.0);
} else {
result.appendFormat(" %" PRId64 " (+%" PRId64 " / %.3f) (%.3f ms ago)\n", presentTime,
presentTime - previous, (presentTime - previous) / (double)mPeriod,
(now - presentTime) / 1000000.0);
}
previous = presentTime;
}
result.appendFormat("current monotonic time: %" PRId64 "\n", now);
}
} // namespace android
| 34.655367 | 100 | 0.610491 | [
"vector",
"model"
] |
7adc4d0d2bdbab06572498be82202699fe6b21d0 | 2,154 | cpp | C++ | Tree/Trie/Trie.cpp | iabhimanyu/Algorithms | adefcd165e591d2338be8fc8a62629ff072620dd | [
"MIT"
] | 715 | 2018-10-01T21:30:10.000Z | 2022-03-23T09:14:10.000Z | Tree/Trie/Trie.cpp | iabhimanyu/Algorithms | adefcd165e591d2338be8fc8a62629ff072620dd | [
"MIT"
] | 157 | 2018-10-01T20:53:11.000Z | 2021-08-03T07:00:58.000Z | Tree/Trie/Trie.cpp | iabhimanyu/Algorithms | adefcd165e591d2338be8fc8a62629ff072620dd | [
"MIT"
] | 1,225 | 2018-10-01T20:56:22.000Z | 2022-02-22T04:00:27.000Z | //TRIE
#include <bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
#define MOD 1000000007
#define si(x) scanf("%d",&x)
#define sii(x,y) scanf("%d%d",&x,&y)
#define siii(x,y,z) scanf("%d%d%d",&x,&y,&z)
#define sl(x) scanf("%lld",&x)
#define sll(x,y) scanf("%lld%lld",&x,&y)
#define slll(x,y,z) scanf("%lld%lld%lld",&x,&y,&z)
#define ll long long
#define mp make_pair
#define pb push_back
#define nl printf("\n");
#define pf printf
#define rep(i,n) for(ll i=0;i<n;i++)
#define repi(i,a,b) for(ll i=a;i<b;i++)
#define vint vector<int>
#define tci int t;scanf("%d",&t);while(t--)
const int maxn=10e6+4;
struct Trie{
struct Trie *child[27];
map<char ,Trie*>m;
int w;
};
struct Trie *getNode(void)
{
struct Trie *p = new Trie;
p->w = 0;
for (int i = 0; i < 27; i++)
p->child[i] = NULL;
return p;
}
int res=0;
int rec(struct Trie *p)
{
for(int i=0;i<27;i++)
{
if(p->child[i]!=NULL)
{
res= max(rec(p->child[i]),res);
}
}
return p->w;
}
void insert(struct Trie *root,string s,int weight)
{
struct Trie *p=root;
for(int i=0;i<s.size();i++)
{
int ind=int(s[i]-'a');
if(p->child[ind]==0)
p->child[ind]=getNode();
p=p->child[ind];
}
p->w=weight;
//cout<<p->w;nl
}
void search(struct Trie *root,string s)
{
int temp=0;
struct Trie *p = root;
for (int i = 0; i < s.size(); i++)
{
int ind = s[i] - 'a';
//cout<<s[i]<<" ";
if (!p->child[ind])
{
temp=1;
cout<<-1<<endl;break;//return false;
}
p = p->child[ind];
}
if(p != NULL && !temp )
{
rec(p);
cout<<res;nl
}
}
int main()
{
ifstream myFile("task.in");
if(!myFile.fail())
{
assert(freopen("task.in", "r", stdin));
}
struct Trie *root=getNode();
int n,q;sii(n,q);
rep(i,n)
{
string s;
int weight;
cin>>s>>weight;
insert(root,s,weight);
}
while(q--)
{
res=0;
string s;
cin>>s;
search(root,s);
}
return 0;
}
| 19.232143 | 50 | 0.492108 | [
"vector"
] |
7adf01820e68db57bba429be3f9cf19c750ab2cb | 665 | cpp | C++ | Cliente.cpp | LeonardoBanegas99/P3Lab5_LeonardoBanegas | e98ba2f621bf233b60d7c2c33f26d323e2ac9834 | [
"MIT"
] | null | null | null | Cliente.cpp | LeonardoBanegas99/P3Lab5_LeonardoBanegas | e98ba2f621bf233b60d7c2c33f26d323e2ac9834 | [
"MIT"
] | null | null | null | Cliente.cpp | LeonardoBanegas99/P3Lab5_LeonardoBanegas | e98ba2f621bf233b60d7c2c33f26d323e2ac9834 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include "Platos.h"
#include "Cliente.h"
#include <vector>
using std::vector;
using namespace std;
Cliente::Cliente(){
}
Cliente::Cliente(string nombre){
this-> nombre = nombre;
}
vector<Platos*> Cliente::getPlatos(){
return PlatosConsumidos;
}
int Cliente::getValoracion(){
return valoracion;
}
string Cliente::getNombre(){
return nombre;
}
int Cliente::getDineroGastado(){
return dinerogastado;
}
void Cliente::setNombre(string n){
this-> nombre = n;
}
void Cliente::setValoracion(int n){
this->valoracion = n;
}
void Cliente::setDineroGastado(int n ){
this-> dinerogastado =n;
}
| 14.148936 | 39 | 0.684211 | [
"vector"
] |
7ae8332ec4c99067dc2b86e678863b0fcf0480ad | 12,212 | cpp | C++ | qtdeclarative/src/qml/qml/qqmltypewrapper.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | 1 | 2020-04-30T15:47:35.000Z | 2020-04-30T15:47:35.000Z | qtdeclarative/src/qml/qml/qqmltypewrapper.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | qtdeclarative/src/qml/qml/qqmltypewrapper.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qqmltypewrapper_p.h"
#include <private/qqmlcontextwrapper_p.h>
#include <private/qv8engine_p.h>
#include <private/qqmlengine_p.h>
#include <private/qqmlcontext_p.h>
#include <private/qjsvalue_p.h>
#include <private/qv4functionobject_p.h>
#include <private/qv4objectproto_p.h>
QT_BEGIN_NAMESPACE
using namespace QV4;
DEFINE_OBJECT_VTABLE(QmlTypeWrapper);
Heap::QmlTypeWrapper::QmlTypeWrapper()
: mode(IncludeEnums)
{
}
Heap::QmlTypeWrapper::~QmlTypeWrapper()
{
if (typeNamespace)
typeNamespace->release();
}
bool QmlTypeWrapper::isSingleton() const
{
return d()->type && d()->type->isSingleton();
}
QObject* QmlTypeWrapper::singletonObject() const
{
if (!isSingleton())
return 0;
QQmlEngine *e = engine()->qmlEngine();
QQmlType::SingletonInstanceInfo *siinfo = d()->type->singletonInstanceInfo();
siinfo->init(e);
return siinfo->qobjectApi(e);
}
QVariant QmlTypeWrapper::toVariant() const
{
if (d()->type && d()->type->isSingleton()) {
QQmlEngine *e = engine()->qmlEngine();
QQmlType::SingletonInstanceInfo *siinfo = d()->type->singletonInstanceInfo();
siinfo->init(e); // note: this will also create QJSValue singleton which isn't strictly required.
QObject *qobjectSingleton = siinfo->qobjectApi(e);
if (qobjectSingleton) {
return QVariant::fromValue<QObject*>(qobjectSingleton);
}
}
// only QObject Singleton Type can be converted to a variant.
return QVariant();
}
// Returns a type wrapper for type t on o. This allows access of enums, and attached properties.
ReturnedValue QmlTypeWrapper::create(QV4::ExecutionEngine *engine, QObject *o, QQmlType *t,
Heap::QmlTypeWrapper::TypeNameMode mode)
{
Q_ASSERT(t);
Scope scope(engine);
Scoped<QmlTypeWrapper> w(scope, engine->memoryManager->allocObject<QmlTypeWrapper>());
w->d()->mode = mode; w->d()->object = o; w->d()->type = t;
return w.asReturnedValue();
}
// Returns a type wrapper for importNamespace (of t) on o. This allows nested resolution of a type in a
// namespace.
ReturnedValue QmlTypeWrapper::create(QV4::ExecutionEngine *engine, QObject *o, QQmlTypeNameCache *t, const void *importNamespace,
Heap::QmlTypeWrapper::TypeNameMode mode)
{
Q_ASSERT(t);
Q_ASSERT(importNamespace);
Scope scope(engine);
Scoped<QmlTypeWrapper> w(scope, engine->memoryManager->allocObject<QmlTypeWrapper>());
w->d()->mode = mode; w->d()->object = o; w->d()->typeNamespace = t; w->d()->importNamespace = importNamespace;
t->addref();
return w.asReturnedValue();
}
static int enumForSingleton(String *name, QObject *qobjectSingleton)
{
// ### Optimize
QByteArray enumName = name->toQString().toUtf8();
const QMetaObject *metaObject = qobjectSingleton->metaObject();
for (int ii = metaObject->enumeratorCount() - 1; ii >= 0; --ii) {
QMetaEnum e = metaObject->enumerator(ii);
bool ok;
int value = e.keyToValue(enumName.constData(), &ok);
if (ok)
return value;
}
return -1;
}
static ReturnedValue throwLowercaseEnumError(QV4::ExecutionEngine *v4, String *name, QQmlType *type)
{
const QString message =
QStringLiteral("Cannot access enum value '%1' of '%2', enum values need to start with an uppercase letter.")
.arg(name->toQString()).arg(QLatin1String(type->typeName()));
return v4->throwTypeError(message);
}
ReturnedValue QmlTypeWrapper::get(const Managed *m, String *name, bool *hasProperty)
{
Q_ASSERT(m->as<QmlTypeWrapper>());
QV4::ExecutionEngine *v4 = static_cast<const QmlTypeWrapper *>(m)->engine();
QV4::Scope scope(v4);
Scoped<QmlTypeWrapper> w(scope, static_cast<const QmlTypeWrapper *>(m));
if (hasProperty)
*hasProperty = true;
QQmlContextData *context = v4->callingQmlContext();
QObject *object = w->d()->object;
QQmlType *type = w->d()->type;
if (type) {
// singleton types are handled differently to other types.
if (type->isSingleton()) {
QQmlEngine *e = v4->qmlEngine();
QQmlType::SingletonInstanceInfo *siinfo = type->singletonInstanceInfo();
siinfo->init(e);
QObject *qobjectSingleton = siinfo->qobjectApi(e);
if (qobjectSingleton) {
// check for enum value
const bool includeEnums = w->d()->mode == Heap::QmlTypeWrapper::IncludeEnums;
if (includeEnums && name->startsWithUpper()) {
const int value = enumForSingleton(name, qobjectSingleton);
if (value != -1)
return QV4::Primitive::fromInt32(value).asReturnedValue();
}
// check for property.
bool ok;
const ReturnedValue result = QV4::QObjectWrapper::getQmlProperty(v4, context, qobjectSingleton, name, QV4::QObjectWrapper::IgnoreRevision, &ok);
if (hasProperty)
*hasProperty = ok;
// Warn when attempting to access a lowercased enum value, singleton case
if (!ok && includeEnums && !name->startsWithUpper()) {
const int value = enumForSingleton(name, qobjectSingleton);
if (value != -1)
return throwLowercaseEnumError(v4, name, type);
}
return result;
} else if (!siinfo->scriptApi(e).isUndefined()) {
// NOTE: if used in a binding, changes will not trigger re-evaluation since non-NOTIFYable.
QV4::ScopedObject o(scope, QJSValuePrivate::convertedToValue(v4, siinfo->scriptApi(e)));
if (!!o)
return o->get(name);
}
// Fall through to base implementation
} else {
if (name->startsWithUpper()) {
bool ok = false;
int value = type->enumValue(QQmlEnginePrivate::get(v4->qmlEngine()), name, &ok);
if (ok)
return QV4::Primitive::fromInt32(value).asReturnedValue();
// Fall through to base implementation
} else if (w->d()->object) {
QObject *ao = qmlAttachedPropertiesObjectById(type->attachedPropertiesId(QQmlEnginePrivate::get(v4->qmlEngine())), object);
if (ao)
return QV4::QObjectWrapper::getQmlProperty(v4, context, ao, name, QV4::QObjectWrapper::IgnoreRevision, hasProperty);
// Fall through to base implementation
}
// Fall through to base implementation
}
// Fall through to base implementation
} else if (w->d()->typeNamespace) {
Q_ASSERT(w->d()->importNamespace);
QQmlTypeNameCache::Result r = w->d()->typeNamespace->query(name, w->d()->importNamespace);
if (r.isValid()) {
if (r.type) {
return create(scope.engine, object, r.type, w->d()->mode);
} else if (r.scriptIndex != -1) {
QV4::ScopedObject scripts(scope, context->importedScripts.valueRef());
return scripts->getIndexed(r.scriptIndex);
} else if (r.importNamespace) {
return create(scope.engine, object, context->imports, r.importNamespace);
}
return QV4::Encode::undefined();
}
// Fall through to base implementation
} else {
Q_ASSERT(!"Unreachable");
}
bool ok = false;
const ReturnedValue result = Object::get(m, name, &ok);
if (hasProperty)
*hasProperty = ok;
// Warn when attempting to access a lowercased enum value, non-singleton case
if (!ok && type && !type->isSingleton() && !name->startsWithUpper()) {
bool enumOk = false;
type->enumValue(QQmlEnginePrivate::get(v4->qmlEngine()), name, &enumOk);
if (enumOk)
return throwLowercaseEnumError(v4, name, type);
}
return result;
}
void QmlTypeWrapper::put(Managed *m, String *name, const Value &value)
{
Q_ASSERT(m->as<QmlTypeWrapper>());
QmlTypeWrapper *w = static_cast<QmlTypeWrapper *>(m);
QV4::ExecutionEngine *v4 = w->engine();
if (v4->hasException)
return;
QV4::Scope scope(v4);
QQmlContextData *context = v4->callingQmlContext();
QQmlType *type = w->d()->type;
if (type && !type->isSingleton() && w->d()->object) {
QObject *object = w->d()->object;
QQmlEngine *e = scope.engine->qmlEngine();
QObject *ao = qmlAttachedPropertiesObjectById(type->attachedPropertiesId(QQmlEnginePrivate::get(e)), object);
if (ao)
QV4::QObjectWrapper::setQmlProperty(v4, context, ao, name, QV4::QObjectWrapper::IgnoreRevision, value);
} else if (type && type->isSingleton()) {
QQmlEngine *e = scope.engine->qmlEngine();
QQmlType::SingletonInstanceInfo *siinfo = type->singletonInstanceInfo();
siinfo->init(e);
QObject *qobjectSingleton = siinfo->qobjectApi(e);
if (qobjectSingleton) {
QV4::QObjectWrapper::setQmlProperty(v4, context, qobjectSingleton, name, QV4::QObjectWrapper::IgnoreRevision, value);
} else if (!siinfo->scriptApi(e).isUndefined()) {
QV4::ScopedObject apiprivate(scope, QJSValuePrivate::convertedToValue(v4, siinfo->scriptApi(e)));
if (!apiprivate) {
QString error = QLatin1String("Cannot assign to read-only property \"") + name->toQString() + QLatin1Char('\"');
v4->throwError(error);
return;
} else {
apiprivate->put(name, value);
}
}
}
}
PropertyAttributes QmlTypeWrapper::query(const Managed *m, String *name)
{
// ### Implement more efficiently.
bool hasProperty = false;
static_cast<Object *>(const_cast<Managed*>(m))->get(name, &hasProperty);
return hasProperty ? Attr_Data : Attr_Invalid;
}
bool QmlTypeWrapper::isEqualTo(Managed *a, Managed *b)
{
Q_ASSERT(a->as<QV4::QmlTypeWrapper>());
QV4::QmlTypeWrapper *qmlTypeWrapperA = static_cast<QV4::QmlTypeWrapper *>(a);
if (QV4::QmlTypeWrapper *qmlTypeWrapperB = b->as<QV4::QmlTypeWrapper>())
return qmlTypeWrapperA->toVariant() == qmlTypeWrapperB->toVariant();
else if (QV4::QObjectWrapper *qobjectWrapper = b->as<QV4::QObjectWrapper>())
return qmlTypeWrapperA->toVariant().value<QObject*>() == qobjectWrapper->object();
return false;
}
QT_END_NAMESPACE
| 37.231707 | 160 | 0.625532 | [
"object"
] |
7aeab3a6ae945f1e3728623c09a4b2f630b85ce6 | 1,313 | cpp | C++ | leetcode/297.serialize-and-deserialize-binary-tree.cpp | vkashkumar/Competitive-Programming | c457e745208c0ca3e45b1ffce254a21504533f51 | [
"MIT"
] | 2 | 2019-01-30T12:45:18.000Z | 2021-05-06T19:02:51.000Z | leetcode/297.serialize-and-deserialize-binary-tree.cpp | vkashkumar/Competitive-Programming | c457e745208c0ca3e45b1ffce254a21504533f51 | [
"MIT"
] | null | null | null | leetcode/297.serialize-and-deserialize-binary-tree.cpp | vkashkumar/Competitive-Programming | c457e745208c0ca3e45b1ffce254a21504533f51 | [
"MIT"
] | 3 | 2020-10-02T15:42:04.000Z | 2022-03-27T15:14:16.000Z | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// [https://www.youtube.com/watch?v=suj1ro8TIVY&t=689s] O(n)
class Codec {
public:
string serialize(TreeNode* root) {
if(root == NULL) return "NULL,";
return to_string(root->val) + "," + serialize(root->left) + serialize(root->right);
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
queue<string> q;
string s;
for(int i=0;i<data.size();i++)
{
if(data[i]==',')
{
q.push(s);
s="";
continue;
}
s+=data[i];
}
if(s.size()!=0)q.push(s);
return deserialize_helper(q);
}
TreeNode* deserialize_helper(queue<string> &q) {
string s=q.front();
q.pop();
if(s=="NULL") return NULL;
TreeNode* root=new TreeNode(stoi(s));
root->left=deserialize_helper(q);
root->right=deserialize_helper(q);
return root;
}
};
// Your Codec object will be instantiated and called as such:
// Codec ser, deser;
// TreeNode* ans = deser.deserialize(ser.serialize(root)); | 25.25 | 91 | 0.531607 | [
"object"
] |
7aed4fe42d19f28fdd8f47dcba6e79772c0bcaf5 | 38,772 | cc | C++ | LiteCore/tests/QueryTest.cc | bjornd/couchbase-lite-core | 5da4cc825021bb90be591ae4ab835be201333a0a | [
"Apache-2.0"
] | null | null | null | LiteCore/tests/QueryTest.cc | bjornd/couchbase-lite-core | 5da4cc825021bb90be591ae4ab835be201333a0a | [
"Apache-2.0"
] | null | null | null | LiteCore/tests/QueryTest.cc | bjornd/couchbase-lite-core | 5da4cc825021bb90be591ae4ab835be201333a0a | [
"Apache-2.0"
] | null | null | null | //
// QueryTest.cc
//
// Copyright (c) 2017 Couchbase, 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 "DataFile.hh"
#include "Query.hh"
#include "Error.hh"
#include "Fleece.hh"
#include "Benchmark.hh"
#include "LiteCoreTest.hh"
using namespace litecore;
using namespace std;
// NOTE: This test does not use RevTree or Database, so it stores plain Fleece in record bodies.
static sequence_t writeNumberedDoc(KeyStore *store, int i, slice str, Transaction &t,
DocumentFlags flags =DocumentFlags::kNone) {
string docID = stringWithFormat("rec-%03d", i);
fleece::Encoder enc;
enc.beginDictionary();
enc.writeKey("num");
enc.writeInt(i);
if (str) {
enc.writeKey("str");
enc.writeString(str);
}
enc.endDictionary();
alloc_slice body = enc.extractOutput();
return store->set(slice(docID), nullslice, body, flags, t);
}
static void writeMultipleTypeDocs(KeyStore* store, Transaction &t) {
string docID = "doc1";
fleece::Encoder enc;
enc.beginDictionary(1);
enc.writeKey("value");
enc.beginArray();
enc.writeInt(1);
enc.endArray();
enc.endDictionary();
alloc_slice body = enc.extractOutput();
store->set(slice(docID), nullslice, body, DocumentFlags::kNone, t);
enc.reset();
docID = "doc2";
enc.beginDictionary(1);
enc.writeKey("value");
enc.writeString("cool value");
enc.endDictionary();
body = enc.extractOutput();
store->set(slice(docID), nullslice, body, DocumentFlags::kNone, t);
enc.reset();
docID = "doc3";
enc.beginDictionary(1);
enc.writeKey("value");
enc.writeDouble(4.5);
enc.endDictionary();
body = enc.extractOutput();
store->set(slice(docID), nullslice, body, DocumentFlags::kNone, t);
enc.reset();
docID = "doc4";
enc.beginDictionary(1);
enc.writeKey("value");
enc.beginDictionary(1);
enc.writeKey("subvalue");
enc.writeString("FTW");
enc.endDictionary();
enc.endDictionary();
body = enc.extractOutput();
store->set(slice(docID), nullslice, body, DocumentFlags::kNone, t);
enc.reset();
docID = "doc5";
enc.beginDictionary(1);
enc.writeKey("value");
enc.writeBool(true);
enc.endDictionary();
body = enc.extractOutput();
store->set(slice(docID), nullslice, body, DocumentFlags::kNone, t);
}
static void writeFalselyDocs(KeyStore* store, Transaction &t) {
string docID = "doc6";
fleece::Encoder enc;
enc.beginDictionary(1);
enc.writeKey("value");
enc.beginArray(0);
enc.endArray();
enc.endDictionary();
alloc_slice body = enc.extractOutput();
store->set(slice(docID), nullslice, body, DocumentFlags::kNone, t);
enc.reset();
docID = "doc7";
enc.beginDictionary(1);
enc.writeKey("value");
enc.beginDictionary(0);
enc.endDictionary();
enc.endDictionary();
body = enc.extractOutput();
store->set(slice(docID), nullslice, body, DocumentFlags::kNone, t);
enc.reset();
docID = "doc8";
enc.beginDictionary(1);
enc.writeKey("value");
enc.writeBool(false);
enc.endDictionary();
body = enc.extractOutput();
store->set(slice(docID), nullslice, body, DocumentFlags::kNone, t);
}
// Write 100 docs with Fleece bodies of the form {"num":n} where n is the rec #
static void addNumberedDocs(KeyStore *store) {
Transaction t(store->dataFile());
for (int i = 1; i <= 100; i++)
REQUIRE(writeNumberedDoc(store, i, nullslice, t) == (sequence_t)i);
t.commit();
}
static vector<string> extractIndexes(slice encodedIndexes) {
vector<string> retVal;
const Array *val = Value::fromTrustedData(encodedIndexes)->asArray();
CHECK(val != nullptr);
Array::iterator iter(val);
int size = iter.count();
for(int i = 0; i < size; i++, ++iter) {
retVal.emplace_back(iter.value()->asString().asString());
}
return retVal;
}
TEST_CASE_METHOD(DataFileTestFixture, "Create/Delete Index", "[Query][FTS]") {
KeyStore::IndexOptions options { "en", true };
ExpectException(error::Domain::LiteCore, error::LiteCoreError::InvalidParameter, [=] {
store->createIndex(""_sl, "[[\".num\"]]"_sl);
});
ExpectException(error::Domain::LiteCore, error::LiteCoreError::InvalidParameter, [=] {
store->createIndex("\"num\""_sl, "[[\".num\"]]"_sl, KeyStore::kFullTextIndex, &options);
});
store->createIndex("num"_sl, "[[\".num\"]]"_sl, KeyStore::kFullTextIndex, &options);
auto indexes = extractIndexes(store->getIndexes());
CHECK(indexes.size() == 1);
CHECK(indexes[0] == "num");
store->deleteIndex("num"_sl);
store->createIndex("num_second"_sl, "[[\".num\"]]"_sl, KeyStore::kFullTextIndex, &options);
store->createIndex("num_second"_sl, "[[\".num_second\"]]"_sl, KeyStore::kFullTextIndex, &options);
indexes = extractIndexes(store->getIndexes());
CHECK(indexes.size() == 1);
CHECK(indexes[0] == "num_second");
store->createIndex("num"_sl, "[\".num\"]"_sl);
store->createIndex("num_second"_sl, "[\".num\"]"_sl);
indexes = extractIndexes(store->getIndexes());
CHECK(indexes.size() == 2);
CHECK(find(indexes.begin(), indexes.end(), "num") != indexes.end());
CHECK(find(indexes.begin(), indexes.end(), "num_second") != indexes.end());
store->deleteIndex("num"_sl);
indexes = extractIndexes(store->getIndexes());
CHECK(indexes.size() == 1);
CHECK(indexes[0] == "num_second");
store->deleteIndex("num_second"_sl);
store->deleteIndex("num_second"_sl); // Duplicate should be no-op
store->deleteIndex("num_second"_sl);
store->deleteIndex("num_second"_sl); // Duplicate should be no-op
indexes = extractIndexes(store->getIndexes());
CHECK(indexes.size() == 0);
}
TEST_CASE_METHOD(DataFileTestFixture, "Query SELECT", "[Query]") {
addNumberedDocs(store);
// Use a (SQL) query based on the Fleece "num" property:
Retained<Query> query{ store->compileQuery(json5("['AND', ['>=', ['.', 'num'], 30], ['<=', ['.', 'num'], 40]]")) };
CHECK(query->columnCount() == 2); // docID and sequence, by default
for (int pass = 0; pass < 2; ++pass) {
Stopwatch st;
int i = 30;
unique_ptr<QueryEnumerator> e(query->createEnumerator());
while (e->next()) {
auto cols = e->columns();
REQUIRE(e->columns().count() == 2);
slice docID = cols[0]->asString();
sequence_t seq = cols[1]->asInt();
string expectedDocID = stringWithFormat("rec-%03d", i);
REQUIRE(docID == slice(expectedDocID));
REQUIRE(seq == (sequence_t)i);
++i;
}
st.printReport("Query of $.num", i, "row");
REQUIRE(i == 41);
// Add an index after the first pass:
if (pass == 0) {
Stopwatch st2;
store->createIndex("num"_sl, "[\".num\"]"_sl);
st2.printReport("Index on .num", 1, "index");
}
}
// Redundant createIndex should not fail:
store->createIndex("num"_sl, "[\".num\"]"_sl);
}
TEST_CASE_METHOD(DataFileTestFixture, "Query SELECT WHAT", "[Query]") {
addNumberedDocs(store);
Retained<Query> query{ store->compileQuery(json5(
"{WHAT: ['.num', ['*', ['.num'], ['.num']]], WHERE: ['>', ['.num'], 10]}")) };
CHECK(query->columnCount() == 2);
int num = 11;
unique_ptr<QueryEnumerator> e(query->createEnumerator());
while (e->next()) {
string expectedDocID = stringWithFormat("rec-%03d", num);
auto cols = e->columns();
REQUIRE(cols.count() == 2);
REQUIRE(cols[0]->asInt() == num);
REQUIRE(cols[1]->asInt() == num * num);
++num;
}
REQUIRE(num == 101);
}
TEST_CASE_METHOD(DataFileTestFixture, "Query SELECT All", "[Query]") {
addNumberedDocs(store);
Retained<Query> query1{ store->compileQuery(json5("{WHAT: [['.main'], ['*', ['.main.num'], ['.main.num']]], WHERE: ['>', ['.main.num'], 10], FROM: [{AS: 'main'}]}")) };
Retained<Query> query2{ store->compileQuery(json5("{WHAT: [ '.main', ['*', ['.main.num'], ['.main.num']]], WHERE: ['>', ['.main.num'], 10], FROM: [{AS: 'main'}]}")) };
SECTION("Just regular docs") {
}
SECTION("Ignore deleted docs") {
Transaction t(store->dataFile());
for (int i = 201; i <= 300; i++)
writeNumberedDoc(store, i, nullslice, t,
DocumentFlags::kDeleted | DocumentFlags::kHasAttachments);
t.commit();
}
int num = 11;
unique_ptr<QueryEnumerator> e(query1->createEnumerator());
unique_ptr<QueryEnumerator> e2(query1->createEnumerator());
while (e->next() && e2->next()) {
string expectedDocID = stringWithFormat("rec-%03d", num);
auto cols = e->columns();
auto cols2 = e2->columns();
REQUIRE(cols.count() == 2);
REQUIRE(cols2.count() == 2);
auto star = cols[0]->asDict();
auto star2 = cols2[0]->asDict();
REQUIRE(star);
REQUIRE(star2);
REQUIRE(star->get("num"_sl)->asInt() == num);
REQUIRE(star2->get("num"_sl)->asInt() == num);
REQUIRE(cols[1]->asInt() == num * num);
REQUIRE(cols2[1]->asInt() == num * num);
++num;
}
REQUIRE(num == 101);
}
TEST_CASE_METHOD(DataFileTestFixture, "Query null value", "[Query]") {
{
Transaction t(store->dataFile());
fleece::Encoder enc;
enc.beginDictionary();
enc.writeKey("n");
enc.writeNull();
enc.endDictionary();
alloc_slice body = enc.extractOutput();
store->set("null-and-void"_sl, body, t);
t.commit();
}
Retained<Query> query{ store->compileQuery(json5("{WHAT: [['.n'], ['.']]}")) };
unique_ptr<QueryEnumerator> e(query->createEnumerator());
REQUIRE(e->next());
auto cols = e->columns();
REQUIRE(cols.count() == 2);
CHECK(cols[0]->type() == kNull);
auto col1 = cols[1]->asDict();
REQUIRE(col1);
auto n = col1->get("n"_sl);
REQUIRE(n);
CHECK(n->type() == kNull);
}
TEST_CASE_METHOD(DataFileTestFixture, "Query refresh", "[Query]") {
addNumberedDocs(store);
Retained<Query> query{ store->compileQuery(json5(
"{WHAT: ['.num', ['*', ['.num'], ['.num']]], WHERE: ['>', ['.num'], 10]}")) };
CHECK(query->columnCount() == 2);
int num = 11;
unique_ptr<QueryEnumerator> e(query->createEnumerator());
while (e->next())
++num;
REQUIRE(num == 101);
CHECK(e->refresh() == nullptr);
// Add a doc that doesn't alter the query:
{
Transaction t(db);
writeNumberedDoc(store, -1, nullslice, t);
t.commit();
}
CHECK(e->refresh() == nullptr);
#if 0 //FIX: This doesn't work yet, because the doc's sequence and revID are in the query results,
// and those do change...
// Modify a doc in a way that doesn't affect the query results
{
Transaction t(db);
writeNumberedDoc(store, 20, "howdy"_sl, t);
t.commit();
}
CHECK(e->refresh() == nullptr);
#endif
// Delete one of the docs in the query -- this does trigger a refresh:
{
Transaction t(db);
store->set("rec-030"_sl, "2-ffff"_sl, nullslice, DocumentFlags::kDeleted, t);
t.commit();
}
unique_ptr<QueryEnumerator> e2(e->refresh());
REQUIRE(e2 != nullptr);
num = 11;
while (e2->next())
++num;
CHECK(num == 100);
}
TEST_CASE_METHOD(DataFileTestFixture, "Query boolean", "[Query]") {
{
Transaction t(store->dataFile());
for(int i = 0; i < 2; i++) {
string docID = stringWithFormat("rec-%03d", i + 1);
fleece::Encoder enc;
enc.beginDictionary();
enc.writeKey("value");
enc.writeBool(i == 0);
enc.endDictionary();
alloc_slice body = enc.extractOutput();
store->set(slice(docID), nullslice, body, DocumentFlags::kNone, t);
}
// Integer 0 and 1 would have fooled ISBOOLEAN() before
for(int i = 2; i < 4; i++) {
string docID = stringWithFormat("rec-%03d", i + 1);
fleece::Encoder enc;
enc.beginDictionary();
enc.writeKey("value");
enc.writeInt(i - 2);
enc.endDictionary();
alloc_slice body = enc.extractOutput();
store->set(slice(docID), nullslice, body, DocumentFlags::kNone, t);
}
t.commit();
}
Retained<Query> query{ store->compileQuery(json5(
"{WHAT: ['._id'], WHERE: ['ISBOOLEAN()', ['.value']]}")) };
unique_ptr<QueryEnumerator> e(query->createEnumerator());
REQUIRE(e->getRowCount() == 2);
int i = 1;
while (e->next()) {
CHECK(e->columns()[0]->asString().asString() == stringWithFormat("rec-%03d", i++));
}
}
#pragma mark Targeted N1QL tests
TEST_CASE_METHOD(DataFileTestFixture, "Query array length", "[Query]") {
{
Transaction t(store->dataFile());
for(int i = 0; i < 2; i++) {
string docID = stringWithFormat("rec-%03d", i + 1);
fleece::Encoder enc;
enc.beginDictionary(1);
enc.writeKey("value");
enc.beginArray(i + 1);
for(int j = 0; j < i + 1; j++) {
enc.writeInt(j);
}
enc.endArray();
enc.endDictionary();
alloc_slice body = enc.extractOutput();
store->set(slice(docID), nullslice, body, DocumentFlags::kNone, t);
}
t.commit();
}
Retained<Query> query{ store->compileQuery(json5(
"{WHAT: ['._id'], WHERE: ['>', ['ARRAY_LENGTH()', ['.value']], 1]}")) };
unique_ptr<QueryEnumerator> e(query->createEnumerator());
REQUIRE(e->getRowCount() == 1);
REQUIRE(e->next());
REQUIRE(e->columns()[0]->asString() == "rec-002"_sl);
}
TEST_CASE_METHOD(DataFileTestFixture, "Query missing and null", "[Query]") {
{
Transaction t(store->dataFile());
string docID = "doc1";
fleece::Encoder enc;
enc.beginDictionary(1);
enc.writeKey("value");
enc.writeNull();
enc.writeKey("real_value");
enc.writeInt(1);
enc.endDictionary();
alloc_slice body = enc.extractOutput();
store->set(slice(docID), nullslice, body, DocumentFlags::kNone, t);
enc.reset();
docID = "doc2";
enc.beginDictionary(2);
enc.writeKey("value");
enc.writeNull();
enc.writeKey("atai");
enc.writeInt(1);
enc.endDictionary();
body = enc.extractOutput();
store->set(slice(docID), nullslice, body, DocumentFlags::kNone, t);
t.commit();
}
Retained<Query> query{ store->compileQuery(json5(
"{'WHAT': ['._id'], WHERE: ['=', ['IFMISSING()', ['.bogus'], ['.value']], null]}")) };
unique_ptr<QueryEnumerator> e(query->createEnumerator());
REQUIRE(e->getRowCount() == 2);
REQUIRE(e->next());
REQUIRE(e->columns()[0]->asString() == "doc1"_sl);
REQUIRE(e->next());
REQUIRE(e->columns()[0]->asString() == "doc2"_sl);
query =store->compileQuery(json5(
"{'WHAT': ['._id'], WHERE: ['=', ['IFMISSINGORNULL()', ['.atai'], ['.value']], 1]}"));
e.reset(query->createEnumerator());
REQUIRE(e->getRowCount() == 1);
REQUIRE(e->next());
REQUIRE(e->columns()[0]->asString() == "doc2"_sl);
query =store->compileQuery(json5(
"{'WHAT': ['._id'], WHERE: ['=', ['IFNULL()', ['.real_value'], ['.atai']], 1]}"));
e.reset(query->createEnumerator());
REQUIRE(e->getRowCount() == 1);
REQUIRE(e->next());
REQUIRE(e->columns()[0]->asString() == "doc1"_sl);
query =store->compileQuery(json5(
"{'WHAT': ['._id'], WHERE: ['=', ['IFMISSINGORNULL()', ['.real_value'], ['.atai']], 1]}"));
e.reset(query->createEnumerator());
REQUIRE(e->getRowCount() == 2);
REQUIRE(e->next());
REQUIRE(e->columns()[0]->asString() == "doc1"_sl);
REQUIRE(e->next());
REQUIRE(e->columns()[0]->asString() == "doc2"_sl);
}
TEST_CASE_METHOD(DataFileTestFixture, "Query regex", "[Query]") {
{
Transaction t(store->dataFile());
string docID = "doc1";
fleece::Encoder enc;
enc.beginDictionary(1);
enc.writeKey("value");
enc.writeString("awesome value");
enc.endDictionary();
alloc_slice body = enc.extractOutput();
store->set(slice(docID), nullslice, body, DocumentFlags::kNone, t);
enc.reset();
docID = "doc2";
enc.beginDictionary(1);
enc.writeKey("value");
enc.writeString("cool value");
enc.endDictionary();
body = enc.extractOutput();
store->set(slice(docID), nullslice, body, DocumentFlags::kNone, t);
enc.reset();
docID = "doc3";
enc.beginDictionary(1);
enc.writeKey("value");
enc.writeString("invalid");
enc.endDictionary();
body = enc.extractOutput();
store->set(slice(docID), nullslice, body, DocumentFlags::kNone, t);
t.commit();
}
Retained<Query> query{ store->compileQuery(json5(
"{'WHAT': ['._id'], WHERE: ['REGEXP_CONTAINS()', ['.value'], '.*? value']}")) };
unique_ptr<QueryEnumerator> e(query->createEnumerator());
REQUIRE(e->getRowCount() == 2);
REQUIRE(e->next());
REQUIRE(e->columns()[0]->asString() == "doc1"_sl);
REQUIRE(e->next());
REQUIRE(e->columns()[0]->asString() == "doc2"_sl);
query = store->compileQuery(json5(
"{'WHAT': ['._id'], WHERE: ['REGEXP_LIKE()', ['.value'], '.*? value']}"));
e.reset(query->createEnumerator());
REQUIRE(e->getRowCount() == 2);
REQUIRE(e->next());
REQUIRE(e->columns()[0]->asString() == "doc1"_sl);
REQUIRE(e->next());
REQUIRE(e->columns()[0]->asString() == "doc2"_sl);
query = store->compileQuery(json5(
"{'WHAT': ['._id'], WHERE: ['>', ['REGEXP_POSITION()', ['.value'], '[ ]+value'], 4]}"));
e.reset(query->createEnumerator());
REQUIRE(e->getRowCount() == 1);
REQUIRE(e->next());
REQUIRE(e->columns()[0]->asString() == "doc1"_sl);
query = store->compileQuery(json5(
"{'WHAT': [['REGEXP_REPLACE()', ['.value'], '.*?value', 'nothing']]}"));
e.reset(query->createEnumerator());
REQUIRE(e->getRowCount() == 3);
REQUIRE(e->next());
REQUIRE(e->columns()[0]->asString() == "nothing"_sl);
REQUIRE(e->next());
REQUIRE(e->columns()[0]->asString() == "nothing"_sl);
REQUIRE(e->next());
REQUIRE(e->columns()[0]->asString() == "invalid"_sl);
}
TEST_CASE_METHOD(DataFileTestFixture, "Query type check", "[Query]") {
{
Transaction t(store->dataFile());
writeMultipleTypeDocs(store, t);
t.commit();
}
Retained<Query> query{ store->compileQuery(json5(
"{'WHAT': [['TYPE()', ['.value']], ['._id']], WHERE: ['ISARRAY()', ['.value']]}")) };
unique_ptr<QueryEnumerator> e(query->createEnumerator());
REQUIRE(e->getRowCount() == 1);
REQUIRE(e->next());
CHECK(e->columns()[0]->asString() == "array"_sl);
CHECK(e->columns()[1]->asString() == "doc1"_sl);
query = store->compileQuery(json5(
"{'WHAT': [['TYPE()', ['.value']], ['._id'], ['.value']], WHERE: ['ISNUMBER()', ['.value']]}"));
e.reset(query->createEnumerator());
REQUIRE(e->getRowCount() == 1);
REQUIRE(e->next());
CHECK(e->columns()[0]->asString() == "number"_sl);
CHECK(e->columns()[1]->asString() == "doc3"_sl);
CHECK(e->columns()[2]->asDouble() == 4.5);
query = store->compileQuery(json5(
"{'WHAT': [['TYPE()', ['.value']], ['._id'], ['.value']], WHERE: ['ISSTRING()', ['.value']]}"));
e.reset(query->createEnumerator());
REQUIRE(e->getRowCount() == 1);
REQUIRE(e->next());
CHECK(e->columns()[0]->asString() == "string"_sl);
CHECK(e->columns()[1]->asString() == "doc2"_sl);
CHECK(e->columns()[2]->asString() == "cool value"_sl);
query = store->compileQuery(json5(
"{'WHAT': [['TYPE()', ['.value']], ['._id']], WHERE: ['ISOBJECT()', ['.value']]}"));
e.reset(query->createEnumerator());
REQUIRE(e->getRowCount() == 1);
REQUIRE(e->next());
CHECK(e->columns()[0]->asString() == "object"_sl);
CHECK(e->columns()[1]->asString() == "doc4"_sl);
query = store->compileQuery(json5(
"{'WHAT': [['TYPE()', ['.value']], ['._id'], ['.value']], WHERE: ['ISBOOLEAN()', ['.value']]}"));
e.reset(query->createEnumerator());
REQUIRE(e->getRowCount() == 1);
REQUIRE(e->next());
CHECK(e->columns()[0]->asString() == "boolean"_sl);
CHECK(e->columns()[1]->asString() == "doc5"_sl);
CHECK(e->columns()[2]->asBool());
query = store->compileQuery(json5(
"{'WHAT': [['TYPE()', ['.value']], ['._id']], WHERE: ['ISATOM()', ['.value']]}"));
e.reset(query->createEnumerator());
REQUIRE(e->getRowCount() == 3);
REQUIRE(e->next());
CHECK(e->columns()[0]->asString() == "string"_sl);
CHECK(e->columns()[1]->asString() == "doc2"_sl);
REQUIRE(e->next());
CHECK(e->columns()[0]->asString() == "number"_sl);
CHECK(e->columns()[1]->asString() == "doc3"_sl);
REQUIRE(e->next());
CHECK(e->columns()[0]->asString() == "boolean"_sl);
CHECK(e->columns()[1]->asString() == "doc5"_sl);
}
TEST_CASE_METHOD(DataFileTestFixture, "Query toboolean", "[Query]") {
{
Transaction t(store->dataFile());
writeMultipleTypeDocs(store, t);
writeFalselyDocs(store, t);
t.commit();
}
Retained<Query> query{ store->compileQuery(json5(
"{'WHAT': [['TOBOOLEAN()', ['.value']]]}")) };
unique_ptr<QueryEnumerator> e(query->createEnumerator());
REQUIRE(e->getRowCount() == 8);
REQUIRE(e->next());
CHECK(e->columns()[0]->asBool());
REQUIRE(e->next());
CHECK(e->columns()[0]->asBool());
REQUIRE(e->next());
CHECK(e->columns()[0]->asBool());
REQUIRE(e->next());
CHECK(e->columns()[0]->asBool());
REQUIRE(e->next());
CHECK(e->columns()[0]->asBool());
REQUIRE(e->next());
CHECK(!e->columns()[0]->asBool());
REQUIRE(e->next());
CHECK(!e->columns()[0]->asBool());
REQUIRE(e->next());
CHECK(!e->columns()[0]->asBool());
}
TEST_CASE_METHOD(DataFileTestFixture, "Query toatom", "[Query]") {
{
Transaction t(store->dataFile());
writeMultipleTypeDocs(store, t);
writeFalselyDocs(store, t);
t.commit();
}
Retained<Query> query{ store->compileQuery(json5(
"{'WHAT': [['TOATOM()', ['.value']]]}")) };
unique_ptr<QueryEnumerator> e(query->createEnumerator());
REQUIRE(e->getRowCount() == 8);
REQUIRE(e->next());
CHECK(e->columns()[0]->asInt() == 1);
REQUIRE(e->next());
CHECK(e->columns()[0]->asString() == "cool value"_sl);
REQUIRE(e->next());
CHECK(e->columns()[0]->asDouble() == 4.5);
REQUIRE(e->next());
CHECK(e->columns()[0]->asString() == "FTW"_sl);
REQUIRE(e->next());
CHECK(e->columns()[0]->asBool());
REQUIRE(e->next());
CHECK(e->columns()[0]->type() == kNull);
REQUIRE(e->next());
CHECK(e->columns()[0]->type() == kNull);
REQUIRE(e->next());
CHECK(!e->columns()[0]->asBool());
}
TEST_CASE_METHOD(DataFileTestFixture, "Query tonumber", "[Query]") {
{
Transaction t(store->dataFile());
writeMultipleTypeDocs(store, t);
t.commit();
}
Retained<Query> query{ store->compileQuery(json5(
"{'WHAT': [['TONUMBER()', ['.value']]]}")) };
unique_ptr<QueryEnumerator> e;
{
ExpectingExceptions x; // tonumber() will internally throw/catch an exception while indexing
e.reset(query->createEnumerator());
}
REQUIRE(e->getRowCount() == 5);
REQUIRE(e->next());
CHECK(e->columns()[0]->asDouble() == 0.0);
REQUIRE(e->next());
CHECK(e->columns()[0]->asDouble() == 0.0);
REQUIRE(e->next());
CHECK(e->columns()[0]->asDouble() == 4.5);
REQUIRE(e->next());
CHECK(e->columns()[0]->asDouble() == 0.0);
REQUIRE(e->next());
CHECK(e->columns()[0]->asDouble() == 1.0);
}
TEST_CASE_METHOD(DataFileTestFixture, "Query tostring", "[Query]") {
{
Transaction t(store->dataFile());
writeMultipleTypeDocs(store, t);
writeFalselyDocs(store, t);
t.commit();
}
Retained<Query> query{ store->compileQuery(json5(
"{'WHAT': [['TOSTRING()', ['.value']]]}")) };
unique_ptr<QueryEnumerator> e(query->createEnumerator());
REQUIRE(e->getRowCount() == 8);
REQUIRE(e->next());
CHECK(e->columns()[0]->type() == kNull);
REQUIRE(e->next());
CHECK(e->columns()[0]->asString() == "cool value"_sl);
REQUIRE(e->next());
CHECK(e->columns()[0]->asString().asString().substr(0, 3) == "4.5");
REQUIRE(e->next());
CHECK(e->columns()[0]->type() == kNull);
REQUIRE(e->next());
CHECK(e->columns()[0]->asString() == "true"_sl);
REQUIRE(e->next());
CHECK(e->columns()[0]->type() == kNull);
REQUIRE(e->next());
CHECK(e->columns()[0]->type() == kNull);
REQUIRE(e->next());
CHECK(e->columns()[0]->asString() == "false"_sl);
}
TEST_CASE_METHOD(DataFileTestFixture, "Query HAVING", "[Query]") {
{
Transaction t(store->dataFile());
char docID[6];
for(int i = 0; i < 20; i++) {
sprintf(docID, "doc%02d", i);
fleece::Encoder enc;
enc.beginDictionary(1);
enc.writeKey("identifier");
enc.writeInt(i >= 5 ? i >= 15 ? 3 : 2 : 1);
enc.writeKey("index");
enc.writeInt(i);
enc.endDictionary();
alloc_slice body = enc.extractOutput();
store->set(slice(docID), nullslice, body, DocumentFlags::kNone, t);
}
t.commit();
}
Retained<Query> query{ store->compileQuery(json5(
"{'WHAT': ['.identifier', ['COUNT()', ['.index']]], 'GROUP_BY': ['.identifier'], 'HAVING': ['=', ['.identifier'], 1]}")) };
unique_ptr<QueryEnumerator> e(query->createEnumerator());
REQUIRE(e->getRowCount() == 1);
REQUIRE(e->next());
CHECK(e->columns()[0]->asInt() == 1);
CHECK(e->columns()[1]->asInt() == 5);
query = store->compileQuery(json5(
"{'WHAT': ['.identifier', ['COUNT()', ['.index']]], 'GROUP_BY': ['.identifier'], 'HAVING': ['!=', ['.identifier'], 1]}"));
e.reset(query->createEnumerator());
REQUIRE(e->getRowCount() == 2);
REQUIRE(e->next());
CHECK(e->columns()[0]->asInt() == 2);
CHECK(e->columns()[1]->asInt() == 10);
REQUIRE(e->next());
CHECK(e->columns()[0]->asInt() == 3);
CHECK(e->columns()[1]->asInt() == 5);
}
TEST_CASE_METHOD(DataFileTestFixture, "Query Functions", "[Query]") {
{
Transaction t(store->dataFile());
writeNumberedDoc(store, 1, nullslice, t);
t.commit();
}
auto query = store->compileQuery(json5(
"{'WHAT': [['e()']]}"));
unique_ptr<QueryEnumerator> e(query->createEnumerator());
REQUIRE(e->getRowCount() == 1);
REQUIRE(e->next());
CHECK(e->columns()[0]->asDouble() == M_E);
query = store->compileQuery(json5(
"{'WHAT': [['pi()']]}"));
e.reset(query->createEnumerator());
REQUIRE(e->getRowCount() == 1);
REQUIRE(e->next());
CHECK(e->columns()[0]->asDouble() == M_PI);
vector<string> what {
"[['atan2()', ['.num'], ['*', ['.num'], 2]]]",
"[['acos()', ['.num']]]",
"[['asin()', ['.num']]]",
"[['atan()', ['.num']]]",
"[['cos()', ['.num']]]",
"[['degrees()', ['.num']]]",
"[['radians()', ['.num']]]",
"[['sin()', ['.num']]]",
"[['tan()', ['.num']]]"
};
vector<double> results {
atan2(2, 1),
acos(1),
asin(1),
atan(1),
cos(1),
180.0 / M_PI,
M_PI / 180.0,
sin(1),
tan(1),
};
for(int i = 0; i < what.size(); i++) {
query = store->compileQuery(json5(
"{'WHAT': " + what[i] + "}"));
e.reset(query->createEnumerator());
REQUIRE(e->getRowCount() == 1);
REQUIRE(e->next());
CHECK(e->columns()[0]->asDouble() == results[i]);
}
query = store->compileQuery(json5(
"{'WHAT': [['sign()', ['.num']]]}"));
e.reset(query->createEnumerator());
REQUIRE(e->getRowCount() == 1);
REQUIRE(e->next());
CHECK(e->columns()[0]->asInt() == 1);
}
TEST_CASE_METHOD(DataFileTestFixture, "Query unsigned", "[Query]") {
{
Transaction t(store->dataFile());
string docID = "rec-001";
fleece::Encoder enc;
enc.beginDictionary();
enc.writeKey("num");
enc.writeUInt(1);
enc.endDictionary();
alloc_slice body = enc.extractOutput();
store->set(slice(docID), nullslice, body, DocumentFlags::kNone, t);
t.commit();
}
auto query = store->compileQuery(json5(
"{'WHAT': ['.num']}"));
unique_ptr<QueryEnumerator> e(query->createEnumerator());
REQUIRE(e->getRowCount() == 1);
REQUIRE(e->next());
CHECK(e->columns()[0]->asUnsigned() == 1U);
CHECK(e->columns()[0]->asInt() == 1);
}
// Test for #341, "kData fleece type unable to be queried"
TEST_CASE_METHOD(DataFileTestFixture, "Query data type", "[Query]") {
{
Transaction t(store->dataFile());
string docID = "rec-001";
fleece::Encoder enc;
enc.beginDictionary();
enc.writeKey("num");
enc.writeData("number one"_sl);
enc.endDictionary();
alloc_slice body = enc.extractOutput();
store->set(slice(docID), nullslice, body, DocumentFlags::kNone, t);
t.commit();
}
auto query = store->compileQuery(json5(
"{'WHAT': ['.num']}"));
unique_ptr<QueryEnumerator> e(query->createEnumerator());
REQUIRE(e->getRowCount() == 1);
REQUIRE(e->next());
CHECK(e->columns()[0]->asData() == "number one"_sl);
query = store->compileQuery(json5(
"{'WHAT': [['type()', ['.num']]]}"));
e.reset(query->createEnumerator());
REQUIRE(e->getRowCount() == 1);
REQUIRE(e->next());
CHECK(e->columns()[0]->asString() == "binary"_sl);
}
TEST_CASE_METHOD(DataFileTestFixture, "Missing columns", "[Query]") {
{
Transaction t(store->dataFile());
string docID = "rec-001";
fleece::Encoder enc;
enc.beginDictionary();
enc.writeKey("num");
enc.writeInt(1234);
enc.writeKey("string");
enc.writeString("FOO");
enc.endDictionary();
alloc_slice body = enc.extractOutput();
store->set(slice(docID), nullslice, body, DocumentFlags::kNone, t);
t.commit();
}
auto query = store->compileQuery(json5(
"{'WHAT': ['.num', '.string']}"));
unique_ptr<QueryEnumerator> e(query->createEnumerator());
REQUIRE(e->next());
CHECK(e->missingColumns() == 0);
CHECK(e->columns()[0]->toJSONString() == "1234");
CHECK(e->columns()[1]->toJSONString() == "\"FOO\"");
query = store->compileQuery(json5(
"{'WHAT': ['.bogus', '.num', '.nope', '.string', '.gone']}"));
e.reset(query->createEnumerator());
REQUIRE(e->next());
CHECK(e->missingColumns() == 0x15); // binary 10101, i.e. cols 0, 2, 4 are missing
CHECK(e->columns()[1]->toJSONString() == "1234");
CHECK(e->columns()[3]->toJSONString() == "\"FOO\"");
}
TEST_CASE_METHOD(DataFileTestFixture, "Negative Limit / Offset", "[Query]") {
{
Transaction t(store->dataFile());
string docID = "rec-001";
fleece::Encoder enc;
enc.beginDictionary();
enc.writeKey("num");
enc.writeInt(1234);
enc.writeKey("string");
enc.writeString("FOO");
enc.endDictionary();
alloc_slice body = enc.extractOutput();
store->set(slice(docID), nullslice, body, DocumentFlags::kNone, t);
t.commit();
}
auto query = store->compileQuery(json5(
"{'WHAT': ['.num', '.string'], 'LIMIT': -1}"));
unique_ptr<QueryEnumerator> e(query->createEnumerator());
CHECK(e->getRowCount() == 0);
query = store->compileQuery(json5(
"{'WHAT': ['.num', '.string'], 'LIMIT': 100, 'OFFSET': -1}"));
e.reset(query->createEnumerator());
CHECK(e->getRowCount() == 1);
REQUIRE(e->next());
CHECK(e->columns()[0]->toJSONString() == "1234");
CHECK(e->columns()[1]->toJSONString() == "\"FOO\"");
Query::Options opts;
opts.paramBindings = R"({"lim": -1})"_sl;
query = store->compileQuery(json5(
"{'WHAT': ['.num', '.string'], 'LIMIT': ['$lim']}"));
e.reset(query->createEnumerator(&opts));
CHECK(e->getRowCount() == 0);
opts.paramBindings = R"({"lim": 100, "skip": -1})"_sl;
query = store->compileQuery(json5(
"{'WHAT': ['.num', '.string'], 'LIMIT': ['$lim'], 'OFFSET': ['$skip']}"));
e.reset(query->createEnumerator(&opts));
CHECK(e->getRowCount() == 1);
REQUIRE(e->next());
CHECK(e->columns()[0]->toJSONString() == "1234");
CHECK(e->columns()[1]->toJSONString() == "\"FOO\"");
}
TEST_CASE_METHOD(DataFileTestFixture, "Query JOINs", "[Query]") {
{
Transaction t(store->dataFile());
string docID = "rec-00";
for(int i = 0; i < 10; i++) {
stringstream ss(docID);
ss << i + 1;
fleece::Encoder enc;
enc.beginDictionary();
enc.writeKey("num1");
enc.writeInt(i);
enc.writeKey("num2");
enc.writeInt(10 - i);
enc.endDictionary();
alloc_slice body = enc.extractOutput();
store->set(slice(ss.str()), nullslice, body, DocumentFlags::kNone, t);
}
fleece::Encoder enc;
enc.beginDictionary();
enc.writeKey("theone");
enc.writeInt(4);
enc.endDictionary();
alloc_slice body = enc.extractOutput();
store->set("magic"_sl, nullslice, body, DocumentFlags::kNone, t);
t.commit();
}
auto query = store->compileQuery(json5(
"{'WHAT': [['.main.num1']], 'FROM': [{'AS':'main'}, {'AS':'secondary', 'ON': ['=', ['.main.num1'], ['.secondary.theone']]}]}"));
unique_ptr<QueryEnumerator> e(query->createEnumerator());
REQUIRE(e->getRowCount() == 1);
REQUIRE(e->next());
CHECK(e->columns()[0]->asInt() == 4);
query = store->compileQuery(json5(
"{'WHAT': [['.main.num1'], ['.secondary.theone']], 'FROM': [{'AS':'main'}, {'AS':'secondary', 'ON': ['=', ['.main.num1'], ['.secondary.theone']], 'JOIN':'LEFT OUTER'}]}"));
e.reset(query->createEnumerator());
REQUIRE(e->getRowCount() == 11);
e->seek(4);
CHECK(e->columns()[0]->asInt() == 4);
CHECK(e->columns()[1]->asInt() == 4);
REQUIRE(e->next());
CHECK(e->columns()[0]->asInt() == 5);
CHECK(e->columns()[1]->asInt() == 0);
// NEED TO DEFINE THIS BEHAVIOR. WHAT IS THE CORRECT RESULT? THE BELOW FAILS!
/*query = store->compileQuery(json5(
"{'WHAT': [['.main.num1'], ['.secondary.num2']], 'FROM': [{'AS':'main'}, {'AS':'secondary', 'JOIN':'CROSS'}], 'ORDER_BY': ['.secondary.num2']}"));
e.reset(query->createEnumerator());
REQUIRE(e->getRowCount() == 100);
for(int i = 0; i < 100; i++) {
REQUIRE(e->next());
CHECK(e->columns()[0]->asInt() == (i % 10));
CHECK(e->columns()[1]->asInt() == (i / 10));
}*/
}
TEST_CASE_METHOD(DataFileTestFixture, "Query NULL check", "[Query]")
{
{
Transaction t(store->dataFile());
string docID = "rec-00";
for(int i = 0; i < 3; i++) {
stringstream ss(docID);
ss << i + 1;
fleece::Encoder enc;
enc.beginDictionary();
if(i > 0) {
enc.writeKey("callsign");
if(i == 1) {
enc.writeNull();
} else {
enc.writeString("ANA");
}
}
enc.endDictionary();
alloc_slice body = enc.extractOutput();
store->set(slice(ss.str()), nullslice, body, DocumentFlags::kNone, t);
}
t.commit();
}
auto query = store->compileQuery(json5(
"{'WHAT': [['COUNT()','.'], ['.callsign']], 'WHERE':['IS NOT', ['.callsign'], null]}"));
unique_ptr<QueryEnumerator> e(query->createEnumerator());
REQUIRE(e->getRowCount() == 1);
REQUIRE(e->next());
CHECK(e->columns()[0]->asInt() == 1);
CHECK(e->columns()[1]->asString() == "ANA"_sl);
query = store->compileQuery(json5(
"{'WHAT': [['COUNT()','.'], ['.callsign']], 'WHERE':['IS', ['.callsign'], null]}"));
e.reset(query->createEnumerator());
REQUIRE(e->getRowCount() == 1);
REQUIRE(e->next());
CHECK(e->columns()[0]->asInt() == 1);
CHECK(e->columns()[1]->asString().buf == nullptr);
query = store->compileQuery(json5(
"{'WHAT': [['.callsign']]}"));
e.reset(query->createEnumerator());
CHECK(e->getRowCount() == 3); // Make sure there are actually three docs!
}
// NOTE: This test cannot be reproduced in this way on Windows, and it is likely a Unix specific
// problem. Leaving an enumerator open in this way will cause a permission denied error when
// trying to delete the database via db->deleteDataFile()
#ifndef _MSC_VER
TEST_CASE_METHOD(DataFileTestFixture, "Query finalized after db deleted", "[Query]") {
Retained<Query> query{ store->compileQuery(json5(
"{WHAT: ['.num', ['*', ['.num'], ['.num']]], WHERE: ['>', ['.num'], 10]}")) };
unique_ptr<QueryEnumerator> e(query->createEnumerator());
e->next();
query = nullptr;
db->deleteDataFile();
db = nullptr;
// Now free the query enum, which will free the sqlite_stmt, triggering a SQLite warning
// callback about the database file being unlinked:
e.reset();
// Assert that the callback did not log a warning:
CHECK(warningsLogged() == 0);
}
#endif
| 33.773519 | 180 | 0.556639 | [
"object",
"vector"
] |
7aefde5911d857a9601661365482a83a812cff18 | 3,468 | cpp | C++ | test-project/program.cpp | wtrsltnk/cpppm | 6d375dae3e65631d6e463f61a9635a302f57d680 | [
"MIT"
] | 1 | 2020-03-09T19:07:25.000Z | 2020-03-09T19:07:25.000Z | test-project/program.cpp | wtrsltnk/cpppm | 6d375dae3e65631d6e463f61a9635a302f57d680 | [
"MIT"
] | null | null | null | test-project/program.cpp | wtrsltnk/cpppm | 6d375dae3e65631d6e463f61a9635a302f57d680 | [
"MIT"
] | null | null | null | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#define SDL_MAIN_HANDLED
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#include <GL/glu.h>
#include <bullet/BulletDynamics/btBulletDynamicsCommon.h>
void Display_InitGL()
{
/* Enable smooth shading */
glShadeModel( GL_SMOOTH );
/* Set the background black */
glClearColor( 0.0f, 0.0f, 0.0f, 0.0f );
/* Depth buffer setup */
glClearDepth( 1.0f );
/* Enables Depth Testing */
glEnable( GL_DEPTH_TEST );
/* The Type Of Depth Test To Do */
glDepthFunc( GL_LEQUAL );
/* Really Nice Perspective Calculations */
glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
}
/* function to reset our viewport after a window resize */
int Display_SetViewport( int width, int height )
{
/* Height / width ration */
GLfloat ratio;
/* Protect against a divide by zero */
if ( height == 0 ) {
height = 1;
}
ratio = ( GLfloat )width / ( GLfloat )height;
/* Setup our viewport. */
glViewport( 0, 0, ( GLsizei )width, ( GLsizei )height );
/* change to the projection matrix and set our viewing volume. */
glMatrixMode( GL_PROJECTION );
glLoadIdentity( );
/* Set our perspective */
gluPerspective( 45.0f, ratio, 0.1f, 100.0f );
/* Make sure we're chaning the model view and not the projection */
glMatrixMode( GL_MODELVIEW );
/* Reset The View */
glLoadIdentity( );
return 1;
}
SDL_Renderer* displayRenderer;
void Display_Render()
{
/* Set the background black */
glClearColor( 0.0f, 0.0f, 0.0f, 0.0f );
/* Clear The Screen And The Depth Buffer */
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
/* Move Left 1.5 Units And Into The Screen 6.0 */
glLoadIdentity();
glTranslatef( -1.5f, 0.0f, -6.0f );
glBegin( GL_TRIANGLES ); /* Drawing Using Triangles */
glVertex3f( 0.0f, 1.0f, 0.0f ); /* Top */
glVertex3f( -1.0f, -1.0f, 0.0f ); /* Bottom Left */
glVertex3f( 1.0f, -1.0f, 0.0f ); /* Bottom Right */
glEnd( ); /* Finished Drawing The Triangle */
/* Move Right 3 Units */
glTranslatef( 3.0f, 0.0f, 0.0f );
glBegin( GL_QUADS ); /* Draw A Quad */
glVertex3f( -1.0f, 1.0f, 0.0f ); /* Top Left */
glVertex3f( 1.0f, 1.0f, 0.0f ); /* Top Right */
glVertex3f( 1.0f, -1.0f, 0.0f ); /* Bottom Right */
glVertex3f( -1.0f, -1.0f, 0.0f ); /* Bottom Left */
glEnd( ); /* Done Drawing The Quad */
SDL_RenderPresent(displayRenderer);
}
int
main(int argc, char *argv[])
{
btVector3 v;
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* displayWindow;
SDL_RendererInfo displayRendererInfo;
SDL_CreateWindowAndRenderer(800, 600, SDL_WINDOW_OPENGL, &displayWindow, &displayRenderer);
SDL_GetRendererInfo(displayRenderer, &displayRendererInfo);
/*TODO: Check that we have OpenGL */
if ((displayRendererInfo.flags & SDL_RENDERER_ACCELERATED) == 0 ||
(displayRendererInfo.flags & SDL_RENDERER_TARGETTEXTURE) == 0) {
/*TODO: Handle this. We have no render surface and not accelerated. */
}
Display_InitGL();
Display_SetViewport(800, 600);
Display_Render();
SDL_Delay(5000);
SDL_Quit();
return 0;
}
| 27.744 | 96 | 0.595732 | [
"render",
"model"
] |
7afaf3c6e0ee5d53c49e4291b0794bde1f2c8899 | 23,550 | cpp | C++ | converter/Analyzer/Default/ImageAnalyzer.cpp | azhirnov/vkTraceConverter | a7049d0005989b434c2a74598eb9a9fc76f4351c | [
"BSD-2-Clause"
] | 6 | 2019-01-24T12:13:13.000Z | 2020-06-01T13:59:04.000Z | converter/Analyzer/Default/ImageAnalyzer.cpp | azhirnov/vkTraceConverter | a7049d0005989b434c2a74598eb9a9fc76f4351c | [
"BSD-2-Clause"
] | null | null | null | converter/Analyzer/Default/ImageAnalyzer.cpp | azhirnov/vkTraceConverter | a7049d0005989b434c2a74598eb9a9fc76f4351c | [
"BSD-2-Clause"
] | null | null | null | // Copyright (c) 2018-2019, Zhirnov Andrey. For more information see 'LICENSE'
#include "Analyzer/Default/ImageAnalyzer.h"
#include "Analyzer/Default/MemoryObjAnalyzer.h"
#include "Analyzer/Default/RenderPassAnalyzer.h"
#include "Parser/AppTrace.h"
namespace VTC
{
/*
=================================================
constructor
=================================================
*/
ImageAnalyzer::ImageAnalyzer ()
{
}
/*
=================================================
PreProcess
=================================================
*/
void ImageAnalyzer::PreProcess (const AppTrace &appTrace)
{
_memoryObjAnalyzer = appTrace.GetAnalyzer< MemoryObjAnalyzer >();
_renderPassAnalyzer = appTrace.GetAnalyzer< RenderPassAnalyzer >();
CHECK( _memoryObjAnalyzer and _renderPassAnalyzer );
// TODO: add link to command buffer analyzer, render pass analyzer, ...
}
/*
=================================================
Process
=================================================
*/
void ImageAnalyzer::Process (const TraceRange::Iterator &pos)
{
switch( pos->packet_id )
{
// CmdWaitEvents
case VKTRACE_TPI_VK_vkCmdWaitEvents : {
auto& packet = pos.Cast<packet_vkCmdWaitEvents>();
CHECK( _ProcessImageMemoryBarriers( pos.GetBookmark(), packet.srcStageMask, packet.dstStageMask,
{ packet.pImageMemoryBarriers, packet.imageMemoryBarrierCount } ));
break;
}
// CmdPipelineBarrier
case VKTRACE_TPI_VK_vkCmdPipelineBarrier : {
packet_vkCmdPipelineBarrier const& packet = pos.Cast<packet_vkCmdPipelineBarrier>();
CHECK( _ProcessImageMemoryBarriers( pos.GetBookmark(), packet.srcStageMask, packet.dstStageMask,
{ packet.pImageMemoryBarriers, packet.imageMemoryBarrierCount } ));
break;
}
}
}
/*
=================================================
AddResourceUsage
=================================================
*/
void ImageAnalyzer::AddResourceUsage (const TraceRange::Iterator &pos, EResourceType type, ResourceID id, FrameID, EResOp op)
{
switch ( type )
{
case VK_OBJECT_TYPE_IMAGE : CHECK( _ProcessImageUsage( pos, id, op )); break;
case VK_OBJECT_TYPE_IMAGE_VIEW : CHECK( _ProcessImageViewUsage( pos, id, op )); break;
case VK_OBJECT_TYPE_RENDER_PASS : CHECK( _ProcessRenderPass( pos, id )); break;
}
}
/*
=================================================
_ProcessImageUsage
=================================================
*/
bool ImageAnalyzer::_ProcessImageUsage (const TraceRange::Iterator &pos, ResourceID id, EResOp op)
{
if ( pos->packet_id == VKTRACE_TPI_VK_vkCreateImage )
return _OnCreateImage( pos, id );
if ( pos->packet_id == VKTRACE_TPI_VK_vkGetSwapchainImagesKHR )
return _OnGetSwapchainImages( pos, id );
ImagesMap_t::iterator image;
CHECK( _images.AddResourceUsage( OUT image, pos, id, op ));
auto& info = image->second.back();
switch ( pos->packet_id )
{
case VKTRACE_TPI_VK_vkCmdClearColorImage : CHECK( _OnClearColorImage( pos, info )); break;
case VKTRACE_TPI_VK_vkCmdClearDepthStencilImage : CHECK( _OnClearDepthStencilImage( pos, info )); break;
case VKTRACE_TPI_VK_vkCmdCopyImageToBuffer : CHECK( _OnCopyImageToBuffer( pos, info )); break;
case VKTRACE_TPI_VK_vkCmdCopyBufferToImage : CHECK( _OnCopyBufferToImage( pos, info )); break;
case VKTRACE_TPI_VK_vkCmdCopyImage : CHECK( _OnCopyImage( pos, info )); break;
case VKTRACE_TPI_VK_vkCmdResolveImage : CHECK( _OnResolveImage( pos, info )); break;
case VKTRACE_TPI_VK_vkCmdBlitImage : CHECK( _OnBlitImage( pos, info )); break;
case VKTRACE_TPI_VK_vkGetImageSubresourceLayout : CHECK( _OnGetImageSubresourceLayout( pos, info )); break;
case VKTRACE_TPI_VK_vkGetImageMemoryRequirements : CHECK( _OnGetImageMemoryRequirements( pos, info )); break;
case VKTRACE_TPI_VK_vkGetImageMemoryRequirements2 :
case VKTRACE_TPI_VK_vkGetImageMemoryRequirements2KHR : CHECK( _OnGetImageMemoryRequirements2( pos, info )); break;
case VKTRACE_TPI_VK_vkGetImageSparseMemoryRequirements : break;
case VKTRACE_TPI_VK_vkGetImageSparseMemoryRequirements2 : break;
case VKTRACE_TPI_VK_vkGetImageSparseMemoryRequirements2KHR : break; // TODO
case VKTRACE_TPI_VK_vkBindImageMemory : CHECK( _OnBindImageMemory( pos, info )); break;
case VKTRACE_TPI_VK_vkBindImageMemory2 :
case VKTRACE_TPI_VK_vkBindImageMemory2KHR : CHECK( _OnBindImageMemory2( pos, info )); break;
case VKTRACE_TPI_VK_vkDestroyImage :
case VKTRACE_TPI_VK_vkAllocateMemory :
case VKTRACE_TPI_VK_vkAcquireNextImageKHR :
case VKTRACE_TPI_VK_vkAcquireNextImage2KHX :
case VKTRACE_TPI_VK_vkAcquireNextImage2KHR :
case VKTRACE_TPI_VK_vkQueuePresentKHR :
case VKTRACE_TPI_VK_vkCmdWaitEvents :
case VKTRACE_TPI_VK_vkCmdPipelineBarrier :
case VKTRACE_TPI_VK_vkCreateImageView :
case VKTRACE_TPI_VK_vkDestroySwapchainKHR :
break;
default :
ASSERT(false); // unknown usage
break;
}
return true;
}
/*
=================================================
_OnCreateImage
=================================================
*/
bool ImageAnalyzer::_OnCreateImage (const TraceRange::Iterator &pos, ResourceID id)
{
auto& packet = pos.Cast<packet_vkCreateImage>();
CHECK_ERR( packet.pCreateInfo );
CHECK_ERR( id == ResourceID(*packet.pImage) );
//ASSERT( packet.pCreateInfo->pNext == null ); // add support if assert triggered
ImagesMap_t::iterator image;
CHECK_ERR( _images.AddResourceUsage( OUT image, pos, ResourceID(*packet.pImage), EResOp::Construct ));
auto& info = image->second.back();
info.id = ResourceID(*packet.pImage);
info.createInfo = *packet.pCreateInfo;
info.deviceId = ResourceID(packet.device);
info.swapchain = ResourceID(0);
return true;
}
/*
=================================================
_OnGetSwapchainImages
=================================================
*/
bool ImageAnalyzer::_OnGetSwapchainImages (const TraceRange::Iterator &pos, ResourceID id)
{
auto& packet = pos.Cast< packet_vkGetSwapchainImagesKHR >();
ImagesMap_t::iterator image;
CHECK_ERR( _images.AddResourceUsage( OUT image, pos, id, EResOp::Construct ));
auto& info = image->second.back();
info.id = id;
info.createInfo = {};
info.deviceId = ResourceID(packet.device);
info.swapchain = ResourceID(packet.swapchain);
return true;
}
/*
=================================================
_OnClearColorImage
=================================================
*/
bool ImageAnalyzer::_OnClearColorImage (const TraceRange::Iterator &pos, ImageInfo_t &image)
{
auto& packet = pos.Cast<packet_vkCmdClearColorImage>();
CHECK_ERR( image.id == ResourceID(packet.image) );
_AddImageUsage( image, VK_IMAGE_USAGE_TRANSFER_DST_BIT, packet.imageLayout );
return true;
}
/*
=================================================
_OnClearDepthStencilImage
=================================================
*/
bool ImageAnalyzer::_OnClearDepthStencilImage (const TraceRange::Iterator &pos, ImageInfo_t &image)
{
auto& packet = pos.Cast<packet_vkCmdClearDepthStencilImage>();
CHECK_ERR( image.id == ResourceID(packet.image) );
_AddImageUsage( image, VK_IMAGE_USAGE_TRANSFER_DST_BIT, packet.imageLayout );
return true;
}
/*
=================================================
_OnCopyImageToBuffer
=================================================
*/
bool ImageAnalyzer::_OnCopyImageToBuffer (const TraceRange::Iterator &pos, ImageInfo_t &image)
{
auto& packet = pos.Cast<packet_vkCmdCopyImageToBuffer>();
CHECK_ERR( image.id == ResourceID(packet.srcImage) );
_AddImageUsage( image, VK_IMAGE_USAGE_TRANSFER_SRC_BIT, packet.srcImageLayout );
return true;
}
/*
=================================================
_OnCopyBufferToImage
=================================================
*/
bool ImageAnalyzer::_OnCopyBufferToImage (const TraceRange::Iterator &pos, ImageInfo_t &image)
{
auto& packet = pos.Cast<packet_vkCmdCopyBufferToImage>();
CHECK_ERR( image.id == ResourceID(packet.dstImage) );
_AddImageUsage( image, VK_IMAGE_USAGE_TRANSFER_DST_BIT, packet.dstImageLayout );
return true;
}
/*
=================================================
_OnCopyImage
=================================================
*/
bool ImageAnalyzer::_OnCopyImage (const TraceRange::Iterator &pos, ImageInfo_t &image)
{
auto& packet = pos.Cast<packet_vkCmdCopyImage>();
CHECK_ERR( image.id == ResourceID(packet.srcImage) or
image.id == ResourceID(packet.dstImage) );
if ( image.id == ResourceID(packet.srcImage) ) {
_AddImageUsage( image, VK_IMAGE_USAGE_TRANSFER_SRC_BIT, packet.srcImageLayout );
}
if ( image.id == ResourceID(packet.dstImage) ) {
_AddImageUsage( image, VK_IMAGE_USAGE_TRANSFER_DST_BIT, packet.dstImageLayout );
}
_AddImageAccess( image, pos.GetBookmark() );
return true;
}
/*
=================================================
_OnResolveImage
=================================================
*/
bool ImageAnalyzer::_OnResolveImage (const TraceRange::Iterator &pos, ImageInfo_t &image)
{
auto& packet = pos.Cast<packet_vkCmdResolveImage>();
CHECK_ERR( image.id == ResourceID(packet.srcImage) or
image.id == ResourceID(packet.dstImage) );
if ( image.id == ResourceID(packet.srcImage) ) {
_AddImageUsage( image, VK_IMAGE_USAGE_TRANSFER_SRC_BIT, packet.srcImageLayout );
}
if ( image.id == ResourceID(packet.dstImage) ) {
_AddImageUsage( image, VK_IMAGE_USAGE_TRANSFER_DST_BIT, packet.dstImageLayout );
}
_AddImageAccess( image, pos.GetBookmark() );
return true;
}
/*
=================================================
_OnBlitImage
=================================================
*/
bool ImageAnalyzer::_OnBlitImage (const TraceRange::Iterator &pos, ImageInfo_t &image)
{
auto& packet = pos.Cast<packet_vkCmdBlitImage >();
CHECK_ERR( image.id == ResourceID(packet.srcImage) or
image.id == ResourceID(packet.dstImage) );
if ( image.id == ResourceID(packet.srcImage) ) {
_AddImageUsage( image, VK_IMAGE_USAGE_TRANSFER_SRC_BIT, packet.srcImageLayout );
}
if ( image.id == ResourceID(packet.dstImage) ) {
_AddImageUsage( image, VK_IMAGE_USAGE_TRANSFER_DST_BIT, packet.dstImageLayout );
}
_AddImageAccess( image, pos.GetBookmark() );
return true;
}
/*
=================================================
_OnGetImageSubresourceLayout
=================================================
*/
bool ImageAnalyzer::_OnGetImageSubresourceLayout (const TraceRange::Iterator &pos, ImageInfo_t &image)
{
auto& packet = pos.Cast< packet_vkGetImageSubresourceLayout >();
CHECK_ERR( image.id == ResourceID(packet.image) );
image.subresLayouts.insert({ ImageSubresource{*packet.pSubresource}, *packet.pLayout });
return true;
}
/*
=================================================
_OnGetImageMemoryRequirements
=================================================
*/
bool ImageAnalyzer::_OnGetImageMemoryRequirements (const TraceRange::Iterator &pos, ImageInfo_t &image)
{
auto& packet = pos.Cast< packet_vkGetImageMemoryRequirements >();
CHECK_ERR( image.id == ResourceID(packet.image) );
image.memRequirements = *packet.pMemoryRequirements;
return true;
}
/*
=================================================
_OnGetImageMemoryRequirements2
=================================================
*/
bool ImageAnalyzer::_OnGetImageMemoryRequirements2 (const TraceRange::Iterator &pos, ImageInfo_t &image)
{
STATIC_ASSERT( sizeof(packet_vkGetImageMemoryRequirements2) == sizeof(packet_vkGetImageMemoryRequirements2KHR) );
auto& packet = pos.Cast< packet_vkGetImageMemoryRequirements2 >();
CHECK_ERR( image.id == ResourceID(packet.pInfo->image) );
ASSERT( packet.pInfo->pNext == null ); // add support if triggered
//ASSERT( packet.pMemoryRequirements->pNext == null ); // add support if triggered
image.memRequirements = packet.pMemoryRequirements->memoryRequirements;
return true;
}
/*
=================================================
_OnBindImageMemory
=================================================
*/
bool ImageAnalyzer::_OnBindImageMemory (const TraceRange::Iterator &pos, ImageInfo_t &image)
{
auto& packet = pos.Cast< packet_vkBindImageMemory >();
CHECK_ERR( image.id == ResourceID(packet.image) );
image.memId = ResourceID(packet.memory);
image.memOffset = packet.memoryOffset;
return true;
}
/*
=================================================
_OnBindImageMemory2
=================================================
*/
bool ImageAnalyzer::_OnBindImageMemory2 (const TraceRange::Iterator &pos, ImageInfo_t &image)
{
STATIC_ASSERT( sizeof(packet_vkBindImageMemory2) == sizeof(packet_vkBindImageMemory2KHR) );
auto& packet = pos.Cast< packet_vkBindImageMemory2 >();
for (uint i = 0; i < packet.bindInfoCount; ++i)
{
if ( image.id == ResourceID(packet.pBindInfos[i].image) )
{
ASSERT( packet.pBindInfos[i].pNext == null ); // add support if triggered
image.memId = ResourceID(packet.pBindInfos[i].memory);
image.memOffset = packet.pBindInfos[i].memoryOffset;
break;
}
}
return true;
}
/*
=================================================
_ProcessImageViewUsage
=================================================
*/
bool ImageAnalyzer::_ProcessImageViewUsage (const TraceRange::Iterator &pos, ResourceID id, EResOp op)
{
if ( pos->packet_id == VKTRACE_TPI_VK_vkCreateImageView )
return _OnCreateImageView( pos, id );
if ( pos->packet_id == VKTRACE_TPI_VK_vkDestroyFramebuffer )
return true; // TODO: image view may be already destroyed
ImageViewsMap_t::iterator view;
CHECK_ERR( _imageViews.AddResourceUsage( OUT view, pos, id, op ));
auto& info = view->second.back();
switch ( pos->packet_id )
{
case VKTRACE_TPI_VK_vkDestroyImageView :
case VKTRACE_TPI_VK_vkCreateFramebuffer :
case VKTRACE_TPI_VK_vkDestroyFramebuffer :
break;
case VKTRACE_TPI_VK_vkUpdateDescriptorSets :
case VKTRACE_TPI_VK_vkCmdBeginRenderPass :
case VKTRACE_TPI_VK_vkCmdNextSubpass :
case VKTRACE_TPI_VK_vkCmdEndRenderPass :
_AddImageAccess( *info.image, pos.GetBookmark() );
break;
// render target usage
case VKTRACE_TPI_VK_vkCmdDraw :
case VKTRACE_TPI_VK_vkCmdDrawIndirect :
case VKTRACE_TPI_VK_vkCmdDrawIndirectCountAMD :
case VKTRACE_TPI_VK_vkCmdDrawIndexed :
case VKTRACE_TPI_VK_vkCmdDrawIndexedIndirect :
case VKTRACE_TPI_VK_vkCmdDrawIndexedIndirectCountAMD :
_AddImageAccess( *info.image, pos.GetBookmark() );
break;
default :
ASSERT(false); // unknown usage
break;
}
return true;
}
/*
=================================================
_OnCreateImageView
=================================================
*/
bool ImageAnalyzer::_OnCreateImageView (const TraceRange::Iterator &pos, ResourceID id)
{
auto& packet = pos.Cast<packet_vkCreateImageView>();
CHECK_ERR( packet.pCreateInfo );
CHECK_ERR( id == ResourceID(*packet.pView) );
ASSERT( packet.pCreateInfo->pNext == null ); // add support if assert triggered
auto* image = _images.FindIn( ResourceID(packet.pCreateInfo->image), pos );
CHECK_ERR( image );
ImageViewsMap_t::iterator view;
CHECK_ERR( _imageViews.AddResourceUsage( OUT view, pos, id, EResOp::Construct ));
auto& info = view->second.back();
info.id = id;
info.createInfo = *packet.pCreateInfo;
info.image = image;
image->imageViews.insert({ id, pos.GetBookmark() });
_AddImageAccess( *image, pos.GetBookmark() );
return true;
}
/*
=================================================
_ProcessRenderPass
=================================================
*/
bool ImageAnalyzer::_ProcessRenderPass (const TraceRange::Iterator &pos, ResourceID)
{
switch ( pos->packet_id )
{
case VKTRACE_TPI_VK_vkCmdBeginRenderPass : CHECK( _OnBeginRenderPass( pos )); break;
}
return true;
}
/*
=================================================
_OnBeginRenderPass
=================================================
*/
bool ImageAnalyzer::_OnBeginRenderPass (const TraceRange::Iterator &pos)
{
auto& packet = pos.Cast< packet_vkCmdBeginRenderPass >();
auto* fb_info = _renderPassAnalyzer->GetFramebuffer( ResourceID(packet.pRenderPassBegin->framebuffer), pos.GetBookmark() );
auto* rp_info = _renderPassAnalyzer->GetRenderPass( ResourceID(packet.pRenderPassBegin->renderPass), pos.GetBookmark() );
CHECK_ERR( fb_info and rp_info );
Array<ImageInfo_t *> images;
for (auto& view : fb_info->imageViews)
{
auto* view_info = _imageViews.FindIn( view, pos.GetBookmark() );
CHECK_ERR( view_info );
images.push_back( view_info->image );
}
// add usage from initial and final state
for (size_t i = 0; i < rp_info->attachments.size(); ++i)
{
_AddImageUsage( *images[i], 0, 0, rp_info->attachments[i].initialLayout );
_AddImageUsage( *images[i], 0, 0, rp_info->attachments[i].finalLayout );
}
// add usage from subpasses
for (auto& subpass : rp_info->subpasses)
{
for (auto& col : subpass.colorAttachments) {
if ( col.attachment < images.size() )
_AddImageUsage( *images[col.attachment], 0, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, col.layout );
}
if ( subpass.depthStencilAttachment.has_value() and subpass.depthStencilAttachment->attachment < images.size() )
_AddImageUsage( *images[subpass.depthStencilAttachment->attachment], 0, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT, subpass.depthStencilAttachment->layout );
for (auto& res : subpass.resolveAttachments) {
if ( res.attachment < images.size() )
_AddImageUsage( *images[res.attachment], 0, VK_ACCESS_TRANSFER_READ_BIT, res.layout );
}
for (auto& in : subpass.inputAttachments) {
if ( in.attachment < images.size() )
_AddImageUsage( *images[in.attachment], 0, VK_ACCESS_INPUT_ATTACHMENT_READ_BIT, in.layout );
}
}
return true;
}
/*
=================================================
_ProcessImageMemoryBarriers
=================================================
*/
bool ImageAnalyzer::_ProcessImageMemoryBarriers (TraceRange::Bookmark pos, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
ArrayView<VkImageMemoryBarrier> barriers)
{
for (auto& bar : barriers)
{
auto* image = _images.FindIn( ResourceID(bar.image), pos );
CHECK_ERR( image );
CHECK_ERR( _AddImageUsage( *image, srcStageMask, bar.srcAccessMask, bar.oldLayout ));
CHECK_ERR( _AddImageUsage( *image, dstStageMask, bar.dstAccessMask, bar.newLayout ));
}
return true;
}
/*
=================================================
ConvertToImageUsage
=================================================
*/
ND_ static VkImageUsageFlags ConvertToImageUsage (VkPipelineStageFlags, VkAccessFlags access, VkImageLayout layout)
{
ENABLE_ENUM_CHECKS();
switch ( layout )
{
case VK_IMAGE_LAYOUT_UNDEFINED : break;
case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL : return VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
case VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL :
case VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL :
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL :
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL : return VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : return VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL : return VK_IMAGE_USAGE_TRANSFER_DST_BIT;
case VK_IMAGE_LAYOUT_PREINITIALIZED : break;
case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR : break;
case VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR : break;
case VK_IMAGE_LAYOUT_SHADING_RATE_OPTIMAL_NV : return VK_IMAGE_USAGE_SHADING_RATE_IMAGE_BIT_NV;
case VK_IMAGE_LAYOUT_RANGE_SIZE : break;
case VK_IMAGE_LAYOUT_MAX_ENUM : break;
case VK_IMAGE_LAYOUT_FRAGMENT_DENSITY_MAP_OPTIMAL_EXT : return VK_IMAGE_USAGE_FRAGMENT_DENSITY_MAP_BIT_EXT;
case VK_IMAGE_LAYOUT_GENERAL :
{
for (VkAccessFlags j = 1; j < VK_ACCESS_FLAG_BITS_MAX_ENUM; j <<= 1)
{
if ( not EnumEq( access, j ) )
continue;
switch ( VkAccessFlagBits(j) )
{
case VK_ACCESS_INDIRECT_COMMAND_READ_BIT : break;
case VK_ACCESS_INDEX_READ_BIT : break;
case VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT : break;
case VK_ACCESS_UNIFORM_READ_BIT : break;
case VK_ACCESS_INPUT_ATTACHMENT_READ_BIT : return VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
case VK_ACCESS_SHADER_READ_BIT :
case VK_ACCESS_SHADER_WRITE_BIT : return VK_IMAGE_USAGE_STORAGE_BIT;
case VK_ACCESS_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT :
case VK_ACCESS_COLOR_ATTACHMENT_READ_BIT :
case VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT : return VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
case VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT :
case VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT : return VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
case VK_ACCESS_TRANSFER_READ_BIT : return VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
case VK_ACCESS_TRANSFER_WRITE_BIT : return VK_IMAGE_USAGE_TRANSFER_DST_BIT;
case VK_ACCESS_HOST_READ_BIT : break;
case VK_ACCESS_HOST_WRITE_BIT : break;
case VK_ACCESS_MEMORY_READ_BIT : break;
case VK_ACCESS_MEMORY_WRITE_BIT : break;
case VK_ACCESS_CONDITIONAL_RENDERING_READ_BIT_EXT : break;
case VK_ACCESS_COMMAND_PROCESS_READ_BIT_NVX : break;
case VK_ACCESS_COMMAND_PROCESS_WRITE_BIT_NVX : break;
case VK_ACCESS_TRANSFORM_FEEDBACK_WRITE_BIT_EXT : break;
case VK_ACCESS_TRANSFORM_FEEDBACK_COUNTER_READ_BIT_EXT: break;
case VK_ACCESS_TRANSFORM_FEEDBACK_COUNTER_WRITE_BIT_EXT:break;
case VK_ACCESS_SHADING_RATE_IMAGE_READ_BIT_NV : return VK_IMAGE_USAGE_SHADING_RATE_IMAGE_BIT_NV;
case VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_NV : break;
case VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_NV : break;
case VK_ACCESS_FRAGMENT_DENSITY_MAP_READ_BIT_EXT : return VK_IMAGE_USAGE_FRAGMENT_DENSITY_MAP_BIT_EXT;
case VK_ACCESS_FLAG_BITS_MAX_ENUM : break;
}
}
break;
}
case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL :
{
if ( access == VK_ACCESS_INPUT_ATTACHMENT_READ_BIT )
return VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
else
return VK_IMAGE_USAGE_SAMPLED_BIT;
}
}
DISABLE_ENUM_CHECKS();
return 0;
}
/*
=================================================
_AddImageUsage
=================================================
*/
bool ImageAnalyzer::_AddImageUsage (ImageInfo_t &image, VkPipelineStageFlags stage, VkAccessFlags access, VkImageLayout layout)
{
image.allAccessFlags |= access;
image.allStageFlags |= stage;
image.usage |= ConvertToImageUsage( stage, access, layout );
image.layouts.insert( layout );
return true;
}
bool ImageAnalyzer::_AddImageUsage (ImageInfo_t &image, VkImageUsageFlags usage, VkImageLayout layout)
{
image.usage |= usage;
image.layouts.insert( layout );
return true;
}
/*
=================================================
_AddImageAccess
=================================================
*/
void ImageAnalyzer::_AddImageAccess (ImageInfo_t &image, TraceRange::Bookmark pos)
{
if ( image.firstAccess == TraceRange::Bookmark() )
image.firstAccess = image.lastAccess = pos;
else
image.lastAccess = std::max( image.lastAccess, pos );
}
} // VTC
| 34.837278 | 162 | 0.658004 | [
"render"
] |
7afc7feee401a2cf0694ed11a15642b3fbd340a6 | 334,640 | cc | C++ | fbench/src/grpcclient/third_party/googleapis/gens/google/datastore/v1/datastore.pb.cc | kashiish/vespa | 307de4bb24463d0f36cd8391a7b8df75bd0949b2 | [
"Apache-2.0"
] | null | null | null | fbench/src/grpcclient/third_party/googleapis/gens/google/datastore/v1/datastore.pb.cc | kashiish/vespa | 307de4bb24463d0f36cd8391a7b8df75bd0949b2 | [
"Apache-2.0"
] | null | null | null | fbench/src/grpcclient/third_party/googleapis/gens/google/datastore/v1/datastore.pb.cc | kashiish/vespa | 307de4bb24463d0f36cd8391a7b8df75bd0949b2 | [
"Apache-2.0"
] | null | null | null | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/datastore/v1/datastore.proto
#include "google/datastore/v1/datastore.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite_inl.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_google_2fdatastore_2fv1_2fdatastore_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_ReadOptions_google_2fdatastore_2fv1_2fdatastore_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_google_2fdatastore_2fv1_2fdatastore_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_TransactionOptions_ReadOnly_google_2fdatastore_2fv1_2fdatastore_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_google_2fdatastore_2fv1_2fdatastore_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_TransactionOptions_ReadWrite_google_2fdatastore_2fv1_2fdatastore_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_google_2fdatastore_2fv1_2fdatastore_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_MutationResult_google_2fdatastore_2fv1_2fdatastore_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_google_2fdatastore_2fv1_2fdatastore_2eproto ::google::protobuf::internal::SCCInfo<2> scc_info_Mutation_google_2fdatastore_2fv1_2fdatastore_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_google_2fdatastore_2fv1_2fdatastore_2eproto ::google::protobuf::internal::SCCInfo<2> scc_info_TransactionOptions_google_2fdatastore_2fv1_2fdatastore_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_google_2fdatastore_2fv1_2fentity_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_PartitionId_google_2fdatastore_2fv1_2fentity_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_google_2fdatastore_2fv1_2fentity_2eproto ::google::protobuf::internal::SCCInfo<2> scc_info_Key_google_2fdatastore_2fv1_2fentity_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_google_2fdatastore_2fv1_2fentity_2eproto ::google::protobuf::internal::SCCInfo<3> scc_info_ArrayValue_google_2fdatastore_2fv1_2fentity_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_google_2fdatastore_2fv1_2fquery_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_EntityResult_google_2fdatastore_2fv1_2fquery_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_google_2fdatastore_2fv1_2fquery_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_QueryResultBatch_google_2fdatastore_2fv1_2fquery_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_google_2fdatastore_2fv1_2fquery_2eproto ::google::protobuf::internal::SCCInfo<2> scc_info_GqlQuery_google_2fdatastore_2fv1_2fquery_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_google_2fdatastore_2fv1_2fquery_2eproto ::google::protobuf::internal::SCCInfo<6> scc_info_Query_google_2fdatastore_2fv1_2fquery_2eproto;
namespace google {
namespace datastore {
namespace v1 {
class LookupRequestDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<LookupRequest> _instance;
} _LookupRequest_default_instance_;
class LookupResponseDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<LookupResponse> _instance;
} _LookupResponse_default_instance_;
class RunQueryRequestDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<RunQueryRequest> _instance;
const ::google::datastore::v1::Query* query_;
const ::google::datastore::v1::GqlQuery* gql_query_;
} _RunQueryRequest_default_instance_;
class RunQueryResponseDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<RunQueryResponse> _instance;
} _RunQueryResponse_default_instance_;
class BeginTransactionRequestDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<BeginTransactionRequest> _instance;
} _BeginTransactionRequest_default_instance_;
class BeginTransactionResponseDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<BeginTransactionResponse> _instance;
} _BeginTransactionResponse_default_instance_;
class RollbackRequestDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<RollbackRequest> _instance;
} _RollbackRequest_default_instance_;
class RollbackResponseDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<RollbackResponse> _instance;
} _RollbackResponse_default_instance_;
class CommitRequestDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<CommitRequest> _instance;
::google::protobuf::internal::ArenaStringPtr transaction_;
} _CommitRequest_default_instance_;
class CommitResponseDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<CommitResponse> _instance;
} _CommitResponse_default_instance_;
class AllocateIdsRequestDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<AllocateIdsRequest> _instance;
} _AllocateIdsRequest_default_instance_;
class AllocateIdsResponseDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<AllocateIdsResponse> _instance;
} _AllocateIdsResponse_default_instance_;
class ReserveIdsRequestDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<ReserveIdsRequest> _instance;
} _ReserveIdsRequest_default_instance_;
class ReserveIdsResponseDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<ReserveIdsResponse> _instance;
} _ReserveIdsResponse_default_instance_;
class MutationDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<Mutation> _instance;
const ::google::datastore::v1::Entity* insert_;
const ::google::datastore::v1::Entity* update_;
const ::google::datastore::v1::Entity* upsert_;
const ::google::datastore::v1::Key* delete__;
::google::protobuf::int64 base_version_;
} _Mutation_default_instance_;
class MutationResultDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<MutationResult> _instance;
} _MutationResult_default_instance_;
class ReadOptionsDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<ReadOptions> _instance;
int read_consistency_;
::google::protobuf::internal::ArenaStringPtr transaction_;
} _ReadOptions_default_instance_;
class TransactionOptions_ReadWriteDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<TransactionOptions_ReadWrite> _instance;
} _TransactionOptions_ReadWrite_default_instance_;
class TransactionOptions_ReadOnlyDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<TransactionOptions_ReadOnly> _instance;
} _TransactionOptions_ReadOnly_default_instance_;
class TransactionOptionsDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<TransactionOptions> _instance;
const ::google::datastore::v1::TransactionOptions_ReadWrite* read_write_;
const ::google::datastore::v1::TransactionOptions_ReadOnly* read_only_;
} _TransactionOptions_default_instance_;
} // namespace v1
} // namespace datastore
} // namespace google
static void InitDefaultsLookupRequest_google_2fdatastore_2fv1_2fdatastore_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::google::datastore::v1::_LookupRequest_default_instance_;
new (ptr) ::google::datastore::v1::LookupRequest();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::google::datastore::v1::LookupRequest::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<2> scc_info_LookupRequest_google_2fdatastore_2fv1_2fdatastore_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsLookupRequest_google_2fdatastore_2fv1_2fdatastore_2eproto}, {
&scc_info_ReadOptions_google_2fdatastore_2fv1_2fdatastore_2eproto.base,
&scc_info_Key_google_2fdatastore_2fv1_2fentity_2eproto.base,}};
static void InitDefaultsLookupResponse_google_2fdatastore_2fv1_2fdatastore_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::google::datastore::v1::_LookupResponse_default_instance_;
new (ptr) ::google::datastore::v1::LookupResponse();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::google::datastore::v1::LookupResponse::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<2> scc_info_LookupResponse_google_2fdatastore_2fv1_2fdatastore_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsLookupResponse_google_2fdatastore_2fv1_2fdatastore_2eproto}, {
&scc_info_EntityResult_google_2fdatastore_2fv1_2fquery_2eproto.base,
&scc_info_Key_google_2fdatastore_2fv1_2fentity_2eproto.base,}};
static void InitDefaultsRunQueryRequest_google_2fdatastore_2fv1_2fdatastore_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::google::datastore::v1::_RunQueryRequest_default_instance_;
new (ptr) ::google::datastore::v1::RunQueryRequest();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::google::datastore::v1::RunQueryRequest::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<4> scc_info_RunQueryRequest_google_2fdatastore_2fv1_2fdatastore_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 4, InitDefaultsRunQueryRequest_google_2fdatastore_2fv1_2fdatastore_2eproto}, {
&scc_info_PartitionId_google_2fdatastore_2fv1_2fentity_2eproto.base,
&scc_info_ReadOptions_google_2fdatastore_2fv1_2fdatastore_2eproto.base,
&scc_info_Query_google_2fdatastore_2fv1_2fquery_2eproto.base,
&scc_info_GqlQuery_google_2fdatastore_2fv1_2fquery_2eproto.base,}};
static void InitDefaultsRunQueryResponse_google_2fdatastore_2fv1_2fdatastore_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::google::datastore::v1::_RunQueryResponse_default_instance_;
new (ptr) ::google::datastore::v1::RunQueryResponse();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::google::datastore::v1::RunQueryResponse::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<2> scc_info_RunQueryResponse_google_2fdatastore_2fv1_2fdatastore_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsRunQueryResponse_google_2fdatastore_2fv1_2fdatastore_2eproto}, {
&scc_info_QueryResultBatch_google_2fdatastore_2fv1_2fquery_2eproto.base,
&scc_info_Query_google_2fdatastore_2fv1_2fquery_2eproto.base,}};
static void InitDefaultsBeginTransactionRequest_google_2fdatastore_2fv1_2fdatastore_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::google::datastore::v1::_BeginTransactionRequest_default_instance_;
new (ptr) ::google::datastore::v1::BeginTransactionRequest();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::google::datastore::v1::BeginTransactionRequest::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<1> scc_info_BeginTransactionRequest_google_2fdatastore_2fv1_2fdatastore_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsBeginTransactionRequest_google_2fdatastore_2fv1_2fdatastore_2eproto}, {
&scc_info_TransactionOptions_google_2fdatastore_2fv1_2fdatastore_2eproto.base,}};
static void InitDefaultsBeginTransactionResponse_google_2fdatastore_2fv1_2fdatastore_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::google::datastore::v1::_BeginTransactionResponse_default_instance_;
new (ptr) ::google::datastore::v1::BeginTransactionResponse();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::google::datastore::v1::BeginTransactionResponse::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<0> scc_info_BeginTransactionResponse_google_2fdatastore_2fv1_2fdatastore_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsBeginTransactionResponse_google_2fdatastore_2fv1_2fdatastore_2eproto}, {}};
static void InitDefaultsRollbackRequest_google_2fdatastore_2fv1_2fdatastore_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::google::datastore::v1::_RollbackRequest_default_instance_;
new (ptr) ::google::datastore::v1::RollbackRequest();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::google::datastore::v1::RollbackRequest::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<0> scc_info_RollbackRequest_google_2fdatastore_2fv1_2fdatastore_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsRollbackRequest_google_2fdatastore_2fv1_2fdatastore_2eproto}, {}};
static void InitDefaultsRollbackResponse_google_2fdatastore_2fv1_2fdatastore_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::google::datastore::v1::_RollbackResponse_default_instance_;
new (ptr) ::google::datastore::v1::RollbackResponse();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::google::datastore::v1::RollbackResponse::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<0> scc_info_RollbackResponse_google_2fdatastore_2fv1_2fdatastore_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsRollbackResponse_google_2fdatastore_2fv1_2fdatastore_2eproto}, {}};
static void InitDefaultsCommitRequest_google_2fdatastore_2fv1_2fdatastore_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::google::datastore::v1::_CommitRequest_default_instance_;
new (ptr) ::google::datastore::v1::CommitRequest();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::google::datastore::v1::CommitRequest::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<1> scc_info_CommitRequest_google_2fdatastore_2fv1_2fdatastore_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsCommitRequest_google_2fdatastore_2fv1_2fdatastore_2eproto}, {
&scc_info_Mutation_google_2fdatastore_2fv1_2fdatastore_2eproto.base,}};
static void InitDefaultsCommitResponse_google_2fdatastore_2fv1_2fdatastore_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::google::datastore::v1::_CommitResponse_default_instance_;
new (ptr) ::google::datastore::v1::CommitResponse();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::google::datastore::v1::CommitResponse::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<1> scc_info_CommitResponse_google_2fdatastore_2fv1_2fdatastore_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsCommitResponse_google_2fdatastore_2fv1_2fdatastore_2eproto}, {
&scc_info_MutationResult_google_2fdatastore_2fv1_2fdatastore_2eproto.base,}};
static void InitDefaultsAllocateIdsRequest_google_2fdatastore_2fv1_2fdatastore_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::google::datastore::v1::_AllocateIdsRequest_default_instance_;
new (ptr) ::google::datastore::v1::AllocateIdsRequest();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::google::datastore::v1::AllocateIdsRequest::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<1> scc_info_AllocateIdsRequest_google_2fdatastore_2fv1_2fdatastore_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsAllocateIdsRequest_google_2fdatastore_2fv1_2fdatastore_2eproto}, {
&scc_info_Key_google_2fdatastore_2fv1_2fentity_2eproto.base,}};
static void InitDefaultsAllocateIdsResponse_google_2fdatastore_2fv1_2fdatastore_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::google::datastore::v1::_AllocateIdsResponse_default_instance_;
new (ptr) ::google::datastore::v1::AllocateIdsResponse();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::google::datastore::v1::AllocateIdsResponse::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<1> scc_info_AllocateIdsResponse_google_2fdatastore_2fv1_2fdatastore_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsAllocateIdsResponse_google_2fdatastore_2fv1_2fdatastore_2eproto}, {
&scc_info_Key_google_2fdatastore_2fv1_2fentity_2eproto.base,}};
static void InitDefaultsReserveIdsRequest_google_2fdatastore_2fv1_2fdatastore_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::google::datastore::v1::_ReserveIdsRequest_default_instance_;
new (ptr) ::google::datastore::v1::ReserveIdsRequest();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::google::datastore::v1::ReserveIdsRequest::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<1> scc_info_ReserveIdsRequest_google_2fdatastore_2fv1_2fdatastore_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsReserveIdsRequest_google_2fdatastore_2fv1_2fdatastore_2eproto}, {
&scc_info_Key_google_2fdatastore_2fv1_2fentity_2eproto.base,}};
static void InitDefaultsReserveIdsResponse_google_2fdatastore_2fv1_2fdatastore_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::google::datastore::v1::_ReserveIdsResponse_default_instance_;
new (ptr) ::google::datastore::v1::ReserveIdsResponse();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::google::datastore::v1::ReserveIdsResponse::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<0> scc_info_ReserveIdsResponse_google_2fdatastore_2fv1_2fdatastore_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsReserveIdsResponse_google_2fdatastore_2fv1_2fdatastore_2eproto}, {}};
static void InitDefaultsMutation_google_2fdatastore_2fv1_2fdatastore_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::google::datastore::v1::_Mutation_default_instance_;
new (ptr) ::google::datastore::v1::Mutation();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::google::datastore::v1::Mutation::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<2> scc_info_Mutation_google_2fdatastore_2fv1_2fdatastore_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsMutation_google_2fdatastore_2fv1_2fdatastore_2eproto}, {
&scc_info_ArrayValue_google_2fdatastore_2fv1_2fentity_2eproto.base,
&scc_info_Key_google_2fdatastore_2fv1_2fentity_2eproto.base,}};
static void InitDefaultsMutationResult_google_2fdatastore_2fv1_2fdatastore_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::google::datastore::v1::_MutationResult_default_instance_;
new (ptr) ::google::datastore::v1::MutationResult();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::google::datastore::v1::MutationResult::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<1> scc_info_MutationResult_google_2fdatastore_2fv1_2fdatastore_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsMutationResult_google_2fdatastore_2fv1_2fdatastore_2eproto}, {
&scc_info_Key_google_2fdatastore_2fv1_2fentity_2eproto.base,}};
static void InitDefaultsReadOptions_google_2fdatastore_2fv1_2fdatastore_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::google::datastore::v1::_ReadOptions_default_instance_;
new (ptr) ::google::datastore::v1::ReadOptions();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::google::datastore::v1::ReadOptions::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<0> scc_info_ReadOptions_google_2fdatastore_2fv1_2fdatastore_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsReadOptions_google_2fdatastore_2fv1_2fdatastore_2eproto}, {}};
static void InitDefaultsTransactionOptions_ReadWrite_google_2fdatastore_2fv1_2fdatastore_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::google::datastore::v1::_TransactionOptions_ReadWrite_default_instance_;
new (ptr) ::google::datastore::v1::TransactionOptions_ReadWrite();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::google::datastore::v1::TransactionOptions_ReadWrite::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<0> scc_info_TransactionOptions_ReadWrite_google_2fdatastore_2fv1_2fdatastore_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsTransactionOptions_ReadWrite_google_2fdatastore_2fv1_2fdatastore_2eproto}, {}};
static void InitDefaultsTransactionOptions_ReadOnly_google_2fdatastore_2fv1_2fdatastore_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::google::datastore::v1::_TransactionOptions_ReadOnly_default_instance_;
new (ptr) ::google::datastore::v1::TransactionOptions_ReadOnly();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::google::datastore::v1::TransactionOptions_ReadOnly::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<0> scc_info_TransactionOptions_ReadOnly_google_2fdatastore_2fv1_2fdatastore_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsTransactionOptions_ReadOnly_google_2fdatastore_2fv1_2fdatastore_2eproto}, {}};
static void InitDefaultsTransactionOptions_google_2fdatastore_2fv1_2fdatastore_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::google::datastore::v1::_TransactionOptions_default_instance_;
new (ptr) ::google::datastore::v1::TransactionOptions();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::google::datastore::v1::TransactionOptions::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<2> scc_info_TransactionOptions_google_2fdatastore_2fv1_2fdatastore_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsTransactionOptions_google_2fdatastore_2fv1_2fdatastore_2eproto}, {
&scc_info_TransactionOptions_ReadWrite_google_2fdatastore_2fv1_2fdatastore_2eproto.base,
&scc_info_TransactionOptions_ReadOnly_google_2fdatastore_2fv1_2fdatastore_2eproto.base,}};
void InitDefaults_google_2fdatastore_2fv1_2fdatastore_2eproto() {
::google::protobuf::internal::InitSCC(&scc_info_LookupRequest_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_LookupResponse_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_RunQueryRequest_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_RunQueryResponse_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_BeginTransactionRequest_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_BeginTransactionResponse_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_RollbackRequest_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_RollbackResponse_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_CommitRequest_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_CommitResponse_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_AllocateIdsRequest_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_AllocateIdsResponse_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_ReserveIdsRequest_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_ReserveIdsResponse_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_Mutation_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_MutationResult_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_ReadOptions_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_TransactionOptions_ReadWrite_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_TransactionOptions_ReadOnly_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_TransactionOptions_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
}
::google::protobuf::Metadata file_level_metadata_google_2fdatastore_2fv1_2fdatastore_2eproto[20];
const ::google::protobuf::EnumDescriptor* file_level_enum_descriptors_google_2fdatastore_2fv1_2fdatastore_2eproto[2];
constexpr ::google::protobuf::ServiceDescriptor const** file_level_service_descriptors_google_2fdatastore_2fv1_2fdatastore_2eproto = nullptr;
const ::google::protobuf::uint32 TableStruct_google_2fdatastore_2fv1_2fdatastore_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::LookupRequest, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::LookupRequest, project_id_),
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::LookupRequest, read_options_),
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::LookupRequest, keys_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::LookupResponse, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::LookupResponse, found_),
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::LookupResponse, missing_),
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::LookupResponse, deferred_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::RunQueryRequest, _internal_metadata_),
~0u, // no _extensions_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::RunQueryRequest, _oneof_case_[0]),
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::RunQueryRequest, project_id_),
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::RunQueryRequest, partition_id_),
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::RunQueryRequest, read_options_),
offsetof(::google::datastore::v1::RunQueryRequestDefaultTypeInternal, query_),
offsetof(::google::datastore::v1::RunQueryRequestDefaultTypeInternal, gql_query_),
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::RunQueryRequest, query_type_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::RunQueryResponse, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::RunQueryResponse, batch_),
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::RunQueryResponse, query_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::BeginTransactionRequest, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::BeginTransactionRequest, project_id_),
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::BeginTransactionRequest, transaction_options_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::BeginTransactionResponse, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::BeginTransactionResponse, transaction_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::RollbackRequest, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::RollbackRequest, project_id_),
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::RollbackRequest, transaction_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::RollbackResponse, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::CommitRequest, _internal_metadata_),
~0u, // no _extensions_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::CommitRequest, _oneof_case_[0]),
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::CommitRequest, project_id_),
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::CommitRequest, mode_),
offsetof(::google::datastore::v1::CommitRequestDefaultTypeInternal, transaction_),
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::CommitRequest, mutations_),
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::CommitRequest, transaction_selector_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::CommitResponse, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::CommitResponse, mutation_results_),
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::CommitResponse, index_updates_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::AllocateIdsRequest, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::AllocateIdsRequest, project_id_),
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::AllocateIdsRequest, keys_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::AllocateIdsResponse, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::AllocateIdsResponse, keys_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::ReserveIdsRequest, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::ReserveIdsRequest, project_id_),
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::ReserveIdsRequest, database_id_),
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::ReserveIdsRequest, keys_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::ReserveIdsResponse, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::Mutation, _internal_metadata_),
~0u, // no _extensions_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::Mutation, _oneof_case_[0]),
~0u, // no _weak_field_map_
offsetof(::google::datastore::v1::MutationDefaultTypeInternal, insert_),
offsetof(::google::datastore::v1::MutationDefaultTypeInternal, update_),
offsetof(::google::datastore::v1::MutationDefaultTypeInternal, upsert_),
offsetof(::google::datastore::v1::MutationDefaultTypeInternal, delete__),
offsetof(::google::datastore::v1::MutationDefaultTypeInternal, base_version_),
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::Mutation, operation_),
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::Mutation, conflict_detection_strategy_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::MutationResult, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::MutationResult, key_),
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::MutationResult, version_),
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::MutationResult, conflict_detected_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::ReadOptions, _internal_metadata_),
~0u, // no _extensions_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::ReadOptions, _oneof_case_[0]),
~0u, // no _weak_field_map_
offsetof(::google::datastore::v1::ReadOptionsDefaultTypeInternal, read_consistency_),
offsetof(::google::datastore::v1::ReadOptionsDefaultTypeInternal, transaction_),
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::ReadOptions, consistency_type_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::TransactionOptions_ReadWrite, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::TransactionOptions_ReadWrite, previous_transaction_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::TransactionOptions_ReadOnly, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::TransactionOptions, _internal_metadata_),
~0u, // no _extensions_
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::TransactionOptions, _oneof_case_[0]),
~0u, // no _weak_field_map_
offsetof(::google::datastore::v1::TransactionOptionsDefaultTypeInternal, read_write_),
offsetof(::google::datastore::v1::TransactionOptionsDefaultTypeInternal, read_only_),
PROTOBUF_FIELD_OFFSET(::google::datastore::v1::TransactionOptions, mode_),
};
static const ::google::protobuf::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(::google::datastore::v1::LookupRequest)},
{ 8, -1, sizeof(::google::datastore::v1::LookupResponse)},
{ 16, -1, sizeof(::google::datastore::v1::RunQueryRequest)},
{ 27, -1, sizeof(::google::datastore::v1::RunQueryResponse)},
{ 34, -1, sizeof(::google::datastore::v1::BeginTransactionRequest)},
{ 41, -1, sizeof(::google::datastore::v1::BeginTransactionResponse)},
{ 47, -1, sizeof(::google::datastore::v1::RollbackRequest)},
{ 54, -1, sizeof(::google::datastore::v1::RollbackResponse)},
{ 59, -1, sizeof(::google::datastore::v1::CommitRequest)},
{ 69, -1, sizeof(::google::datastore::v1::CommitResponse)},
{ 76, -1, sizeof(::google::datastore::v1::AllocateIdsRequest)},
{ 83, -1, sizeof(::google::datastore::v1::AllocateIdsResponse)},
{ 89, -1, sizeof(::google::datastore::v1::ReserveIdsRequest)},
{ 97, -1, sizeof(::google::datastore::v1::ReserveIdsResponse)},
{ 102, -1, sizeof(::google::datastore::v1::Mutation)},
{ 114, -1, sizeof(::google::datastore::v1::MutationResult)},
{ 122, -1, sizeof(::google::datastore::v1::ReadOptions)},
{ 130, -1, sizeof(::google::datastore::v1::TransactionOptions_ReadWrite)},
{ 136, -1, sizeof(::google::datastore::v1::TransactionOptions_ReadOnly)},
{ 141, -1, sizeof(::google::datastore::v1::TransactionOptions)},
};
static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::google::datastore::v1::_LookupRequest_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::google::datastore::v1::_LookupResponse_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::google::datastore::v1::_RunQueryRequest_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::google::datastore::v1::_RunQueryResponse_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::google::datastore::v1::_BeginTransactionRequest_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::google::datastore::v1::_BeginTransactionResponse_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::google::datastore::v1::_RollbackRequest_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::google::datastore::v1::_RollbackResponse_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::google::datastore::v1::_CommitRequest_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::google::datastore::v1::_CommitResponse_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::google::datastore::v1::_AllocateIdsRequest_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::google::datastore::v1::_AllocateIdsResponse_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::google::datastore::v1::_ReserveIdsRequest_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::google::datastore::v1::_ReserveIdsResponse_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::google::datastore::v1::_Mutation_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::google::datastore::v1::_MutationResult_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::google::datastore::v1::_ReadOptions_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::google::datastore::v1::_TransactionOptions_ReadWrite_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::google::datastore::v1::_TransactionOptions_ReadOnly_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::google::datastore::v1::_TransactionOptions_default_instance_),
};
::google::protobuf::internal::AssignDescriptorsTable assign_descriptors_table_google_2fdatastore_2fv1_2fdatastore_2eproto = {
{}, AddDescriptors_google_2fdatastore_2fv1_2fdatastore_2eproto, "google/datastore/v1/datastore.proto", schemas,
file_default_instances, TableStruct_google_2fdatastore_2fv1_2fdatastore_2eproto::offsets,
file_level_metadata_google_2fdatastore_2fv1_2fdatastore_2eproto, 20, file_level_enum_descriptors_google_2fdatastore_2fv1_2fdatastore_2eproto, file_level_service_descriptors_google_2fdatastore_2fv1_2fdatastore_2eproto,
};
const char descriptor_table_protodef_google_2fdatastore_2fv1_2fdatastore_2eproto[] =
"\n#google/datastore/v1/datastore.proto\022\023g"
"oogle.datastore.v1\032\034google/api/annotatio"
"ns.proto\032\027google/api/client.proto\032\037googl"
"e/api/field_behavior.proto\032 google/datas"
"tore/v1/entity.proto\032\037google/datastore/v"
"1/query.proto\"\215\001\n\rLookupRequest\022\027\n\nproje"
"ct_id\030\010 \001(\tB\003\340A\002\0226\n\014read_options\030\001 \001(\0132 "
".google.datastore.v1.ReadOptions\022+\n\004keys"
"\030\003 \003(\0132\030.google.datastore.v1.KeyB\003\340A\002\"\242\001"
"\n\016LookupResponse\0220\n\005found\030\001 \003(\0132!.google"
".datastore.v1.EntityResult\0222\n\007missing\030\002 "
"\003(\0132!.google.datastore.v1.EntityResult\022*"
"\n\010deferred\030\003 \003(\0132\030.google.datastore.v1.K"
"ey\"\211\002\n\017RunQueryRequest\022\027\n\nproject_id\030\010 \001"
"(\tB\003\340A\002\0226\n\014partition_id\030\002 \001(\0132 .google.d"
"atastore.v1.PartitionId\0226\n\014read_options\030"
"\001 \001(\0132 .google.datastore.v1.ReadOptions\022"
"+\n\005query\030\003 \001(\0132\032.google.datastore.v1.Que"
"ryH\000\0222\n\tgql_query\030\007 \001(\0132\035.google.datasto"
"re.v1.GqlQueryH\000B\014\n\nquery_type\"s\n\020RunQue"
"ryResponse\0224\n\005batch\030\001 \001(\0132%.google.datas"
"tore.v1.QueryResultBatch\022)\n\005query\030\002 \001(\0132"
"\032.google.datastore.v1.Query\"x\n\027BeginTran"
"sactionRequest\022\027\n\nproject_id\030\010 \001(\tB\003\340A\002\022"
"D\n\023transaction_options\030\n \001(\0132\'.google.da"
"tastore.v1.TransactionOptions\"/\n\030BeginTr"
"ansactionResponse\022\023\n\013transaction\030\001 \001(\014\"D"
"\n\017RollbackRequest\022\027\n\nproject_id\030\010 \001(\tB\003\340"
"A\002\022\030\n\013transaction\030\001 \001(\014B\003\340A\002\"\022\n\020Rollback"
"Response\"\210\002\n\rCommitRequest\022\027\n\nproject_id"
"\030\010 \001(\tB\003\340A\002\0225\n\004mode\030\005 \001(\0162\'.google.datas"
"tore.v1.CommitRequest.Mode\022\025\n\013transactio"
"n\030\001 \001(\014H\000\0220\n\tmutations\030\006 \003(\0132\035.google.da"
"tastore.v1.Mutation\"F\n\004Mode\022\024\n\020MODE_UNSP"
"ECIFIED\020\000\022\021\n\rTRANSACTIONAL\020\001\022\025\n\021NON_TRAN"
"SACTIONAL\020\002B\026\n\024transaction_selector\"f\n\016C"
"ommitResponse\022=\n\020mutation_results\030\003 \003(\0132"
"#.google.datastore.v1.MutationResult\022\025\n\r"
"index_updates\030\004 \001(\005\"Z\n\022AllocateIdsReques"
"t\022\027\n\nproject_id\030\010 \001(\tB\003\340A\002\022+\n\004keys\030\001 \003(\013"
"2\030.google.datastore.v1.KeyB\003\340A\002\"=\n\023Alloc"
"ateIdsResponse\022&\n\004keys\030\001 \003(\0132\030.google.da"
"tastore.v1.Key\"n\n\021ReserveIdsRequest\022\027\n\np"
"roject_id\030\010 \001(\tB\003\340A\002\022\023\n\013database_id\030\t \001("
"\t\022+\n\004keys\030\001 \003(\0132\030.google.datastore.v1.Ke"
"yB\003\340A\002\"\024\n\022ReserveIdsResponse\"\207\002\n\010Mutatio"
"n\022-\n\006insert\030\004 \001(\0132\033.google.datastore.v1."
"EntityH\000\022-\n\006update\030\005 \001(\0132\033.google.datast"
"ore.v1.EntityH\000\022-\n\006upsert\030\006 \001(\0132\033.google"
".datastore.v1.EntityH\000\022*\n\006delete\030\007 \001(\0132\030"
".google.datastore.v1.KeyH\000\022\026\n\014base_versi"
"on\030\010 \001(\003H\001B\013\n\toperationB\035\n\033conflict_dete"
"ction_strategy\"c\n\016MutationResult\022%\n\003key\030"
"\003 \001(\0132\030.google.datastore.v1.Key\022\017\n\007versi"
"on\030\004 \001(\003\022\031\n\021conflict_detected\030\005 \001(\010\"\325\001\n\013"
"ReadOptions\022L\n\020read_consistency\030\001 \001(\01620."
"google.datastore.v1.ReadOptions.ReadCons"
"istencyH\000\022\025\n\013transaction\030\002 \001(\014H\000\"M\n\017Read"
"Consistency\022 \n\034READ_CONSISTENCY_UNSPECIF"
"IED\020\000\022\n\n\006STRONG\020\001\022\014\n\010EVENTUAL\020\002B\022\n\020consi"
"stency_type\"\343\001\n\022TransactionOptions\022G\n\nre"
"ad_write\030\001 \001(\01321.google.datastore.v1.Tra"
"nsactionOptions.ReadWriteH\000\022E\n\tread_only"
"\030\002 \001(\01320.google.datastore.v1.Transaction"
"Options.ReadOnlyH\000\032)\n\tReadWrite\022\034\n\024previ"
"ous_transaction\030\001 \001(\014\032\n\n\010ReadOnlyB\006\n\004mod"
"e2\223\n\n\tDatastore\022\235\001\n\006Lookup\022\".google.data"
"store.v1.LookupRequest\032#.google.datastor"
"e.v1.LookupResponse\"J\202\323\344\223\002%\" /v1/project"
"s/{project_id}:lookup:\001*\332A\034project_id,re"
"ad_options,keys\022\206\001\n\010RunQuery\022$.google.da"
"tastore.v1.RunQueryRequest\032%.google.data"
"store.v1.RunQueryResponse\"-\202\323\344\223\002\'\"\"/v1/p"
"rojects/{project_id}:runQuery:\001*\022\263\001\n\020Beg"
"inTransaction\022,.google.datastore.v1.Begi"
"nTransactionRequest\032-.google.datastore.v"
"1.BeginTransactionResponse\"B\202\323\344\223\002/\"*/v1/"
"projects/{project_id}:beginTransaction:\001"
"*\332A\nproject_id\022\302\001\n\006Commit\022\".google.datas"
"tore.v1.CommitRequest\032#.google.datastore"
".v1.CommitResponse\"o\202\323\344\223\002%\" /v1/projects"
"/{project_id}:commit:\001*\332A%project_id,mod"
"e,transaction,mutations\332A\031project_id,mod"
"e,mutations\022\237\001\n\010Rollback\022$.google.datast"
"ore.v1.RollbackRequest\032%.google.datastor"
"e.v1.RollbackResponse\"F\202\323\344\223\002\'\"\"/v1/proje"
"cts/{project_id}:rollback:\001*\332A\026project_i"
"d,transaction\022\244\001\n\013AllocateIds\022\'.google.d"
"atastore.v1.AllocateIdsRequest\032(.google."
"datastore.v1.AllocateIdsResponse\"B\202\323\344\223\002*"
"\"%/v1/projects/{project_id}:allocateIds:"
"\001*\332A\017project_id,keys\022\240\001\n\nReserveIds\022&.go"
"ogle.datastore.v1.ReserveIdsRequest\032\'.go"
"ogle.datastore.v1.ReserveIdsResponse\"A\202\323"
"\344\223\002)\"$/v1/projects/{project_id}:reserveI"
"ds:\001*\332A\017project_id,keys\032v\312A\030datastore.go"
"ogleapis.com\322AXhttps://www.googleapis.co"
"m/auth/cloud-platform,https://www.google"
"apis.com/auth/datastoreB\300\001\n\027com.google.d"
"atastore.v1B\016DatastoreProtoP\001Z<google.go"
"lang.org/genproto/googleapis/datastore/v"
"1;datastore\252\002\031Google.Cloud.Datastore.V1\312"
"\002\031Google\\Cloud\\Datastore\\V1\352\002\034Google::Cl"
"oud::Datastore::V1b\006proto3"
;
::google::protobuf::internal::DescriptorTable descriptor_table_google_2fdatastore_2fv1_2fdatastore_2eproto = {
false, InitDefaults_google_2fdatastore_2fv1_2fdatastore_2eproto,
descriptor_table_protodef_google_2fdatastore_2fv1_2fdatastore_2eproto,
"google/datastore/v1/datastore.proto", &assign_descriptors_table_google_2fdatastore_2fv1_2fdatastore_2eproto, 4146,
};
void AddDescriptors_google_2fdatastore_2fv1_2fdatastore_2eproto() {
static constexpr ::google::protobuf::internal::InitFunc deps[5] =
{
::AddDescriptors_google_2fapi_2fannotations_2eproto,
::AddDescriptors_google_2fapi_2fclient_2eproto,
::AddDescriptors_google_2fapi_2ffield_5fbehavior_2eproto,
::AddDescriptors_google_2fdatastore_2fv1_2fentity_2eproto,
::AddDescriptors_google_2fdatastore_2fv1_2fquery_2eproto,
};
::google::protobuf::internal::AddDescriptors(&descriptor_table_google_2fdatastore_2fv1_2fdatastore_2eproto, deps, 5);
}
// Force running AddDescriptors() at dynamic initialization time.
static bool dynamic_init_dummy_google_2fdatastore_2fv1_2fdatastore_2eproto = []() { AddDescriptors_google_2fdatastore_2fv1_2fdatastore_2eproto(); return true; }();
namespace google {
namespace datastore {
namespace v1 {
const ::google::protobuf::EnumDescriptor* CommitRequest_Mode_descriptor() {
::google::protobuf::internal::AssignDescriptors(&assign_descriptors_table_google_2fdatastore_2fv1_2fdatastore_2eproto);
return file_level_enum_descriptors_google_2fdatastore_2fv1_2fdatastore_2eproto[0];
}
bool CommitRequest_Mode_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
return true;
default:
return false;
}
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const CommitRequest_Mode CommitRequest::MODE_UNSPECIFIED;
const CommitRequest_Mode CommitRequest::TRANSACTIONAL;
const CommitRequest_Mode CommitRequest::NON_TRANSACTIONAL;
const CommitRequest_Mode CommitRequest::Mode_MIN;
const CommitRequest_Mode CommitRequest::Mode_MAX;
const int CommitRequest::Mode_ARRAYSIZE;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
const ::google::protobuf::EnumDescriptor* ReadOptions_ReadConsistency_descriptor() {
::google::protobuf::internal::AssignDescriptors(&assign_descriptors_table_google_2fdatastore_2fv1_2fdatastore_2eproto);
return file_level_enum_descriptors_google_2fdatastore_2fv1_2fdatastore_2eproto[1];
}
bool ReadOptions_ReadConsistency_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
return true;
default:
return false;
}
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const ReadOptions_ReadConsistency ReadOptions::READ_CONSISTENCY_UNSPECIFIED;
const ReadOptions_ReadConsistency ReadOptions::STRONG;
const ReadOptions_ReadConsistency ReadOptions::EVENTUAL;
const ReadOptions_ReadConsistency ReadOptions::ReadConsistency_MIN;
const ReadOptions_ReadConsistency ReadOptions::ReadConsistency_MAX;
const int ReadOptions::ReadConsistency_ARRAYSIZE;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
// ===================================================================
void LookupRequest::InitAsDefaultInstance() {
::google::datastore::v1::_LookupRequest_default_instance_._instance.get_mutable()->read_options_ = const_cast< ::google::datastore::v1::ReadOptions*>(
::google::datastore::v1::ReadOptions::internal_default_instance());
}
class LookupRequest::HasBitSetters {
public:
static const ::google::datastore::v1::ReadOptions& read_options(const LookupRequest* msg);
};
const ::google::datastore::v1::ReadOptions&
LookupRequest::HasBitSetters::read_options(const LookupRequest* msg) {
return *msg->read_options_;
}
void LookupRequest::clear_keys() {
keys_.Clear();
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int LookupRequest::kProjectIdFieldNumber;
const int LookupRequest::kReadOptionsFieldNumber;
const int LookupRequest::kKeysFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
LookupRequest::LookupRequest()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:google.datastore.v1.LookupRequest)
}
LookupRequest::LookupRequest(const LookupRequest& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr),
keys_(from.keys_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
project_id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.project_id().size() > 0) {
project_id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.project_id_);
}
if (from.has_read_options()) {
read_options_ = new ::google::datastore::v1::ReadOptions(*from.read_options_);
} else {
read_options_ = nullptr;
}
// @@protoc_insertion_point(copy_constructor:google.datastore.v1.LookupRequest)
}
void LookupRequest::SharedCtor() {
::google::protobuf::internal::InitSCC(
&scc_info_LookupRequest_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
project_id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
read_options_ = nullptr;
}
LookupRequest::~LookupRequest() {
// @@protoc_insertion_point(destructor:google.datastore.v1.LookupRequest)
SharedDtor();
}
void LookupRequest::SharedDtor() {
project_id_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (this != internal_default_instance()) delete read_options_;
}
void LookupRequest::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const LookupRequest& LookupRequest::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_LookupRequest_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
return *internal_default_instance();
}
void LookupRequest::Clear() {
// @@protoc_insertion_point(message_clear_start:google.datastore.v1.LookupRequest)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
keys_.Clear();
project_id_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (GetArenaNoVirtual() == nullptr && read_options_ != nullptr) {
delete read_options_;
}
read_options_ = nullptr;
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* LookupRequest::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<LookupRequest*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// .google.datastore.v1.ReadOptions read_options = 1;
case 1: {
if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::datastore::v1::ReadOptions::_InternalParse;
object = msg->mutable_read_options();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
break;
}
// repeated .google.datastore.v1.Key keys = 3 [(.google.api.field_behavior) = REQUIRED];
case 3: {
if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual;
do {
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::datastore::v1::Key::_InternalParse;
object = msg->add_keys();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
if (ptr >= end) break;
} while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 26 && (ptr += 1));
break;
}
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
case 8: {
if (static_cast<::google::protobuf::uint8>(tag) != 66) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
ctx->extra_parse_data().SetFieldName("google.datastore.v1.LookupRequest.project_id");
object = msg->mutable_project_id();
if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) {
parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8;
goto string_till_end;
}
GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx));
::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx);
ptr += size;
break;
}
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
string_till_end:
static_cast<::std::string*>(object)->clear();
static_cast<::std::string*>(object)->reserve(size);
goto len_delim_till_end;
len_delim_till_end:
return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
{parser_till_end, object}, size);
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool LookupRequest::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.datastore.v1.LookupRequest)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .google.datastore.v1.ReadOptions read_options = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_read_options()));
} else {
goto handle_unusual;
}
break;
}
// repeated .google.datastore.v1.Key keys = 3 [(.google.api.field_behavior) = REQUIRED];
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_keys()));
} else {
goto handle_unusual;
}
break;
}
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
case 8: {
if (static_cast< ::google::protobuf::uint8>(tag) == (66 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_project_id()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->project_id().data(), static_cast<int>(this->project_id().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.datastore.v1.LookupRequest.project_id"));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:google.datastore.v1.LookupRequest)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.datastore.v1.LookupRequest)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void LookupRequest::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.datastore.v1.LookupRequest)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .google.datastore.v1.ReadOptions read_options = 1;
if (this->has_read_options()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, HasBitSetters::read_options(this), output);
}
// repeated .google.datastore.v1.Key keys = 3 [(.google.api.field_behavior) = REQUIRED];
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->keys_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3,
this->keys(static_cast<int>(i)),
output);
}
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
if (this->project_id().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->project_id().data(), static_cast<int>(this->project_id().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.datastore.v1.LookupRequest.project_id");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
8, this->project_id(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.datastore.v1.LookupRequest)
}
::google::protobuf::uint8* LookupRequest::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:google.datastore.v1.LookupRequest)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .google.datastore.v1.ReadOptions read_options = 1;
if (this->has_read_options()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
1, HasBitSetters::read_options(this), target);
}
// repeated .google.datastore.v1.Key keys = 3 [(.google.api.field_behavior) = REQUIRED];
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->keys_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
3, this->keys(static_cast<int>(i)), target);
}
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
if (this->project_id().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->project_id().data(), static_cast<int>(this->project_id().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.datastore.v1.LookupRequest.project_id");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
8, this->project_id(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.datastore.v1.LookupRequest)
return target;
}
size_t LookupRequest::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.datastore.v1.LookupRequest)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// repeated .google.datastore.v1.Key keys = 3 [(.google.api.field_behavior) = REQUIRED];
{
unsigned int count = static_cast<unsigned int>(this->keys_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSize(
this->keys(static_cast<int>(i)));
}
}
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
if (this->project_id().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->project_id());
}
// .google.datastore.v1.ReadOptions read_options = 1;
if (this->has_read_options()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*read_options_);
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void LookupRequest::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.datastore.v1.LookupRequest)
GOOGLE_DCHECK_NE(&from, this);
const LookupRequest* source =
::google::protobuf::DynamicCastToGenerated<LookupRequest>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.datastore.v1.LookupRequest)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.datastore.v1.LookupRequest)
MergeFrom(*source);
}
}
void LookupRequest::MergeFrom(const LookupRequest& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.datastore.v1.LookupRequest)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
keys_.MergeFrom(from.keys_);
if (from.project_id().size() > 0) {
project_id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.project_id_);
}
if (from.has_read_options()) {
mutable_read_options()->::google::datastore::v1::ReadOptions::MergeFrom(from.read_options());
}
}
void LookupRequest::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.datastore.v1.LookupRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void LookupRequest::CopyFrom(const LookupRequest& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.datastore.v1.LookupRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool LookupRequest::IsInitialized() const {
return true;
}
void LookupRequest::Swap(LookupRequest* other) {
if (other == this) return;
InternalSwap(other);
}
void LookupRequest::InternalSwap(LookupRequest* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
CastToBase(&keys_)->InternalSwap(CastToBase(&other->keys_));
project_id_.Swap(&other->project_id_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
swap(read_options_, other->read_options_);
}
::google::protobuf::Metadata LookupRequest::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fdatastore_2fv1_2fdatastore_2eproto);
return ::file_level_metadata_google_2fdatastore_2fv1_2fdatastore_2eproto[kIndexInFileMessages];
}
// ===================================================================
void LookupResponse::InitAsDefaultInstance() {
}
class LookupResponse::HasBitSetters {
public:
};
void LookupResponse::clear_found() {
found_.Clear();
}
void LookupResponse::clear_missing() {
missing_.Clear();
}
void LookupResponse::clear_deferred() {
deferred_.Clear();
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int LookupResponse::kFoundFieldNumber;
const int LookupResponse::kMissingFieldNumber;
const int LookupResponse::kDeferredFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
LookupResponse::LookupResponse()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:google.datastore.v1.LookupResponse)
}
LookupResponse::LookupResponse(const LookupResponse& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr),
found_(from.found_),
missing_(from.missing_),
deferred_(from.deferred_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:google.datastore.v1.LookupResponse)
}
void LookupResponse::SharedCtor() {
::google::protobuf::internal::InitSCC(
&scc_info_LookupResponse_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
}
LookupResponse::~LookupResponse() {
// @@protoc_insertion_point(destructor:google.datastore.v1.LookupResponse)
SharedDtor();
}
void LookupResponse::SharedDtor() {
}
void LookupResponse::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const LookupResponse& LookupResponse::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_LookupResponse_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
return *internal_default_instance();
}
void LookupResponse::Clear() {
// @@protoc_insertion_point(message_clear_start:google.datastore.v1.LookupResponse)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
found_.Clear();
missing_.Clear();
deferred_.Clear();
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* LookupResponse::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<LookupResponse*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// repeated .google.datastore.v1.EntityResult found = 1;
case 1: {
if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
do {
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::datastore::v1::EntityResult::_InternalParse;
object = msg->add_found();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
if (ptr >= end) break;
} while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 10 && (ptr += 1));
break;
}
// repeated .google.datastore.v1.EntityResult missing = 2;
case 2: {
if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual;
do {
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::datastore::v1::EntityResult::_InternalParse;
object = msg->add_missing();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
if (ptr >= end) break;
} while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 18 && (ptr += 1));
break;
}
// repeated .google.datastore.v1.Key deferred = 3;
case 3: {
if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual;
do {
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::datastore::v1::Key::_InternalParse;
object = msg->add_deferred();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
if (ptr >= end) break;
} while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 26 && (ptr += 1));
break;
}
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
len_delim_till_end:
return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
{parser_till_end, object}, size);
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool LookupResponse::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.datastore.v1.LookupResponse)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated .google.datastore.v1.EntityResult found = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_found()));
} else {
goto handle_unusual;
}
break;
}
// repeated .google.datastore.v1.EntityResult missing = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_missing()));
} else {
goto handle_unusual;
}
break;
}
// repeated .google.datastore.v1.Key deferred = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_deferred()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:google.datastore.v1.LookupResponse)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.datastore.v1.LookupResponse)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void LookupResponse::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.datastore.v1.LookupResponse)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated .google.datastore.v1.EntityResult found = 1;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->found_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1,
this->found(static_cast<int>(i)),
output);
}
// repeated .google.datastore.v1.EntityResult missing = 2;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->missing_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2,
this->missing(static_cast<int>(i)),
output);
}
// repeated .google.datastore.v1.Key deferred = 3;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->deferred_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3,
this->deferred(static_cast<int>(i)),
output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.datastore.v1.LookupResponse)
}
::google::protobuf::uint8* LookupResponse::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:google.datastore.v1.LookupResponse)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated .google.datastore.v1.EntityResult found = 1;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->found_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
1, this->found(static_cast<int>(i)), target);
}
// repeated .google.datastore.v1.EntityResult missing = 2;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->missing_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
2, this->missing(static_cast<int>(i)), target);
}
// repeated .google.datastore.v1.Key deferred = 3;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->deferred_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
3, this->deferred(static_cast<int>(i)), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.datastore.v1.LookupResponse)
return target;
}
size_t LookupResponse::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.datastore.v1.LookupResponse)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// repeated .google.datastore.v1.EntityResult found = 1;
{
unsigned int count = static_cast<unsigned int>(this->found_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSize(
this->found(static_cast<int>(i)));
}
}
// repeated .google.datastore.v1.EntityResult missing = 2;
{
unsigned int count = static_cast<unsigned int>(this->missing_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSize(
this->missing(static_cast<int>(i)));
}
}
// repeated .google.datastore.v1.Key deferred = 3;
{
unsigned int count = static_cast<unsigned int>(this->deferred_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSize(
this->deferred(static_cast<int>(i)));
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void LookupResponse::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.datastore.v1.LookupResponse)
GOOGLE_DCHECK_NE(&from, this);
const LookupResponse* source =
::google::protobuf::DynamicCastToGenerated<LookupResponse>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.datastore.v1.LookupResponse)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.datastore.v1.LookupResponse)
MergeFrom(*source);
}
}
void LookupResponse::MergeFrom(const LookupResponse& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.datastore.v1.LookupResponse)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
found_.MergeFrom(from.found_);
missing_.MergeFrom(from.missing_);
deferred_.MergeFrom(from.deferred_);
}
void LookupResponse::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.datastore.v1.LookupResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void LookupResponse::CopyFrom(const LookupResponse& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.datastore.v1.LookupResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool LookupResponse::IsInitialized() const {
return true;
}
void LookupResponse::Swap(LookupResponse* other) {
if (other == this) return;
InternalSwap(other);
}
void LookupResponse::InternalSwap(LookupResponse* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
CastToBase(&found_)->InternalSwap(CastToBase(&other->found_));
CastToBase(&missing_)->InternalSwap(CastToBase(&other->missing_));
CastToBase(&deferred_)->InternalSwap(CastToBase(&other->deferred_));
}
::google::protobuf::Metadata LookupResponse::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fdatastore_2fv1_2fdatastore_2eproto);
return ::file_level_metadata_google_2fdatastore_2fv1_2fdatastore_2eproto[kIndexInFileMessages];
}
// ===================================================================
void RunQueryRequest::InitAsDefaultInstance() {
::google::datastore::v1::_RunQueryRequest_default_instance_._instance.get_mutable()->partition_id_ = const_cast< ::google::datastore::v1::PartitionId*>(
::google::datastore::v1::PartitionId::internal_default_instance());
::google::datastore::v1::_RunQueryRequest_default_instance_._instance.get_mutable()->read_options_ = const_cast< ::google::datastore::v1::ReadOptions*>(
::google::datastore::v1::ReadOptions::internal_default_instance());
::google::datastore::v1::_RunQueryRequest_default_instance_.query_ = const_cast< ::google::datastore::v1::Query*>(
::google::datastore::v1::Query::internal_default_instance());
::google::datastore::v1::_RunQueryRequest_default_instance_.gql_query_ = const_cast< ::google::datastore::v1::GqlQuery*>(
::google::datastore::v1::GqlQuery::internal_default_instance());
}
class RunQueryRequest::HasBitSetters {
public:
static const ::google::datastore::v1::PartitionId& partition_id(const RunQueryRequest* msg);
static const ::google::datastore::v1::ReadOptions& read_options(const RunQueryRequest* msg);
static const ::google::datastore::v1::Query& query(const RunQueryRequest* msg);
static const ::google::datastore::v1::GqlQuery& gql_query(const RunQueryRequest* msg);
};
const ::google::datastore::v1::PartitionId&
RunQueryRequest::HasBitSetters::partition_id(const RunQueryRequest* msg) {
return *msg->partition_id_;
}
const ::google::datastore::v1::ReadOptions&
RunQueryRequest::HasBitSetters::read_options(const RunQueryRequest* msg) {
return *msg->read_options_;
}
const ::google::datastore::v1::Query&
RunQueryRequest::HasBitSetters::query(const RunQueryRequest* msg) {
return *msg->query_type_.query_;
}
const ::google::datastore::v1::GqlQuery&
RunQueryRequest::HasBitSetters::gql_query(const RunQueryRequest* msg) {
return *msg->query_type_.gql_query_;
}
void RunQueryRequest::clear_partition_id() {
if (GetArenaNoVirtual() == nullptr && partition_id_ != nullptr) {
delete partition_id_;
}
partition_id_ = nullptr;
}
void RunQueryRequest::set_allocated_query(::google::datastore::v1::Query* query) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
clear_query_type();
if (query) {
::google::protobuf::Arena* submessage_arena = nullptr;
if (message_arena != submessage_arena) {
query = ::google::protobuf::internal::GetOwnedMessage(
message_arena, query, submessage_arena);
}
set_has_query();
query_type_.query_ = query;
}
// @@protoc_insertion_point(field_set_allocated:google.datastore.v1.RunQueryRequest.query)
}
void RunQueryRequest::clear_query() {
if (has_query()) {
delete query_type_.query_;
clear_has_query_type();
}
}
void RunQueryRequest::set_allocated_gql_query(::google::datastore::v1::GqlQuery* gql_query) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
clear_query_type();
if (gql_query) {
::google::protobuf::Arena* submessage_arena = nullptr;
if (message_arena != submessage_arena) {
gql_query = ::google::protobuf::internal::GetOwnedMessage(
message_arena, gql_query, submessage_arena);
}
set_has_gql_query();
query_type_.gql_query_ = gql_query;
}
// @@protoc_insertion_point(field_set_allocated:google.datastore.v1.RunQueryRequest.gql_query)
}
void RunQueryRequest::clear_gql_query() {
if (has_gql_query()) {
delete query_type_.gql_query_;
clear_has_query_type();
}
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int RunQueryRequest::kProjectIdFieldNumber;
const int RunQueryRequest::kPartitionIdFieldNumber;
const int RunQueryRequest::kReadOptionsFieldNumber;
const int RunQueryRequest::kQueryFieldNumber;
const int RunQueryRequest::kGqlQueryFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
RunQueryRequest::RunQueryRequest()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:google.datastore.v1.RunQueryRequest)
}
RunQueryRequest::RunQueryRequest(const RunQueryRequest& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
project_id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.project_id().size() > 0) {
project_id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.project_id_);
}
if (from.has_read_options()) {
read_options_ = new ::google::datastore::v1::ReadOptions(*from.read_options_);
} else {
read_options_ = nullptr;
}
if (from.has_partition_id()) {
partition_id_ = new ::google::datastore::v1::PartitionId(*from.partition_id_);
} else {
partition_id_ = nullptr;
}
clear_has_query_type();
switch (from.query_type_case()) {
case kQuery: {
mutable_query()->::google::datastore::v1::Query::MergeFrom(from.query());
break;
}
case kGqlQuery: {
mutable_gql_query()->::google::datastore::v1::GqlQuery::MergeFrom(from.gql_query());
break;
}
case QUERY_TYPE_NOT_SET: {
break;
}
}
// @@protoc_insertion_point(copy_constructor:google.datastore.v1.RunQueryRequest)
}
void RunQueryRequest::SharedCtor() {
::google::protobuf::internal::InitSCC(
&scc_info_RunQueryRequest_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
project_id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
::memset(&read_options_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&partition_id_) -
reinterpret_cast<char*>(&read_options_)) + sizeof(partition_id_));
clear_has_query_type();
}
RunQueryRequest::~RunQueryRequest() {
// @@protoc_insertion_point(destructor:google.datastore.v1.RunQueryRequest)
SharedDtor();
}
void RunQueryRequest::SharedDtor() {
project_id_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (this != internal_default_instance()) delete read_options_;
if (this != internal_default_instance()) delete partition_id_;
if (has_query_type()) {
clear_query_type();
}
}
void RunQueryRequest::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const RunQueryRequest& RunQueryRequest::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_RunQueryRequest_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
return *internal_default_instance();
}
void RunQueryRequest::clear_query_type() {
// @@protoc_insertion_point(one_of_clear_start:google.datastore.v1.RunQueryRequest)
switch (query_type_case()) {
case kQuery: {
delete query_type_.query_;
break;
}
case kGqlQuery: {
delete query_type_.gql_query_;
break;
}
case QUERY_TYPE_NOT_SET: {
break;
}
}
_oneof_case_[0] = QUERY_TYPE_NOT_SET;
}
void RunQueryRequest::Clear() {
// @@protoc_insertion_point(message_clear_start:google.datastore.v1.RunQueryRequest)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
project_id_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (GetArenaNoVirtual() == nullptr && read_options_ != nullptr) {
delete read_options_;
}
read_options_ = nullptr;
if (GetArenaNoVirtual() == nullptr && partition_id_ != nullptr) {
delete partition_id_;
}
partition_id_ = nullptr;
clear_query_type();
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* RunQueryRequest::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<RunQueryRequest*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// .google.datastore.v1.ReadOptions read_options = 1;
case 1: {
if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::datastore::v1::ReadOptions::_InternalParse;
object = msg->mutable_read_options();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
break;
}
// .google.datastore.v1.PartitionId partition_id = 2;
case 2: {
if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::datastore::v1::PartitionId::_InternalParse;
object = msg->mutable_partition_id();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
break;
}
// .google.datastore.v1.Query query = 3;
case 3: {
if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::datastore::v1::Query::_InternalParse;
object = msg->mutable_query();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
break;
}
// .google.datastore.v1.GqlQuery gql_query = 7;
case 7: {
if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::datastore::v1::GqlQuery::_InternalParse;
object = msg->mutable_gql_query();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
break;
}
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
case 8: {
if (static_cast<::google::protobuf::uint8>(tag) != 66) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
ctx->extra_parse_data().SetFieldName("google.datastore.v1.RunQueryRequest.project_id");
object = msg->mutable_project_id();
if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) {
parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8;
goto string_till_end;
}
GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx));
::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx);
ptr += size;
break;
}
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
string_till_end:
static_cast<::std::string*>(object)->clear();
static_cast<::std::string*>(object)->reserve(size);
goto len_delim_till_end;
len_delim_till_end:
return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
{parser_till_end, object}, size);
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool RunQueryRequest::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.datastore.v1.RunQueryRequest)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .google.datastore.v1.ReadOptions read_options = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_read_options()));
} else {
goto handle_unusual;
}
break;
}
// .google.datastore.v1.PartitionId partition_id = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_partition_id()));
} else {
goto handle_unusual;
}
break;
}
// .google.datastore.v1.Query query = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_query()));
} else {
goto handle_unusual;
}
break;
}
// .google.datastore.v1.GqlQuery gql_query = 7;
case 7: {
if (static_cast< ::google::protobuf::uint8>(tag) == (58 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_gql_query()));
} else {
goto handle_unusual;
}
break;
}
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
case 8: {
if (static_cast< ::google::protobuf::uint8>(tag) == (66 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_project_id()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->project_id().data(), static_cast<int>(this->project_id().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.datastore.v1.RunQueryRequest.project_id"));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:google.datastore.v1.RunQueryRequest)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.datastore.v1.RunQueryRequest)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void RunQueryRequest::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.datastore.v1.RunQueryRequest)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .google.datastore.v1.ReadOptions read_options = 1;
if (this->has_read_options()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, HasBitSetters::read_options(this), output);
}
// .google.datastore.v1.PartitionId partition_id = 2;
if (this->has_partition_id()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2, HasBitSetters::partition_id(this), output);
}
// .google.datastore.v1.Query query = 3;
if (has_query()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3, HasBitSetters::query(this), output);
}
// .google.datastore.v1.GqlQuery gql_query = 7;
if (has_gql_query()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
7, HasBitSetters::gql_query(this), output);
}
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
if (this->project_id().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->project_id().data(), static_cast<int>(this->project_id().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.datastore.v1.RunQueryRequest.project_id");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
8, this->project_id(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.datastore.v1.RunQueryRequest)
}
::google::protobuf::uint8* RunQueryRequest::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:google.datastore.v1.RunQueryRequest)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .google.datastore.v1.ReadOptions read_options = 1;
if (this->has_read_options()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
1, HasBitSetters::read_options(this), target);
}
// .google.datastore.v1.PartitionId partition_id = 2;
if (this->has_partition_id()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
2, HasBitSetters::partition_id(this), target);
}
// .google.datastore.v1.Query query = 3;
if (has_query()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
3, HasBitSetters::query(this), target);
}
// .google.datastore.v1.GqlQuery gql_query = 7;
if (has_gql_query()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
7, HasBitSetters::gql_query(this), target);
}
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
if (this->project_id().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->project_id().data(), static_cast<int>(this->project_id().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.datastore.v1.RunQueryRequest.project_id");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
8, this->project_id(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.datastore.v1.RunQueryRequest)
return target;
}
size_t RunQueryRequest::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.datastore.v1.RunQueryRequest)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
if (this->project_id().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->project_id());
}
// .google.datastore.v1.ReadOptions read_options = 1;
if (this->has_read_options()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*read_options_);
}
// .google.datastore.v1.PartitionId partition_id = 2;
if (this->has_partition_id()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*partition_id_);
}
switch (query_type_case()) {
// .google.datastore.v1.Query query = 3;
case kQuery: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*query_type_.query_);
break;
}
// .google.datastore.v1.GqlQuery gql_query = 7;
case kGqlQuery: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*query_type_.gql_query_);
break;
}
case QUERY_TYPE_NOT_SET: {
break;
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void RunQueryRequest::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.datastore.v1.RunQueryRequest)
GOOGLE_DCHECK_NE(&from, this);
const RunQueryRequest* source =
::google::protobuf::DynamicCastToGenerated<RunQueryRequest>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.datastore.v1.RunQueryRequest)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.datastore.v1.RunQueryRequest)
MergeFrom(*source);
}
}
void RunQueryRequest::MergeFrom(const RunQueryRequest& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.datastore.v1.RunQueryRequest)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.project_id().size() > 0) {
project_id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.project_id_);
}
if (from.has_read_options()) {
mutable_read_options()->::google::datastore::v1::ReadOptions::MergeFrom(from.read_options());
}
if (from.has_partition_id()) {
mutable_partition_id()->::google::datastore::v1::PartitionId::MergeFrom(from.partition_id());
}
switch (from.query_type_case()) {
case kQuery: {
mutable_query()->::google::datastore::v1::Query::MergeFrom(from.query());
break;
}
case kGqlQuery: {
mutable_gql_query()->::google::datastore::v1::GqlQuery::MergeFrom(from.gql_query());
break;
}
case QUERY_TYPE_NOT_SET: {
break;
}
}
}
void RunQueryRequest::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.datastore.v1.RunQueryRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void RunQueryRequest::CopyFrom(const RunQueryRequest& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.datastore.v1.RunQueryRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool RunQueryRequest::IsInitialized() const {
return true;
}
void RunQueryRequest::Swap(RunQueryRequest* other) {
if (other == this) return;
InternalSwap(other);
}
void RunQueryRequest::InternalSwap(RunQueryRequest* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
project_id_.Swap(&other->project_id_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
swap(read_options_, other->read_options_);
swap(partition_id_, other->partition_id_);
swap(query_type_, other->query_type_);
swap(_oneof_case_[0], other->_oneof_case_[0]);
}
::google::protobuf::Metadata RunQueryRequest::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fdatastore_2fv1_2fdatastore_2eproto);
return ::file_level_metadata_google_2fdatastore_2fv1_2fdatastore_2eproto[kIndexInFileMessages];
}
// ===================================================================
void RunQueryResponse::InitAsDefaultInstance() {
::google::datastore::v1::_RunQueryResponse_default_instance_._instance.get_mutable()->batch_ = const_cast< ::google::datastore::v1::QueryResultBatch*>(
::google::datastore::v1::QueryResultBatch::internal_default_instance());
::google::datastore::v1::_RunQueryResponse_default_instance_._instance.get_mutable()->query_ = const_cast< ::google::datastore::v1::Query*>(
::google::datastore::v1::Query::internal_default_instance());
}
class RunQueryResponse::HasBitSetters {
public:
static const ::google::datastore::v1::QueryResultBatch& batch(const RunQueryResponse* msg);
static const ::google::datastore::v1::Query& query(const RunQueryResponse* msg);
};
const ::google::datastore::v1::QueryResultBatch&
RunQueryResponse::HasBitSetters::batch(const RunQueryResponse* msg) {
return *msg->batch_;
}
const ::google::datastore::v1::Query&
RunQueryResponse::HasBitSetters::query(const RunQueryResponse* msg) {
return *msg->query_;
}
void RunQueryResponse::clear_batch() {
if (GetArenaNoVirtual() == nullptr && batch_ != nullptr) {
delete batch_;
}
batch_ = nullptr;
}
void RunQueryResponse::clear_query() {
if (GetArenaNoVirtual() == nullptr && query_ != nullptr) {
delete query_;
}
query_ = nullptr;
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int RunQueryResponse::kBatchFieldNumber;
const int RunQueryResponse::kQueryFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
RunQueryResponse::RunQueryResponse()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:google.datastore.v1.RunQueryResponse)
}
RunQueryResponse::RunQueryResponse(const RunQueryResponse& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from.has_batch()) {
batch_ = new ::google::datastore::v1::QueryResultBatch(*from.batch_);
} else {
batch_ = nullptr;
}
if (from.has_query()) {
query_ = new ::google::datastore::v1::Query(*from.query_);
} else {
query_ = nullptr;
}
// @@protoc_insertion_point(copy_constructor:google.datastore.v1.RunQueryResponse)
}
void RunQueryResponse::SharedCtor() {
::google::protobuf::internal::InitSCC(
&scc_info_RunQueryResponse_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
::memset(&batch_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&query_) -
reinterpret_cast<char*>(&batch_)) + sizeof(query_));
}
RunQueryResponse::~RunQueryResponse() {
// @@protoc_insertion_point(destructor:google.datastore.v1.RunQueryResponse)
SharedDtor();
}
void RunQueryResponse::SharedDtor() {
if (this != internal_default_instance()) delete batch_;
if (this != internal_default_instance()) delete query_;
}
void RunQueryResponse::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const RunQueryResponse& RunQueryResponse::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_RunQueryResponse_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
return *internal_default_instance();
}
void RunQueryResponse::Clear() {
// @@protoc_insertion_point(message_clear_start:google.datastore.v1.RunQueryResponse)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
if (GetArenaNoVirtual() == nullptr && batch_ != nullptr) {
delete batch_;
}
batch_ = nullptr;
if (GetArenaNoVirtual() == nullptr && query_ != nullptr) {
delete query_;
}
query_ = nullptr;
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* RunQueryResponse::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<RunQueryResponse*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// .google.datastore.v1.QueryResultBatch batch = 1;
case 1: {
if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::datastore::v1::QueryResultBatch::_InternalParse;
object = msg->mutable_batch();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
break;
}
// .google.datastore.v1.Query query = 2;
case 2: {
if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::datastore::v1::Query::_InternalParse;
object = msg->mutable_query();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
break;
}
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
len_delim_till_end:
return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
{parser_till_end, object}, size);
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool RunQueryResponse::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.datastore.v1.RunQueryResponse)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .google.datastore.v1.QueryResultBatch batch = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_batch()));
} else {
goto handle_unusual;
}
break;
}
// .google.datastore.v1.Query query = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_query()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:google.datastore.v1.RunQueryResponse)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.datastore.v1.RunQueryResponse)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void RunQueryResponse::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.datastore.v1.RunQueryResponse)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .google.datastore.v1.QueryResultBatch batch = 1;
if (this->has_batch()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, HasBitSetters::batch(this), output);
}
// .google.datastore.v1.Query query = 2;
if (this->has_query()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2, HasBitSetters::query(this), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.datastore.v1.RunQueryResponse)
}
::google::protobuf::uint8* RunQueryResponse::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:google.datastore.v1.RunQueryResponse)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .google.datastore.v1.QueryResultBatch batch = 1;
if (this->has_batch()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
1, HasBitSetters::batch(this), target);
}
// .google.datastore.v1.Query query = 2;
if (this->has_query()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
2, HasBitSetters::query(this), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.datastore.v1.RunQueryResponse)
return target;
}
size_t RunQueryResponse::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.datastore.v1.RunQueryResponse)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// .google.datastore.v1.QueryResultBatch batch = 1;
if (this->has_batch()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*batch_);
}
// .google.datastore.v1.Query query = 2;
if (this->has_query()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*query_);
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void RunQueryResponse::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.datastore.v1.RunQueryResponse)
GOOGLE_DCHECK_NE(&from, this);
const RunQueryResponse* source =
::google::protobuf::DynamicCastToGenerated<RunQueryResponse>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.datastore.v1.RunQueryResponse)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.datastore.v1.RunQueryResponse)
MergeFrom(*source);
}
}
void RunQueryResponse::MergeFrom(const RunQueryResponse& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.datastore.v1.RunQueryResponse)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.has_batch()) {
mutable_batch()->::google::datastore::v1::QueryResultBatch::MergeFrom(from.batch());
}
if (from.has_query()) {
mutable_query()->::google::datastore::v1::Query::MergeFrom(from.query());
}
}
void RunQueryResponse::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.datastore.v1.RunQueryResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void RunQueryResponse::CopyFrom(const RunQueryResponse& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.datastore.v1.RunQueryResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool RunQueryResponse::IsInitialized() const {
return true;
}
void RunQueryResponse::Swap(RunQueryResponse* other) {
if (other == this) return;
InternalSwap(other);
}
void RunQueryResponse::InternalSwap(RunQueryResponse* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(batch_, other->batch_);
swap(query_, other->query_);
}
::google::protobuf::Metadata RunQueryResponse::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fdatastore_2fv1_2fdatastore_2eproto);
return ::file_level_metadata_google_2fdatastore_2fv1_2fdatastore_2eproto[kIndexInFileMessages];
}
// ===================================================================
void BeginTransactionRequest::InitAsDefaultInstance() {
::google::datastore::v1::_BeginTransactionRequest_default_instance_._instance.get_mutable()->transaction_options_ = const_cast< ::google::datastore::v1::TransactionOptions*>(
::google::datastore::v1::TransactionOptions::internal_default_instance());
}
class BeginTransactionRequest::HasBitSetters {
public:
static const ::google::datastore::v1::TransactionOptions& transaction_options(const BeginTransactionRequest* msg);
};
const ::google::datastore::v1::TransactionOptions&
BeginTransactionRequest::HasBitSetters::transaction_options(const BeginTransactionRequest* msg) {
return *msg->transaction_options_;
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int BeginTransactionRequest::kProjectIdFieldNumber;
const int BeginTransactionRequest::kTransactionOptionsFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
BeginTransactionRequest::BeginTransactionRequest()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:google.datastore.v1.BeginTransactionRequest)
}
BeginTransactionRequest::BeginTransactionRequest(const BeginTransactionRequest& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
project_id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.project_id().size() > 0) {
project_id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.project_id_);
}
if (from.has_transaction_options()) {
transaction_options_ = new ::google::datastore::v1::TransactionOptions(*from.transaction_options_);
} else {
transaction_options_ = nullptr;
}
// @@protoc_insertion_point(copy_constructor:google.datastore.v1.BeginTransactionRequest)
}
void BeginTransactionRequest::SharedCtor() {
::google::protobuf::internal::InitSCC(
&scc_info_BeginTransactionRequest_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
project_id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
transaction_options_ = nullptr;
}
BeginTransactionRequest::~BeginTransactionRequest() {
// @@protoc_insertion_point(destructor:google.datastore.v1.BeginTransactionRequest)
SharedDtor();
}
void BeginTransactionRequest::SharedDtor() {
project_id_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (this != internal_default_instance()) delete transaction_options_;
}
void BeginTransactionRequest::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const BeginTransactionRequest& BeginTransactionRequest::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_BeginTransactionRequest_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
return *internal_default_instance();
}
void BeginTransactionRequest::Clear() {
// @@protoc_insertion_point(message_clear_start:google.datastore.v1.BeginTransactionRequest)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
project_id_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (GetArenaNoVirtual() == nullptr && transaction_options_ != nullptr) {
delete transaction_options_;
}
transaction_options_ = nullptr;
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* BeginTransactionRequest::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<BeginTransactionRequest*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
case 8: {
if (static_cast<::google::protobuf::uint8>(tag) != 66) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
ctx->extra_parse_data().SetFieldName("google.datastore.v1.BeginTransactionRequest.project_id");
object = msg->mutable_project_id();
if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) {
parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8;
goto string_till_end;
}
GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx));
::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx);
ptr += size;
break;
}
// .google.datastore.v1.TransactionOptions transaction_options = 10;
case 10: {
if (static_cast<::google::protobuf::uint8>(tag) != 82) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::datastore::v1::TransactionOptions::_InternalParse;
object = msg->mutable_transaction_options();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
break;
}
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
string_till_end:
static_cast<::std::string*>(object)->clear();
static_cast<::std::string*>(object)->reserve(size);
goto len_delim_till_end;
len_delim_till_end:
return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
{parser_till_end, object}, size);
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool BeginTransactionRequest::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.datastore.v1.BeginTransactionRequest)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
case 8: {
if (static_cast< ::google::protobuf::uint8>(tag) == (66 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_project_id()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->project_id().data(), static_cast<int>(this->project_id().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.datastore.v1.BeginTransactionRequest.project_id"));
} else {
goto handle_unusual;
}
break;
}
// .google.datastore.v1.TransactionOptions transaction_options = 10;
case 10: {
if (static_cast< ::google::protobuf::uint8>(tag) == (82 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_transaction_options()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:google.datastore.v1.BeginTransactionRequest)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.datastore.v1.BeginTransactionRequest)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void BeginTransactionRequest::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.datastore.v1.BeginTransactionRequest)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
if (this->project_id().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->project_id().data(), static_cast<int>(this->project_id().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.datastore.v1.BeginTransactionRequest.project_id");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
8, this->project_id(), output);
}
// .google.datastore.v1.TransactionOptions transaction_options = 10;
if (this->has_transaction_options()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
10, HasBitSetters::transaction_options(this), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.datastore.v1.BeginTransactionRequest)
}
::google::protobuf::uint8* BeginTransactionRequest::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:google.datastore.v1.BeginTransactionRequest)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
if (this->project_id().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->project_id().data(), static_cast<int>(this->project_id().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.datastore.v1.BeginTransactionRequest.project_id");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
8, this->project_id(), target);
}
// .google.datastore.v1.TransactionOptions transaction_options = 10;
if (this->has_transaction_options()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
10, HasBitSetters::transaction_options(this), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.datastore.v1.BeginTransactionRequest)
return target;
}
size_t BeginTransactionRequest::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.datastore.v1.BeginTransactionRequest)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
if (this->project_id().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->project_id());
}
// .google.datastore.v1.TransactionOptions transaction_options = 10;
if (this->has_transaction_options()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*transaction_options_);
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void BeginTransactionRequest::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.datastore.v1.BeginTransactionRequest)
GOOGLE_DCHECK_NE(&from, this);
const BeginTransactionRequest* source =
::google::protobuf::DynamicCastToGenerated<BeginTransactionRequest>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.datastore.v1.BeginTransactionRequest)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.datastore.v1.BeginTransactionRequest)
MergeFrom(*source);
}
}
void BeginTransactionRequest::MergeFrom(const BeginTransactionRequest& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.datastore.v1.BeginTransactionRequest)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.project_id().size() > 0) {
project_id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.project_id_);
}
if (from.has_transaction_options()) {
mutable_transaction_options()->::google::datastore::v1::TransactionOptions::MergeFrom(from.transaction_options());
}
}
void BeginTransactionRequest::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.datastore.v1.BeginTransactionRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void BeginTransactionRequest::CopyFrom(const BeginTransactionRequest& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.datastore.v1.BeginTransactionRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool BeginTransactionRequest::IsInitialized() const {
return true;
}
void BeginTransactionRequest::Swap(BeginTransactionRequest* other) {
if (other == this) return;
InternalSwap(other);
}
void BeginTransactionRequest::InternalSwap(BeginTransactionRequest* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
project_id_.Swap(&other->project_id_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
swap(transaction_options_, other->transaction_options_);
}
::google::protobuf::Metadata BeginTransactionRequest::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fdatastore_2fv1_2fdatastore_2eproto);
return ::file_level_metadata_google_2fdatastore_2fv1_2fdatastore_2eproto[kIndexInFileMessages];
}
// ===================================================================
void BeginTransactionResponse::InitAsDefaultInstance() {
}
class BeginTransactionResponse::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int BeginTransactionResponse::kTransactionFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
BeginTransactionResponse::BeginTransactionResponse()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:google.datastore.v1.BeginTransactionResponse)
}
BeginTransactionResponse::BeginTransactionResponse(const BeginTransactionResponse& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
transaction_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.transaction().size() > 0) {
transaction_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.transaction_);
}
// @@protoc_insertion_point(copy_constructor:google.datastore.v1.BeginTransactionResponse)
}
void BeginTransactionResponse::SharedCtor() {
::google::protobuf::internal::InitSCC(
&scc_info_BeginTransactionResponse_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
transaction_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
BeginTransactionResponse::~BeginTransactionResponse() {
// @@protoc_insertion_point(destructor:google.datastore.v1.BeginTransactionResponse)
SharedDtor();
}
void BeginTransactionResponse::SharedDtor() {
transaction_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void BeginTransactionResponse::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const BeginTransactionResponse& BeginTransactionResponse::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_BeginTransactionResponse_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
return *internal_default_instance();
}
void BeginTransactionResponse::Clear() {
// @@protoc_insertion_point(message_clear_start:google.datastore.v1.BeginTransactionResponse)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
transaction_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* BeginTransactionResponse::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<BeginTransactionResponse*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// bytes transaction = 1;
case 1: {
if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
object = msg->mutable_transaction();
if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) {
parser_till_end = ::google::protobuf::internal::GreedyStringParser;
goto string_till_end;
}
GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheck(ptr, size, ctx));
::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx);
ptr += size;
break;
}
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
string_till_end:
static_cast<::std::string*>(object)->clear();
static_cast<::std::string*>(object)->reserve(size);
goto len_delim_till_end;
len_delim_till_end:
return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
{parser_till_end, object}, size);
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool BeginTransactionResponse::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.datastore.v1.BeginTransactionResponse)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// bytes transaction = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadBytes(
input, this->mutable_transaction()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:google.datastore.v1.BeginTransactionResponse)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.datastore.v1.BeginTransactionResponse)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void BeginTransactionResponse::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.datastore.v1.BeginTransactionResponse)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// bytes transaction = 1;
if (this->transaction().size() > 0) {
::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased(
1, this->transaction(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.datastore.v1.BeginTransactionResponse)
}
::google::protobuf::uint8* BeginTransactionResponse::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:google.datastore.v1.BeginTransactionResponse)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// bytes transaction = 1;
if (this->transaction().size() > 0) {
target =
::google::protobuf::internal::WireFormatLite::WriteBytesToArray(
1, this->transaction(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.datastore.v1.BeginTransactionResponse)
return target;
}
size_t BeginTransactionResponse::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.datastore.v1.BeginTransactionResponse)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// bytes transaction = 1;
if (this->transaction().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::BytesSize(
this->transaction());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void BeginTransactionResponse::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.datastore.v1.BeginTransactionResponse)
GOOGLE_DCHECK_NE(&from, this);
const BeginTransactionResponse* source =
::google::protobuf::DynamicCastToGenerated<BeginTransactionResponse>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.datastore.v1.BeginTransactionResponse)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.datastore.v1.BeginTransactionResponse)
MergeFrom(*source);
}
}
void BeginTransactionResponse::MergeFrom(const BeginTransactionResponse& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.datastore.v1.BeginTransactionResponse)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.transaction().size() > 0) {
transaction_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.transaction_);
}
}
void BeginTransactionResponse::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.datastore.v1.BeginTransactionResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void BeginTransactionResponse::CopyFrom(const BeginTransactionResponse& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.datastore.v1.BeginTransactionResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool BeginTransactionResponse::IsInitialized() const {
return true;
}
void BeginTransactionResponse::Swap(BeginTransactionResponse* other) {
if (other == this) return;
InternalSwap(other);
}
void BeginTransactionResponse::InternalSwap(BeginTransactionResponse* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
transaction_.Swap(&other->transaction_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
::google::protobuf::Metadata BeginTransactionResponse::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fdatastore_2fv1_2fdatastore_2eproto);
return ::file_level_metadata_google_2fdatastore_2fv1_2fdatastore_2eproto[kIndexInFileMessages];
}
// ===================================================================
void RollbackRequest::InitAsDefaultInstance() {
}
class RollbackRequest::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int RollbackRequest::kProjectIdFieldNumber;
const int RollbackRequest::kTransactionFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
RollbackRequest::RollbackRequest()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:google.datastore.v1.RollbackRequest)
}
RollbackRequest::RollbackRequest(const RollbackRequest& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
transaction_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.transaction().size() > 0) {
transaction_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.transaction_);
}
project_id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.project_id().size() > 0) {
project_id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.project_id_);
}
// @@protoc_insertion_point(copy_constructor:google.datastore.v1.RollbackRequest)
}
void RollbackRequest::SharedCtor() {
::google::protobuf::internal::InitSCC(
&scc_info_RollbackRequest_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
transaction_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
project_id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
RollbackRequest::~RollbackRequest() {
// @@protoc_insertion_point(destructor:google.datastore.v1.RollbackRequest)
SharedDtor();
}
void RollbackRequest::SharedDtor() {
transaction_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
project_id_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void RollbackRequest::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const RollbackRequest& RollbackRequest::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_RollbackRequest_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
return *internal_default_instance();
}
void RollbackRequest::Clear() {
// @@protoc_insertion_point(message_clear_start:google.datastore.v1.RollbackRequest)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
transaction_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
project_id_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* RollbackRequest::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<RollbackRequest*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// bytes transaction = 1 [(.google.api.field_behavior) = REQUIRED];
case 1: {
if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
object = msg->mutable_transaction();
if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) {
parser_till_end = ::google::protobuf::internal::GreedyStringParser;
goto string_till_end;
}
GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheck(ptr, size, ctx));
::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx);
ptr += size;
break;
}
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
case 8: {
if (static_cast<::google::protobuf::uint8>(tag) != 66) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
ctx->extra_parse_data().SetFieldName("google.datastore.v1.RollbackRequest.project_id");
object = msg->mutable_project_id();
if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) {
parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8;
goto string_till_end;
}
GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx));
::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx);
ptr += size;
break;
}
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
string_till_end:
static_cast<::std::string*>(object)->clear();
static_cast<::std::string*>(object)->reserve(size);
goto len_delim_till_end;
len_delim_till_end:
return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
{parser_till_end, object}, size);
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool RollbackRequest::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.datastore.v1.RollbackRequest)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// bytes transaction = 1 [(.google.api.field_behavior) = REQUIRED];
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadBytes(
input, this->mutable_transaction()));
} else {
goto handle_unusual;
}
break;
}
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
case 8: {
if (static_cast< ::google::protobuf::uint8>(tag) == (66 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_project_id()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->project_id().data(), static_cast<int>(this->project_id().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.datastore.v1.RollbackRequest.project_id"));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:google.datastore.v1.RollbackRequest)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.datastore.v1.RollbackRequest)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void RollbackRequest::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.datastore.v1.RollbackRequest)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// bytes transaction = 1 [(.google.api.field_behavior) = REQUIRED];
if (this->transaction().size() > 0) {
::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased(
1, this->transaction(), output);
}
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
if (this->project_id().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->project_id().data(), static_cast<int>(this->project_id().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.datastore.v1.RollbackRequest.project_id");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
8, this->project_id(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.datastore.v1.RollbackRequest)
}
::google::protobuf::uint8* RollbackRequest::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:google.datastore.v1.RollbackRequest)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// bytes transaction = 1 [(.google.api.field_behavior) = REQUIRED];
if (this->transaction().size() > 0) {
target =
::google::protobuf::internal::WireFormatLite::WriteBytesToArray(
1, this->transaction(), target);
}
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
if (this->project_id().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->project_id().data(), static_cast<int>(this->project_id().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.datastore.v1.RollbackRequest.project_id");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
8, this->project_id(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.datastore.v1.RollbackRequest)
return target;
}
size_t RollbackRequest::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.datastore.v1.RollbackRequest)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// bytes transaction = 1 [(.google.api.field_behavior) = REQUIRED];
if (this->transaction().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::BytesSize(
this->transaction());
}
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
if (this->project_id().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->project_id());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void RollbackRequest::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.datastore.v1.RollbackRequest)
GOOGLE_DCHECK_NE(&from, this);
const RollbackRequest* source =
::google::protobuf::DynamicCastToGenerated<RollbackRequest>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.datastore.v1.RollbackRequest)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.datastore.v1.RollbackRequest)
MergeFrom(*source);
}
}
void RollbackRequest::MergeFrom(const RollbackRequest& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.datastore.v1.RollbackRequest)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.transaction().size() > 0) {
transaction_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.transaction_);
}
if (from.project_id().size() > 0) {
project_id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.project_id_);
}
}
void RollbackRequest::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.datastore.v1.RollbackRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void RollbackRequest::CopyFrom(const RollbackRequest& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.datastore.v1.RollbackRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool RollbackRequest::IsInitialized() const {
return true;
}
void RollbackRequest::Swap(RollbackRequest* other) {
if (other == this) return;
InternalSwap(other);
}
void RollbackRequest::InternalSwap(RollbackRequest* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
transaction_.Swap(&other->transaction_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
project_id_.Swap(&other->project_id_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
::google::protobuf::Metadata RollbackRequest::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fdatastore_2fv1_2fdatastore_2eproto);
return ::file_level_metadata_google_2fdatastore_2fv1_2fdatastore_2eproto[kIndexInFileMessages];
}
// ===================================================================
void RollbackResponse::InitAsDefaultInstance() {
}
class RollbackResponse::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
RollbackResponse::RollbackResponse()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:google.datastore.v1.RollbackResponse)
}
RollbackResponse::RollbackResponse(const RollbackResponse& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:google.datastore.v1.RollbackResponse)
}
void RollbackResponse::SharedCtor() {
}
RollbackResponse::~RollbackResponse() {
// @@protoc_insertion_point(destructor:google.datastore.v1.RollbackResponse)
SharedDtor();
}
void RollbackResponse::SharedDtor() {
}
void RollbackResponse::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const RollbackResponse& RollbackResponse::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_RollbackResponse_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
return *internal_default_instance();
}
void RollbackResponse::Clear() {
// @@protoc_insertion_point(message_clear_start:google.datastore.v1.RollbackResponse)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* RollbackResponse::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<RollbackResponse*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
default: {
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool RollbackResponse::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.datastore.v1.RollbackResponse)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
}
success:
// @@protoc_insertion_point(parse_success:google.datastore.v1.RollbackResponse)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.datastore.v1.RollbackResponse)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void RollbackResponse::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.datastore.v1.RollbackResponse)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.datastore.v1.RollbackResponse)
}
::google::protobuf::uint8* RollbackResponse::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:google.datastore.v1.RollbackResponse)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.datastore.v1.RollbackResponse)
return target;
}
size_t RollbackResponse::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.datastore.v1.RollbackResponse)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void RollbackResponse::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.datastore.v1.RollbackResponse)
GOOGLE_DCHECK_NE(&from, this);
const RollbackResponse* source =
::google::protobuf::DynamicCastToGenerated<RollbackResponse>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.datastore.v1.RollbackResponse)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.datastore.v1.RollbackResponse)
MergeFrom(*source);
}
}
void RollbackResponse::MergeFrom(const RollbackResponse& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.datastore.v1.RollbackResponse)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
}
void RollbackResponse::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.datastore.v1.RollbackResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void RollbackResponse::CopyFrom(const RollbackResponse& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.datastore.v1.RollbackResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool RollbackResponse::IsInitialized() const {
return true;
}
void RollbackResponse::Swap(RollbackResponse* other) {
if (other == this) return;
InternalSwap(other);
}
void RollbackResponse::InternalSwap(RollbackResponse* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata RollbackResponse::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fdatastore_2fv1_2fdatastore_2eproto);
return ::file_level_metadata_google_2fdatastore_2fv1_2fdatastore_2eproto[kIndexInFileMessages];
}
// ===================================================================
void CommitRequest::InitAsDefaultInstance() {
::google::datastore::v1::_CommitRequest_default_instance_.transaction_.UnsafeSetDefault(
&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
class CommitRequest::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int CommitRequest::kProjectIdFieldNumber;
const int CommitRequest::kModeFieldNumber;
const int CommitRequest::kTransactionFieldNumber;
const int CommitRequest::kMutationsFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
CommitRequest::CommitRequest()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:google.datastore.v1.CommitRequest)
}
CommitRequest::CommitRequest(const CommitRequest& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr),
mutations_(from.mutations_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
project_id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.project_id().size() > 0) {
project_id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.project_id_);
}
mode_ = from.mode_;
clear_has_transaction_selector();
switch (from.transaction_selector_case()) {
case kTransaction: {
set_transaction(from.transaction());
break;
}
case TRANSACTION_SELECTOR_NOT_SET: {
break;
}
}
// @@protoc_insertion_point(copy_constructor:google.datastore.v1.CommitRequest)
}
void CommitRequest::SharedCtor() {
::google::protobuf::internal::InitSCC(
&scc_info_CommitRequest_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
project_id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
mode_ = 0;
clear_has_transaction_selector();
}
CommitRequest::~CommitRequest() {
// @@protoc_insertion_point(destructor:google.datastore.v1.CommitRequest)
SharedDtor();
}
void CommitRequest::SharedDtor() {
project_id_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (has_transaction_selector()) {
clear_transaction_selector();
}
}
void CommitRequest::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const CommitRequest& CommitRequest::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_CommitRequest_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
return *internal_default_instance();
}
void CommitRequest::clear_transaction_selector() {
// @@protoc_insertion_point(one_of_clear_start:google.datastore.v1.CommitRequest)
switch (transaction_selector_case()) {
case kTransaction: {
transaction_selector_.transaction_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
break;
}
case TRANSACTION_SELECTOR_NOT_SET: {
break;
}
}
_oneof_case_[0] = TRANSACTION_SELECTOR_NOT_SET;
}
void CommitRequest::Clear() {
// @@protoc_insertion_point(message_clear_start:google.datastore.v1.CommitRequest)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
mutations_.Clear();
project_id_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
mode_ = 0;
clear_transaction_selector();
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* CommitRequest::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<CommitRequest*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// bytes transaction = 1;
case 1: {
if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
object = msg->mutable_transaction();
if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) {
parser_till_end = ::google::protobuf::internal::GreedyStringParser;
goto string_till_end;
}
GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheck(ptr, size, ctx));
::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx);
ptr += size;
break;
}
// .google.datastore.v1.CommitRequest.Mode mode = 5;
case 5: {
if (static_cast<::google::protobuf::uint8>(tag) != 40) goto handle_unusual;
::google::protobuf::uint64 val = ::google::protobuf::internal::ReadVarint(&ptr);
msg->set_mode(static_cast<::google::datastore::v1::CommitRequest_Mode>(val));
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
break;
}
// repeated .google.datastore.v1.Mutation mutations = 6;
case 6: {
if (static_cast<::google::protobuf::uint8>(tag) != 50) goto handle_unusual;
do {
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::datastore::v1::Mutation::_InternalParse;
object = msg->add_mutations();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
if (ptr >= end) break;
} while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 50 && (ptr += 1));
break;
}
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
case 8: {
if (static_cast<::google::protobuf::uint8>(tag) != 66) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
ctx->extra_parse_data().SetFieldName("google.datastore.v1.CommitRequest.project_id");
object = msg->mutable_project_id();
if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) {
parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8;
goto string_till_end;
}
GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx));
::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx);
ptr += size;
break;
}
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
string_till_end:
static_cast<::std::string*>(object)->clear();
static_cast<::std::string*>(object)->reserve(size);
goto len_delim_till_end;
len_delim_till_end:
return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
{parser_till_end, object}, size);
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool CommitRequest::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.datastore.v1.CommitRequest)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// bytes transaction = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadBytes(
input, this->mutable_transaction()));
} else {
goto handle_unusual;
}
break;
}
// .google.datastore.v1.CommitRequest.Mode mode = 5;
case 5: {
if (static_cast< ::google::protobuf::uint8>(tag) == (40 & 0xFF)) {
int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
set_mode(static_cast< ::google::datastore::v1::CommitRequest_Mode >(value));
} else {
goto handle_unusual;
}
break;
}
// repeated .google.datastore.v1.Mutation mutations = 6;
case 6: {
if (static_cast< ::google::protobuf::uint8>(tag) == (50 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_mutations()));
} else {
goto handle_unusual;
}
break;
}
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
case 8: {
if (static_cast< ::google::protobuf::uint8>(tag) == (66 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_project_id()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->project_id().data(), static_cast<int>(this->project_id().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.datastore.v1.CommitRequest.project_id"));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:google.datastore.v1.CommitRequest)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.datastore.v1.CommitRequest)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void CommitRequest::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.datastore.v1.CommitRequest)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// bytes transaction = 1;
if (has_transaction()) {
::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased(
1, this->transaction(), output);
}
// .google.datastore.v1.CommitRequest.Mode mode = 5;
if (this->mode() != 0) {
::google::protobuf::internal::WireFormatLite::WriteEnum(
5, this->mode(), output);
}
// repeated .google.datastore.v1.Mutation mutations = 6;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->mutations_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
6,
this->mutations(static_cast<int>(i)),
output);
}
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
if (this->project_id().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->project_id().data(), static_cast<int>(this->project_id().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.datastore.v1.CommitRequest.project_id");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
8, this->project_id(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.datastore.v1.CommitRequest)
}
::google::protobuf::uint8* CommitRequest::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:google.datastore.v1.CommitRequest)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// bytes transaction = 1;
if (has_transaction()) {
target =
::google::protobuf::internal::WireFormatLite::WriteBytesToArray(
1, this->transaction(), target);
}
// .google.datastore.v1.CommitRequest.Mode mode = 5;
if (this->mode() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(
5, this->mode(), target);
}
// repeated .google.datastore.v1.Mutation mutations = 6;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->mutations_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
6, this->mutations(static_cast<int>(i)), target);
}
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
if (this->project_id().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->project_id().data(), static_cast<int>(this->project_id().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.datastore.v1.CommitRequest.project_id");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
8, this->project_id(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.datastore.v1.CommitRequest)
return target;
}
size_t CommitRequest::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.datastore.v1.CommitRequest)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// repeated .google.datastore.v1.Mutation mutations = 6;
{
unsigned int count = static_cast<unsigned int>(this->mutations_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSize(
this->mutations(static_cast<int>(i)));
}
}
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
if (this->project_id().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->project_id());
}
// .google.datastore.v1.CommitRequest.Mode mode = 5;
if (this->mode() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::EnumSize(this->mode());
}
switch (transaction_selector_case()) {
// bytes transaction = 1;
case kTransaction: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::BytesSize(
this->transaction());
break;
}
case TRANSACTION_SELECTOR_NOT_SET: {
break;
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void CommitRequest::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.datastore.v1.CommitRequest)
GOOGLE_DCHECK_NE(&from, this);
const CommitRequest* source =
::google::protobuf::DynamicCastToGenerated<CommitRequest>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.datastore.v1.CommitRequest)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.datastore.v1.CommitRequest)
MergeFrom(*source);
}
}
void CommitRequest::MergeFrom(const CommitRequest& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.datastore.v1.CommitRequest)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
mutations_.MergeFrom(from.mutations_);
if (from.project_id().size() > 0) {
project_id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.project_id_);
}
if (from.mode() != 0) {
set_mode(from.mode());
}
switch (from.transaction_selector_case()) {
case kTransaction: {
set_transaction(from.transaction());
break;
}
case TRANSACTION_SELECTOR_NOT_SET: {
break;
}
}
}
void CommitRequest::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.datastore.v1.CommitRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void CommitRequest::CopyFrom(const CommitRequest& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.datastore.v1.CommitRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool CommitRequest::IsInitialized() const {
return true;
}
void CommitRequest::Swap(CommitRequest* other) {
if (other == this) return;
InternalSwap(other);
}
void CommitRequest::InternalSwap(CommitRequest* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
CastToBase(&mutations_)->InternalSwap(CastToBase(&other->mutations_));
project_id_.Swap(&other->project_id_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
swap(mode_, other->mode_);
swap(transaction_selector_, other->transaction_selector_);
swap(_oneof_case_[0], other->_oneof_case_[0]);
}
::google::protobuf::Metadata CommitRequest::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fdatastore_2fv1_2fdatastore_2eproto);
return ::file_level_metadata_google_2fdatastore_2fv1_2fdatastore_2eproto[kIndexInFileMessages];
}
// ===================================================================
void CommitResponse::InitAsDefaultInstance() {
}
class CommitResponse::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int CommitResponse::kMutationResultsFieldNumber;
const int CommitResponse::kIndexUpdatesFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
CommitResponse::CommitResponse()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:google.datastore.v1.CommitResponse)
}
CommitResponse::CommitResponse(const CommitResponse& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr),
mutation_results_(from.mutation_results_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
index_updates_ = from.index_updates_;
// @@protoc_insertion_point(copy_constructor:google.datastore.v1.CommitResponse)
}
void CommitResponse::SharedCtor() {
::google::protobuf::internal::InitSCC(
&scc_info_CommitResponse_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
index_updates_ = 0;
}
CommitResponse::~CommitResponse() {
// @@protoc_insertion_point(destructor:google.datastore.v1.CommitResponse)
SharedDtor();
}
void CommitResponse::SharedDtor() {
}
void CommitResponse::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const CommitResponse& CommitResponse::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_CommitResponse_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
return *internal_default_instance();
}
void CommitResponse::Clear() {
// @@protoc_insertion_point(message_clear_start:google.datastore.v1.CommitResponse)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
mutation_results_.Clear();
index_updates_ = 0;
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* CommitResponse::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<CommitResponse*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// repeated .google.datastore.v1.MutationResult mutation_results = 3;
case 3: {
if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual;
do {
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::datastore::v1::MutationResult::_InternalParse;
object = msg->add_mutation_results();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
if (ptr >= end) break;
} while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 26 && (ptr += 1));
break;
}
// int32 index_updates = 4;
case 4: {
if (static_cast<::google::protobuf::uint8>(tag) != 32) goto handle_unusual;
msg->set_index_updates(::google::protobuf::internal::ReadVarint(&ptr));
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
break;
}
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
len_delim_till_end:
return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
{parser_till_end, object}, size);
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool CommitResponse::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.datastore.v1.CommitResponse)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated .google.datastore.v1.MutationResult mutation_results = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_mutation_results()));
} else {
goto handle_unusual;
}
break;
}
// int32 index_updates = 4;
case 4: {
if (static_cast< ::google::protobuf::uint8>(tag) == (32 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &index_updates_)));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:google.datastore.v1.CommitResponse)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.datastore.v1.CommitResponse)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void CommitResponse::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.datastore.v1.CommitResponse)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated .google.datastore.v1.MutationResult mutation_results = 3;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->mutation_results_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3,
this->mutation_results(static_cast<int>(i)),
output);
}
// int32 index_updates = 4;
if (this->index_updates() != 0) {
::google::protobuf::internal::WireFormatLite::WriteInt32(4, this->index_updates(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.datastore.v1.CommitResponse)
}
::google::protobuf::uint8* CommitResponse::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:google.datastore.v1.CommitResponse)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated .google.datastore.v1.MutationResult mutation_results = 3;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->mutation_results_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
3, this->mutation_results(static_cast<int>(i)), target);
}
// int32 index_updates = 4;
if (this->index_updates() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(4, this->index_updates(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.datastore.v1.CommitResponse)
return target;
}
size_t CommitResponse::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.datastore.v1.CommitResponse)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// repeated .google.datastore.v1.MutationResult mutation_results = 3;
{
unsigned int count = static_cast<unsigned int>(this->mutation_results_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSize(
this->mutation_results(static_cast<int>(i)));
}
}
// int32 index_updates = 4;
if (this->index_updates() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->index_updates());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void CommitResponse::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.datastore.v1.CommitResponse)
GOOGLE_DCHECK_NE(&from, this);
const CommitResponse* source =
::google::protobuf::DynamicCastToGenerated<CommitResponse>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.datastore.v1.CommitResponse)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.datastore.v1.CommitResponse)
MergeFrom(*source);
}
}
void CommitResponse::MergeFrom(const CommitResponse& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.datastore.v1.CommitResponse)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
mutation_results_.MergeFrom(from.mutation_results_);
if (from.index_updates() != 0) {
set_index_updates(from.index_updates());
}
}
void CommitResponse::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.datastore.v1.CommitResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void CommitResponse::CopyFrom(const CommitResponse& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.datastore.v1.CommitResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool CommitResponse::IsInitialized() const {
return true;
}
void CommitResponse::Swap(CommitResponse* other) {
if (other == this) return;
InternalSwap(other);
}
void CommitResponse::InternalSwap(CommitResponse* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
CastToBase(&mutation_results_)->InternalSwap(CastToBase(&other->mutation_results_));
swap(index_updates_, other->index_updates_);
}
::google::protobuf::Metadata CommitResponse::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fdatastore_2fv1_2fdatastore_2eproto);
return ::file_level_metadata_google_2fdatastore_2fv1_2fdatastore_2eproto[kIndexInFileMessages];
}
// ===================================================================
void AllocateIdsRequest::InitAsDefaultInstance() {
}
class AllocateIdsRequest::HasBitSetters {
public:
};
void AllocateIdsRequest::clear_keys() {
keys_.Clear();
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int AllocateIdsRequest::kProjectIdFieldNumber;
const int AllocateIdsRequest::kKeysFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
AllocateIdsRequest::AllocateIdsRequest()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:google.datastore.v1.AllocateIdsRequest)
}
AllocateIdsRequest::AllocateIdsRequest(const AllocateIdsRequest& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr),
keys_(from.keys_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
project_id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.project_id().size() > 0) {
project_id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.project_id_);
}
// @@protoc_insertion_point(copy_constructor:google.datastore.v1.AllocateIdsRequest)
}
void AllocateIdsRequest::SharedCtor() {
::google::protobuf::internal::InitSCC(
&scc_info_AllocateIdsRequest_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
project_id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
AllocateIdsRequest::~AllocateIdsRequest() {
// @@protoc_insertion_point(destructor:google.datastore.v1.AllocateIdsRequest)
SharedDtor();
}
void AllocateIdsRequest::SharedDtor() {
project_id_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void AllocateIdsRequest::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const AllocateIdsRequest& AllocateIdsRequest::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_AllocateIdsRequest_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
return *internal_default_instance();
}
void AllocateIdsRequest::Clear() {
// @@protoc_insertion_point(message_clear_start:google.datastore.v1.AllocateIdsRequest)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
keys_.Clear();
project_id_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* AllocateIdsRequest::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<AllocateIdsRequest*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// repeated .google.datastore.v1.Key keys = 1 [(.google.api.field_behavior) = REQUIRED];
case 1: {
if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
do {
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::datastore::v1::Key::_InternalParse;
object = msg->add_keys();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
if (ptr >= end) break;
} while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 10 && (ptr += 1));
break;
}
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
case 8: {
if (static_cast<::google::protobuf::uint8>(tag) != 66) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
ctx->extra_parse_data().SetFieldName("google.datastore.v1.AllocateIdsRequest.project_id");
object = msg->mutable_project_id();
if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) {
parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8;
goto string_till_end;
}
GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx));
::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx);
ptr += size;
break;
}
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
string_till_end:
static_cast<::std::string*>(object)->clear();
static_cast<::std::string*>(object)->reserve(size);
goto len_delim_till_end;
len_delim_till_end:
return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
{parser_till_end, object}, size);
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool AllocateIdsRequest::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.datastore.v1.AllocateIdsRequest)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated .google.datastore.v1.Key keys = 1 [(.google.api.field_behavior) = REQUIRED];
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_keys()));
} else {
goto handle_unusual;
}
break;
}
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
case 8: {
if (static_cast< ::google::protobuf::uint8>(tag) == (66 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_project_id()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->project_id().data(), static_cast<int>(this->project_id().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.datastore.v1.AllocateIdsRequest.project_id"));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:google.datastore.v1.AllocateIdsRequest)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.datastore.v1.AllocateIdsRequest)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void AllocateIdsRequest::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.datastore.v1.AllocateIdsRequest)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated .google.datastore.v1.Key keys = 1 [(.google.api.field_behavior) = REQUIRED];
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->keys_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1,
this->keys(static_cast<int>(i)),
output);
}
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
if (this->project_id().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->project_id().data(), static_cast<int>(this->project_id().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.datastore.v1.AllocateIdsRequest.project_id");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
8, this->project_id(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.datastore.v1.AllocateIdsRequest)
}
::google::protobuf::uint8* AllocateIdsRequest::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:google.datastore.v1.AllocateIdsRequest)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated .google.datastore.v1.Key keys = 1 [(.google.api.field_behavior) = REQUIRED];
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->keys_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
1, this->keys(static_cast<int>(i)), target);
}
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
if (this->project_id().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->project_id().data(), static_cast<int>(this->project_id().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.datastore.v1.AllocateIdsRequest.project_id");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
8, this->project_id(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.datastore.v1.AllocateIdsRequest)
return target;
}
size_t AllocateIdsRequest::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.datastore.v1.AllocateIdsRequest)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// repeated .google.datastore.v1.Key keys = 1 [(.google.api.field_behavior) = REQUIRED];
{
unsigned int count = static_cast<unsigned int>(this->keys_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSize(
this->keys(static_cast<int>(i)));
}
}
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
if (this->project_id().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->project_id());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void AllocateIdsRequest::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.datastore.v1.AllocateIdsRequest)
GOOGLE_DCHECK_NE(&from, this);
const AllocateIdsRequest* source =
::google::protobuf::DynamicCastToGenerated<AllocateIdsRequest>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.datastore.v1.AllocateIdsRequest)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.datastore.v1.AllocateIdsRequest)
MergeFrom(*source);
}
}
void AllocateIdsRequest::MergeFrom(const AllocateIdsRequest& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.datastore.v1.AllocateIdsRequest)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
keys_.MergeFrom(from.keys_);
if (from.project_id().size() > 0) {
project_id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.project_id_);
}
}
void AllocateIdsRequest::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.datastore.v1.AllocateIdsRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void AllocateIdsRequest::CopyFrom(const AllocateIdsRequest& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.datastore.v1.AllocateIdsRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool AllocateIdsRequest::IsInitialized() const {
return true;
}
void AllocateIdsRequest::Swap(AllocateIdsRequest* other) {
if (other == this) return;
InternalSwap(other);
}
void AllocateIdsRequest::InternalSwap(AllocateIdsRequest* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
CastToBase(&keys_)->InternalSwap(CastToBase(&other->keys_));
project_id_.Swap(&other->project_id_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
::google::protobuf::Metadata AllocateIdsRequest::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fdatastore_2fv1_2fdatastore_2eproto);
return ::file_level_metadata_google_2fdatastore_2fv1_2fdatastore_2eproto[kIndexInFileMessages];
}
// ===================================================================
void AllocateIdsResponse::InitAsDefaultInstance() {
}
class AllocateIdsResponse::HasBitSetters {
public:
};
void AllocateIdsResponse::clear_keys() {
keys_.Clear();
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int AllocateIdsResponse::kKeysFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
AllocateIdsResponse::AllocateIdsResponse()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:google.datastore.v1.AllocateIdsResponse)
}
AllocateIdsResponse::AllocateIdsResponse(const AllocateIdsResponse& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr),
keys_(from.keys_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:google.datastore.v1.AllocateIdsResponse)
}
void AllocateIdsResponse::SharedCtor() {
::google::protobuf::internal::InitSCC(
&scc_info_AllocateIdsResponse_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
}
AllocateIdsResponse::~AllocateIdsResponse() {
// @@protoc_insertion_point(destructor:google.datastore.v1.AllocateIdsResponse)
SharedDtor();
}
void AllocateIdsResponse::SharedDtor() {
}
void AllocateIdsResponse::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const AllocateIdsResponse& AllocateIdsResponse::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_AllocateIdsResponse_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
return *internal_default_instance();
}
void AllocateIdsResponse::Clear() {
// @@protoc_insertion_point(message_clear_start:google.datastore.v1.AllocateIdsResponse)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
keys_.Clear();
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* AllocateIdsResponse::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<AllocateIdsResponse*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// repeated .google.datastore.v1.Key keys = 1;
case 1: {
if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
do {
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::datastore::v1::Key::_InternalParse;
object = msg->add_keys();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
if (ptr >= end) break;
} while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 10 && (ptr += 1));
break;
}
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
len_delim_till_end:
return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
{parser_till_end, object}, size);
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool AllocateIdsResponse::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.datastore.v1.AllocateIdsResponse)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated .google.datastore.v1.Key keys = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_keys()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:google.datastore.v1.AllocateIdsResponse)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.datastore.v1.AllocateIdsResponse)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void AllocateIdsResponse::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.datastore.v1.AllocateIdsResponse)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated .google.datastore.v1.Key keys = 1;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->keys_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1,
this->keys(static_cast<int>(i)),
output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.datastore.v1.AllocateIdsResponse)
}
::google::protobuf::uint8* AllocateIdsResponse::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:google.datastore.v1.AllocateIdsResponse)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated .google.datastore.v1.Key keys = 1;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->keys_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
1, this->keys(static_cast<int>(i)), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.datastore.v1.AllocateIdsResponse)
return target;
}
size_t AllocateIdsResponse::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.datastore.v1.AllocateIdsResponse)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// repeated .google.datastore.v1.Key keys = 1;
{
unsigned int count = static_cast<unsigned int>(this->keys_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSize(
this->keys(static_cast<int>(i)));
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void AllocateIdsResponse::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.datastore.v1.AllocateIdsResponse)
GOOGLE_DCHECK_NE(&from, this);
const AllocateIdsResponse* source =
::google::protobuf::DynamicCastToGenerated<AllocateIdsResponse>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.datastore.v1.AllocateIdsResponse)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.datastore.v1.AllocateIdsResponse)
MergeFrom(*source);
}
}
void AllocateIdsResponse::MergeFrom(const AllocateIdsResponse& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.datastore.v1.AllocateIdsResponse)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
keys_.MergeFrom(from.keys_);
}
void AllocateIdsResponse::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.datastore.v1.AllocateIdsResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void AllocateIdsResponse::CopyFrom(const AllocateIdsResponse& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.datastore.v1.AllocateIdsResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool AllocateIdsResponse::IsInitialized() const {
return true;
}
void AllocateIdsResponse::Swap(AllocateIdsResponse* other) {
if (other == this) return;
InternalSwap(other);
}
void AllocateIdsResponse::InternalSwap(AllocateIdsResponse* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
CastToBase(&keys_)->InternalSwap(CastToBase(&other->keys_));
}
::google::protobuf::Metadata AllocateIdsResponse::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fdatastore_2fv1_2fdatastore_2eproto);
return ::file_level_metadata_google_2fdatastore_2fv1_2fdatastore_2eproto[kIndexInFileMessages];
}
// ===================================================================
void ReserveIdsRequest::InitAsDefaultInstance() {
}
class ReserveIdsRequest::HasBitSetters {
public:
};
void ReserveIdsRequest::clear_keys() {
keys_.Clear();
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int ReserveIdsRequest::kProjectIdFieldNumber;
const int ReserveIdsRequest::kDatabaseIdFieldNumber;
const int ReserveIdsRequest::kKeysFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
ReserveIdsRequest::ReserveIdsRequest()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:google.datastore.v1.ReserveIdsRequest)
}
ReserveIdsRequest::ReserveIdsRequest(const ReserveIdsRequest& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr),
keys_(from.keys_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
project_id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.project_id().size() > 0) {
project_id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.project_id_);
}
database_id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.database_id().size() > 0) {
database_id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.database_id_);
}
// @@protoc_insertion_point(copy_constructor:google.datastore.v1.ReserveIdsRequest)
}
void ReserveIdsRequest::SharedCtor() {
::google::protobuf::internal::InitSCC(
&scc_info_ReserveIdsRequest_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
project_id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
database_id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
ReserveIdsRequest::~ReserveIdsRequest() {
// @@protoc_insertion_point(destructor:google.datastore.v1.ReserveIdsRequest)
SharedDtor();
}
void ReserveIdsRequest::SharedDtor() {
project_id_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
database_id_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void ReserveIdsRequest::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const ReserveIdsRequest& ReserveIdsRequest::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_ReserveIdsRequest_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
return *internal_default_instance();
}
void ReserveIdsRequest::Clear() {
// @@protoc_insertion_point(message_clear_start:google.datastore.v1.ReserveIdsRequest)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
keys_.Clear();
project_id_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
database_id_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* ReserveIdsRequest::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<ReserveIdsRequest*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// repeated .google.datastore.v1.Key keys = 1 [(.google.api.field_behavior) = REQUIRED];
case 1: {
if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
do {
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::datastore::v1::Key::_InternalParse;
object = msg->add_keys();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
if (ptr >= end) break;
} while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 10 && (ptr += 1));
break;
}
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
case 8: {
if (static_cast<::google::protobuf::uint8>(tag) != 66) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
ctx->extra_parse_data().SetFieldName("google.datastore.v1.ReserveIdsRequest.project_id");
object = msg->mutable_project_id();
if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) {
parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8;
goto string_till_end;
}
GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx));
::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx);
ptr += size;
break;
}
// string database_id = 9;
case 9: {
if (static_cast<::google::protobuf::uint8>(tag) != 74) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
ctx->extra_parse_data().SetFieldName("google.datastore.v1.ReserveIdsRequest.database_id");
object = msg->mutable_database_id();
if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) {
parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8;
goto string_till_end;
}
GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx));
::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx);
ptr += size;
break;
}
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
string_till_end:
static_cast<::std::string*>(object)->clear();
static_cast<::std::string*>(object)->reserve(size);
goto len_delim_till_end;
len_delim_till_end:
return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
{parser_till_end, object}, size);
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool ReserveIdsRequest::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.datastore.v1.ReserveIdsRequest)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated .google.datastore.v1.Key keys = 1 [(.google.api.field_behavior) = REQUIRED];
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_keys()));
} else {
goto handle_unusual;
}
break;
}
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
case 8: {
if (static_cast< ::google::protobuf::uint8>(tag) == (66 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_project_id()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->project_id().data(), static_cast<int>(this->project_id().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.datastore.v1.ReserveIdsRequest.project_id"));
} else {
goto handle_unusual;
}
break;
}
// string database_id = 9;
case 9: {
if (static_cast< ::google::protobuf::uint8>(tag) == (74 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_database_id()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->database_id().data(), static_cast<int>(this->database_id().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.datastore.v1.ReserveIdsRequest.database_id"));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:google.datastore.v1.ReserveIdsRequest)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.datastore.v1.ReserveIdsRequest)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void ReserveIdsRequest::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.datastore.v1.ReserveIdsRequest)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated .google.datastore.v1.Key keys = 1 [(.google.api.field_behavior) = REQUIRED];
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->keys_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1,
this->keys(static_cast<int>(i)),
output);
}
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
if (this->project_id().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->project_id().data(), static_cast<int>(this->project_id().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.datastore.v1.ReserveIdsRequest.project_id");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
8, this->project_id(), output);
}
// string database_id = 9;
if (this->database_id().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->database_id().data(), static_cast<int>(this->database_id().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.datastore.v1.ReserveIdsRequest.database_id");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
9, this->database_id(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.datastore.v1.ReserveIdsRequest)
}
::google::protobuf::uint8* ReserveIdsRequest::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:google.datastore.v1.ReserveIdsRequest)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated .google.datastore.v1.Key keys = 1 [(.google.api.field_behavior) = REQUIRED];
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->keys_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
1, this->keys(static_cast<int>(i)), target);
}
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
if (this->project_id().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->project_id().data(), static_cast<int>(this->project_id().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.datastore.v1.ReserveIdsRequest.project_id");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
8, this->project_id(), target);
}
// string database_id = 9;
if (this->database_id().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->database_id().data(), static_cast<int>(this->database_id().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.datastore.v1.ReserveIdsRequest.database_id");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
9, this->database_id(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.datastore.v1.ReserveIdsRequest)
return target;
}
size_t ReserveIdsRequest::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.datastore.v1.ReserveIdsRequest)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// repeated .google.datastore.v1.Key keys = 1 [(.google.api.field_behavior) = REQUIRED];
{
unsigned int count = static_cast<unsigned int>(this->keys_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSize(
this->keys(static_cast<int>(i)));
}
}
// string project_id = 8 [(.google.api.field_behavior) = REQUIRED];
if (this->project_id().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->project_id());
}
// string database_id = 9;
if (this->database_id().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->database_id());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void ReserveIdsRequest::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.datastore.v1.ReserveIdsRequest)
GOOGLE_DCHECK_NE(&from, this);
const ReserveIdsRequest* source =
::google::protobuf::DynamicCastToGenerated<ReserveIdsRequest>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.datastore.v1.ReserveIdsRequest)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.datastore.v1.ReserveIdsRequest)
MergeFrom(*source);
}
}
void ReserveIdsRequest::MergeFrom(const ReserveIdsRequest& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.datastore.v1.ReserveIdsRequest)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
keys_.MergeFrom(from.keys_);
if (from.project_id().size() > 0) {
project_id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.project_id_);
}
if (from.database_id().size() > 0) {
database_id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.database_id_);
}
}
void ReserveIdsRequest::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.datastore.v1.ReserveIdsRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void ReserveIdsRequest::CopyFrom(const ReserveIdsRequest& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.datastore.v1.ReserveIdsRequest)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool ReserveIdsRequest::IsInitialized() const {
return true;
}
void ReserveIdsRequest::Swap(ReserveIdsRequest* other) {
if (other == this) return;
InternalSwap(other);
}
void ReserveIdsRequest::InternalSwap(ReserveIdsRequest* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
CastToBase(&keys_)->InternalSwap(CastToBase(&other->keys_));
project_id_.Swap(&other->project_id_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
database_id_.Swap(&other->database_id_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
::google::protobuf::Metadata ReserveIdsRequest::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fdatastore_2fv1_2fdatastore_2eproto);
return ::file_level_metadata_google_2fdatastore_2fv1_2fdatastore_2eproto[kIndexInFileMessages];
}
// ===================================================================
void ReserveIdsResponse::InitAsDefaultInstance() {
}
class ReserveIdsResponse::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
ReserveIdsResponse::ReserveIdsResponse()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:google.datastore.v1.ReserveIdsResponse)
}
ReserveIdsResponse::ReserveIdsResponse(const ReserveIdsResponse& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:google.datastore.v1.ReserveIdsResponse)
}
void ReserveIdsResponse::SharedCtor() {
}
ReserveIdsResponse::~ReserveIdsResponse() {
// @@protoc_insertion_point(destructor:google.datastore.v1.ReserveIdsResponse)
SharedDtor();
}
void ReserveIdsResponse::SharedDtor() {
}
void ReserveIdsResponse::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const ReserveIdsResponse& ReserveIdsResponse::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_ReserveIdsResponse_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
return *internal_default_instance();
}
void ReserveIdsResponse::Clear() {
// @@protoc_insertion_point(message_clear_start:google.datastore.v1.ReserveIdsResponse)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* ReserveIdsResponse::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<ReserveIdsResponse*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
default: {
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool ReserveIdsResponse::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.datastore.v1.ReserveIdsResponse)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
}
success:
// @@protoc_insertion_point(parse_success:google.datastore.v1.ReserveIdsResponse)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.datastore.v1.ReserveIdsResponse)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void ReserveIdsResponse::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.datastore.v1.ReserveIdsResponse)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.datastore.v1.ReserveIdsResponse)
}
::google::protobuf::uint8* ReserveIdsResponse::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:google.datastore.v1.ReserveIdsResponse)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.datastore.v1.ReserveIdsResponse)
return target;
}
size_t ReserveIdsResponse::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.datastore.v1.ReserveIdsResponse)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void ReserveIdsResponse::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.datastore.v1.ReserveIdsResponse)
GOOGLE_DCHECK_NE(&from, this);
const ReserveIdsResponse* source =
::google::protobuf::DynamicCastToGenerated<ReserveIdsResponse>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.datastore.v1.ReserveIdsResponse)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.datastore.v1.ReserveIdsResponse)
MergeFrom(*source);
}
}
void ReserveIdsResponse::MergeFrom(const ReserveIdsResponse& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.datastore.v1.ReserveIdsResponse)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
}
void ReserveIdsResponse::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.datastore.v1.ReserveIdsResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void ReserveIdsResponse::CopyFrom(const ReserveIdsResponse& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.datastore.v1.ReserveIdsResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool ReserveIdsResponse::IsInitialized() const {
return true;
}
void ReserveIdsResponse::Swap(ReserveIdsResponse* other) {
if (other == this) return;
InternalSwap(other);
}
void ReserveIdsResponse::InternalSwap(ReserveIdsResponse* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata ReserveIdsResponse::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fdatastore_2fv1_2fdatastore_2eproto);
return ::file_level_metadata_google_2fdatastore_2fv1_2fdatastore_2eproto[kIndexInFileMessages];
}
// ===================================================================
void Mutation::InitAsDefaultInstance() {
::google::datastore::v1::_Mutation_default_instance_.insert_ = const_cast< ::google::datastore::v1::Entity*>(
::google::datastore::v1::Entity::internal_default_instance());
::google::datastore::v1::_Mutation_default_instance_.update_ = const_cast< ::google::datastore::v1::Entity*>(
::google::datastore::v1::Entity::internal_default_instance());
::google::datastore::v1::_Mutation_default_instance_.upsert_ = const_cast< ::google::datastore::v1::Entity*>(
::google::datastore::v1::Entity::internal_default_instance());
::google::datastore::v1::_Mutation_default_instance_.delete__ = const_cast< ::google::datastore::v1::Key*>(
::google::datastore::v1::Key::internal_default_instance());
::google::datastore::v1::_Mutation_default_instance_.base_version_ = PROTOBUF_LONGLONG(0);
}
class Mutation::HasBitSetters {
public:
static const ::google::datastore::v1::Entity& insert(const Mutation* msg);
static const ::google::datastore::v1::Entity& update(const Mutation* msg);
static const ::google::datastore::v1::Entity& upsert(const Mutation* msg);
static const ::google::datastore::v1::Key& delete_(const Mutation* msg);
};
const ::google::datastore::v1::Entity&
Mutation::HasBitSetters::insert(const Mutation* msg) {
return *msg->operation_.insert_;
}
const ::google::datastore::v1::Entity&
Mutation::HasBitSetters::update(const Mutation* msg) {
return *msg->operation_.update_;
}
const ::google::datastore::v1::Entity&
Mutation::HasBitSetters::upsert(const Mutation* msg) {
return *msg->operation_.upsert_;
}
const ::google::datastore::v1::Key&
Mutation::HasBitSetters::delete_(const Mutation* msg) {
return *msg->operation_.delete__;
}
void Mutation::set_allocated_insert(::google::datastore::v1::Entity* insert) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
clear_operation();
if (insert) {
::google::protobuf::Arena* submessage_arena = nullptr;
if (message_arena != submessage_arena) {
insert = ::google::protobuf::internal::GetOwnedMessage(
message_arena, insert, submessage_arena);
}
set_has_insert();
operation_.insert_ = insert;
}
// @@protoc_insertion_point(field_set_allocated:google.datastore.v1.Mutation.insert)
}
void Mutation::clear_insert() {
if (has_insert()) {
delete operation_.insert_;
clear_has_operation();
}
}
void Mutation::set_allocated_update(::google::datastore::v1::Entity* update) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
clear_operation();
if (update) {
::google::protobuf::Arena* submessage_arena = nullptr;
if (message_arena != submessage_arena) {
update = ::google::protobuf::internal::GetOwnedMessage(
message_arena, update, submessage_arena);
}
set_has_update();
operation_.update_ = update;
}
// @@protoc_insertion_point(field_set_allocated:google.datastore.v1.Mutation.update)
}
void Mutation::clear_update() {
if (has_update()) {
delete operation_.update_;
clear_has_operation();
}
}
void Mutation::set_allocated_upsert(::google::datastore::v1::Entity* upsert) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
clear_operation();
if (upsert) {
::google::protobuf::Arena* submessage_arena = nullptr;
if (message_arena != submessage_arena) {
upsert = ::google::protobuf::internal::GetOwnedMessage(
message_arena, upsert, submessage_arena);
}
set_has_upsert();
operation_.upsert_ = upsert;
}
// @@protoc_insertion_point(field_set_allocated:google.datastore.v1.Mutation.upsert)
}
void Mutation::clear_upsert() {
if (has_upsert()) {
delete operation_.upsert_;
clear_has_operation();
}
}
void Mutation::set_allocated_delete_(::google::datastore::v1::Key* delete_) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
clear_operation();
if (delete_) {
::google::protobuf::Arena* submessage_arena = nullptr;
if (message_arena != submessage_arena) {
delete_ = ::google::protobuf::internal::GetOwnedMessage(
message_arena, delete_, submessage_arena);
}
set_has_delete_();
operation_.delete__ = delete_;
}
// @@protoc_insertion_point(field_set_allocated:google.datastore.v1.Mutation.delete)
}
void Mutation::clear_delete_() {
if (has_delete_()) {
delete operation_.delete__;
clear_has_operation();
}
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Mutation::kInsertFieldNumber;
const int Mutation::kUpdateFieldNumber;
const int Mutation::kUpsertFieldNumber;
const int Mutation::kDeleteFieldNumber;
const int Mutation::kBaseVersionFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
Mutation::Mutation()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:google.datastore.v1.Mutation)
}
Mutation::Mutation(const Mutation& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
clear_has_operation();
switch (from.operation_case()) {
case kInsert: {
mutable_insert()->::google::datastore::v1::Entity::MergeFrom(from.insert());
break;
}
case kUpdate: {
mutable_update()->::google::datastore::v1::Entity::MergeFrom(from.update());
break;
}
case kUpsert: {
mutable_upsert()->::google::datastore::v1::Entity::MergeFrom(from.upsert());
break;
}
case kDelete: {
mutable_delete_()->::google::datastore::v1::Key::MergeFrom(from.delete_());
break;
}
case OPERATION_NOT_SET: {
break;
}
}
clear_has_conflict_detection_strategy();
switch (from.conflict_detection_strategy_case()) {
case kBaseVersion: {
set_base_version(from.base_version());
break;
}
case CONFLICT_DETECTION_STRATEGY_NOT_SET: {
break;
}
}
// @@protoc_insertion_point(copy_constructor:google.datastore.v1.Mutation)
}
void Mutation::SharedCtor() {
::google::protobuf::internal::InitSCC(
&scc_info_Mutation_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
clear_has_operation();
clear_has_conflict_detection_strategy();
}
Mutation::~Mutation() {
// @@protoc_insertion_point(destructor:google.datastore.v1.Mutation)
SharedDtor();
}
void Mutation::SharedDtor() {
if (has_operation()) {
clear_operation();
}
if (has_conflict_detection_strategy()) {
clear_conflict_detection_strategy();
}
}
void Mutation::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const Mutation& Mutation::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_Mutation_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
return *internal_default_instance();
}
void Mutation::clear_operation() {
// @@protoc_insertion_point(one_of_clear_start:google.datastore.v1.Mutation)
switch (operation_case()) {
case kInsert: {
delete operation_.insert_;
break;
}
case kUpdate: {
delete operation_.update_;
break;
}
case kUpsert: {
delete operation_.upsert_;
break;
}
case kDelete: {
delete operation_.delete__;
break;
}
case OPERATION_NOT_SET: {
break;
}
}
_oneof_case_[0] = OPERATION_NOT_SET;
}
void Mutation::clear_conflict_detection_strategy() {
// @@protoc_insertion_point(one_of_clear_start:google.datastore.v1.Mutation)
switch (conflict_detection_strategy_case()) {
case kBaseVersion: {
// No need to clear
break;
}
case CONFLICT_DETECTION_STRATEGY_NOT_SET: {
break;
}
}
_oneof_case_[1] = CONFLICT_DETECTION_STRATEGY_NOT_SET;
}
void Mutation::Clear() {
// @@protoc_insertion_point(message_clear_start:google.datastore.v1.Mutation)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
clear_operation();
clear_conflict_detection_strategy();
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* Mutation::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<Mutation*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// .google.datastore.v1.Entity insert = 4;
case 4: {
if (static_cast<::google::protobuf::uint8>(tag) != 34) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::datastore::v1::Entity::_InternalParse;
object = msg->mutable_insert();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
break;
}
// .google.datastore.v1.Entity update = 5;
case 5: {
if (static_cast<::google::protobuf::uint8>(tag) != 42) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::datastore::v1::Entity::_InternalParse;
object = msg->mutable_update();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
break;
}
// .google.datastore.v1.Entity upsert = 6;
case 6: {
if (static_cast<::google::protobuf::uint8>(tag) != 50) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::datastore::v1::Entity::_InternalParse;
object = msg->mutable_upsert();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
break;
}
// .google.datastore.v1.Key delete = 7;
case 7: {
if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::datastore::v1::Key::_InternalParse;
object = msg->mutable_delete_();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
break;
}
// int64 base_version = 8;
case 8: {
if (static_cast<::google::protobuf::uint8>(tag) != 64) goto handle_unusual;
msg->set_base_version(::google::protobuf::internal::ReadVarint(&ptr));
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
break;
}
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
len_delim_till_end:
return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
{parser_till_end, object}, size);
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool Mutation::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.datastore.v1.Mutation)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .google.datastore.v1.Entity insert = 4;
case 4: {
if (static_cast< ::google::protobuf::uint8>(tag) == (34 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_insert()));
} else {
goto handle_unusual;
}
break;
}
// .google.datastore.v1.Entity update = 5;
case 5: {
if (static_cast< ::google::protobuf::uint8>(tag) == (42 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_update()));
} else {
goto handle_unusual;
}
break;
}
// .google.datastore.v1.Entity upsert = 6;
case 6: {
if (static_cast< ::google::protobuf::uint8>(tag) == (50 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_upsert()));
} else {
goto handle_unusual;
}
break;
}
// .google.datastore.v1.Key delete = 7;
case 7: {
if (static_cast< ::google::protobuf::uint8>(tag) == (58 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_delete_()));
} else {
goto handle_unusual;
}
break;
}
// int64 base_version = 8;
case 8: {
if (static_cast< ::google::protobuf::uint8>(tag) == (64 & 0xFF)) {
clear_conflict_detection_strategy();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
input, &conflict_detection_strategy_.base_version_)));
set_has_base_version();
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:google.datastore.v1.Mutation)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.datastore.v1.Mutation)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void Mutation::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.datastore.v1.Mutation)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .google.datastore.v1.Entity insert = 4;
if (has_insert()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
4, HasBitSetters::insert(this), output);
}
// .google.datastore.v1.Entity update = 5;
if (has_update()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
5, HasBitSetters::update(this), output);
}
// .google.datastore.v1.Entity upsert = 6;
if (has_upsert()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
6, HasBitSetters::upsert(this), output);
}
// .google.datastore.v1.Key delete = 7;
if (has_delete_()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
7, HasBitSetters::delete_(this), output);
}
// int64 base_version = 8;
if (has_base_version()) {
::google::protobuf::internal::WireFormatLite::WriteInt64(8, this->base_version(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.datastore.v1.Mutation)
}
::google::protobuf::uint8* Mutation::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:google.datastore.v1.Mutation)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .google.datastore.v1.Entity insert = 4;
if (has_insert()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
4, HasBitSetters::insert(this), target);
}
// .google.datastore.v1.Entity update = 5;
if (has_update()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
5, HasBitSetters::update(this), target);
}
// .google.datastore.v1.Entity upsert = 6;
if (has_upsert()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
6, HasBitSetters::upsert(this), target);
}
// .google.datastore.v1.Key delete = 7;
if (has_delete_()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
7, HasBitSetters::delete_(this), target);
}
// int64 base_version = 8;
if (has_base_version()) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(8, this->base_version(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.datastore.v1.Mutation)
return target;
}
size_t Mutation::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.datastore.v1.Mutation)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
switch (operation_case()) {
// .google.datastore.v1.Entity insert = 4;
case kInsert: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*operation_.insert_);
break;
}
// .google.datastore.v1.Entity update = 5;
case kUpdate: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*operation_.update_);
break;
}
// .google.datastore.v1.Entity upsert = 6;
case kUpsert: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*operation_.upsert_);
break;
}
// .google.datastore.v1.Key delete = 7;
case kDelete: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*operation_.delete__);
break;
}
case OPERATION_NOT_SET: {
break;
}
}
switch (conflict_detection_strategy_case()) {
// int64 base_version = 8;
case kBaseVersion: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int64Size(
this->base_version());
break;
}
case CONFLICT_DETECTION_STRATEGY_NOT_SET: {
break;
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void Mutation::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.datastore.v1.Mutation)
GOOGLE_DCHECK_NE(&from, this);
const Mutation* source =
::google::protobuf::DynamicCastToGenerated<Mutation>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.datastore.v1.Mutation)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.datastore.v1.Mutation)
MergeFrom(*source);
}
}
void Mutation::MergeFrom(const Mutation& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.datastore.v1.Mutation)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
switch (from.operation_case()) {
case kInsert: {
mutable_insert()->::google::datastore::v1::Entity::MergeFrom(from.insert());
break;
}
case kUpdate: {
mutable_update()->::google::datastore::v1::Entity::MergeFrom(from.update());
break;
}
case kUpsert: {
mutable_upsert()->::google::datastore::v1::Entity::MergeFrom(from.upsert());
break;
}
case kDelete: {
mutable_delete_()->::google::datastore::v1::Key::MergeFrom(from.delete_());
break;
}
case OPERATION_NOT_SET: {
break;
}
}
switch (from.conflict_detection_strategy_case()) {
case kBaseVersion: {
set_base_version(from.base_version());
break;
}
case CONFLICT_DETECTION_STRATEGY_NOT_SET: {
break;
}
}
}
void Mutation::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.datastore.v1.Mutation)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void Mutation::CopyFrom(const Mutation& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.datastore.v1.Mutation)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool Mutation::IsInitialized() const {
return true;
}
void Mutation::Swap(Mutation* other) {
if (other == this) return;
InternalSwap(other);
}
void Mutation::InternalSwap(Mutation* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(operation_, other->operation_);
swap(conflict_detection_strategy_, other->conflict_detection_strategy_);
swap(_oneof_case_[0], other->_oneof_case_[0]);
swap(_oneof_case_[1], other->_oneof_case_[1]);
}
::google::protobuf::Metadata Mutation::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fdatastore_2fv1_2fdatastore_2eproto);
return ::file_level_metadata_google_2fdatastore_2fv1_2fdatastore_2eproto[kIndexInFileMessages];
}
// ===================================================================
void MutationResult::InitAsDefaultInstance() {
::google::datastore::v1::_MutationResult_default_instance_._instance.get_mutable()->key_ = const_cast< ::google::datastore::v1::Key*>(
::google::datastore::v1::Key::internal_default_instance());
}
class MutationResult::HasBitSetters {
public:
static const ::google::datastore::v1::Key& key(const MutationResult* msg);
};
const ::google::datastore::v1::Key&
MutationResult::HasBitSetters::key(const MutationResult* msg) {
return *msg->key_;
}
void MutationResult::clear_key() {
if (GetArenaNoVirtual() == nullptr && key_ != nullptr) {
delete key_;
}
key_ = nullptr;
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int MutationResult::kKeyFieldNumber;
const int MutationResult::kVersionFieldNumber;
const int MutationResult::kConflictDetectedFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
MutationResult::MutationResult()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:google.datastore.v1.MutationResult)
}
MutationResult::MutationResult(const MutationResult& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from.has_key()) {
key_ = new ::google::datastore::v1::Key(*from.key_);
} else {
key_ = nullptr;
}
::memcpy(&version_, &from.version_,
static_cast<size_t>(reinterpret_cast<char*>(&conflict_detected_) -
reinterpret_cast<char*>(&version_)) + sizeof(conflict_detected_));
// @@protoc_insertion_point(copy_constructor:google.datastore.v1.MutationResult)
}
void MutationResult::SharedCtor() {
::google::protobuf::internal::InitSCC(
&scc_info_MutationResult_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
::memset(&key_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&conflict_detected_) -
reinterpret_cast<char*>(&key_)) + sizeof(conflict_detected_));
}
MutationResult::~MutationResult() {
// @@protoc_insertion_point(destructor:google.datastore.v1.MutationResult)
SharedDtor();
}
void MutationResult::SharedDtor() {
if (this != internal_default_instance()) delete key_;
}
void MutationResult::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const MutationResult& MutationResult::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_MutationResult_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
return *internal_default_instance();
}
void MutationResult::Clear() {
// @@protoc_insertion_point(message_clear_start:google.datastore.v1.MutationResult)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
if (GetArenaNoVirtual() == nullptr && key_ != nullptr) {
delete key_;
}
key_ = nullptr;
::memset(&version_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&conflict_detected_) -
reinterpret_cast<char*>(&version_)) + sizeof(conflict_detected_));
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* MutationResult::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<MutationResult*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// .google.datastore.v1.Key key = 3;
case 3: {
if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::datastore::v1::Key::_InternalParse;
object = msg->mutable_key();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
break;
}
// int64 version = 4;
case 4: {
if (static_cast<::google::protobuf::uint8>(tag) != 32) goto handle_unusual;
msg->set_version(::google::protobuf::internal::ReadVarint(&ptr));
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
break;
}
// bool conflict_detected = 5;
case 5: {
if (static_cast<::google::protobuf::uint8>(tag) != 40) goto handle_unusual;
msg->set_conflict_detected(::google::protobuf::internal::ReadVarint(&ptr));
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
break;
}
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
len_delim_till_end:
return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
{parser_till_end, object}, size);
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool MutationResult::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.datastore.v1.MutationResult)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .google.datastore.v1.Key key = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_key()));
} else {
goto handle_unusual;
}
break;
}
// int64 version = 4;
case 4: {
if (static_cast< ::google::protobuf::uint8>(tag) == (32 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
input, &version_)));
} else {
goto handle_unusual;
}
break;
}
// bool conflict_detected = 5;
case 5: {
if (static_cast< ::google::protobuf::uint8>(tag) == (40 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &conflict_detected_)));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:google.datastore.v1.MutationResult)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.datastore.v1.MutationResult)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void MutationResult::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.datastore.v1.MutationResult)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .google.datastore.v1.Key key = 3;
if (this->has_key()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3, HasBitSetters::key(this), output);
}
// int64 version = 4;
if (this->version() != 0) {
::google::protobuf::internal::WireFormatLite::WriteInt64(4, this->version(), output);
}
// bool conflict_detected = 5;
if (this->conflict_detected() != 0) {
::google::protobuf::internal::WireFormatLite::WriteBool(5, this->conflict_detected(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.datastore.v1.MutationResult)
}
::google::protobuf::uint8* MutationResult::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:google.datastore.v1.MutationResult)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .google.datastore.v1.Key key = 3;
if (this->has_key()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
3, HasBitSetters::key(this), target);
}
// int64 version = 4;
if (this->version() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(4, this->version(), target);
}
// bool conflict_detected = 5;
if (this->conflict_detected() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(5, this->conflict_detected(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.datastore.v1.MutationResult)
return target;
}
size_t MutationResult::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.datastore.v1.MutationResult)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// .google.datastore.v1.Key key = 3;
if (this->has_key()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*key_);
}
// int64 version = 4;
if (this->version() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int64Size(
this->version());
}
// bool conflict_detected = 5;
if (this->conflict_detected() != 0) {
total_size += 1 + 1;
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void MutationResult::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.datastore.v1.MutationResult)
GOOGLE_DCHECK_NE(&from, this);
const MutationResult* source =
::google::protobuf::DynamicCastToGenerated<MutationResult>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.datastore.v1.MutationResult)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.datastore.v1.MutationResult)
MergeFrom(*source);
}
}
void MutationResult::MergeFrom(const MutationResult& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.datastore.v1.MutationResult)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.has_key()) {
mutable_key()->::google::datastore::v1::Key::MergeFrom(from.key());
}
if (from.version() != 0) {
set_version(from.version());
}
if (from.conflict_detected() != 0) {
set_conflict_detected(from.conflict_detected());
}
}
void MutationResult::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.datastore.v1.MutationResult)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void MutationResult::CopyFrom(const MutationResult& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.datastore.v1.MutationResult)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool MutationResult::IsInitialized() const {
return true;
}
void MutationResult::Swap(MutationResult* other) {
if (other == this) return;
InternalSwap(other);
}
void MutationResult::InternalSwap(MutationResult* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(key_, other->key_);
swap(version_, other->version_);
swap(conflict_detected_, other->conflict_detected_);
}
::google::protobuf::Metadata MutationResult::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fdatastore_2fv1_2fdatastore_2eproto);
return ::file_level_metadata_google_2fdatastore_2fv1_2fdatastore_2eproto[kIndexInFileMessages];
}
// ===================================================================
void ReadOptions::InitAsDefaultInstance() {
::google::datastore::v1::_ReadOptions_default_instance_.read_consistency_ = 0;
::google::datastore::v1::_ReadOptions_default_instance_.transaction_.UnsafeSetDefault(
&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
class ReadOptions::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int ReadOptions::kReadConsistencyFieldNumber;
const int ReadOptions::kTransactionFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
ReadOptions::ReadOptions()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:google.datastore.v1.ReadOptions)
}
ReadOptions::ReadOptions(const ReadOptions& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
clear_has_consistency_type();
switch (from.consistency_type_case()) {
case kReadConsistency: {
set_read_consistency(from.read_consistency());
break;
}
case kTransaction: {
set_transaction(from.transaction());
break;
}
case CONSISTENCY_TYPE_NOT_SET: {
break;
}
}
// @@protoc_insertion_point(copy_constructor:google.datastore.v1.ReadOptions)
}
void ReadOptions::SharedCtor() {
::google::protobuf::internal::InitSCC(
&scc_info_ReadOptions_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
clear_has_consistency_type();
}
ReadOptions::~ReadOptions() {
// @@protoc_insertion_point(destructor:google.datastore.v1.ReadOptions)
SharedDtor();
}
void ReadOptions::SharedDtor() {
if (has_consistency_type()) {
clear_consistency_type();
}
}
void ReadOptions::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const ReadOptions& ReadOptions::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_ReadOptions_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
return *internal_default_instance();
}
void ReadOptions::clear_consistency_type() {
// @@protoc_insertion_point(one_of_clear_start:google.datastore.v1.ReadOptions)
switch (consistency_type_case()) {
case kReadConsistency: {
// No need to clear
break;
}
case kTransaction: {
consistency_type_.transaction_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
break;
}
case CONSISTENCY_TYPE_NOT_SET: {
break;
}
}
_oneof_case_[0] = CONSISTENCY_TYPE_NOT_SET;
}
void ReadOptions::Clear() {
// @@protoc_insertion_point(message_clear_start:google.datastore.v1.ReadOptions)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
clear_consistency_type();
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* ReadOptions::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<ReadOptions*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// .google.datastore.v1.ReadOptions.ReadConsistency read_consistency = 1;
case 1: {
if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual;
::google::protobuf::uint64 val = ::google::protobuf::internal::ReadVarint(&ptr);
msg->set_read_consistency(static_cast<::google::datastore::v1::ReadOptions_ReadConsistency>(val));
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
break;
}
// bytes transaction = 2;
case 2: {
if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
object = msg->mutable_transaction();
if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) {
parser_till_end = ::google::protobuf::internal::GreedyStringParser;
goto string_till_end;
}
GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheck(ptr, size, ctx));
::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx);
ptr += size;
break;
}
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
string_till_end:
static_cast<::std::string*>(object)->clear();
static_cast<::std::string*>(object)->reserve(size);
goto len_delim_till_end;
len_delim_till_end:
return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
{parser_till_end, object}, size);
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool ReadOptions::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.datastore.v1.ReadOptions)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .google.datastore.v1.ReadOptions.ReadConsistency read_consistency = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) == (8 & 0xFF)) {
int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
set_read_consistency(static_cast< ::google::datastore::v1::ReadOptions_ReadConsistency >(value));
} else {
goto handle_unusual;
}
break;
}
// bytes transaction = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadBytes(
input, this->mutable_transaction()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:google.datastore.v1.ReadOptions)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.datastore.v1.ReadOptions)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void ReadOptions::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.datastore.v1.ReadOptions)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .google.datastore.v1.ReadOptions.ReadConsistency read_consistency = 1;
if (has_read_consistency()) {
::google::protobuf::internal::WireFormatLite::WriteEnum(
1, this->read_consistency(), output);
}
// bytes transaction = 2;
if (has_transaction()) {
::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased(
2, this->transaction(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.datastore.v1.ReadOptions)
}
::google::protobuf::uint8* ReadOptions::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:google.datastore.v1.ReadOptions)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .google.datastore.v1.ReadOptions.ReadConsistency read_consistency = 1;
if (has_read_consistency()) {
target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(
1, this->read_consistency(), target);
}
// bytes transaction = 2;
if (has_transaction()) {
target =
::google::protobuf::internal::WireFormatLite::WriteBytesToArray(
2, this->transaction(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.datastore.v1.ReadOptions)
return target;
}
size_t ReadOptions::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.datastore.v1.ReadOptions)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
switch (consistency_type_case()) {
// .google.datastore.v1.ReadOptions.ReadConsistency read_consistency = 1;
case kReadConsistency: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::EnumSize(this->read_consistency());
break;
}
// bytes transaction = 2;
case kTransaction: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::BytesSize(
this->transaction());
break;
}
case CONSISTENCY_TYPE_NOT_SET: {
break;
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void ReadOptions::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.datastore.v1.ReadOptions)
GOOGLE_DCHECK_NE(&from, this);
const ReadOptions* source =
::google::protobuf::DynamicCastToGenerated<ReadOptions>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.datastore.v1.ReadOptions)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.datastore.v1.ReadOptions)
MergeFrom(*source);
}
}
void ReadOptions::MergeFrom(const ReadOptions& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.datastore.v1.ReadOptions)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
switch (from.consistency_type_case()) {
case kReadConsistency: {
set_read_consistency(from.read_consistency());
break;
}
case kTransaction: {
set_transaction(from.transaction());
break;
}
case CONSISTENCY_TYPE_NOT_SET: {
break;
}
}
}
void ReadOptions::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.datastore.v1.ReadOptions)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void ReadOptions::CopyFrom(const ReadOptions& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.datastore.v1.ReadOptions)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool ReadOptions::IsInitialized() const {
return true;
}
void ReadOptions::Swap(ReadOptions* other) {
if (other == this) return;
InternalSwap(other);
}
void ReadOptions::InternalSwap(ReadOptions* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(consistency_type_, other->consistency_type_);
swap(_oneof_case_[0], other->_oneof_case_[0]);
}
::google::protobuf::Metadata ReadOptions::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fdatastore_2fv1_2fdatastore_2eproto);
return ::file_level_metadata_google_2fdatastore_2fv1_2fdatastore_2eproto[kIndexInFileMessages];
}
// ===================================================================
void TransactionOptions_ReadWrite::InitAsDefaultInstance() {
}
class TransactionOptions_ReadWrite::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int TransactionOptions_ReadWrite::kPreviousTransactionFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
TransactionOptions_ReadWrite::TransactionOptions_ReadWrite()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:google.datastore.v1.TransactionOptions.ReadWrite)
}
TransactionOptions_ReadWrite::TransactionOptions_ReadWrite(const TransactionOptions_ReadWrite& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
previous_transaction_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.previous_transaction().size() > 0) {
previous_transaction_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.previous_transaction_);
}
// @@protoc_insertion_point(copy_constructor:google.datastore.v1.TransactionOptions.ReadWrite)
}
void TransactionOptions_ReadWrite::SharedCtor() {
::google::protobuf::internal::InitSCC(
&scc_info_TransactionOptions_ReadWrite_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
previous_transaction_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
TransactionOptions_ReadWrite::~TransactionOptions_ReadWrite() {
// @@protoc_insertion_point(destructor:google.datastore.v1.TransactionOptions.ReadWrite)
SharedDtor();
}
void TransactionOptions_ReadWrite::SharedDtor() {
previous_transaction_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void TransactionOptions_ReadWrite::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const TransactionOptions_ReadWrite& TransactionOptions_ReadWrite::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_TransactionOptions_ReadWrite_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
return *internal_default_instance();
}
void TransactionOptions_ReadWrite::Clear() {
// @@protoc_insertion_point(message_clear_start:google.datastore.v1.TransactionOptions.ReadWrite)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
previous_transaction_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* TransactionOptions_ReadWrite::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<TransactionOptions_ReadWrite*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// bytes previous_transaction = 1;
case 1: {
if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
object = msg->mutable_previous_transaction();
if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) {
parser_till_end = ::google::protobuf::internal::GreedyStringParser;
goto string_till_end;
}
GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheck(ptr, size, ctx));
::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx);
ptr += size;
break;
}
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
string_till_end:
static_cast<::std::string*>(object)->clear();
static_cast<::std::string*>(object)->reserve(size);
goto len_delim_till_end;
len_delim_till_end:
return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
{parser_till_end, object}, size);
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool TransactionOptions_ReadWrite::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.datastore.v1.TransactionOptions.ReadWrite)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// bytes previous_transaction = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadBytes(
input, this->mutable_previous_transaction()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:google.datastore.v1.TransactionOptions.ReadWrite)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.datastore.v1.TransactionOptions.ReadWrite)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void TransactionOptions_ReadWrite::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.datastore.v1.TransactionOptions.ReadWrite)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// bytes previous_transaction = 1;
if (this->previous_transaction().size() > 0) {
::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased(
1, this->previous_transaction(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.datastore.v1.TransactionOptions.ReadWrite)
}
::google::protobuf::uint8* TransactionOptions_ReadWrite::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:google.datastore.v1.TransactionOptions.ReadWrite)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// bytes previous_transaction = 1;
if (this->previous_transaction().size() > 0) {
target =
::google::protobuf::internal::WireFormatLite::WriteBytesToArray(
1, this->previous_transaction(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.datastore.v1.TransactionOptions.ReadWrite)
return target;
}
size_t TransactionOptions_ReadWrite::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.datastore.v1.TransactionOptions.ReadWrite)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// bytes previous_transaction = 1;
if (this->previous_transaction().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::BytesSize(
this->previous_transaction());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void TransactionOptions_ReadWrite::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.datastore.v1.TransactionOptions.ReadWrite)
GOOGLE_DCHECK_NE(&from, this);
const TransactionOptions_ReadWrite* source =
::google::protobuf::DynamicCastToGenerated<TransactionOptions_ReadWrite>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.datastore.v1.TransactionOptions.ReadWrite)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.datastore.v1.TransactionOptions.ReadWrite)
MergeFrom(*source);
}
}
void TransactionOptions_ReadWrite::MergeFrom(const TransactionOptions_ReadWrite& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.datastore.v1.TransactionOptions.ReadWrite)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.previous_transaction().size() > 0) {
previous_transaction_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.previous_transaction_);
}
}
void TransactionOptions_ReadWrite::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.datastore.v1.TransactionOptions.ReadWrite)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void TransactionOptions_ReadWrite::CopyFrom(const TransactionOptions_ReadWrite& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.datastore.v1.TransactionOptions.ReadWrite)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool TransactionOptions_ReadWrite::IsInitialized() const {
return true;
}
void TransactionOptions_ReadWrite::Swap(TransactionOptions_ReadWrite* other) {
if (other == this) return;
InternalSwap(other);
}
void TransactionOptions_ReadWrite::InternalSwap(TransactionOptions_ReadWrite* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
previous_transaction_.Swap(&other->previous_transaction_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
::google::protobuf::Metadata TransactionOptions_ReadWrite::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fdatastore_2fv1_2fdatastore_2eproto);
return ::file_level_metadata_google_2fdatastore_2fv1_2fdatastore_2eproto[kIndexInFileMessages];
}
// ===================================================================
void TransactionOptions_ReadOnly::InitAsDefaultInstance() {
}
class TransactionOptions_ReadOnly::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
TransactionOptions_ReadOnly::TransactionOptions_ReadOnly()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:google.datastore.v1.TransactionOptions.ReadOnly)
}
TransactionOptions_ReadOnly::TransactionOptions_ReadOnly(const TransactionOptions_ReadOnly& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:google.datastore.v1.TransactionOptions.ReadOnly)
}
void TransactionOptions_ReadOnly::SharedCtor() {
}
TransactionOptions_ReadOnly::~TransactionOptions_ReadOnly() {
// @@protoc_insertion_point(destructor:google.datastore.v1.TransactionOptions.ReadOnly)
SharedDtor();
}
void TransactionOptions_ReadOnly::SharedDtor() {
}
void TransactionOptions_ReadOnly::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const TransactionOptions_ReadOnly& TransactionOptions_ReadOnly::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_TransactionOptions_ReadOnly_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
return *internal_default_instance();
}
void TransactionOptions_ReadOnly::Clear() {
// @@protoc_insertion_point(message_clear_start:google.datastore.v1.TransactionOptions.ReadOnly)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* TransactionOptions_ReadOnly::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<TransactionOptions_ReadOnly*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
default: {
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool TransactionOptions_ReadOnly::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.datastore.v1.TransactionOptions.ReadOnly)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
}
success:
// @@protoc_insertion_point(parse_success:google.datastore.v1.TransactionOptions.ReadOnly)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.datastore.v1.TransactionOptions.ReadOnly)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void TransactionOptions_ReadOnly::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.datastore.v1.TransactionOptions.ReadOnly)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.datastore.v1.TransactionOptions.ReadOnly)
}
::google::protobuf::uint8* TransactionOptions_ReadOnly::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:google.datastore.v1.TransactionOptions.ReadOnly)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.datastore.v1.TransactionOptions.ReadOnly)
return target;
}
size_t TransactionOptions_ReadOnly::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.datastore.v1.TransactionOptions.ReadOnly)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void TransactionOptions_ReadOnly::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.datastore.v1.TransactionOptions.ReadOnly)
GOOGLE_DCHECK_NE(&from, this);
const TransactionOptions_ReadOnly* source =
::google::protobuf::DynamicCastToGenerated<TransactionOptions_ReadOnly>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.datastore.v1.TransactionOptions.ReadOnly)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.datastore.v1.TransactionOptions.ReadOnly)
MergeFrom(*source);
}
}
void TransactionOptions_ReadOnly::MergeFrom(const TransactionOptions_ReadOnly& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.datastore.v1.TransactionOptions.ReadOnly)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
}
void TransactionOptions_ReadOnly::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.datastore.v1.TransactionOptions.ReadOnly)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void TransactionOptions_ReadOnly::CopyFrom(const TransactionOptions_ReadOnly& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.datastore.v1.TransactionOptions.ReadOnly)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool TransactionOptions_ReadOnly::IsInitialized() const {
return true;
}
void TransactionOptions_ReadOnly::Swap(TransactionOptions_ReadOnly* other) {
if (other == this) return;
InternalSwap(other);
}
void TransactionOptions_ReadOnly::InternalSwap(TransactionOptions_ReadOnly* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata TransactionOptions_ReadOnly::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fdatastore_2fv1_2fdatastore_2eproto);
return ::file_level_metadata_google_2fdatastore_2fv1_2fdatastore_2eproto[kIndexInFileMessages];
}
// ===================================================================
void TransactionOptions::InitAsDefaultInstance() {
::google::datastore::v1::_TransactionOptions_default_instance_.read_write_ = const_cast< ::google::datastore::v1::TransactionOptions_ReadWrite*>(
::google::datastore::v1::TransactionOptions_ReadWrite::internal_default_instance());
::google::datastore::v1::_TransactionOptions_default_instance_.read_only_ = const_cast< ::google::datastore::v1::TransactionOptions_ReadOnly*>(
::google::datastore::v1::TransactionOptions_ReadOnly::internal_default_instance());
}
class TransactionOptions::HasBitSetters {
public:
static const ::google::datastore::v1::TransactionOptions_ReadWrite& read_write(const TransactionOptions* msg);
static const ::google::datastore::v1::TransactionOptions_ReadOnly& read_only(const TransactionOptions* msg);
};
const ::google::datastore::v1::TransactionOptions_ReadWrite&
TransactionOptions::HasBitSetters::read_write(const TransactionOptions* msg) {
return *msg->mode_.read_write_;
}
const ::google::datastore::v1::TransactionOptions_ReadOnly&
TransactionOptions::HasBitSetters::read_only(const TransactionOptions* msg) {
return *msg->mode_.read_only_;
}
void TransactionOptions::set_allocated_read_write(::google::datastore::v1::TransactionOptions_ReadWrite* read_write) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
clear_mode();
if (read_write) {
::google::protobuf::Arena* submessage_arena = nullptr;
if (message_arena != submessage_arena) {
read_write = ::google::protobuf::internal::GetOwnedMessage(
message_arena, read_write, submessage_arena);
}
set_has_read_write();
mode_.read_write_ = read_write;
}
// @@protoc_insertion_point(field_set_allocated:google.datastore.v1.TransactionOptions.read_write)
}
void TransactionOptions::set_allocated_read_only(::google::datastore::v1::TransactionOptions_ReadOnly* read_only) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
clear_mode();
if (read_only) {
::google::protobuf::Arena* submessage_arena = nullptr;
if (message_arena != submessage_arena) {
read_only = ::google::protobuf::internal::GetOwnedMessage(
message_arena, read_only, submessage_arena);
}
set_has_read_only();
mode_.read_only_ = read_only;
}
// @@protoc_insertion_point(field_set_allocated:google.datastore.v1.TransactionOptions.read_only)
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int TransactionOptions::kReadWriteFieldNumber;
const int TransactionOptions::kReadOnlyFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
TransactionOptions::TransactionOptions()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:google.datastore.v1.TransactionOptions)
}
TransactionOptions::TransactionOptions(const TransactionOptions& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
clear_has_mode();
switch (from.mode_case()) {
case kReadWrite: {
mutable_read_write()->::google::datastore::v1::TransactionOptions_ReadWrite::MergeFrom(from.read_write());
break;
}
case kReadOnly: {
mutable_read_only()->::google::datastore::v1::TransactionOptions_ReadOnly::MergeFrom(from.read_only());
break;
}
case MODE_NOT_SET: {
break;
}
}
// @@protoc_insertion_point(copy_constructor:google.datastore.v1.TransactionOptions)
}
void TransactionOptions::SharedCtor() {
::google::protobuf::internal::InitSCC(
&scc_info_TransactionOptions_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
clear_has_mode();
}
TransactionOptions::~TransactionOptions() {
// @@protoc_insertion_point(destructor:google.datastore.v1.TransactionOptions)
SharedDtor();
}
void TransactionOptions::SharedDtor() {
if (has_mode()) {
clear_mode();
}
}
void TransactionOptions::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const TransactionOptions& TransactionOptions::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_TransactionOptions_google_2fdatastore_2fv1_2fdatastore_2eproto.base);
return *internal_default_instance();
}
void TransactionOptions::clear_mode() {
// @@protoc_insertion_point(one_of_clear_start:google.datastore.v1.TransactionOptions)
switch (mode_case()) {
case kReadWrite: {
delete mode_.read_write_;
break;
}
case kReadOnly: {
delete mode_.read_only_;
break;
}
case MODE_NOT_SET: {
break;
}
}
_oneof_case_[0] = MODE_NOT_SET;
}
void TransactionOptions::Clear() {
// @@protoc_insertion_point(message_clear_start:google.datastore.v1.TransactionOptions)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
clear_mode();
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* TransactionOptions::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<TransactionOptions*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// .google.datastore.v1.TransactionOptions.ReadWrite read_write = 1;
case 1: {
if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::datastore::v1::TransactionOptions_ReadWrite::_InternalParse;
object = msg->mutable_read_write();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
break;
}
// .google.datastore.v1.TransactionOptions.ReadOnly read_only = 2;
case 2: {
if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual;
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::datastore::v1::TransactionOptions_ReadOnly::_InternalParse;
object = msg->mutable_read_only();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
break;
}
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
len_delim_till_end:
return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
{parser_till_end, object}, size);
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool TransactionOptions::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.datastore.v1.TransactionOptions)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .google.datastore.v1.TransactionOptions.ReadWrite read_write = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_read_write()));
} else {
goto handle_unusual;
}
break;
}
// .google.datastore.v1.TransactionOptions.ReadOnly read_only = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_read_only()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:google.datastore.v1.TransactionOptions)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.datastore.v1.TransactionOptions)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void TransactionOptions::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.datastore.v1.TransactionOptions)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .google.datastore.v1.TransactionOptions.ReadWrite read_write = 1;
if (has_read_write()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, HasBitSetters::read_write(this), output);
}
// .google.datastore.v1.TransactionOptions.ReadOnly read_only = 2;
if (has_read_only()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2, HasBitSetters::read_only(this), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.datastore.v1.TransactionOptions)
}
::google::protobuf::uint8* TransactionOptions::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:google.datastore.v1.TransactionOptions)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .google.datastore.v1.TransactionOptions.ReadWrite read_write = 1;
if (has_read_write()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
1, HasBitSetters::read_write(this), target);
}
// .google.datastore.v1.TransactionOptions.ReadOnly read_only = 2;
if (has_read_only()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
2, HasBitSetters::read_only(this), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.datastore.v1.TransactionOptions)
return target;
}
size_t TransactionOptions::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.datastore.v1.TransactionOptions)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
switch (mode_case()) {
// .google.datastore.v1.TransactionOptions.ReadWrite read_write = 1;
case kReadWrite: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*mode_.read_write_);
break;
}
// .google.datastore.v1.TransactionOptions.ReadOnly read_only = 2;
case kReadOnly: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*mode_.read_only_);
break;
}
case MODE_NOT_SET: {
break;
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void TransactionOptions::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.datastore.v1.TransactionOptions)
GOOGLE_DCHECK_NE(&from, this);
const TransactionOptions* source =
::google::protobuf::DynamicCastToGenerated<TransactionOptions>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.datastore.v1.TransactionOptions)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.datastore.v1.TransactionOptions)
MergeFrom(*source);
}
}
void TransactionOptions::MergeFrom(const TransactionOptions& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.datastore.v1.TransactionOptions)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
switch (from.mode_case()) {
case kReadWrite: {
mutable_read_write()->::google::datastore::v1::TransactionOptions_ReadWrite::MergeFrom(from.read_write());
break;
}
case kReadOnly: {
mutable_read_only()->::google::datastore::v1::TransactionOptions_ReadOnly::MergeFrom(from.read_only());
break;
}
case MODE_NOT_SET: {
break;
}
}
}
void TransactionOptions::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.datastore.v1.TransactionOptions)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void TransactionOptions::CopyFrom(const TransactionOptions& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.datastore.v1.TransactionOptions)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool TransactionOptions::IsInitialized() const {
return true;
}
void TransactionOptions::Swap(TransactionOptions* other) {
if (other == this) return;
InternalSwap(other);
}
void TransactionOptions::InternalSwap(TransactionOptions* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(mode_, other->mode_);
swap(_oneof_case_[0], other->_oneof_case_[0]);
}
::google::protobuf::Metadata TransactionOptions::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fdatastore_2fv1_2fdatastore_2eproto);
return ::file_level_metadata_google_2fdatastore_2fv1_2fdatastore_2eproto[kIndexInFileMessages];
}
// @@protoc_insertion_point(namespace_scope)
} // namespace v1
} // namespace datastore
} // namespace google
namespace google {
namespace protobuf {
template<> PROTOBUF_NOINLINE ::google::datastore::v1::LookupRequest* Arena::CreateMaybeMessage< ::google::datastore::v1::LookupRequest >(Arena* arena) {
return Arena::CreateInternal< ::google::datastore::v1::LookupRequest >(arena);
}
template<> PROTOBUF_NOINLINE ::google::datastore::v1::LookupResponse* Arena::CreateMaybeMessage< ::google::datastore::v1::LookupResponse >(Arena* arena) {
return Arena::CreateInternal< ::google::datastore::v1::LookupResponse >(arena);
}
template<> PROTOBUF_NOINLINE ::google::datastore::v1::RunQueryRequest* Arena::CreateMaybeMessage< ::google::datastore::v1::RunQueryRequest >(Arena* arena) {
return Arena::CreateInternal< ::google::datastore::v1::RunQueryRequest >(arena);
}
template<> PROTOBUF_NOINLINE ::google::datastore::v1::RunQueryResponse* Arena::CreateMaybeMessage< ::google::datastore::v1::RunQueryResponse >(Arena* arena) {
return Arena::CreateInternal< ::google::datastore::v1::RunQueryResponse >(arena);
}
template<> PROTOBUF_NOINLINE ::google::datastore::v1::BeginTransactionRequest* Arena::CreateMaybeMessage< ::google::datastore::v1::BeginTransactionRequest >(Arena* arena) {
return Arena::CreateInternal< ::google::datastore::v1::BeginTransactionRequest >(arena);
}
template<> PROTOBUF_NOINLINE ::google::datastore::v1::BeginTransactionResponse* Arena::CreateMaybeMessage< ::google::datastore::v1::BeginTransactionResponse >(Arena* arena) {
return Arena::CreateInternal< ::google::datastore::v1::BeginTransactionResponse >(arena);
}
template<> PROTOBUF_NOINLINE ::google::datastore::v1::RollbackRequest* Arena::CreateMaybeMessage< ::google::datastore::v1::RollbackRequest >(Arena* arena) {
return Arena::CreateInternal< ::google::datastore::v1::RollbackRequest >(arena);
}
template<> PROTOBUF_NOINLINE ::google::datastore::v1::RollbackResponse* Arena::CreateMaybeMessage< ::google::datastore::v1::RollbackResponse >(Arena* arena) {
return Arena::CreateInternal< ::google::datastore::v1::RollbackResponse >(arena);
}
template<> PROTOBUF_NOINLINE ::google::datastore::v1::CommitRequest* Arena::CreateMaybeMessage< ::google::datastore::v1::CommitRequest >(Arena* arena) {
return Arena::CreateInternal< ::google::datastore::v1::CommitRequest >(arena);
}
template<> PROTOBUF_NOINLINE ::google::datastore::v1::CommitResponse* Arena::CreateMaybeMessage< ::google::datastore::v1::CommitResponse >(Arena* arena) {
return Arena::CreateInternal< ::google::datastore::v1::CommitResponse >(arena);
}
template<> PROTOBUF_NOINLINE ::google::datastore::v1::AllocateIdsRequest* Arena::CreateMaybeMessage< ::google::datastore::v1::AllocateIdsRequest >(Arena* arena) {
return Arena::CreateInternal< ::google::datastore::v1::AllocateIdsRequest >(arena);
}
template<> PROTOBUF_NOINLINE ::google::datastore::v1::AllocateIdsResponse* Arena::CreateMaybeMessage< ::google::datastore::v1::AllocateIdsResponse >(Arena* arena) {
return Arena::CreateInternal< ::google::datastore::v1::AllocateIdsResponse >(arena);
}
template<> PROTOBUF_NOINLINE ::google::datastore::v1::ReserveIdsRequest* Arena::CreateMaybeMessage< ::google::datastore::v1::ReserveIdsRequest >(Arena* arena) {
return Arena::CreateInternal< ::google::datastore::v1::ReserveIdsRequest >(arena);
}
template<> PROTOBUF_NOINLINE ::google::datastore::v1::ReserveIdsResponse* Arena::CreateMaybeMessage< ::google::datastore::v1::ReserveIdsResponse >(Arena* arena) {
return Arena::CreateInternal< ::google::datastore::v1::ReserveIdsResponse >(arena);
}
template<> PROTOBUF_NOINLINE ::google::datastore::v1::Mutation* Arena::CreateMaybeMessage< ::google::datastore::v1::Mutation >(Arena* arena) {
return Arena::CreateInternal< ::google::datastore::v1::Mutation >(arena);
}
template<> PROTOBUF_NOINLINE ::google::datastore::v1::MutationResult* Arena::CreateMaybeMessage< ::google::datastore::v1::MutationResult >(Arena* arena) {
return Arena::CreateInternal< ::google::datastore::v1::MutationResult >(arena);
}
template<> PROTOBUF_NOINLINE ::google::datastore::v1::ReadOptions* Arena::CreateMaybeMessage< ::google::datastore::v1::ReadOptions >(Arena* arena) {
return Arena::CreateInternal< ::google::datastore::v1::ReadOptions >(arena);
}
template<> PROTOBUF_NOINLINE ::google::datastore::v1::TransactionOptions_ReadWrite* Arena::CreateMaybeMessage< ::google::datastore::v1::TransactionOptions_ReadWrite >(Arena* arena) {
return Arena::CreateInternal< ::google::datastore::v1::TransactionOptions_ReadWrite >(arena);
}
template<> PROTOBUF_NOINLINE ::google::datastore::v1::TransactionOptions_ReadOnly* Arena::CreateMaybeMessage< ::google::datastore::v1::TransactionOptions_ReadOnly >(Arena* arena) {
return Arena::CreateInternal< ::google::datastore::v1::TransactionOptions_ReadOnly >(arena);
}
template<> PROTOBUF_NOINLINE ::google::datastore::v1::TransactionOptions* Arena::CreateMaybeMessage< ::google::datastore::v1::TransactionOptions >(Arena* arena) {
return Arena::CreateInternal< ::google::datastore::v1::TransactionOptions >(arena);
}
} // namespace protobuf
} // namespace google
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
| 39.795457 | 219 | 0.71544 | [
"object"
] |
bb053e234f3a112f5796746648a1a8847c7963a9 | 10,324 | cpp | C++ | divi/src/kernel.cpp | DiviProject/Divi | 4d4e34a134c2497a3f272f48beacaf292f4b6d14 | [
"MIT"
] | 56 | 2019-05-16T21:31:18.000Z | 2022-03-16T16:13:02.000Z | divi/src/kernel.cpp | Divicoin/Divi | 4d4e34a134c2497a3f272f48beacaf292f4b6d14 | [
"MIT"
] | 98 | 2018-03-07T19:30:42.000Z | 2019-04-29T14:17:12.000Z | divi/src/kernel.cpp | DiviProject/Divi | 4d4e34a134c2497a3f272f48beacaf292f4b6d14 | [
"MIT"
] | 38 | 2019-05-07T11:08:41.000Z | 2022-03-02T20:06:12.000Z | /* @flow */
// Copyright (c) 2012-2013 The PPCoin developers
// Copyright (c) 2015-2017 The PIVX Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "kernel.h"
#include <uint256.h>
#include <primitives/transaction.h>
#include <primitives/block.h>
#include "blockmap.h"
#include "BlockDiskAccessor.h"
#include "BlockRewards.h"
#include "chain.h"
#include "chainparams.h"
#include "coins.h"
#include <ForkActivation.h>
#include "script/interpreter.h"
#include "script/SignatureCheckers.h"
#include "script/standard.h"
#include "script/StakingVaultScript.h"
#include <TransactionDiskAccessor.h>
#include <streams.h>
#include "utilmoneystr.h"
#include "utilstrencodings.h"
#include <boost/assign/list_of.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/foreach.hpp>
#include <StakingData.h>
#include <StakeModifierIntervalHelpers.h>
#include <Logging.h>
#include <utiltime.h>
#include <I_ProofOfStakeGenerator.h>
#include <Settings.h>
// Hard checkpoints of stake modifiers to ensure they are deterministic
static std::map<int, unsigned int> mapStakeModifierCheckpoints =
boost::assign::map_list_of(0, 0xfd11f4e7u);
// Get the last stake modifier and its generation time from a given block
const CBlockIndex* GetLastBlockIndexWithGeneratedStakeModifier(const CBlockIndex* pindex)
{
while (pindex && pindex->pprev && !pindex->GeneratedStakeModifier())
{
pindex = pindex->pprev;
}
return pindex;
}
// select a block from the candidate blocks in timestampSortedBlockHashes, excluding
// already selected blocks in vSelectedBlocks, and with timestamp up to
// timestampUpperBound.
static const CBlockIndex* SelectBlockIndexWithTimestampUpperBound(
const BlockMap& blockIndicesByHash,
const std::vector<std::pair<int64_t, uint256> >& timestampSortedBlockHashes,
const std::set<uint256>& selectedBlockHashes,
const int64_t timestampUpperBound,
const uint64_t lastStakeModifier)
{
bool fSelected = false;
uint256 hashBest = 0;
const CBlockIndex* pindexSelected = nullptr;
for (const std::pair<int64_t, uint256>& item: timestampSortedBlockHashes)
{
if (!blockIndicesByHash.count(item.second))
{
error("%s: failed to find block index for candidate block %s",__func__, item.second);
return nullptr;
}
const CBlockIndex* pindex = blockIndicesByHash.find(item.second)->second;
if (fSelected && pindex->GetBlockTime() > timestampUpperBound)
break;
if (selectedBlockHashes.count(pindex->GetBlockHash()) > 0)
continue;
// compute the selection hash by hashing an input that is unique to that block
const uint256 blockSelectionRandomnessSeed = pindex->IsProofOfStake() ? 0 : pindex->GetBlockHash();
// the selection hash is divided by 2**32 so that proof-of-stake block
// is always favored over proof-of-work block. this is to preserve
// the energy efficiency property
CDataStream ss(SER_GETHASH, 0);
ss << blockSelectionRandomnessSeed << lastStakeModifier;
const uint256 hashSelection = pindex->IsProofOfStake()? Hash(ss.begin(), ss.end()) >> 32 : Hash(ss.begin(), ss.end());
if (fSelected && hashSelection < hashBest)
{
hashBest = hashSelection;
pindexSelected = pindex;
}
else if (!fSelected)
{
fSelected = true;
hashBest = hashSelection;
pindexSelected = pindex;
}
}
return pindexSelected;
}
// Stake Modifier (hash modifier of proof-of-stake):
// The purpose of stake modifier is to prevent a txout (coin) owner from
// computing future proof-of-stake generated by this txout at the time
// of transaction confirmation. To meet kernel protocol, the txout
// must hash with a future stake modifier to generate the proof.
// Stake modifier consists of bits each of which is contributed from a
// selected block of a given block group in the past.
// The selection of a block is based on a hash of the block's proof-hash and
// the previous stake modifier.
// Stake modifier is recomputed at a fixed time interval instead of every
// block. This is to make it difficult for an attacker to gain control of
// additional bits in the stake modifier, even after generating a chain of
// blocks.
struct RecentBlockHashesSortedByIncreasingTimestamp
{
std::vector<std::pair<int64_t, uint256> > timestampSortedBlockHashes;
int64_t timestampLowerBound;
RecentBlockHashesSortedByIncreasingTimestamp(int64_t smallestTimestamp): timestampSortedBlockHashes(),timestampLowerBound(smallestTimestamp)
{
timestampSortedBlockHashes.reserve(64);
}
void recordBlockHashesAndTimestamps(const CBlockIndex* blockIndex)
{
while (blockIndex && blockIndex->GetBlockTime() >= timestampLowerBound)
{
timestampSortedBlockHashes.push_back(std::make_pair(blockIndex->GetBlockTime(), blockIndex->GetBlockHash()));
blockIndex = blockIndex->pprev;
}
std::reverse(timestampSortedBlockHashes.begin(), timestampSortedBlockHashes.end());
std::sort(timestampSortedBlockHashes.begin(), timestampSortedBlockHashes.end());
}
};
RecentBlockHashesSortedByIncreasingTimestamp GetRecentBlocksSortedByIncreasingTimestamp(const CBlockIndex* pindexPrev)
{
// Sort candidate blocks by timestamp
int64_t blockSelectionTimestampLowerBound = (pindexPrev->GetBlockTime() / MODIFIER_INTERVAL) * MODIFIER_INTERVAL - GetStakeModifierSelectionInterval();
RecentBlockHashesSortedByIncreasingTimestamp sortedBlockHashes(blockSelectionTimestampLowerBound);
sortedBlockHashes.recordBlockHashesAndTimestamps(pindexPrev);
return sortedBlockHashes;
}
bool ComputeNextStakeModifier(
const BlockMap& blockIndicesByHash,
const CBlockIndex* pindexPrev,
uint64_t& nextStakeModifier,
bool& fGeneratedStakeModifier)
{
nextStakeModifier = 0;
fGeneratedStakeModifier = false;
if (!pindexPrev) {
fGeneratedStakeModifier = true;
return true; // genesis block's modifier is 0
}
if (pindexPrev->nHeight == 0) {
//Give a stake modifier to the first block
fGeneratedStakeModifier = true;
nextStakeModifier = 0x7374616b656d6f64;
return true;
}
// First find current stake modifier and its generation block time
// if it's not old enough, return the same stake modifier
const CBlockIndex* indexWhereLastStakeModifierWasSet = GetLastBlockIndexWithGeneratedStakeModifier(pindexPrev);
if (!indexWhereLastStakeModifierWasSet || !indexWhereLastStakeModifierWasSet->GeneratedStakeModifier())
return error("ComputeNextStakeModifier: unable to get last modifier prior to blockhash %s\n",pindexPrev->GetBlockHash());
if (indexWhereLastStakeModifierWasSet->GetBlockTime() / MODIFIER_INTERVAL >= pindexPrev->GetBlockTime() / MODIFIER_INTERVAL)
{
nextStakeModifier = indexWhereLastStakeModifierWasSet->nStakeModifier;
return true;
}
uint64_t nStakeModifierNew = 0;
RecentBlockHashesSortedByIncreasingTimestamp recentBlockHashesAndTimestamps = GetRecentBlocksSortedByIncreasingTimestamp(pindexPrev);
const std::vector<std::pair<int64_t, uint256> >& timestampSortedBlockHashes = recentBlockHashesAndTimestamps.timestampSortedBlockHashes;
int64_t timestampUpperBound = recentBlockHashesAndTimestamps.timestampLowerBound;
std::set<uint256> selectedBlockHashes;
for (int nRound = 0; nRound < std::min(64, (int)timestampSortedBlockHashes.size()); nRound++) {
timestampUpperBound += GetStakeModifierSelectionIntervalSection(nRound);
const CBlockIndex* pindex = SelectBlockIndexWithTimestampUpperBound(
blockIndicesByHash, timestampSortedBlockHashes, selectedBlockHashes, timestampUpperBound, indexWhereLastStakeModifierWasSet->nStakeModifier);
if (!pindex) return error("ComputeNextStakeModifier: unable to select block at round %d", nRound);
nStakeModifierNew |= (((uint64_t)pindex->GetStakeEntropyBit()) << nRound);
selectedBlockHashes.insert(pindex->GetBlockHash());
}
if(ActivationState(pindexPrev).IsActive(Fork::HardenedStakeModifier))
{
CHashWriter hasher(SER_GETHASH,0);
hasher << pindexPrev->GetBlockHash() << nStakeModifierNew;
nextStakeModifier = hasher.GetHash().GetLow64();
}
else
{
nextStakeModifier = nStakeModifierNew;
}
fGeneratedStakeModifier = true;
return true;
}
// Get stake modifier checksum
unsigned int GetStakeModifierChecksum(const CBlockIndex* pindex)
{
assert(pindex->pprev || pindex->GetBlockHash() == Params().HashGenesisBlock());
// Hash previous checksum with flags, hashProofOfStake and nStakeModifier
CDataStream ss(SER_GETHASH, 0);
if (pindex->pprev)
ss << pindex->pprev->nStakeModifierChecksum;
ss << pindex->nFlags << pindex->hashProofOfStake << pindex->nStakeModifier;
uint256 hashChecksum = Hash(ss.begin(), ss.end());
hashChecksum >>= (256 - 32);
return hashChecksum.Get64();
}
// Check stake modifier hard checkpoints
bool CheckStakeModifierCheckpoints(int nHeight, unsigned int nStakeModifierChecksum)
{
if (mapStakeModifierCheckpoints.count(nHeight)) {
return nStakeModifierChecksum == mapStakeModifierCheckpoints[nHeight];
}
return true;
}
void SetStakeModifiersForNewBlockIndex(const BlockMap& blockIndicesByHash, CBlockIndex* pindexNew)
{
uint64_t nextStakeModifier = 0;
bool fGeneratedStakeModifier = false;
if (!ComputeNextStakeModifier(blockIndicesByHash, pindexNew->pprev, nextStakeModifier, fGeneratedStakeModifier))
LogPrintf("%s : ComputeNextStakeModifier() failed \n",__func__);
pindexNew->SetStakeModifier(nextStakeModifier, fGeneratedStakeModifier);
pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
LogPrintf("%s : Rejected by stake modifier checkpoint height=%d, modifier=%s \n", __func__, pindexNew->nHeight, boost::lexical_cast<std::string>(nextStakeModifier));
} | 41.629032 | 173 | 0.736149 | [
"vector"
] |
bb0c3ba975c9f56f1890e6c80cb9920394d87ec0 | 1,560 | cpp | C++ | stl/vector2.cpp | immol/bologs | 04e3a07a6098220f66b7bc19c1ab9e30fb73eb8c | [
"MIT"
] | 1 | 2021-05-30T03:28:19.000Z | 2021-05-30T03:28:19.000Z | stl/vector2.cpp | immol/bologs | 04e3a07a6098220f66b7bc19c1ab9e30fb73eb8c | [
"MIT"
] | null | null | null | stl/vector2.cpp | immol/bologs | 04e3a07a6098220f66b7bc19c1ab9e30fb73eb8c | [
"MIT"
] | null | null | null | #define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
#include<string>
void printVector(vector<int>& v) {
for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
cout << *it << " ";
}
cout << endl;
cout << "容器容量"<<v.capacity() << endl;
}
void test01() {
//常用api
vector<int>v;
//构造函数
int arr[] = { 1,2,3,4,5,6,7,8 };
vector<int> v1(arr, arr + sizeof(arr) / sizeof(int));
vector<int>v2(v1.begin(), v1.end());
printVector(v2);
//构造函数 将n个m拷贝
vector<int>v3(10, 100);
printVector(v3);
v3.resize(10, 0);
printVector(v3);
//容器大小
v3.size();
}
void test02() {
//使用swap收缩空间
vector<int>v;
for (int i = 0; i < 10; i++) {
v.push_back(i);
}
v.resize(3);
//收缩空间
vector<int>(v).swap(v);
}
void test03() {
vector<int>v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(40);
cout << "v的front:" << v.front() << endl;
cout << "v的back:" << v.back() << endl;
v.insert(v.begin(), 2,100);//参数一 迭代器 参数2 N 参数三 具体插入的内容
printVector(v);
v.pop_back();//尾删
printVector(v);
v.erase(v.begin(), v.end());//删除某个区间的数
if (v.empty()) {
cout << "为空" << endl;
}
v.clear();//清空所有数据
}
void test04() {
vector<int>v;
for (int i = 0; i < 10; i++) {
v.push_back(i);
}
//逆序遍历
for (vector<int>::reverse_iterator it = v.rbegin(); it != v.rend(); it++) {
cout << *it << " ";
}
cout << endl;
//vector迭代器是随机访问的迭代器 支持跳跃式访问
vector<int>::iterator itBegin = v.begin();
itBegin = itBegin + 3;//此步不报错 可以支持随机访问
}
int main() {
//test01();
//test03();
test04();
return 0;
}
| 19.02439 | 76 | 0.591026 | [
"vector"
] |
bb10335f6571ec543a6d3d583341446f58b94b88 | 2,540 | hpp | C++ | inst/include/dust/filter.hpp | mrc-ide/dust | 24f843d3af30ccd14c233c2db8bcd03bfc42369b | [
"MIT"
] | 14 | 2020-06-02T00:29:43.000Z | 2021-06-20T06:46:33.000Z | inst/include/dust/filter.hpp | mrc-ide/dust | 24f843d3af30ccd14c233c2db8bcd03bfc42369b | [
"MIT"
] | 350 | 2020-06-01T18:05:42.000Z | 2022-03-24T17:06:21.000Z | inst/include/dust/filter.hpp | mrc-ide/dust | 24f843d3af30ccd14c233c2db8bcd03bfc42369b | [
"MIT"
] | 1 | 2021-09-13T15:25:39.000Z | 2021-09-13T15:25:39.000Z | #ifndef DUST_FILTER_HPP
#define DUST_FILTER_HPP
#include "dust/filter_state.hpp"
#include "dust/filter_tools.hpp"
namespace dust {
namespace filter {
// Host version
template <typename T>
std::vector<typename T::real_type>
filter(T * obj,
filter_state_host<typename T::real_type>& state,
bool save_trajectories,
std::vector<size_t> step_snapshot) {
using real_type = typename T::real_type;
const size_t n_particles = obj->n_particles();
const size_t n_data = obj->n_data();
const size_t n_pars = obj->n_pars_effective();
const size_t n_particles_each = n_particles / n_pars;
std::vector<real_type> log_likelihood(n_pars);
std::vector<real_type> log_likelihood_step(n_pars);
std::vector<real_type> weights(n_particles);
std::vector<size_t> kappa(n_particles);
if (save_trajectories) {
state.trajectories.resize(obj->n_state(), n_particles, n_data);
obj->state(state.trajectories.value_iterator());
state.trajectories.advance();
}
bool save_snapshots = false;
if (step_snapshot.size() > 0) {
save_snapshots = true;
state.snapshots.resize(obj->n_state_full(), n_particles, step_snapshot);
}
for (auto & d : obj->data()) {
obj->run(d.first);
obj->compare_data(weights, d.second);
// TODO: we should cope better with the case where all weights
// are 0; I think that is the behaviour in the model (or rather
// the case where there is no data and so we do not resample)
//
// TODO: we should cope better with the case where one filter
// has become impossible but others continue, but that's hard!
auto wi = weights.begin();
for (size_t i = 0; i < n_pars; ++i) {
log_likelihood_step[i] = scale_log_weights<real_type>(wi, n_particles_each);
log_likelihood[i] += log_likelihood_step[i];
wi += n_particles_each;
}
// We could move this below if wanted but we'd have to rewrite
// the re-sort algorithm; that would be worth doing I think
// https://github.com/mrc-ide/dust/issues/202
if (save_trajectories) {
obj->state(state.trajectories.value_iterator());
}
obj->resample(weights, kappa);
if (save_trajectories) {
std::copy(kappa.begin(), kappa.end(),
state.trajectories.order_iterator());
state.trajectories.advance();
}
if (save_snapshots && state.snapshots.is_snapshot_step(d.first)) {
obj->state_full(state.snapshots.value_iterator());
state.snapshots.advance();
}
}
return log_likelihood;
}
}
}
#endif
| 29.195402 | 82 | 0.684252 | [
"vector",
"model"
] |
bb1d7c1909d67955dd3ad6a5f0a5daef823bfe45 | 7,884 | cpp | C++ | src/linux_parser.cpp | ppfenninger/CppND-System-Monitor | b683043700c50d68f89af8acbaf474abaaf24915 | [
"MIT"
] | null | null | null | src/linux_parser.cpp | ppfenninger/CppND-System-Monitor | b683043700c50d68f89af8acbaf474abaaf24915 | [
"MIT"
] | null | null | null | src/linux_parser.cpp | ppfenninger/CppND-System-Monitor | b683043700c50d68f89af8acbaf474abaaf24915 | [
"MIT"
] | null | null | null | #include <dirent.h>
#include <unistd.h>
#include <sstream>
#include <string>
#include <vector>
#include <iostream>
#include "linux_parser.h"
using std::stof;
using std::string;
using std::to_string;
using std::vector;
string LinuxParser::OperatingSystem() {
string line;
string key;
string value;
std::ifstream filestream(kOSPath);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::replace(line.begin(), line.end(), ' ', '_');
std::replace(line.begin(), line.end(), '=', ' ');
std::replace(line.begin(), line.end(), '"', ' ');
std::istringstream linestream(line);
while (linestream >> key >> value) {
if (key == "PRETTY_NAME") {
std::replace(value.begin(), value.end(), '_', ' ');
return value;
}
}
}
}
return value;
}
string LinuxParser::Kernel() {
string os, kernel, version;
string line;
std::ifstream stream(kProcDirectory + kVersionFilename);
if (stream.is_open()) {
std::getline(stream, line);
std::istringstream linestream(line);
linestream >> os >> version >> kernel;
}
return kernel;
}
vector<int> LinuxParser::Pids() {
vector<int> pids;
DIR* directory = opendir(kProcDirectory.c_str());
struct dirent* file;
while ((file = readdir(directory)) != nullptr) {
// Is this a directory?
if (file->d_type == DT_DIR) {
// Is every character of the name a digit?
string filename(file->d_name);
if (std::all_of(filename.begin(), filename.end(), isdigit)) {
int pid = stoi(filename);
pids.push_back(pid);
}
}
}
closedir(directory);
return pids;
}
float LinuxParser::MemoryUtilization() {
string line;
string key;
string value;
float memoryFree;
float memoryTotal;
std::ifstream filestream(kProcDirectory + kMeminfoFilename);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::remove_if(line.begin(), line.end(), isspace);
std::replace(line.begin(), line.end(), ':', ' ');
std::istringstream linestream(line);
while (linestream >> key >> value) {
if (key == "MemTotal") {
value = value.erase(value.length() - 2); //remove KB from the end
memoryTotal = std::stof(value);
}
if (key == "MemFree") {
value = value.erase(value.length() - 2); //remove KB from the end
memoryFree = std::stof(value);
}
}
}
}
return (memoryTotal - memoryFree) / memoryTotal;
}
long LinuxParser::UpTime() {
string line;
string uptimeString;
string idletimeString;
float uptime;
std::ifstream filestream(kProcDirectory + kUptimeFilename);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::istringstream linestream(line);
while (linestream >> uptimeString >> idletimeString) {
uptime = std::stol(uptimeString);
}
}
}
return uptime;
}
long LinuxParser::CpuUtilization(int pid) {
string line;
vector<std::string> values;
size_t pos = 0;
std::ifstream filestream(kProcDirectory + std::to_string(pid) + kStatFilename);
if (filestream.is_open()) {
std::getline(filestream, line);
while((pos = line.find(" ")) != std::string::npos) {
values.push_back(line.substr(0, pos));
line.erase(0, pos + 1);
}
}
long utime = stol(values[13]);
long stime = stol(values[14]);
long cutime = stol(values[15]);
long cstime = stol(values[16]);
long uptime = UpTime();
long starttime = UpTime(pid);
long hertz = sysconf(_SC_CLK_TCK);
long totalTime = utime + stime + cutime + cstime;
long seconds = uptime - starttime;
if(seconds) {
return ((totalTime / hertz) / seconds);
}
return 0;
}
float LinuxParser::CpuUtilization() {
string line;
string substring;
vector<std::string> values;
size_t pos = 0;
std::ifstream filestream(kProcDirectory + kStatFilename);
if (filestream.is_open()) {
std::getline(filestream, line);
while((pos = line.find(" ")) != std::string::npos) {
substring = line.substr(0, pos);
values.push_back(line.substr(0, pos));
line.erase(0, pos + 1);
}
}
float user = stof(values[2]);
float nice = stof(values[3]);
float system = stof(values[4]);
float idle = stof(values[5]);
float iowait = stof(values[6]);
// float irq = stof(values[6]);
// float softIrq = stof(values[7]);
// float steal = stof(values[8]);
// float guest = stof(values[9]);
// float guestNice = stof(values[10]);
float idletime = idle + iowait;
float busytime = user + nice + system;
return (busytime / (idletime + busytime));
}
int LinuxParser::TotalProcesses() {
string line;
string key;
string value;
std::ifstream filestream(kProcDirectory + kStatFilename);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::istringstream linestream(line);
while (linestream >> key >> value) {
if (key == "processes") {
return std::stoi(value);
}
}
}
}
return 0;
}
int LinuxParser::RunningProcesses() {
string line;
string key;
string value;
std::ifstream filestream(kProcDirectory + kStatFilename);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::istringstream linestream(line);
while (linestream >> key >> value) {
if (key == "procs_running") {
return std::stoi(value);
}
}
}
}
return 0;
}
string LinuxParser::Command(int pid) {
string line;
string key;
string value;
std::ifstream filestream(kProcDirectory + std::to_string(pid) + kCmdlineFilename);
if (filestream.is_open()) {
std::getline(filestream, line);
return line;
}
return "";
}
string LinuxParser::Ram(int pid) {
string line;
string key;
string value;
std::ifstream filestream(kProcDirectory + std::to_string(pid) + kStatusFilename);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::remove_if(line.begin(), line.end(), isspace);
std::replace(line.begin(), line.end(), ':', ' ');
std::istringstream linestream(line);
while (linestream >> key >> value) {
if (key == "VmSize") {
value = value.erase(value.length() - 2); //remove KB from the end
return std::to_string(stoi(value)/1000) + "MB"; //convert to MB
}
}
}
}
return "";
}
string LinuxParser::Uid(int pid) {
string line;
string key;
string value;
std::ifstream filestream(kProcDirectory + std::to_string(pid) + kStatusFilename);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::istringstream linestream(line);
while (linestream >> key >> value) {
if (key == "Uid:") {
return value;
}
}
}
}
return "";
}
string LinuxParser::User(int pid) {
string line;
string key;
string x;
string id;
string userId = Uid(pid);
std::ifstream filestream(kPasswordPath);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::remove_if(line.begin(), line.end(), isspace);
std::replace(line.begin(), line.end(), ':', ' ');
std::istringstream linestream(line);
while (linestream >> key >> x >> id) {
if (id == userId) {
return key;
}
}
}
}
return "";
}
long LinuxParser::UpTime(int pid) {
string line;
string key;
string value;
vector<std::string> values;
size_t pos = 0;
std::ifstream filestream(kProcDirectory + std::to_string(pid) + kStatFilename);
if (filestream.is_open()) {
std::getline(filestream, line);
while((pos = line.find(" ")) != std::string::npos) {
values.push_back(line.substr(0, pos));
line.erase(0, pos + 1);
}
}
return UpTime() - stol(values[21])/sysconf(_SC_CLK_TCK);
}
| 25.10828 | 84 | 0.609589 | [
"vector"
] |
bb233d7f097f2766707e9efb5c1856b3e130da28 | 966 | cpp | C++ | Cplus/MaximumNumberofTasksYouCanAssign.cpp | JumHorn/leetcode | 1447237ae8fc3920b19f60b30c71a84b088cc200 | [
"MIT"
] | 1 | 2018-01-22T12:06:28.000Z | 2018-01-22T12:06:28.000Z | Cplus/MaximumNumberofTasksYouCanAssign.cpp | JumHorn/leetcode | 1447237ae8fc3920b19f60b30c71a84b088cc200 | [
"MIT"
] | null | null | null | Cplus/MaximumNumberofTasksYouCanAssign.cpp | JumHorn/leetcode | 1447237ae8fc3920b19f60b30c71a84b088cc200 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <set>
#include <vector>
using namespace std;
class Solution
{
public:
int maxTaskAssign(vector<int> &tasks, vector<int> &workers, int pills, int strength)
{
sort(tasks.begin(), tasks.end());
sort(workers.begin(), workers.end(), greater<int>());
int lo = 0, hi = min(workers.size(), tasks.size()) + 1;
while (lo < hi)
{
int mi = (hi - lo) / 2 + lo;
if (check(tasks, workers, mi, pills, strength))
lo = mi + 1;
else
hi = mi;
}
return lo - 1;
}
bool check(vector<int> &tasks, vector<int> &workers, int index, int pills, int strength)
{
multiset<int> worker(workers.begin(), workers.begin() + index);
for (int i = index - 1; i >= 0; --i)
{
auto it = --worker.end();
if (tasks[i] > *it)
{
if (pills <= 0)
return false;
it = worker.lower_bound(tasks[i] - strength);
if (it == worker.end())
return false;
--pills;
}
worker.erase(it);
}
return true;
}
}; | 21.954545 | 89 | 0.583851 | [
"vector"
] |
bb269b6232d06b68a30230605c306fe3bb5a11f4 | 1,040 | hpp | C++ | cpp-projects/3d-engine/imgui/imgui_utility.hpp | FlorianLance/toolbox | 87882a14ec86852d90527c81475b451b9f6e12cf | [
"MIT"
] | null | null | null | cpp-projects/3d-engine/imgui/imgui_utility.hpp | FlorianLance/toolbox | 87882a14ec86852d90527c81475b451b9f6e12cf | [
"MIT"
] | null | null | null | cpp-projects/3d-engine/imgui/imgui_utility.hpp | FlorianLance/toolbox | 87882a14ec86852d90527c81475b451b9f6e12cf | [
"MIT"
] | 1 | 2021-07-06T14:47:41.000Z | 2021-07-06T14:47:41.000Z |
#pragma once
// std
#include <vector>
#include <string>
// imgui
#include "imgui.h"
namespace ImGui{
static auto vector_getter = [](void* vec, int idx, const char** out_text){
auto& vector = *static_cast<std::vector<std::string>*>(vec);
if (idx < 0 || idx >= static_cast<int>(vector.size())) {
return false;
}
*out_text = vector.at(idx).c_str();
return true;
};
[[maybe_unused]] static bool Combo(const char* label, int* currIndex, std::vector<std::string>& values){
if (values.empty()) {
return false;
}
return Combo(label, currIndex, vector_getter,static_cast<void*>(&values), values.size());
}
[[maybe_unused]] static bool ListBox(const char* label, int* currIndex, std::vector<std::string>& values){
if (values.empty()) {
return false;
}
return ListBox(label, currIndex, vector_getter,static_cast<void*>(&values), values.size());
}
[[maybe_unused]] static void Text(const std::string &text){
auto d = text.c_str();
ImGui::Text(d, d + text.size());
}
}
| 25.365854 | 106 | 0.639423 | [
"vector"
] |
bb2a3e663767279e79a1b29845064f8add7a499d | 2,291 | cpp | C++ | multisig/MultiSigTrxResultDialog.cpp | whitexwc15184/WhitecoinLightWallet | cfc458faa1695d90d2210903425377612113c064 | [
"MIT"
] | null | null | null | multisig/MultiSigTrxResultDialog.cpp | whitexwc15184/WhitecoinLightWallet | cfc458faa1695d90d2210903425377612113c064 | [
"MIT"
] | 3 | 2020-03-16T05:23:24.000Z | 2020-03-31T03:29:39.000Z | multisig/MultiSigTrxResultDialog.cpp | whitexwc15184/WhitecoinLightWallet | cfc458faa1695d90d2210903425377612113c064 | [
"MIT"
] | 1 | 2020-02-16T00:28:39.000Z | 2020-02-16T00:28:39.000Z | #include "MultiSigTrxResultDialog.h"
#include "ui_MultiSigTrxResultDialog.h"
#include <QClipboard>
#include "wallet.h"
MultiSigTrxResultDialog::MultiSigTrxResultDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::MultiSigTrxResultDialog)
{
ui->setupUi(this);
connect( XWCWallet::getInstance(), SIGNAL(jsonDataUpdated(QString)), this, SLOT(jsonDataUpdated(QString)));
setParent(XWCWallet::getInstance()->mainFrame->containerWidget);
setAttribute(Qt::WA_TranslucentBackground, true);
setWindowFlags(Qt::FramelessWindowHint);
}
MultiSigTrxResultDialog::~MultiSigTrxResultDialog()
{
delete ui;
}
void MultiSigTrxResultDialog::setTrxCode(QString code)
{
ui->trxCodeTextBrowser->setText(code);
XWCWallet::getInstance()->postRPC( "MultiSigTrxResultDialog-decode_multisig_transaction",
toJsonFormat( "decode_multisig_transaction",
QJsonArray() << code ));
}
void MultiSigTrxResultDialog::pop()
{
move(0,0);
exec();
}
void MultiSigTrxResultDialog::jsonDataUpdated(QString id)
{
if( id == "MultiSigTrxResultDialog-decode_multisig_transaction")
{
QString result = XWCWallet::getInstance()->jsonDataValue(id);
qDebug() << id << result;
if( result.startsWith("\"result\":"))
{
result.prepend("{");
result.append("}");
QJsonObject object = QJsonDocument::fromJson(result.toUtf8()).object();
QJsonObject resultObject = object.value("result").toObject();
ui->trxStructTextBrowser->setText( QJsonDocument(resultObject).toJson());
}
else
{
ui->trxStructTextBrowser->setText("error: \n" + result);
}
return;
}
}
void MultiSigTrxResultDialog::on_closeBtn_clicked()
{
close();
}
void MultiSigTrxResultDialog::on_okBtn_clicked()
{
close();
}
void MultiSigTrxResultDialog::on_copyBtn_clicked()
{
QClipboard* clipBoard = QApplication::clipboard();
clipBoard->setText(ui->trxCodeTextBrowser->toPlainText());
}
void MultiSigTrxResultDialog::on_copyBtn2_clicked()
{
QClipboard* clipBoard = QApplication::clipboard();
clipBoard->setText(ui->trxStructTextBrowser->toPlainText());
}
| 25.455556 | 111 | 0.666085 | [
"object"
] |
bb2ee60e52a7edae8220699cb10b39d26646da2b | 3,335 | cpp | C++ | papi_test.cpp | indrekis/blog_samples_timing_2017 | ec246727c1886bb0f91bc29f9e7ddcc0e387b63e | [
"BSD-3-Clause"
] | null | null | null | papi_test.cpp | indrekis/blog_samples_timing_2017 | ec246727c1886bb0f91bc29f9e7ddcc0e387b63e | [
"BSD-3-Clause"
] | null | null | null | papi_test.cpp | indrekis/blog_samples_timing_2017 | ec246727c1886bb0f91bc29f9e7ddcc0e387b63e | [
"BSD-3-Clause"
] | null | null | null | #include <papi.h>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <map>
#include <random>
#include <algorithm>
using namespace std;
int main()
{
std::random_device rd;
std::mt19937 rand_g(rd());
// See http://icl.cs.utk.edu/projects/papi/wiki/PAPIC:Preset_Event_Definitions
int ret = PAPI_library_init(PAPI_VER_CURRENT);
if (ret != PAPI_VER_CURRENT) {
cout << "PAPI library init error!" << endl;
exit(1);
}
// ret = PAPI_multiplex_init();
// if (ret != PAPI_OK) {
// cout << "PAPI multiplexing init error!" << endl;
// exit(1);
// }
vector<int> Events {
PAPI_L1_DCM, PAPI_L1_ICM, PAPI_L2_DCM, PAPI_L2_ICM, PAPI_L3_DCM, PAPI_L3_ICM,
PAPI_L1_TCM, PAPI_L2_TCM, PAPI_L3_TCM,
PAPI_TLB_DM, PAPI_TLB_IM, PAPI_TLB_TL,
PAPI_PRF_DM,
PAPI_STL_ICY, PAPI_FUL_ICY, PAPI_STL_CCY, PAPI_FUL_CCY,
PAPI_BR_CN, PAPI_BR_TKN, PAPI_BR_NTK, PAPI_BR_MSP, PAPI_BR_PRC,
PAPI_TOT_IIS, PAPI_TOT_INS, PAPI_INT_INS, PAPI_FP_INS,
PAPI_LD_INS, PAPI_SR_INS, PAPI_BR_INS,
PAPI_VEC_INS,
PAPI_RES_STL, PAPI_FP_STAL,
PAPI_HW_INT,
PAPI_LST_INS, PAPI_SYC_INS,
PAPI_FML_INS, PAPI_FAD_INS, PAPI_FDV_INS, PAPI_FSQ_INS, PAPI_FNV_INS, PAPI_FP_OPS,
PAPI_VEC_SP, PAPI_VEC_DP,PAPI_TOT_INS,PAPI_TOT_CYC
};
map<int, PAPI_event_info_t> events_info;
for(int event: Events)
{
PAPI_event_info_t info;
if ( (ret = PAPI_get_event_info(event, &info)) == PAPI_OK)
{
events_info[event] = info;
}else{
cout << "Error obtaining event info, code: " << ret << ", " << PAPI_strerror(ret) << endl;
}
}
vector<int> SupportedEvents;
for(int event: Events)
{
if(events_info[event].count > 0)
SupportedEvents.push_back(event);
}
cout << "Supported " << SupportedEvents.size() << " of " << Events.size() << " events" << endl;
cout << "Hardware countes: " << PAPI_num_counters() << endl;
vector<long_long> values(SupportedEvents.size());
//cout << "Maximal events: " << PAPI_MAX_PRESET_EVENTS << endl;
//! Hardware counters are toooo limited, so -- this trick.
std::shuffle(SupportedEvents.begin(), SupportedEvents.end(), rand_g);
size_t NUM_EVENTS = min(static_cast<size_t>(PAPI_num_counters()), SupportedEvents.size());
if ( (ret = PAPI_start_counters(SupportedEvents.data(), NUM_EVENTS)) != PAPI_OK)
{
cout << "Error starting counters, code: " << ret << ", " << PAPI_strerror(ret) << endl;
return 1;
}
/* Begin of code for testing */
double x = 1;
for(size_t i = 0; i<100000000; ++i)
{
x += std::sqrt(x);
}
/* End of code for testing */
if ( (ret = PAPI_read_counters(values.data(), NUM_EVENTS)) != PAPI_OK)
{
cout << "Err code: " << ret << ", " << PAPI_strerror(ret) << endl;
return 1;
}
char EventCodeStr[PAPI_MAX_STR_LEN];
for(size_t i = 0; i<NUM_EVENTS; ++i)
{
cout << "Event code " << hex << SupportedEvents[i] << dec;
if (PAPI_event_code_to_name(SupportedEvents[i], EventCodeStr) == PAPI_OK)
{
cout << ", " << EventCodeStr;
}
cout << ": " << values[i];
PAPI_event_info_t info;
if (PAPI_get_event_info(SupportedEvents[i], &info) == PAPI_OK)
{
cout << "\t" << info.long_descr;
}else{
cout << "\t" << "No description";
}
cout << endl;
}
} | 29.254386 | 97 | 0.63988 | [
"vector"
] |
7d6cdce87b0fd087f20d89bc05785c15c982e6b7 | 2,306 | hpp | C++ | include/sge/node.hpp | smaudet/sdl-game-engine | e49a001541c6e30c0cc0ee6aa04ee6ba2b5f4af7 | [
"MIT"
] | 75 | 2017-07-19T14:00:55.000Z | 2022-01-10T21:50:44.000Z | include/sge/node.hpp | smaudet/sdl-game-engine | e49a001541c6e30c0cc0ee6aa04ee6ba2b5f4af7 | [
"MIT"
] | 3 | 2017-04-05T00:57:33.000Z | 2018-11-14T07:48:40.000Z | include/sge/node.hpp | smaudet/sdl-game-engine | e49a001541c6e30c0cc0ee6aa04ee6ba2b5f4af7 | [
"MIT"
] | 12 | 2017-09-19T09:51:48.000Z | 2021-12-05T18:11:53.000Z | #ifndef __SGE_NODE_HPP
#define __SGE_NODE_HPP
#include <sge/engine-forward.hpp>
#include <SDL.h>
#include <memory>
#include <string>
#include <vector>
namespace sge
{
class Node : public std::enable_shared_from_this<Node>
{
public:
Node(const std::string &name, Engine &engine);
virtual void init();
const char *get_name() const;
virtual std::vector<std::string> mro() const;
bool is_of(const std::string &nodetype) const;
std::shared_ptr<Node> get_root();
std::shared_ptr<Node> get_parent() const;
std::vector<std::shared_ptr<Node>> get_children() const;
std::shared_ptr<Node> get_node(const std::string &path);
std::vector<std::shared_ptr<Node>> find_children_by_type(const std::vector<std::string> &types) const;
std::shared_ptr<Node> find_first_ancestor_by_type(const std::string &type) const;
void add_child(std::shared_ptr<Node> child, bool reparent = true);
void remove_child(std::shared_ptr<Node> child, bool reparent = true);
void reparent(std::shared_ptr<Node> parent, bool remove = true, bool add = true);
bool has_input() const;
void set_input(bool enabled);
bool send_input(SDL_Event *event);
virtual bool input(SDL_Event *event);
bool has_process() const;
void set_process(bool enabled);
void send_process(Uint32 delta);
virtual void process(Uint32 delta);
bool has_draw() const;
void set_draw(bool enabled);
void send_draw();
virtual void draw();
void send_enter_tree();
virtual void enter_tree();
virtual void ready();
void send_exit_tree();
virtual void exit_tree();
bool is_in_tree() const;
private:
bool input_enabled{false};
bool process_enabled{false};
bool draw_enabled{false};
bool in_tree{false};
std::string name;
std::weak_ptr<Node> parent;
std::vector<std::shared_ptr<Node>> children;
protected:
Engine &engine;
};
}
#endif /* __SGE_NODE_HPP */
| 30.342105 | 114 | 0.587598 | [
"vector"
] |
7d81cf94376617e30365c6297b8c222c464abd34 | 18,560 | cpp | C++ | src/slave/wpa-crack-s.cpp | sdsunjay/DWPACLEC2 | 96ba5c01ec5785de1534841c3e7cb09783be2d32 | [
"Unlicense"
] | 3 | 2015-02-25T02:40:14.000Z | 2021-05-17T00:17:29.000Z | src/slave/wpa-crack-s.cpp | sdsunjay/DWPACLEC2 | 96ba5c01ec5785de1534841c3e7cb09783be2d32 | [
"Unlicense"
] | null | null | null | src/slave/wpa-crack-s.cpp | sdsunjay/DWPACLEC2 | 96ba5c01ec5785de1534841c3e7cb09783be2d32 | [
"Unlicense"
] | 3 | 2015-04-20T07:36:10.000Z | 2017-10-04T05:29:12.000Z | #include <stdio.h>
#include <stdlib.h>
#include <string>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <sqlite3.h>
#include <iostream>
#include "headers/common.h"
#include "headers/cpu-crack.h"
#include "headers/gpu-crack.h"
#include <iostream>
using std::cout;
using std::endl;
#include <fstream>
using std::ifstream;
#include <cstring>
const int MAX_CHARS_PER_LINE = 25;
const int MIN_CHARS_PER_LINE = 8;
using namespace std;
//in case there are 8 cpu threads + 1 for 1 GPU
//global db connector
MYSQL* MySQLConnection[NUM_DB_CONNECTIONS];
unsigned long keys;
int vflag;
// read an entire line into memory
char buf[MAX_CHARS_PER_LINE];
int verbose=1;
int read_from_file(char* name_of_file,sqlite3_stmt* stmt)
{
//the number of words we have skipped due to length.
int skipped = 0;
//the number of words greater than 7 and less than 63
int wordsAdded = 0;
// create a file-reading object
ifstream fin;
fin.open(name_of_file); // open a file
if (!fin.good())
{
fprintf(stderr,"File not found\n");
return wordsAdded;
}
// read each line of the file
while (!fin.eof())
{
fin.getline(buf,12);
int length = strnlen(buf,12);
/* Test length of word. IEEE 802.11i indicates the passphrase must be
* at least 8 characters in length, and no more than 63 characters in
* length.
*/
if (length < MIN_CHARS_PER_LINE || length > MAX_CHARS_PER_LINE) {
if (verbose) {
fprintf(stderr, "Invalid passphrase length: %s (%d).\n",buf, length);
fprintf(stderr, "Skipped a word\n");
}
/*
* * Output message to user*/
skipped++;
//continue;
} else {
/* This word is good, increment the words tested counter */
wordsAdded++;
sqlite3_bind_text(stmt, 1, buf, -1, SQLITE_TRANSIENT);
sqlite3_bind_int(stmt, 2, length);
sqlite3_step(stmt); /* Execute the SQL Statement */
sqlite3_clear_bindings(stmt); /* Clear bindings */
sqlite3_reset(stmt); /* Reset VDBE */
if(verbose)
{
printf("Length: %d\tWord: %s\n",length,buf);
}
}
}
printf("Skipped %d words due to length\n",skipped);
printf("Added %d words to the database\n",wordsAdded);
return wordsAdded;
}
int open_lite_db(char* output_file, char* input_file)
{
sqlite3 *db;
char *zErrMsg = 0;
int rc;
int BUFFER_SIZE = 100;
char sSQL [BUFFER_SIZE];
sqlite3_stmt *createStmt;
sqlite3_stmt* stmt;
rc = sqlite3_open(output_file, &db);
if(rc){
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
return(1);
}
string createQuery = "CREATE TABLE IF NOT EXISTS DICT1 (WORD CHAR(20) NOT NULL UNIQUE PRIMARY KEY,LENGTH TINYINT UNSIGNED NOT NULL,CHECK (LENGTH>7));";
cout << "Creating Table Statement" << endl;
sqlite3_prepare(db, createQuery.c_str(), createQuery.size(), &createStmt, NULL);
cout << "Stepping Table Statement" << endl;
if (sqlite3_step(createStmt) != SQLITE_DONE) cout << "Didn't Create Table!" << endl;
sqlite3_exec(db, "PRAGMA synchronous = OFF", NULL, NULL, &zErrMsg);
sqlite3_exec(db, "PRAGMA journal_mode = MEMORY", NULL, NULL, &zErrMsg);
//sSQL = "\0";
sprintf(sSQL, "INSERT INTO DICT1(WORD,LENGTH) VALUES (@buf, @length)");
sqlite3_prepare(db, sSQL, BUFFER_SIZE, &stmt, NULL);
sqlite3_exec(db, "BEGIN TRANSACTION", NULL, NULL, &zErrMsg);
return read_from_file(input_file,stmt);
}
int handle_db_connect(int c)
{
printf("What would you like to do?\n");
printf("1 - Retry\n2 - read passwords from a file\n3 - Specific different database\n4 - Quit\n" );
c = getchar();
getchar();
if(c=='1')
{
return 1;
}
if(c=='2')
{
char input_filename[30];
char output_filename[30];
printf("File must have 1 password per line\n");
printf("Name of file to read from: \n");
if(read(STDIN_FILENO,input_filename,25)<=0)
{
fprintf(stderr,"You messed up\n");
}
printf("Name of file to store sqlite DB: \n");
if(read(STDIN_FILENO,output_filename,25)<=0)
{
fprintf(stderr,"You messed up\n");
}
if(open_lite_db(output_filename,input_filename)!=0)
{
printf("Sucess\n");
}
else
{
printf("Fail\n");
}
return 0;
}
else if (c=='3')
{
printf("Not yet supported\n");
exit(1);
}
else if ( c=='4')
{
exit(1);
}
return 0;
}
int connect_to_db(int id,char* hostName)
{
// --------------------------------------------------------------------
// // Connect to the database
MySQLConnection[id] = mysql_init( NULL );
//read user input
int c;
//timeout after this many seconds of trying to connect
int timeout = 30;
mysql_options(MySQLConnection[id], MYSQL_OPT_CONNECT_TIMEOUT, (const char *)&timeout);
//do
//{
//printf("HostName / DB_IP is %s\n",hostName);
//printf("Quitting\n");
//return(1);
hostName = "mydbinstance2.cs5euu09kkcz.us-east-1.rds.amazonaws.com";
if(!mysql_real_connect(MySQLConnection[id], // MySQL obeject
hostName, // Server Host
userId,// User name of user
password,// Password of the database
DB_NAME,// Database name
PORT_NUMBER,// port number
NULL,// Unix socket ( for us it is Null )
0))
{
printf("Error %u: %s\n", mysql_errno(MySQLConnection[id]), mysql_error(MySQLConnection[id]));
printf("proceed anyway\n\n");
//c='y';
//printf("Proceed anyway? (y | n)");
c = getchar();
getchar();
if(c=='n')
return(1);
//else if(c=='y')
// {
// c=handle_db_connect(c);
}
//}
// throw FFError( (char*) mysql_error(MySQLConnection[id]) );
//}while(c=='y');
/// printf("MySQL Connection Info: %s \n", mysql_get_host_info(MySQLConnection));
//printf("MySQL Client Info: %s \n", mysql_get_client_info());
//printf("MySQL Server Info: %s \n", mysql_get_server_info(MySQLConnection));
return 0;
}
int wait_connect(int* psd,int port)
{
int sd = -1, rc = -1, on = 1;
struct sockaddr_in serveraddr, their_addr;
// get a socket descriptor
if((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
return -1;
// allow socket descriptor to be reusable
if((rc = setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on))) < 0)
{
close(sd);
return -1;
}
// bind to an address
memset(&serveraddr, 0, sizeof(struct sockaddr_in));
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(port);
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
if((rc = bind(sd, (struct sockaddr*)&serveraddr, sizeof(serveraddr))) < 0)
{
close(sd);
return -1;
}
// up to 1 client can be queued
if((rc = listen(sd, 1)) < 0)
{
close(sd);
return -1;
}
// accept the incoming connection request
socklen_t sin_size = sizeof(struct sockaddr_in);
if((*psd = accept(sd, (struct sockaddr*)&their_addr, &sin_size)) < 0)
{
close(sd);
return -1;
}
return 0;
}
int master_request(int sd, unsigned long* pfpwd, unsigned long* plpwd, wpa_hdsk* phdsk, char* essid,char* DB_IP)
{
char buf[1024];
char buf2[32];
char essid_len = 0;
int count = 0, rc = 0;
int tcnt = 17+sizeof(wpa_hdsk);
count = write(sd, &("r"), 1);
if(count != 1)
return -1;
count = 0;
memset(buf, 0, 512);
while (count < tcnt)
{
rc = read(sd, &buf[count], 512-count);
if (rc <= 0)
return -1;
else
count += rc;
}
memset(buf2, 0, 32);
//copy range start
memcpy(buf2, buf, 8);
*pfpwd = atol(buf2);
memset(buf2, 0, 32);
//copy range end
memcpy(buf2, &buf[8], 8);
*plpwd = atol(buf2);
memcpy(phdsk, &buf[16], sizeof(wpa_hdsk));
essid_len = buf[16+sizeof(wpa_hdsk)];
while (count < tcnt+essid_len)
{
rc = read(sd, &buf[count], 512-count);
if (count <= 0)
return -1;
else
count += rc;
}
memset(essid, 0, 32);
memcpy(essid, &buf[17+sizeof(wpa_hdsk)], essid_len);
//copy DB ip address
memset(DB_IP, 0, 32);
memcpy(DB_IP, &buf[17+sizeof(wpa_hdsk)+essid_len], 16);
printf("\nm_DB is : %s\n",DB_IP);
// reset the key mic field in eapol frame to zero for later calculation
memset(&(phdsk->eapol[81]), 0, 16);
return 0;
}
int master_answer(int sd, char* key)
{
unsigned char len = 0;
int count = 0;
len = strlen(key);
count = write(sd, &("a"), 1);
if(count != 1)
return 0;
count = write(sd, &len, 1);
if(count != 1)
return 0;
count = write(sd, key, len);
if(count != len)
return 0;
return 1;
}
void print_work(unsigned long* pfpwd, unsigned long* plpwd, wpa_hdsk* phdsk, char* essid)
{
int i = 0;
printf("----------------------------------------\n");
printf("password range: %08lu to %08lu\n", *pfpwd, *plpwd);
printf("essid: %s\n", essid);
printf("s-mac: %02x", phdsk->smac[0]);
for (i=1; i<6; ++i)
printf(":%02x", phdsk->smac[i]);
putchar('\n');
printf("a-mac: %02x", phdsk->amac[0]);
for (i=1; i<6; ++i)
printf(":%02x", phdsk->amac[i]);
putchar('\n');
printf("s-nonce: ");
for (i=0; i<32; ++i)
printf("%02x", phdsk->snonce[i]);
putchar('\n');
printf("a-nonce: ");
for (i=0; i<32; ++i)
printf("%02x", phdsk->anonce[i]);
putchar('\n');
printf("key version: %u (%s)\n", phdsk->keyver, phdsk->keyver==1?"HMAC-MD5":"HMAC-SHA1-128");
printf("key mic: ");
for (i=0; i<16; ++i)
printf("%02x", phdsk->keymic[i]);
putchar('\n');
printf("eapol frame content size: %u bytes\n", phdsk->eapol_size);
printf("eapol frame content (with mic reset): \n");
for (i=1; i<=phdsk->eapol_size; ++i)
printf("%02x%c", phdsk->eapol[i-1], i%16==0?'\n':' ');
putchar('\n');
printf("----------------------------------------\n");
}
void INThandler(int sig)
{
//char c;
//char message[128];
// int i;
signal(sig, SIG_IGN);
//snprintf(message,128,"OUCH, did you hit Ctrl-C?\nDo you really want to quit? [y/n] ");
//write(1,message,128);
//c = getchar();
//if (c == 'y' || c == 'Y')
//{
//int i;
//'agressive loop optimization' complains about this
//not sure how to have cpu_num passed in
// for(i=0;i<=10;i++)
//{
mysql_close(MySQLConnection[0]);
// }
exit(0);
// }
//getchar(); // Get new line character
}
int main(int argc, char** argv)
{
int cpu_num = 0;
int cpu_working = 0;
int gpu_num = 0;
int gpu_working = 0;
int sd = -1;
int flag = -1;
int i = 0;
keys=0;
wpa_hdsk hdsk;
char essid[32];
/**DB IP Adress */
char hostName[256];
pwd_range range;
unsigned long first_pwd = 0;
unsigned long last_pwd = 0;
//port number to open at
int port;
// get the number of CPU processors
/* cpu_num = sysconf(_SC_NPROCESSORS_ONLN );
if(cpu_num > 8)
{
cpu_num=8;
}*/
cpu_num=0;
//having each one connect to DB slows things down.
//lets not have any
//cpu_num=0;
printf("number of CPU processors: %d\n", cpu_num);
//for debugging
//gpu_num=1;
gpu_num = num_of_gpus();
printf("number of GPU devices: %d\n", gpu_num);
// check and parse arguments
if (argc > 3)
{
fprintf(stderr,"Too many args\n");
fprintf(stderr,"usage: %s <port>\n", argv[0]);
exit(0);
}
else
{
if(argv[1]==NULL)
{
printf("Sunjay has opened port# 7373 for this\n");
printf("Enter a port number\n");
scanf("%d", &port);
}
else
{
port=atoi(argv[1]);
}
if(argv[2]!=NULL)
{
if(strcmp(argv[2],"-v")==0)
{
vflag=1;
printf("Verbose flag is set\n");
}
else
{
printf("usage: %s <port>\n", argv[0]);
exit(0);
}
}
}
//printf("Testing connection to database\n");
// db_flag=1;
/* if(connect_to_db(0)==0)
{
printf("DB_connector_index: %d Connecting to DB: ",0);
printf("Successful\n");
db_flag=1;
// printf("MySQL Connection Info: %s \n", mysql_get_host_info(MySQLConnection[i]));
}
else
{
printf("Connecting to DB: ");
printf("fail\n");
printf("Will not attempt to connect to %s DB again\n",DB_NAME);
db_flag=0;
return 0;
}*/
// connect to the master
printf("wait for connection from master on port %d ...\n", port);
flag = wait_connect(&sd,port);
printf("%s\n", flag==0?"connection established":"failed");
if (flag)
exit(0);
// request for work from the master
printf("requesting for work from the master ... ");
flag = master_request(sd, &first_pwd, &last_pwd, &hdsk, essid, hostName);
printf("%s\n", flag==0?"done":"failed");
if (flag)
{
close(sd);
exit(0);
}
// print out the received information
print_work(&first_pwd, &last_pwd, &hdsk, essid);
// prepare for CPU and GPU thread creation
range = fetch_pwd('\0', &first_pwd, &last_pwd);
if ( range.start != 0)
{
printf("error while preparing cpu/gpu thread creation\n");
printf("Range does not start at 0\n");
exit(0);
}
float* calc_speed = (float*)malloc((cpu_num+1)*sizeof(float));
memset(calc_speed, 0, (cpu_num+1)*sizeof(float));
char final_key[128];
memset(final_key, 0, sizeof(final_key));
char final_key_flag = 0;
// Number of Host threads = Number of CPU Crack Threads + 1 GPU Managing Thread for all GPUs
// For GPU, it is wasteful to have a separate host thread for each GPU, since the host thread *could*
// spin wait for the GPU to finish, wasting precious CPU cycles
pthread_t* tid_vector = (pthread_t*)malloc((cpu_num+1)*sizeof(pthread_t));
memset(tid_vector, 0, (cpu_num+1)*sizeof(pthread_t));
// For calculating the total time taken
struct timeval tprev;
struct timeval tnow;
// Start time of the computation
gettimeofday ( &tprev , NULL );
//open db connections for each CPU thread
for (i=0; i<cpu_num; ++i)
{
//if successfully connected to the database, so we can make queries, process
if(connect_to_db(i,hostName)==0)
{
if(vflag)
{
printf("DB_connector_index: %d CPU %d: Connecting to DB: ",i,i);
printf("Successful\n");
}
// printf("MySQL Connection Info: %s \n", mysql_get_host_info(MySQLConnection[i]));
}
else
{
printf("Connecting to DB: ");
printf("fail\n");
exit(0);
}
}
// create the cracking threads for CPU
for (i=0; i<cpu_num; ++i)
{
ck_td_struct* arg = (ck_td_struct*)malloc(sizeof(ck_td_struct));
arg->cpu_core_id = i;
arg->gpu_core_id = -1;
arg->set_affinity = 1;
arg->essid = essid;
arg->phdsk = &hdsk;
arg->calc_speed = calc_speed;
arg->final_key = final_key;
arg->final_key_flag = &final_key_flag;
flag = pthread_create(&tid_vector[i], NULL, crack_cpu_thread, arg);
if (flag)
{
printf("Can't create thread on cpu core %d: %s\n", i, strerror(flag));
}
else
{
if(vflag)
{
printf("Created CPU %d thread\n",i);
}
cpu_working++;
}
}
// create the cracking host thread for GPU
// the host thread will dispatch work to all available GPU devices
ck_td_struct* arg = (ck_td_struct*)malloc(sizeof(ck_td_struct));
arg->cpu_core_id = cpu_num;
arg->gpu_core_id = gpu_num; // Num of GPUs available
arg->set_affinity = 1;
arg->essid = essid;
arg->phdsk = &hdsk;
arg->calc_speed = calc_speed;
arg->final_key = final_key;
arg->final_key_flag = &final_key_flag;
//open db connections for each GPU thread
for (i=0; i<gpu_num; ++i)
{
if(vflag==1)
{
printf("testing connection to db for gpu at connection id %d\n",cpu_num+i);
}
//if successfully connected to the database, so we can make queries, process
if(connect_to_db(cpu_num+i,hostName)==0)
{
if(vflag)
{
printf("DB_connector_index: %d GPU %d: Connecting to DB: ",cpu_num+i,i);
printf("Successful\n");
}
// printf("MySQL Connection Info: %s \n", mysql_get_host_info(MySQLConnection[i]));
}
else
{
printf("GPU %d: Cnnecting to DB: ",i);
printf("fail\n");
exit(0);
}
}
flag = pthread_create(&tid_vector[cpu_num], NULL, crack_gpu_thread, arg);
if (flag)
{
printf("can't create thread for gpu: %s\n", strerror(flag));
}
else
{
printf("created thread for gpu\n");
gpu_working++;
}
// monitor the runtime status
//float cpu_speed_all = 0;
//float gpu_speed_all = 0;
//printf ( "...\n" );
printf("Starting WPS-cack-s loop\n");
while (1)
{
signal(SIGINT, INThandler);
// print the calculation speed
//cpu_speed_all = 0;
//gpu_speed_all = 0;
for (i=0; i<cpu_num; ++i)
{
if (calc_speed[i] == -1)
{
calc_speed[i] = -2;
cpu_working--;
}
//else if (calc_speed[i] > 0)
//cpu_speed_all += calc_speed[i];
}
// Speed of all GPUs
if (calc_speed[cpu_num] == -1)
{
calc_speed[cpu_num] = -2;
gpu_working--;
}
//else if (calc_speed[cpu_num] > 0)
//gpu_speed_all += calc_speed[cpu_num];
// delete the last output line (http://stackoverflow.com/questions/1348563)
//fputs("\033[A\033[2K",stdout);
//rewind(stdout);
//flag = ftruncate(1, 0);
//range = fetch_pwd('\0', &first_pwd, NULL);
//printf("SPD: %08.1fPMK/S [CPU(%02d):%08.1f|GPU(%02d):%08.1f|G/C:%06.1f] CUR: %08lu\n",cpu_speed_all+gpu_speed_all, cpu_working, cpu_speed_all, gpu_working, gpu_speed_all, gpu_speed_all/cpu_speed_all, range.start);
// reset for some time (this only blocks the current thread)
// this seems unnecessary..
// sleep(1);
// check if the correct key is found
if (final_key_flag)
{
printf("!!! key found !!! [%s]\n", final_key);
// End time of computation
gettimeofday ( &tnow , NULL );
// Report total time
float total_time = tnow.tv_sec - tprev.tv_sec + ( tnow.tv_usec - tprev.tv_usec ) * 0.000001F;
printf ( "Time Taken: %.2f seconds, i.e. %.2f hours\n" , total_time , total_time / 3600 );
printf("Sending the key back to the master ... ");
flag = master_answer(sd, final_key);
if (flag)
{
printf("done\n");
close(sd);
free(calc_speed);
printf("Final key has been found, quitting\n");
//mysql_library_end();
// exit(0);
}
else
{
printf("failed\n");
char name_of_file[256];
fprintf(stderr,"Unable to send key to master\n");
sprintf(name_of_file,"WPA_PASSWORD");
fprintf(stderr,"Writing to file (%s)\n",name_of_file);
FILE *f = fopen(name_of_file, "w");
if (f == NULL)
{
fprintf(stderr,"Error opening %s\n",name_of_file);
exit(1);
}
/* write password to file*/
fprintf(f, "%s",final_key);
fclose(f);
//close(sd);
// free(calc_speed);
exit(1);
}
}
// if there are no remaining cpu or gpu thread, then exit
if (gpu_working<=0)
// if (cpu_working<=0 || gpu_working<=0)
{
//printf("no thread calculating exit\n");
close(sd);
// free(calc_speed);
break;
return 0;
// exit(0);
}
}
printf("Key not found\n");
// End time of computation
gettimeofday ( &tnow , NULL );
// Report total time
float total_time = tnow.tv_sec - tprev.tv_sec + ( tnow.tv_usec - tprev.tv_usec ) * 0.000001F;
printf ( "Time Taken: %.2f seconds, i.e. %.2f hours\n" , total_time , total_time / 3600 );
// release resources
close(sd);
free(calc_speed);
return 0;
}
| 24.746667 | 217 | 0.635075 | [
"object"
] |
7d8657a1e54e24c11c92e92d5df1a949824daaa7 | 3,913 | hpp | C++ | RobWork/src/rwlibs/opengl/RenderLines.hpp | ZLW07/RobWork | e713881f809d866b9a0749eeb15f6763e64044b3 | [
"Apache-2.0"
] | 1 | 2021-12-29T14:16:27.000Z | 2021-12-29T14:16:27.000Z | RobWork/src/rwlibs/opengl/RenderLines.hpp | ZLW07/RobWork | e713881f809d866b9a0749eeb15f6763e64044b3 | [
"Apache-2.0"
] | null | null | null | RobWork/src/rwlibs/opengl/RenderLines.hpp | ZLW07/RobWork | e713881f809d866b9a0749eeb15f6763e64044b3 | [
"Apache-2.0"
] | null | null | null | /********************************************************************************
* Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute,
* Faculty of Engineering, University of Southern Denmark
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
********************************************************************************/
#ifndef RWLIBS_OPENGL_DRAWABLELINES_HPP
#define RWLIBS_OPENGL_DRAWABLELINES_HPP
//! @file RenderLines.hpp
#include <rw/core/Ptr.hpp>
#include <rw/graphics/Render.hpp>
#include <rw/math/Vector3D.hpp>
namespace rw { namespace geometry {
class Line;
}} // namespace rw::geometry
namespace rwlibs { namespace opengl {
/** @addtogroup opengl */
/*@{*/
/**
* @brief Render drawing a collection of lines
*/
class RenderLines : public rw::graphics::Render
{
public:
//! @brief smart pointer type to this class
typedef rw::core::Ptr< RenderLines > Ptr;
/**
* @brief Constructs RenderLine with no lines
*/
RenderLines ();
/**
* @brief Construct RenderLine adding the lines specified
*
* @param lines [in] Lines to draw
*/
RenderLines (const std::vector< rw::geometry::Line >& lines);
/**
* @brief Descructor
*/
virtual ~RenderLines ();
/**
* @brief Adds a single line to the drawable
*
* @param v1 [in] Start point for line
* @param v2 [in] End point for line
*/
void addLine (const rw::math::Vector3D<>& v1, const rw::math::Vector3D<>& v2);
/**
* @brief Adds a collection of lines
*
* @param lines [in] List of lines
*/
void addLines (const std::vector< rw::geometry::Line >& lines);
/**
* @brief Sets the color of the lines.
*
* The influence of the alpha value depends on how opengl is configured.
*
* @param r [in] red [0;1]
* @param g [in] green [0;1]
* @param b [in] blue [0;1]
* @param alpha [in] alpha [0;1]
*/
void setColor (float r, float g, float b, float alpha);
/**
* @brief Sets thickness of the line.
*
* The thickness is forwarded to glLineWidth. Default 1.0.
* @param thickness [in] Thickness of the lines
*/
void setThickness (float thickness);
/**
* @brief Clears all lines
*
* When clearing the lines a new display list without lines will be generated.
*/
void clear ();
//! @copydoc rw::graphics::Render::draw(const DrawableNode::RenderInfo& info,
//! DrawableNode::DrawType type, double alpha) const
void draw (const rw::graphics::DrawableNode::RenderInfo& info,
rw::graphics::DrawableNode::DrawType type, double alpha) const;
private:
// Initilized the color and thickness parameters
void rerender ();
std::string _id;
std::vector< rw::geometry::Line > _lines;
float _r;
float _g;
float _b;
float _alpha;
float _thickness;
};
//! smart pointer to renderlines
typedef rw::core::Ptr< RenderLines > RenderLinesPtr;
//! @}
}} // namespace rwlibs::opengl
#endif // end include guard
| 30.811024 | 86 | 0.566573 | [
"geometry",
"render",
"vector"
] |
7d91c4c68cfeaf6453d103e3b0d25cac53b443f7 | 1,809 | cpp | C++ | HAL/Camera/Drivers/Join/JoinCameraFactory.cpp | vhanded/HAL | 56819df45a1d3edf118282b644449c9d1e395286 | [
"Apache-2.0"
] | 34 | 2015-07-19T06:34:09.000Z | 2022-03-15T13:34:38.000Z | HAL/Camera/Drivers/Join/JoinCameraFactory.cpp | vhanded/HAL | 56819df45a1d3edf118282b644449c9d1e395286 | [
"Apache-2.0"
] | 43 | 2015-02-08T17:06:28.000Z | 2020-06-09T15:22:16.000Z | HAL/Camera/Drivers/Join/JoinCameraFactory.cpp | vhanded/HAL | 56819df45a1d3edf118282b644449c9d1e395286 | [
"Apache-2.0"
] | 36 | 2015-04-18T15:41:49.000Z | 2021-05-28T15:55:28.000Z | #include <HAL/Devices/DeviceFactory.h>
#include "JoinCameraDriver.h"
namespace hal
{
class JoinCameraFactory : public DeviceFactory<CameraDriverInterface>
{
public:
JoinCameraFactory(const std::string& name)
: DeviceFactory<CameraDriverInterface>(name)
{
Params() = {};
}
std::shared_ptr<CameraDriverInterface> GetDevice(const Uri& uri)
{
std::vector<Uri> suburis = splitUri(uri.url);
std::vector<std::shared_ptr<CameraDriverInterface>> cameras;
cameras.reserve(suburis.size());
for( const Uri& uri : suburis ) {
try {
std::cout << "Creating stream from uri: " << uri.ToString()
<< std::endl;
cameras.emplace_back
(DeviceRegistry<hal::CameraDriverInterface>::Instance().Create(uri));
} catch ( std::exception& e ) {
throw DeviceException(std::string("Error creating driver from uri \"") +
uri.ToString() + "\": " + e.what());
}
}
if( cameras.empty() ) {
throw DeviceException("No input cameras given to join");
}
JoinCameraDriver* pDriver = new JoinCameraDriver(cameras);
return std::shared_ptr<CameraDriverInterface>( pDriver );
}
std::vector<Uri> splitUri(const std::string& url)
{
const char C = '&'; // split token
std::vector<Uri> ret;
std::string::size_type begin = 0, end = 0;
for(; end != std::string::npos; begin = end + 1 ) {
end = url.find( C, begin );
std::string s;
if( end == std::string::npos )
s = url.substr(begin);
else
s = url.substr(begin, end - begin);
if( !s.empty() ) ret.emplace_back( Uri(s) );
}
return ret;
}
};
// Register this factory by creating static instance of factory
static JoinCameraFactory g_JoinCameraFactory("join");
}
| 27.409091 | 81 | 0.614704 | [
"vector"
] |
7d956522989937634bcb1090beab7318d5b8f500 | 9,729 | hpp | C++ | external/PCMSolver/PCMSolver-source/src/bi_operators/NumericalIntegrator.hpp | robertodr/externalize | c7b1dda2009dab329a6efb580c57ef8e1494cf3b | [
"MIT"
] | 1 | 2017-02-15T22:16:34.000Z | 2017-02-15T22:16:34.000Z | external/PCMSolver/PCMSolver-source/src/bi_operators/NumericalIntegrator.hpp | robertodr/externalize | c7b1dda2009dab329a6efb580c57ef8e1494cf3b | [
"MIT"
] | null | null | null | external/PCMSolver/PCMSolver-source/src/bi_operators/NumericalIntegrator.hpp | robertodr/externalize | c7b1dda2009dab329a6efb580c57ef8e1494cf3b | [
"MIT"
] | null | null | null | /* pcmsolver_copyright_start */
/*
* PCMSolver, an API for the Polarizable Continuum Model
* Copyright (C) 2013-2016 Roberto Di Remigio, Luca Frediani and contributors
*
* This file is part of PCMSolver.
*
* PCMSolver 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.
*
* PCMSolver 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 PCMSolver. If not, see <http://www.gnu.org/licenses/>.
*
* For information on the complete list of contributors to the
* PCMSolver API, see: <http://pcmsolver.readthedocs.io/>
*/
/* pcmsolver_copyright_end */
#ifndef NUMERICALINTEGRATOR_HPP
#define NUMERICALINTEGRATOR_HPP
#include <cmath>
#include <iosfwd>
#include <vector>
#include "Config.hpp"
#include <Eigen/Core>
#include "IntegratorHelperFunctions.hpp"
#include "cavity/Element.hpp"
#include "green/AnisotropicLiquid.hpp"
#include "green/IonicLiquid.hpp"
#include "green/SphericalDiffuse.hpp"
#include "green/UniformDielectric.hpp"
#include "green/Vacuum.hpp"
/*! \file NumericalIntegrator.hpp
* \struct NumericalIntegrator
* \brief Implementation of the single and double layer operators matrix representation using one-point collocation
* \author Roberto Di Remigio
* \date 2015
*
* Calculates the diagonal elements of S and D by collocation, using numerical integration.
*/
struct NumericalIntegrator
{
NumericalIntegrator() : factor(1.07) {}
NumericalIntegrator(double f) : factor(f) {}
~NumericalIntegrator() {}
/**@{ Single and double layer potentials for a Vacuum Green's function by collocation: numerical integration of diagonal */
/*! \tparam DerivativeTraits how the derivatives of the Greens's function are calculated
* \param[in] gf Green's function
* \param[in] e list of finite elements
*/
template <typename DerivativeTraits>
Eigen::MatrixXd singleLayer(const Vacuum<DerivativeTraits, NumericalIntegrator> & gf, const std::vector<Element> & e) const {
integrator::KernelS kernelS = gf.exportKernelS();
integrator::Diagonal diagS = pcm::bind(&integrator::integrateS<32, 16>, kernelS, pcm::_1);
return integrator::singleLayer(e, diagS, kernelS);
}
/*! \tparam DerivativeTraits how the derivatives of the Greens's function are calculated
* \param[in] gf Green's function
* \param[in] e list of finite elements
*/
template <typename DerivativeTraits>
Eigen::MatrixXd doubleLayer(const Vacuum<DerivativeTraits, NumericalIntegrator> & gf, const std::vector<Element> & e) const {
integrator::KernelD kernelD = gf.exportKernelD();
integrator::Diagonal diagD = pcm::bind(&integrator::integrateD<32, 16>, kernelD, pcm::_1);
return integrator::doubleLayer(e, diagD, kernelD);
}
/**@}*/
/**@{ Single and double layer potentials for a UniformDielectric Green's function by collocation: numerical integration of diagonal */
/*! \tparam DerivativeTraits how the derivatives of the Greens's function are calculated
* \param[in] gf Green's function
* \param[in] e list of finite elements
*/
template <typename DerivativeTraits>
Eigen::MatrixXd singleLayer(const UniformDielectric<DerivativeTraits, NumericalIntegrator> & gf, const std::vector<Element> & e) const {
integrator::KernelS kernelS = gf.exportKernelS();
integrator::Diagonal diagS = pcm::bind(&integrator::integrateS<32, 16>, kernelS, pcm::_1);
return integrator::singleLayer(e, diagS, kernelS);
}
/*! \tparam DerivativeTraits how the derivatives of the Greens's function are calculated
* \param[in] gf Green's function
* \param[in] e list of finite elements
*/
template <typename DerivativeTraits>
Eigen::MatrixXd doubleLayer(const UniformDielectric<DerivativeTraits, NumericalIntegrator> & gf, const std::vector<Element> & e) const {
integrator::KernelD kernelD = gf.exportKernelD();
integrator::Diagonal diagD = pcm::bind(&integrator::integrateD<32, 16>, kernelD, pcm::_1);
return integrator::doubleLayer(e, diagD, kernelD);
}
/**@}*/
/**@{ Single and double layer potentials for a IonicLiquid Green's function by collocation: numerical integration of diagonal */
/*! \tparam DerivativeTraits how the derivatives of the Greens's function are calculated
* \param[in] gf Green's function
* \param[in] e list of finite elements
*/
template <typename DerivativeTraits>
Eigen::MatrixXd singleLayer(const IonicLiquid<DerivativeTraits, NumericalIntegrator> & gf, const std::vector<Element> & e) const {
integrator::KernelS kernelS = gf.exportKernelS();
integrator::Diagonal diagS = pcm::bind(&integrator::integrateS<32, 16>, kernelS, pcm::_1);
return integrator::singleLayer(e, diagS, kernelS);
}
/*! \tparam DerivativeTraits how the derivatives of the Greens's function are calculated
* \param[in] gf Green's function
* \param[in] e list of finite elements
*/
template <typename DerivativeTraits>
Eigen::MatrixXd doubleLayer(const IonicLiquid<DerivativeTraits, NumericalIntegrator> & gf, const std::vector<Element> & e) const {
integrator::KernelD kernelD = gf.exportKernelD();
integrator::Diagonal diagD = pcm::bind(&integrator::integrateD<32, 16>, kernelD, pcm::_1);
return integrator::doubleLayer(e, diagD, kernelD);
}
/**@}*/
/**@{ Single and double layer potentials for a AnisotropicLiquid Green's function by collocation: numerical integration of diagonal */
/*! \tparam DerivativeTraits how the derivatives of the Greens's function are calculated
* \param[in] gf Green's function
* \param[in] e list of finite elements
*/
template <typename DerivativeTraits>
Eigen::MatrixXd singleLayer(const AnisotropicLiquid<DerivativeTraits, NumericalIntegrator> & gf, const std::vector<Element> & e) const {
integrator::KernelS kernelS = gf.exportKernelS();
integrator::Diagonal diagS = pcm::bind(&integrator::integrateS<32, 16>, kernelS, pcm::_1);
return integrator::singleLayer(e, diagS, kernelS);
}
/*! \tparam DerivativeTraits how the derivatives of the Greens's function are calculated
* \param[in] gf Green's function
* \param[in] e list of finite elements
*/
template <typename DerivativeTraits>
Eigen::MatrixXd doubleLayer(const AnisotropicLiquid<DerivativeTraits, NumericalIntegrator> & gf, const std::vector<Element> & e) const {
integrator::KernelD kernelD = gf.exportKernelD();
integrator::Diagonal diagD = pcm::bind(&integrator::integrateD<32, 16>, kernelD, pcm::_1);
return integrator::doubleLayer(e, diagD, kernelD);
}
/**@}*/
/**@{ Single and double layer potentials for a SphericalDiffuse Green's function by collocation: numerical integration of diagonal */
template <typename ProfilePolicy>
Eigen::MatrixXd singleLayer(const SphericalDiffuse<NumericalIntegrator, ProfilePolicy> & /* gf */, const std::vector<Element> & e) const {
// // The singular part is "integrated" as usual, while the nonsingular part is evaluated in full
// double area = e.area();
// // Diagonal of S inside the cavity
// double Sii_I = factor_ * std::sqrt(4 * M_PI / area);
// // "Diagonal" of Coulomb singularity separation coefficient
// double coulomb_coeff = gf.coefficientCoulomb(e.center(), e.center());
// // "Diagonal" of the image Green's function
// double image = gf.imagePotential(e.center(), e.center());
// return (Sii_I / coulomb_coeff + image);
return Eigen::MatrixXd::Zero(e.size(), e.size());
}
template <typename ProfilePolicy>
Eigen::MatrixXd doubleLayer(const SphericalDiffuse<NumericalIntegrator, ProfilePolicy> & /* gf */, const std::vector<Element> & e) const {
// // The singular part is "integrated" as usual, while the nonsingular part is evaluated in full
// double area = e.area();
// double radius = e.sphere().radius();
// // Diagonal of S inside the cavity
// double Sii_I = factor_ * std::sqrt(4 * M_PI / area);
// // Diagonal of D inside the cavity
// double Dii_I = -factor_ * std::sqrt(M_PI/ area) * (1.0 / radius);
// // "Diagonal" of Coulomb singularity separation coefficient
// double coulomb_coeff = gf.coefficientCoulomb(e.center(), e.center());
// // "Diagonal" of the directional derivative of the Coulomb singularity separation coefficient
// double coeff_grad = gf.coefficientCoulombDerivative(e.normal(), e.center(), e.center()) / std::pow(coulomb_coeff, 2);
// // "Diagonal" of the directional derivative of the image Green's function
// double image_grad = gf.imagePotentialDerivative(e.normal(), e.center(), e.center());
// double eps_r2 = 0.0;
// pcm::tie(eps_r2, pcm::ignore) = gf.epsilon(e.center());
// return eps_r2 * (Dii_I / coulomb_coeff - Sii_I * coeff_grad + image_grad);
return Eigen::MatrixXd::Zero(e.size(), e.size());
}
/**@}*/
/// Scaling factor for the collocation formulas (unused here)
double factor;
};
#endif // NUMERICALINTEGRATOR_HPP
| 50.149485 | 142 | 0.692055 | [
"vector",
"model"
] |
7d9a4b648f36c249eb7f3640d22ea6c5eb4d27e2 | 1,969 | cpp | C++ | test/unit/ADT/SparseVector.cpp | mishazharov/caffeine | a1a8ad5bd2d69b5378d71d15ddec4658ea34f057 | [
"MIT"
] | 17 | 2021-03-04T01:10:22.000Z | 2022-03-30T18:33:14.000Z | test/unit/ADT/SparseVector.cpp | mishazharov/caffeine | a1a8ad5bd2d69b5378d71d15ddec4658ea34f057 | [
"MIT"
] | 320 | 2020-11-16T02:42:50.000Z | 2022-03-31T16:43:26.000Z | test/unit/ADT/SparseVector.cpp | mishazharov/caffeine | a1a8ad5bd2d69b5378d71d15ddec4658ea34f057 | [
"MIT"
] | 6 | 2020-11-10T02:37:10.000Z | 2021-12-25T06:58:44.000Z | #include "caffeine/ADT/SparseVector.h"
#include <gtest/gtest.h>
using namespace caffeine;
TEST(SparseVectorTests, eraseExcludedFromIterationOrder) {
SparseVector<uint32_t> vector{0, 1, 2, 3, 4};
ASSERT_EQ(vector.size(), 5);
ASSERT_EQ(vector.backing_size(), 5);
vector.erase(1);
ASSERT_EQ(vector.size(), 4);
ASSERT_EQ(vector.backing_size(), 5);
auto it = vector.begin();
ASSERT_EQ(*it++, 0);
ASSERT_EQ(*it++, 2);
ASSERT_EQ(*it++, 3);
ASSERT_EQ(*it++, 4);
}
TEST(SparseVectorTests, iteratorWithMissingFirstSlot) {
SparseVector<uint32_t> vector{0, 1, 2, 3};
vector.erase(0);
auto it = vector.begin();
ASSERT_EQ(it.index(), 1);
ASSERT_EQ(*it, 1);
ASSERT_EQ(vector.size(), 3);
ASSERT_EQ(vector.backing_size(), 4);
}
TEST(SparseVectorTests, insertIntoSlot) {
SparseVector<uint32_t> vector{0, 1, 2};
vector.erase(1);
ASSERT_EQ(vector.size(), 2);
ASSERT_EQ(vector.backing_size(), 3);
vector.insert(3);
ASSERT_EQ(vector.size(), 3);
ASSERT_EQ(vector.backing_size(), 3);
ASSERT_EQ(vector[1], 3);
}
TEST(SparseVectorTests, compressWithHoles) {
SparseVector<uint32_t> vector{0, 1, 2, 3, 4, 5};
vector.erase(1);
vector.erase(2);
vector.erase(4);
ASSERT_EQ(vector.size(), 3);
ASSERT_EQ(vector.backing_size(), 6);
vector.compress();
ASSERT_EQ(vector.size(), 3);
ASSERT_EQ(vector.backing_size(), 3);
ASSERT_EQ(vector[0], 0);
ASSERT_EQ(vector[1], 3);
ASSERT_EQ(vector[2], 5);
}
TEST(SparseVectorTests, indexAtEnd) {
SparseVector<uint32_t> vector{0, 1};
vector.erase(0);
ASSERT_EQ(vector[1], 1);
}
TEST(SparseVectorTests, iteratorAtEnd) {
SparseVector<uint32_t> vector{0, 1, 2};
vector.erase(0);
vector.erase(1);
ASSERT_EQ(vector.iterator_at(2).index(), 2);
}
TEST(SparseVectorTests, eraseElementAtIteratorRef) {
SparseVector<uint32_t> vector{0, 1};
auto it = vector.begin();
ASSERT_EQ(vector[0], 0);
vector.erase(0);
ASSERT_THROW(*it, std::bad_variant_access);
}
| 21.402174 | 58 | 0.68258 | [
"vector"
] |
7d9d596b47d0a4e8fd113af50803a8275ad77261 | 144 | hpp | C++ | sortAlgs/interface.hpp | Lw-Cui/sortAlgs | 9f030aa76b743736db5056de411641b92018a362 | [
"MIT"
] | 1 | 2016-02-25T01:56:48.000Z | 2016-02-25T01:56:48.000Z | sortAlgs/interface.hpp | Lw-Cui/sortAlgs | 9f030aa76b743736db5056de411641b92018a362 | [
"MIT"
] | null | null | null | sortAlgs/interface.hpp | Lw-Cui/sortAlgs | 9f030aa76b743736db5056de411641b92018a362 | [
"MIT"
] | null | null | null | #ifndef _INTERFACE_
#define _INTERFACE_
#include <vector>
extern "C" {
void sort(std::vector<int> &array);
const char *self();
}
#endif
| 16 | 39 | 0.673611 | [
"vector"
] |
7da042e5ec04c9360f4489778b9cb9c9c629d666 | 13,467 | cpp | C++ | newbase/NFmiStreamQueryData.cpp | fmidev/smartmet-library-newbase | 12d93660c06e3c66a039ea75530bd9ca5daf7ab8 | [
"MIT"
] | null | null | null | newbase/NFmiStreamQueryData.cpp | fmidev/smartmet-library-newbase | 12d93660c06e3c66a039ea75530bd9ca5daf7ab8 | [
"MIT"
] | 7 | 2017-01-17T10:46:33.000Z | 2019-11-21T07:50:17.000Z | newbase/NFmiStreamQueryData.cpp | fmidev/smartmet-library-newbase | 12d93660c06e3c66a039ea75530bd9ca5daf7ab8 | [
"MIT"
] | 2 | 2017-01-17T07:33:28.000Z | 2018-04-26T07:10:23.000Z | // ======================================================================
/*!
* \file NFmiStreamQueryData.cpp
* \brief Implementation of class NFmiStreamQueryData
*/
// ======================================================================
/*!
* \class NFmiStreamQueryData
*
* Undocumented
*
*/
// ======================================================================
#include "NFmiStreamQueryData.h"
#include "NFmiFileSystem.h"
#include "NFmiValueString.h"
#include <macgyver/Exception.h>
#include <cstdio>
#include <fcntl.h>
#include <fstream>
#ifndef UNIX
#include <io.h>
#endif
using namespace std;
#include "NFmiVersion.h"
// ----------------------------------------------------------------------
/*!
* \brief Local function for finding newest .sqd or .fqd file
*
* This was made by copying NFmiFileSystem::NewestFile and
* making the necessary modifications.
*/
// ----------------------------------------------------------------------
const string find_newest_querydata(const string &thePath)
{
try
{
if (!NFmiFileSystem::DirectoryExists(thePath))
return "";
list<string> files = NFmiFileSystem::DirectoryFiles(thePath);
if (files.empty())
return "";
string newestfile;
time_t newesttime = 0;
for (list<string>::const_iterator f = files.begin(); f != files.end(); ++f)
{
string filename = thePath + '/' + *f;
if (NFmiFileSystem::FileReadable(filename))
{
string suffix = NFmiStringTools::Suffix(*f);
NFmiStringTools::LowerCase(suffix);
if (suffix == "sqd" || suffix == "fqd")
{
time_t modtime = NFmiFileSystem::FileModificationTime(filename);
if (modtime > newesttime)
{
newesttime = modtime;
newestfile = *f;
}
}
}
}
return newestfile;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* Destructor
*/
// ----------------------------------------------------------------------
NFmiStreamQueryData::~NFmiStreamQueryData()
{
try
{
if (!itsOwnerData && itsQueryData)
delete itsQueryData;
if (itsQueryDataIter)
delete itsQueryDataIter;
}
catch (...)
{
Fmi::Exception exception(BCP, "Destructor failed", nullptr);
exception.printError();
}
}
// ----------------------------------------------------------------------
/*!
* Void constructor
*/
// ----------------------------------------------------------------------
NFmiStreamQueryData::NFmiStreamQueryData()
: itsQueryData(nullptr), itsQueryDataIter(nullptr), itsOwnerData(false)
{
}
// ----------------------------------------------------------------------
/*!
* Constructor
*
* \param theQueryData Undocumented
*/
// ----------------------------------------------------------------------
NFmiStreamQueryData::NFmiStreamQueryData(NFmiQueryData *theQueryData, bool isOwnerData)
: itsQueryData(theQueryData), itsQueryDataIter(nullptr), itsOwnerData(isOwnerData)
{
}
// ----------------------------------------------------------------------
/*!
* \return Undocumented
*/
// ----------------------------------------------------------------------
NFmiFastQueryInfo *NFmiStreamQueryData::QueryInfoIter()
{
try
{
if (itsQueryData)
{
if (!itsQueryDataIter)
{
itsQueryDataIter = new NFmiFastQueryInfo(itsQueryData);
}
}
return itsQueryDataIter;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \param theOwnerData Undocumented
* \return Undocumented
*/
// ----------------------------------------------------------------------
NFmiQueryData *NFmiStreamQueryData::QueryData(bool theOwnerData)
{
try
{
NFmiQueryData *tmp = itsQueryData; // otetaan väliaikaismuuttujaan talteen siltä varalta jos
// omistajuus vaihtuu ja itsQueryData nollataan
itsOwnerData = theOwnerData;
if (itsOwnerData)
itsQueryData = nullptr; // pitää nollata pointteri, muuten voi tapahtua kauheita jos luetaan
// uusi data sisään
return tmp;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \return Undocumented
*/
// ----------------------------------------------------------------------
bool NFmiStreamQueryData::IsData()
{
try
{
if (itsQueryData)
return true;
return false;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \param theFileName Undocumented
* \param theQueryData Undocumented
* \param theLibVersion Undocumented
* \return Undocumented
*/
// ----------------------------------------------------------------------
bool NFmiStreamQueryData::WriteData(const NFmiString &theFileName,
NFmiQueryData *theQueryData,
long theLibVersion) const
{
try
{
auto version = static_cast<unsigned short>(theLibVersion);
if (version < 5)
version = 5;
ofstream dataFile(theFileName, ios::binary | ios::out);
if (dataFile)
{
if (theQueryData)
{
theQueryData->UseBinaryStorage(theLibVersion <= 5 ? false : true);
theQueryData->InfoVersion(version);
dataFile << *theQueryData;
}
else
{
if (itsQueryData)
{
itsQueryData->UseBinaryStorage(theLibVersion <= 5 ? false : true);
itsQueryData->InfoVersion(version);
dataFile << *itsQueryData;
}
else
{
cerr << "QueryData-object not found" << endl;
return false;
}
}
return true;
}
return false;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \param theFileName Undocumented
* \param theQueryData Undocumented
* \return Undocumented
*/
// ----------------------------------------------------------------------
bool NFmiStreamQueryData::ReadLatestData(const NFmiString &theFileName,
NFmiQueryData **theQueryData)
{
try
{
// If the file is a plain file, read it directly
if (!NFmiFileSystem::DirectoryExists(theFileName.CharPtr()))
return ReadData(theFileName, theQueryData);
string newestfile = NFmiFileSystem::NewestFile(theFileName.CharPtr());
if (newestfile.empty())
return false;
string fullname = theFileName.CharPtr();
fullname += '/';
fullname += newestfile;
return ReadData(NFmiString(fullname), theQueryData);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \param theFileName Undocumented
* \param theQueryData Undocumented
* \return Undocumented
*/
// ----------------------------------------------------------------------
bool NFmiStreamQueryData::SafeReadLatestData(const NFmiString &theFileName,
NFmiQueryData **theQueryData)
{
try
{
// If the file is a plain file, read it directly
if (!NFmiFileSystem::DirectoryExists(theFileName.CharPtr()))
return ReadData(theFileName, theQueryData);
string newestfile = find_newest_querydata(theFileName.CharPtr());
if (newestfile.empty())
return false;
string fullname = theFileName.CharPtr();
fullname += '/';
fullname += newestfile;
return ReadData(NFmiString(fullname), theQueryData);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \param theFileName Undocumented
* \param theQueryData Undocumented
* \return Undocumented
*/
// ----------------------------------------------------------------------
bool NFmiStreamQueryData::ReadData(const NFmiString &theFileName, NFmiQueryData **theQueryData)
{
try
{
if (theFileName ==
NFmiString("")) // pitää tarkistaa, ettei tyhjä stringi, muuten kaatuu open:issa
return false;
ifstream dataFile;
dataFile.open(theFileName, ios::in | ios::binary);
if (!dataFile)
{
cerr << "File not found: '" << theFileName.CharPtr() << "'" << endl;
return false;
}
NFmiQueryData *theTempData = static_cast<NFmiQueryData *>(new NFmiQueryData);
try
{
dataFile >> *theTempData;
}
// TODO tämä poikkeus käsittely on surkea surkea, koska se tunkee tekstiä vain cerr:iin.
// Pitäisi tehdä fiksummin (esim. heittää runtime-poikkeus), mutta uskaltaako muuttaa enää tätä
// toiminnallisuutta?
catch (char *msg)
{
cerr << msg << endl;
cerr << "Could not open file: " << static_cast<char *>(theFileName) << " for reading."
<< endl;
dataFile.close();
delete theTempData; // siivotaan jäljet kun ongelmia tuli
theTempData = nullptr;
return false;
}
#ifdef FMI_MET_EDITOR_CONTINUOIS_MEMORY_ALLOC_FAILED
catch (double eDataMBSize)
{
// tee metEditori spesifinen virheilmoitus!!!
std::string errStr("SmartMet: cannot create large enough continuous array (");
errStr += NFmiValueString::GetStringWithMaxDecimalsSmartWay(eDataMBSize, 1);
errStr += " MB) for wanted data.";
dataFile.close();
delete theTempData; // siivotaan jäljet kun ongelmia tuli
theTempData = 0;
throw Fmi::Exception(BCP, errStr);
}
#endif // FMI_MET_EDITOR_CONTINUOIS_MEMORY_ALLOC_FAILED
catch (...)
{
dataFile.close();
delete theTempData; // siivotaan jäljet kun ongelmia tuli
theTempData = nullptr;
throw;
}
dataFile.close();
itsOwnerData = false;
delete itsQueryData;
delete itsQueryDataIter;
itsQueryData = nullptr;
itsQueryDataIter = nullptr;
if (theQueryData)
{
itsOwnerData = true;
*theQueryData =
theTempData; // Data ja sen omistus siirtyy argumenttina annettuun qdata-pointteriin.
}
else
{
itsQueryData = theTempData;
}
return true;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \param theQueryInfo Undocumented
* \return Undocumented
*/
// ----------------------------------------------------------------------
bool NFmiStreamQueryData::ReadIn(NFmiQueryInfo *theQueryInfo)
{
try
{
#ifndef UNIX
int result = ::_setmode(_fileno(stdin), _O_BINARY);
if (result == -1)
{
cerr << "Could not set standard input into binary mode!";
return false;
}
#endif
try
{
cin >> *theQueryInfo;
}
catch (char *msg)
{
cerr << msg << endl;
return false;
}
return true;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \param theQueryData Undocumented
* \return Undocumented
*/
// ----------------------------------------------------------------------
bool NFmiStreamQueryData::ReadIn(NFmiQueryData *theQueryData)
{
try
{
// Muunnetaan "stdin" binääri moodiin --> pystyy lukemaan binääriä
#ifndef UNIX
int result = ::_setmode(_fileno(stdin), _O_BINARY);
if (result == -1)
{
cerr << "Could not set standard input into binary mode!";
return false;
}
#endif
NFmiQueryData *theTempData = static_cast<NFmiQueryData *>(new NFmiQueryData);
try
{
cin >> *theTempData;
}
catch (char *msg)
{
delete theTempData;
cerr << msg << endl;
return false;
}
itsOwnerData = false;
delete itsQueryData;
delete itsQueryDataIter;
itsQueryData = nullptr;
itsQueryDataIter = nullptr;
if (theQueryData)
{
itsOwnerData = true;
theQueryData = theTempData;
}
else
{
itsQueryData = theTempData;
}
return true;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \param theQueryData Undocumented
* \return Undocumented
*/
// ----------------------------------------------------------------------
bool NFmiStreamQueryData::WriteCout(NFmiQueryData *theQueryData) const
{
try
{
NFmiQueryData *tempData = theQueryData ? theQueryData : itsQueryData;
tempData->UseBinaryStorage(true);
if (tempData->InfoVersion() < 6.)
tempData->InfoVersion(DefaultFmiInfoVersion);
// Asetetaan 'stdout' binääri moodiin --> kirjoittaa binääriä
#ifndef UNIX
int result = ::_setmode(_fileno(stdout), _O_BINARY);
if (result == -1)
cerr << "Could not set standard input into binary mode!";
#endif
cout << *tempData;
return true;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ======================================================================
| 24.755515 | 99 | 0.517784 | [
"object"
] |
7da4e190a25a2439ff02540d490970be88086036 | 8,086 | hpp | C++ | Code/MXA/DataWrappers/MXA2DArray.hpp | mpartio/MXADataModel | cfab4b41bca5c71d0ab16fb4f3ed3097093f0a57 | [
"BSD-3-Clause"
] | null | null | null | Code/MXA/DataWrappers/MXA2DArray.hpp | mpartio/MXADataModel | cfab4b41bca5c71d0ab16fb4f3ed3097093f0a57 | [
"BSD-3-Clause"
] | null | null | null | Code/MXA/DataWrappers/MXA2DArray.hpp | mpartio/MXADataModel | cfab4b41bca5c71d0ab16fb4f3ed3097093f0a57 | [
"BSD-3-Clause"
] | 1 | 2020-08-26T07:08:26.000Z | 2020-08-26T07:08:26.000Z | ///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2008, mjackson
// All rights reserved.
// BSD License: http://www.opensource.org/licenses/bsd-license.html
//
// This code was written under United States Air Force Contract number
// FA8650-04-C-5229
//
///////////////////////////////////////////////////////////////////////////////
#ifndef _MXA2DArray_h_
#define _MXA2DArray_h_
#include <MXA/DataWrappers/MXAArrayTemplate.hpp>
#include <MXA/Common/LogTime.h>
#include <MXA/HDF5/H5Lite.h>
#include <MXA/HDF5/H5Image.h>
#include <MXA/HDF5/H5TiffIO.h>
#include <iostream>
#include <hdf5.h>
/**
* @class MXA2DArray MXA2DArray.hpp HDF5/MXA2DArray.hpp
* @brief This class represents a generic 2D array of data.
* @author mjackson
* @date Jan 9, 2008
* @version $Revision: 1.2 $
*/
template<typename T>
class MXA2DArray : public MXAArrayTemplate<T>
{
public:
/**
* @brief Creates a MXA2DArray wrapped in a Boost::SharedPointer that represents a 2D array
* typically used for images. The memory is allocated immediately. If the memory
* can not be allocated then a NULL wrapped pointer is returned.
* @param width The width of the array
* @param height The height of the array.
* @return Boost::shared_pointer wrapped MXA2DArray pointer
*/
static IMXAArray::Pointer CreateAbstractDataArray( int32_t width, int32_t height)
{
IMXAArray::Pointer ptr;
int32_t err = 1;
MXA2DArray<T>* d = new MXA2DArray<T>( width, height);
err = d->_allocate();
if (err >= 0)
{ // No errors, swap in the pointer
ptr.reset(d);
}
else
{
delete d; // Clean up the memory
}
return ptr;
}
/**
* @brief Creates and allocates an MXA2DArray object. You are repsonsible for cleaning
* up the memory if you select to allocate the array in this way.
* @param width The width of the array
* @param height The height of the array.
* @return Pointer to an MXA2DArray Object
*/
static MXA2DArray* New( int32_t width, int32_t height)
{
int32_t err = 1;
MXA2DArray* d = new MXA2DArray( width, height);
err = d->_allocate();
if (err < 0)
{
delete d;
d = NULL;
}
return d;
}
virtual ~MXA2DArray() {}
/**
* @brief Returns the number of dimensions the data has.
*/
virtual int32_t getNumberOfDimensions ()
{
return 2;
}
/**
* @brief Returns the sizes of the dimensions
* @param dims A pointer to an array of at least size=2.
*/
virtual void getDimensions(size_t* dims)
{
dims[0] = _width;
dims[1] = _height;
}
/**
* @brief Returns the width of the array
* @return
*/
virtual int32_t getWidth() { return _width; }
/**
* @brief Returns the height of the array.
* @return
*/
virtual int32_t getHeight() { return _height; }
/**
* @brief Returns the a pointer to the data value located at pixel (x,y)
* @param x The x location of the pixel
* @param y The y location of the pixel
* @return A pointer to the value.
*/
T* getPointer(int32_t x, int32_t y)
{
if (x < 0 || y < 0 || y >= _height || x >= _width)
{
return NULL;
}
size_t index = ((size_t)_width * (size_t)y ) + (size_t)x ;
return static_cast<T*>(this->getVoidPointer(index));
}
/**
* @brief Resizes the array
* @param size The new size of the array
* @return 1 if the resize succeeded, 0 on error
*/
virtual int32_t resize(size_t size)
{
if(this->_resizeAndExtend(size) || size <= 0)
{
this->_width = static_cast<int32_t>(size);
this->_height = 1;
return 1;
}
else
{
return 0;
}
}
/**
* @brief Resizes the data array to the specified width and height
* @param width The new width of the array
* @param height The new height of the array
* @return 1 on success and Zero (0) on failure
*/
int32_t resizeArray(int32_t width, int32_t height)
{
int32_t err = this->resize( (size_t)width * (size_t)height);
this->_width = width;
this->_height = height;
if (err == 0)
{
this->_width = 0;
this->_height = 0;
}
return err;
}
/**
* @brief Initializes the array to width and height = 0
*/
virtual void initialize()
{
MXAArrayTemplate<T>::initialize();
this->_width = 0;
this->_height = 0;
}
#if 0
// -----------------------------------------------------------------------------
// IDataFileIO Implementation (IFileWriter)
// -----------------------------------------------------------------------------
virtual int32_t writeToFile (IDataFile::Pointer dataFile)
{
int32_t err = -1;
std::vector<uint64_t> dims (2, 0 );
dims[0] = this->_width;
dims[1] = this->_height;
err = H5Utilities::createGroupsForDataset(this->getDatasetPath(), dataFile->getFileId() );
if (err < 0)
{
return err;
}
err = H5Lite::writePointerDataset(dataFile->getFileId(), this->getDatasetPath(), 2, &(dims.front()), this->getPointer(0, 0) );
return err;
}
// -----------------------------------------------------------------------------
// IDataFileIO Implementation (IFileReader)
// -----------------------------------------------------------------------------
virtual int32_t readFromFile(IDataFile::Pointer dataFile)
{
hid_t fileId = dataFile->getFileId();
if (fileId < 0)
{
return fileId;
}
herr_t err = -1;
H5T_class_t attr_type;
size_t attr_size;
std::string res;
std::vector<hsize_t> dims; //Reusable for the loop
err = H5Lite::getDatasetInfo(fileId, this->getDatasetPath(), dims, attr_type, attr_size);
if (err < 0 )
{
return err;
}
if (dims.size() != 2)
{
return -1;
}
uint64_t numElements = 1;
for (std::vector<uint64_t>::size_type i = 0; i < dims.size(); ++i)
{
numElements = numElements * dims[i];
}
if (this->getNumberOfElements() != numElements)
{
err = this->resize(numElements); //Resize the array to hold the data from the file
if (err < 0) { return err; }
}
this->_width = dims[0];
this->_height = dims[1];
err = H5Lite::readPointerDataset(fileId, this->getDatasetPath(), this->getPointer(0,0) );
return err;
}
#endif
/**
* @brief Converts the data array into a string delimited by the supplied
* delimiter.
* @param delimiter The delimiter to use between each value. Default is a single space
* @return The generated string
*/
virtual std::string valueToString(char delimiter = ' ')
{
std::stringstream sstream;
uint64_t nElements = this->getNumberOfElements();
uint64_t limit = nElements - 1;
int32_t width = 0;
T* data = this->getPointer(0, 0);
for(uint64_t i = 0; i < nElements; ++i)
{
if (sizeof(T) != 1 )
{
sstream << data[i];
}
else
{
sstream << static_cast<int32_t>(data[i]);
}
if (i < limit && width != _width)
{
sstream << delimiter;
}
if (width == _width) // Format in multiple rows
{
sstream << "\n";
width = 0;
}
++width;
}
return sstream.str();
}
protected:
MXA2DArray( int32_t width, int32_t height):
MXAArrayTemplate<T>( width * height, true),
_width(width),
_height(height)
{ }
private:
int32_t _width;
int32_t _height;
MXA2DArray(const MXA2DArray&); //Not Implemented
void operator=(const MXA2DArray&); //Not Implemented
};
#endif //_MXA2DArray_h_
| 27.134228 | 132 | 0.543903 | [
"object",
"vector"
] |
7daf92ba89c40a9225cc5c9d190ee35471e7b0a9 | 32,837 | cpp | C++ | src/core/runtime/amd_blit_sdma.cpp | pzins/ROCR-Runtime | 7284822462ba776c89bc15a42bf70860f3ce2544 | [
"AMDPLPA"
] | null | null | null | src/core/runtime/amd_blit_sdma.cpp | pzins/ROCR-Runtime | 7284822462ba776c89bc15a42bf70860f3ce2544 | [
"AMDPLPA"
] | null | null | null | src/core/runtime/amd_blit_sdma.cpp | pzins/ROCR-Runtime | 7284822462ba776c89bc15a42bf70860f3ce2544 | [
"AMDPLPA"
] | 1 | 2019-07-04T00:48:20.000Z | 2019-07-04T00:48:20.000Z | ////////////////////////////////////////////////////////////////////////////////
//
// The University of Illinois/NCSA
// Open Source License (NCSA)
//
// Copyright (c) 2014-2015, Advanced Micro Devices, Inc. All rights reserved.
//
// Developed by:
//
// AMD Research and AMD HSA Software Development
//
// Advanced Micro Devices, Inc.
//
// www.amd.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal with 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:
//
// - Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimers.
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimers in
// the documentation and/or other materials provided with the distribution.
// - Neither the names of Advanced Micro Devices, Inc,
// nor the names of its contributors may be used to endorse or promote
// products derived from this Software without specific prior written
// permission.
//
// 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 CONTRIBUTORS 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 WITH THE SOFTWARE.
//
////////////////////////////////////////////////////////////////////////////////
#include "core/inc/amd_blit_sdma.h"
#include <algorithm>
#include <atomic>
#include <cmath>
#include <cstring>
#include <limits>
#include "core/inc/amd_gpu_agent.h"
#include "core/inc/amd_memory_region.h"
#include "core/inc/runtime.h"
#include "core/inc/signal.h"
namespace amd {
// SDMA packet for VI device.
// Reference: http://people.freedesktop.org/~agd5f/dma_packets.txt
const unsigned int SDMA_OP_COPY = 1;
const unsigned int SDMA_OP_FENCE = 5;
const unsigned int SDMA_OP_TRAP = 6;
const unsigned int SDMA_OP_POLL_REGMEM = 8;
const unsigned int SDMA_OP_ATOMIC = 10;
const unsigned int SDMA_OP_CONST_FILL = 11;
const unsigned int SDMA_OP_TIMESTAMP = 13;
const unsigned int SDMA_SUBOP_COPY_LINEAR = 0;
const unsigned int SDMA_SUBOP_TIMESTAMP_GET_GLOBAL = 2;
const unsigned int SDMA_ATOMIC_ADD64 = 47;
typedef struct SDMA_PKT_COPY_LINEAR_TAG {
union {
struct {
unsigned int op : 8;
unsigned int sub_op : 8;
unsigned int extra_info : 16;
};
unsigned int DW_0_DATA;
} HEADER_UNION;
union {
struct {
unsigned int count : 22;
unsigned int reserved_0 : 10;
};
unsigned int DW_1_DATA;
} COUNT_UNION;
union {
struct {
unsigned int reserved_0 : 16;
unsigned int dst_swap : 2;
unsigned int reserved_1 : 6;
unsigned int src_swap : 2;
unsigned int reserved_2 : 6;
};
unsigned int DW_2_DATA;
} PARAMETER_UNION;
union {
struct {
unsigned int src_addr_31_0 : 32;
};
unsigned int DW_3_DATA;
} SRC_ADDR_LO_UNION;
union {
struct {
unsigned int src_addr_63_32 : 32;
};
unsigned int DW_4_DATA;
} SRC_ADDR_HI_UNION;
union {
struct {
unsigned int dst_addr_31_0 : 32;
};
unsigned int DW_5_DATA;
} DST_ADDR_LO_UNION;
union {
struct {
unsigned int dst_addr_63_32 : 32;
};
unsigned int DW_6_DATA;
} DST_ADDR_HI_UNION;
} SDMA_PKT_COPY_LINEAR;
typedef struct SDMA_PKT_CONSTANT_FILL_TAG {
union {
struct {
unsigned int op : 8;
unsigned int sub_op : 8;
unsigned int sw : 2;
unsigned int reserved_0 : 12;
unsigned int fillsize : 2;
};
unsigned int DW_0_DATA;
} HEADER_UNION;
union {
struct {
unsigned int dst_addr_31_0 : 32;
};
unsigned int DW_1_DATA;
} DST_ADDR_LO_UNION;
union {
struct {
unsigned int dst_addr_63_32 : 32;
};
unsigned int DW_2_DATA;
} DST_ADDR_HI_UNION;
union {
struct {
unsigned int src_data_31_0 : 32;
};
unsigned int DW_3_DATA;
} DATA_UNION;
union {
struct {
unsigned int count : 22;
unsigned int reserved_0 : 10;
};
unsigned int DW_4_DATA;
} COUNT_UNION;
} SDMA_PKT_CONSTANT_FILL;
typedef struct SDMA_PKT_FENCE_TAG {
union {
struct {
unsigned int op : 8;
unsigned int sub_op : 8;
unsigned int reserved_0 : 16;
};
unsigned int DW_0_DATA;
} HEADER_UNION;
union {
struct {
unsigned int addr_31_0 : 32;
};
unsigned int DW_1_DATA;
} ADDR_LO_UNION;
union {
struct {
unsigned int addr_63_32 : 32;
};
unsigned int DW_2_DATA;
} ADDR_HI_UNION;
union {
struct {
unsigned int data : 32;
};
unsigned int DW_3_DATA;
} DATA_UNION;
} SDMA_PKT_FENCE;
typedef struct SDMA_PKT_POLL_REGMEM_TAG {
union {
struct {
unsigned int op : 8;
unsigned int sub_op : 8;
unsigned int reserved_0 : 10;
unsigned int hdp_flush : 1;
unsigned int reserved_1 : 1;
unsigned int func : 3;
unsigned int mem_poll : 1;
};
unsigned int DW_0_DATA;
} HEADER_UNION;
union {
struct {
unsigned int addr_31_0 : 32;
};
unsigned int DW_1_DATA;
} ADDR_LO_UNION;
union {
struct {
unsigned int addr_63_32 : 32;
};
unsigned int DW_2_DATA;
} ADDR_HI_UNION;
union {
struct {
unsigned int value : 32;
};
unsigned int DW_3_DATA;
} VALUE_UNION;
union {
struct {
unsigned int mask : 32;
};
unsigned int DW_4_DATA;
} MASK_UNION;
union {
struct {
unsigned int interval : 16;
unsigned int retry_count : 12;
unsigned int reserved_0 : 4;
};
unsigned int DW_5_DATA;
} DW5_UNION;
} SDMA_PKT_POLL_REGMEM;
typedef struct SDMA_PKT_ATOMIC_TAG {
union {
struct {
unsigned int op : 8;
unsigned int sub_op : 8;
unsigned int l : 1;
unsigned int reserved_0 : 8;
unsigned int operation : 7;
};
unsigned int DW_0_DATA;
} HEADER_UNION;
union {
struct {
unsigned int addr_31_0 : 32;
};
unsigned int DW_1_DATA;
} ADDR_LO_UNION;
union {
struct {
unsigned int addr_63_32 : 32;
};
unsigned int DW_2_DATA;
} ADDR_HI_UNION;
union {
struct {
unsigned int src_data_31_0 : 32;
};
unsigned int DW_3_DATA;
} SRC_DATA_LO_UNION;
union {
struct {
unsigned int src_data_63_32 : 32;
};
unsigned int DW_4_DATA;
} SRC_DATA_HI_UNION;
union {
struct {
unsigned int cmp_data_31_0 : 32;
};
unsigned int DW_5_DATA;
} CMP_DATA_LO_UNION;
union {
struct {
unsigned int cmp_data_63_32 : 32;
};
unsigned int DW_6_DATA;
} CMP_DATA_HI_UNION;
union {
struct {
unsigned int loop_interval : 13;
unsigned int reserved_0 : 19;
};
unsigned int DW_7_DATA;
} LOOP_UNION;
} SDMA_PKT_ATOMIC;
typedef struct SDMA_PKT_TIMESTAMP_TAG {
union {
struct {
unsigned int op : 8;
unsigned int sub_op : 8;
unsigned int reserved_0 : 16;
};
unsigned int DW_0_DATA;
} HEADER_UNION;
union {
struct {
unsigned int addr_31_0 : 32;
};
unsigned int DW_1_DATA;
} ADDR_LO_UNION;
union {
struct {
unsigned int addr_63_32 : 32;
};
unsigned int DW_2_DATA;
} ADDR_HI_UNION;
} SDMA_PKT_TIMESTAMP;
typedef struct SDMA_PKT_TRAP_TAG {
union {
struct {
unsigned int op : 8;
unsigned int sub_op : 8;
unsigned int reserved_0 : 16;
};
unsigned int DW_0_DATA;
} HEADER_UNION;
union {
struct {
unsigned int int_ctx : 28;
unsigned int reserved_1 : 4;
};
unsigned int DW_1_DATA;
} INT_CONTEXT_UNION;
} SDMA_PKT_TRAP;
inline uint32_t ptrlow32(const void* p) {
return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(p));
}
inline uint32_t ptrhigh32(const void* p) {
#if defined(HSA_LARGE_MODEL)
return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(p) >> 32);
#else
return 0;
#endif
}
const size_t BlitSdmaBase::kQueueSize = 1024 * 1024;
const size_t BlitSdmaBase::kCopyPacketSize = sizeof(SDMA_PKT_COPY_LINEAR);
const size_t BlitSdmaBase::kMaxSingleCopySize = 0x3fffe0; // From HW documentation
const size_t BlitSdmaBase::kMaxSingleFillSize = 0x3fffe0;
template <typename RingIndexTy, bool HwIndexMonotonic, int SizeToCountOffset>
BlitSdma<RingIndexTy, HwIndexMonotonic, SizeToCountOffset>::BlitSdma()
: agent_(NULL),
queue_start_addr_(NULL),
fence_base_addr_(NULL),
fence_pool_size_(0),
fence_pool_counter_(0),
cached_reserve_index_(0),
cached_commit_index_(0),
platform_atomic_support_(true) {
std::memset(&queue_resource_, 0, sizeof(queue_resource_));
}
template <typename RingIndexTy, bool HwIndexMonotonic, int SizeToCountOffset>
BlitSdma<RingIndexTy, HwIndexMonotonic, SizeToCountOffset>::~BlitSdma() {}
template <typename RingIndexTy, bool HwIndexMonotonic, int SizeToCountOffset>
hsa_status_t BlitSdma<RingIndexTy, HwIndexMonotonic, SizeToCountOffset>::Initialize(
const core::Agent& agent) {
agent_ = reinterpret_cast<amd::GpuAgent*>(&const_cast<core::Agent&>(agent));
if (queue_start_addr_ != NULL) {
// Already initialized.
return HSA_STATUS_SUCCESS;
}
if (agent.device_type() != core::Agent::kAmdGpuDevice) {
return HSA_STATUS_ERROR;
}
linear_copy_command_size_ = sizeof(SDMA_PKT_COPY_LINEAR);
fill_command_size_ = sizeof(SDMA_PKT_CONSTANT_FILL);
fence_command_size_ = sizeof(SDMA_PKT_FENCE);
poll_command_size_ = sizeof(SDMA_PKT_POLL_REGMEM);
atomic_command_size_ = sizeof(SDMA_PKT_ATOMIC);
timestamp_command_size_ = sizeof(SDMA_PKT_TIMESTAMP);
trap_command_size_ = sizeof(SDMA_PKT_TRAP);
const amd::GpuAgentInt& amd_gpu_agent =
static_cast<const amd::GpuAgentInt&>(agent);
if (HSA_PROFILE_FULL == amd_gpu_agent.profile()) {
assert(false && "Only support SDMA for dgpu currently");
return HSA_STATUS_ERROR;
}
if (amd_gpu_agent.isa()->version() == core::Isa::Version(7, 0, 1)) {
platform_atomic_support_ = false;
}
// Allocate queue buffer.
queue_start_addr_ = (char*)core::Runtime::runtime_singleton_->system_allocator()(
kQueueSize, 0x1000, core::MemoryRegion::AllocateExecutable);
if (queue_start_addr_ == NULL) {
return HSA_STATUS_ERROR_OUT_OF_RESOURCES;
}
std::memset(queue_start_addr_, 0, kQueueSize);
// Access kernel driver to initialize the queue control block
// This call binds user mode queue object to underlying compute
// device.
const HSA_QUEUE_TYPE kQueueType_ = HSA_QUEUE_SDMA;
if (HSAKMT_STATUS_SUCCESS != hsaKmtCreateQueue(amd_gpu_agent.node_id(), kQueueType_, 100,
HSA_QUEUE_PRIORITY_MAXIMUM, queue_start_addr_,
kQueueSize, NULL, &queue_resource_)) {
Destroy(agent);
return HSA_STATUS_ERROR_OUT_OF_RESOURCES;
}
cached_reserve_index_ = *reinterpret_cast<RingIndexTy*>(queue_resource_.Queue_write_ptr);
cached_commit_index_ = cached_reserve_index_;
fence_pool_size_ =
static_cast<uint32_t>((kQueueSize + fence_command_size_ - 1) / fence_command_size_);
fence_pool_mask_ = fence_pool_size_ - 1;
fence_base_addr_ = reinterpret_cast<uint32_t*>(
core::Runtime::runtime_singleton_->system_allocator()(
fence_pool_size_ * sizeof(uint32_t), 256,
core::MemoryRegion::AllocateNoFlags));
if (fence_base_addr_ == NULL) {
Destroy(agent);
return HSA_STATUS_ERROR_OUT_OF_RESOURCES;
}
return HSA_STATUS_SUCCESS;
}
template <typename RingIndexTy, bool HwIndexMonotonic, int SizeToCountOffset>
hsa_status_t BlitSdma<RingIndexTy, HwIndexMonotonic, SizeToCountOffset>::Destroy(
const core::Agent& agent) {
// Release all allocated resources and reset them to zero.
if (queue_resource_.QueueId != 0) {
// Release queue resources from the kernel
auto err = hsaKmtDestroyQueue(queue_resource_.QueueId);
assert(err == HSAKMT_STATUS_SUCCESS);
memset(&queue_resource_, 0, sizeof(queue_resource_));
}
if (queue_start_addr_ != NULL) {
// Release queue buffer.
core::Runtime::runtime_singleton_->system_deallocator()(queue_start_addr_);
}
if (fence_base_addr_ != NULL) {
core::Runtime::runtime_singleton_->system_deallocator()(fence_base_addr_);
}
queue_start_addr_ = NULL;
cached_reserve_index_ = 0;
cached_commit_index_ = 0;
return HSA_STATUS_SUCCESS;
}
template <typename RingIndexTy, bool HwIndexMonotonic, int SizeToCountOffset>
hsa_status_t BlitSdma<RingIndexTy, HwIndexMonotonic, SizeToCountOffset>::SubmitLinearCopyCommand(
void* dst, const void* src, size_t size) {
// Break the copy into multiple copy operation incase the copy size exceeds
// the SDMA linear copy limit.
const uint32_t num_copy_command = (size + kMaxSingleCopySize - 1) / kMaxSingleCopySize;
const uint32_t total_copy_command_size =
num_copy_command * linear_copy_command_size_;
const uint32_t total_command_size =
total_copy_command_size + fence_command_size_;
const uint32_t kFenceValue = 2015;
uint32_t* fence_addr = ObtainFenceObject();
*fence_addr = 0;
RingIndexTy curr_index;
char* command_addr = AcquireWriteAddress(total_command_size, curr_index);
if (command_addr == NULL) {
return HSA_STATUS_ERROR_OUT_OF_RESOURCES;
}
BuildCopyCommand(command_addr, num_copy_command, dst, src, size);
command_addr += total_copy_command_size;
BuildFenceCommand(command_addr, fence_addr, kFenceValue);
ReleaseWriteAddress(curr_index, total_command_size);
WaitFence(fence_addr, kFenceValue);
return HSA_STATUS_SUCCESS;
}
template <typename RingIndexTy, bool HwIndexMonotonic, int SizeToCountOffset>
hsa_status_t BlitSdma<RingIndexTy, HwIndexMonotonic, SizeToCountOffset>::SubmitLinearCopyCommand(
void* dst, const void* src, size_t size, std::vector<core::Signal*>& dep_signals,
core::Signal& out_signal) {
// The signal is 64 bit value, and poll checks for 32 bit value. So we
// need to use two poll operations per dependent signal.
const uint32_t num_poll_command =
static_cast<uint32_t>(2 * dep_signals.size());
const uint32_t total_poll_command_size =
(num_poll_command * poll_command_size_);
// Break the copy into multiple copy operation incase the copy size exceeds
// the SDMA linear copy limit.
const uint32_t num_copy_command = (size + kMaxSingleCopySize - 1) / kMaxSingleCopySize;
const uint32_t total_copy_command_size =
num_copy_command * linear_copy_command_size_;
// Load the profiling state early in case the user disable or enable the
// profiling in the middle of the call.
const bool profiling_enabled = agent_->profiling_enabled();
uint64_t* end_ts_addr = NULL;
uint32_t total_timestamp_command_size = 0;
if (profiling_enabled) {
// SDMA timestamp packet requires 32 byte of aligned memory, but
// amd_signal_t::end_ts is not 32 byte aligned. So an extra copy packet to
// read from a 32 byte aligned bounce buffer is required to avoid changing
// the amd_signal_t ABI.
end_ts_addr = agent_->ObtainEndTsObject();
if (end_ts_addr == NULL) {
return HSA_STATUS_ERROR_OUT_OF_RESOURCES;
}
total_timestamp_command_size =
(2 * timestamp_command_size_) + linear_copy_command_size_;
}
// On agent that does not support platform atomic, we replace it with
// one or two fence packet(s) to update the signal value. The reason fence
// is used and not write packet is because the SDMA engine may overlap a
// serial copy/write packets.
const uint64_t completion_signal_value =
static_cast<uint64_t>(out_signal.LoadRelaxed() - 1);
const size_t sync_command_size = (platform_atomic_support_)
? atomic_command_size_
: (completion_signal_value > UINT32_MAX)
? 2 * fence_command_size_
: fence_command_size_;
// If the signal is an interrupt signal, we also need to make SDMA engine to
// send interrupt packet to IH.
const size_t interrupt_command_size =
(out_signal.signal_.event_mailbox_ptr != 0)
? (fence_command_size_ + trap_command_size_)
: 0;
const uint32_t total_command_size =
total_poll_command_size + total_copy_command_size + sync_command_size +
total_timestamp_command_size + interrupt_command_size;
RingIndexTy curr_index;
char* command_addr = AcquireWriteAddress(total_command_size, curr_index);
if (command_addr == NULL) {
return HSA_STATUS_ERROR_OUT_OF_RESOURCES;
}
for (size_t i = 0; i < dep_signals.size(); ++i) {
uint32_t* signal_addr =
reinterpret_cast<uint32_t*>(dep_signals[i]->ValueLocation());
// Wait for the higher 64 bit to 0.
BuildPollCommand(command_addr, &signal_addr[1], 0);
command_addr += poll_command_size_;
// Then wait for the lower 64 bit to 0.
BuildPollCommand(command_addr, &signal_addr[0], 0);
command_addr += poll_command_size_;
}
if (profiling_enabled) {
BuildGetGlobalTimestampCommand(
command_addr, reinterpret_cast<void*>(&out_signal.signal_.start_ts));
command_addr += timestamp_command_size_;
}
// Do the transfer after all polls are satisfied.
BuildCopyCommand(command_addr, num_copy_command, dst, src, size);
command_addr += total_copy_command_size;
if (profiling_enabled) {
assert(IsMultipleOf(end_ts_addr, 32));
BuildGetGlobalTimestampCommand(command_addr,
reinterpret_cast<void*>(end_ts_addr));
command_addr += timestamp_command_size_;
BuildCopyCommand(command_addr, 1,
reinterpret_cast<void*>(&out_signal.signal_.end_ts),
reinterpret_cast<void*>(end_ts_addr), sizeof(uint64_t));
command_addr += linear_copy_command_size_;
}
// After transfer is completed, decrement the signal value.
if (platform_atomic_support_) {
BuildAtomicDecrementCommand(command_addr, out_signal.ValueLocation());
command_addr += atomic_command_size_;
} else {
uint32_t* signal_value_location =
reinterpret_cast<uint32_t*>(out_signal.ValueLocation());
if (completion_signal_value > UINT32_MAX) {
BuildFenceCommand(command_addr, signal_value_location + 1,
static_cast<uint32_t>(completion_signal_value >> 32));
command_addr += fence_command_size_;
}
BuildFenceCommand(command_addr, signal_value_location,
static_cast<uint32_t>(completion_signal_value));
command_addr += fence_command_size_;
}
// Update mailbox event and send interrupt to IH.
if (out_signal.signal_.event_mailbox_ptr != 0) {
BuildFenceCommand(command_addr, reinterpret_cast<uint32_t*>(
out_signal.signal_.event_mailbox_ptr),
static_cast<uint32_t>(out_signal.signal_.event_id));
command_addr += fence_command_size_;
BuildTrapCommand(command_addr);
}
ReleaseWriteAddress(curr_index, total_command_size);
return HSA_STATUS_SUCCESS;
}
template <typename RingIndexTy, bool HwIndexMonotonic, int SizeToCountOffset>
hsa_status_t BlitSdma<RingIndexTy, HwIndexMonotonic, SizeToCountOffset>::SubmitLinearFillCommand(
void* ptr, uint32_t value, size_t count) {
const size_t size = count * sizeof(uint32_t);
// Break the copy into multiple copy operation incase the copy size exceeds
// the SDMA linear copy limit.
const uint32_t num_fill_command = (size + kMaxSingleFillSize - 1) / kMaxSingleFillSize;
const uint32_t total_fill_command_size =
num_fill_command * fill_command_size_;
const uint32_t total_command_size =
total_fill_command_size + fence_command_size_;
RingIndexTy curr_index;
char* command_addr = AcquireWriteAddress(total_command_size, curr_index);
if (command_addr == NULL) {
return HSA_STATUS_ERROR_OUT_OF_RESOURCES;
}
const uint32_t fill_command_size = fill_command_size_;
size_t cur_size = 0;
for (uint32_t i = 0; i < num_fill_command; ++i) {
const uint32_t fill_size =
static_cast<uint32_t>(std::min((size - cur_size), kMaxSingleFillSize));
void* cur_ptr = static_cast<char*>(ptr) + cur_size;
SDMA_PKT_CONSTANT_FILL* packet_addr =
reinterpret_cast<SDMA_PKT_CONSTANT_FILL*>(command_addr);
memset(packet_addr, 0, sizeof(SDMA_PKT_CONSTANT_FILL));
packet_addr->HEADER_UNION.op = SDMA_OP_CONST_FILL;
packet_addr->HEADER_UNION.fillsize = 2; // DW fill
packet_addr->DST_ADDR_LO_UNION.dst_addr_31_0 = ptrlow32(cur_ptr);
packet_addr->DST_ADDR_HI_UNION.dst_addr_63_32 = ptrhigh32(cur_ptr);
packet_addr->DATA_UNION.src_data_31_0 = value;
packet_addr->COUNT_UNION.count = fill_size + SizeToCountOffset;
command_addr += fill_command_size;
cur_size += fill_size;
}
assert(cur_size == size);
const uint32_t kFenceValue = 2015;
uint32_t* fence_addr = ObtainFenceObject();
*fence_addr = 0;
BuildFenceCommand(command_addr, fence_addr, kFenceValue);
ReleaseWriteAddress(curr_index, total_command_size);
WaitFence(fence_addr, kFenceValue);
return HSA_STATUS_SUCCESS;
}
template <typename RingIndexTy, bool HwIndexMonotonic, int SizeToCountOffset>
hsa_status_t BlitSdma<RingIndexTy, HwIndexMonotonic, SizeToCountOffset>::EnableProfiling(
bool enable) {
return HSA_STATUS_SUCCESS;
}
template <typename RingIndexTy, bool HwIndexMonotonic, int SizeToCountOffset>
char* BlitSdma<RingIndexTy, HwIndexMonotonic, SizeToCountOffset>::AcquireWriteAddress(
uint32_t cmd_size, RingIndexTy& curr_index) {
// Ring is full when all but one byte is written.
if (cmd_size >= kQueueSize) {
return NULL;
}
while (true) {
curr_index = atomic::Load(&cached_reserve_index_, std::memory_order_acquire);
// Check whether a linear region of the requested size is available.
// If == cmd_size: region is at beginning of ring.
// If < cmd_size: region intersects end of ring, pad with no-ops and retry.
if (WrapIntoRing(curr_index + cmd_size) < cmd_size) {
PadRingToEnd(curr_index);
continue;
}
// Check whether the engine has finished using this region.
const RingIndexTy new_index = curr_index + cmd_size;
if (CanWriteUpto(new_index) == false) {
// Wait for read index to move and try again.
os::YieldThread();
continue;
}
// Try to reserve this part of the ring.
if (atomic::Cas(&cached_reserve_index_, new_index, curr_index, std::memory_order_release) ==
curr_index) {
return queue_start_addr_ + WrapIntoRing(curr_index);
}
// Another thread reserved curr_index, try again.
os::YieldThread();
}
return NULL;
}
template <typename RingIndexTy, bool HwIndexMonotonic, int SizeToCountOffset>
void BlitSdma<RingIndexTy, HwIndexMonotonic, SizeToCountOffset>::UpdateWriteAndDoorbellRegister(
RingIndexTy curr_index, RingIndexTy new_index) {
while (true) {
// Make sure that the address before ::curr_index is already released.
// Otherwise the CP may read invalid packets.
if (atomic::Load(&cached_commit_index_, std::memory_order_acquire) == curr_index) {
if (core::Runtime::runtime_singleton_->flag().sdma_wait_idle()) {
// TODO: remove when sdma wpointer issue is resolved.
// Wait until the SDMA engine finish processing all packets before
// updating the wptr and doorbell.
while (WrapIntoRing(*reinterpret_cast<RingIndexTy*>(queue_resource_.Queue_read_ptr)) !=
WrapIntoRing(curr_index)) {
os::YieldThread();
}
}
// Update write pointer and doorbel register.
*reinterpret_cast<RingIndexTy*>(queue_resource_.Queue_write_ptr) =
(HwIndexMonotonic ? new_index : WrapIntoRing(new_index));
// Ensure write pointer is visible to GPU before doorbell.
std::atomic_thread_fence(std::memory_order_release);
*reinterpret_cast<RingIndexTy*>(queue_resource_.Queue_DoorBell) =
(HwIndexMonotonic ? new_index : WrapIntoRing(new_index));
atomic::Store(&cached_commit_index_, new_index, std::memory_order_release);
break;
}
// Waiting for another thread to submit preceding commands first.
os::YieldThread();
}
}
template <typename RingIndexTy, bool HwIndexMonotonic, int SizeToCountOffset>
void BlitSdma<RingIndexTy, HwIndexMonotonic, SizeToCountOffset>::ReleaseWriteAddress(
RingIndexTy curr_index, uint32_t cmd_size) {
if (cmd_size > kQueueSize) {
assert(false && "cmd_addr is outside the queue buffer range");
return;
}
UpdateWriteAndDoorbellRegister(curr_index, curr_index + cmd_size);
}
template <typename RingIndexTy, bool HwIndexMonotonic, int SizeToCountOffset>
void BlitSdma<RingIndexTy, HwIndexMonotonic, SizeToCountOffset>::PadRingToEnd(
RingIndexTy curr_index) {
// Reserve region from here to the end of the ring.
RingIndexTy new_index = curr_index + (kQueueSize - WrapIntoRing(curr_index));
// Check whether the engine has finished using this region.
if (CanWriteUpto(new_index) == false) {
// Wait for read index to move and try again.
return;
}
if (atomic::Cas(&cached_reserve_index_, new_index, curr_index, std::memory_order_release) ==
curr_index) {
// Write and submit NOP commands in reserved region.
char* nop_address = queue_start_addr_ + WrapIntoRing(curr_index);
memset(nop_address, 0, new_index - curr_index);
UpdateWriteAndDoorbellRegister(curr_index, new_index);
}
}
template <typename RingIndexTy, bool HwIndexMonotonic, int SizeToCountOffset>
uint32_t BlitSdma<RingIndexTy, HwIndexMonotonic, SizeToCountOffset>::WrapIntoRing(
RingIndexTy index) {
return index & (kQueueSize - 1);
}
template <typename RingIndexTy, bool HwIndexMonotonic, int SizeToCountOffset>
bool BlitSdma<RingIndexTy, HwIndexMonotonic, SizeToCountOffset>::CanWriteUpto(
RingIndexTy upto_index) {
// Get/calculate the monotonic read index.
RingIndexTy hw_read_index = *reinterpret_cast<RingIndexTy*>(queue_resource_.Queue_read_ptr);
RingIndexTy read_index;
if (HwIndexMonotonic) {
read_index = hw_read_index;
} else {
// Calculate distance from commit index to HW read index.
// Commit index is always < kQueueSize away from HW read index.
RingIndexTy commit_index = atomic::Load(&cached_commit_index_, std::memory_order_relaxed);
RingIndexTy dist_to_read_index = WrapIntoRing(commit_index - hw_read_index);
read_index = commit_index - dist_to_read_index;
}
// Check whether the read pointer has passed the given index.
// At most we can submit (kQueueSize - 1) bytes at a time.
return (upto_index - read_index) < kQueueSize;
}
template <typename RingIndexTy, bool HwIndexMonotonic, int SizeToCountOffset>
void BlitSdma<RingIndexTy, HwIndexMonotonic, SizeToCountOffset>::BuildFenceCommand(
char* fence_command_addr, uint32_t* fence, uint32_t fence_value) {
assert(fence_command_addr != NULL);
SDMA_PKT_FENCE* packet_addr =
reinterpret_cast<SDMA_PKT_FENCE*>(fence_command_addr);
memset(packet_addr, 0, sizeof(SDMA_PKT_FENCE));
packet_addr->HEADER_UNION.op = SDMA_OP_FENCE;
packet_addr->ADDR_LO_UNION.addr_31_0 = ptrlow32(fence);
packet_addr->ADDR_HI_UNION.addr_63_32 = ptrhigh32(fence);
packet_addr->DATA_UNION.data = fence_value;
}
template <typename RingIndexTy, bool HwIndexMonotonic, int SizeToCountOffset>
uint32_t* BlitSdma<RingIndexTy, HwIndexMonotonic, SizeToCountOffset>::ObtainFenceObject() {
const uint32_t fence_index =
atomic::Add(&fence_pool_counter_, 1U, std::memory_order_acquire);
uint32_t* fence_addr = &fence_base_addr_[fence_index & fence_pool_mask_];
assert(IsMultipleOf(fence_addr, 4));
return fence_addr;
}
template <typename RingIndexTy, bool HwIndexMonotonic, int SizeToCountOffset>
void BlitSdma<RingIndexTy, HwIndexMonotonic, SizeToCountOffset>::WaitFence(uint32_t* fence,
uint32_t fence_value) {
int spin_count = 51;
while (atomic::Load(fence, std::memory_order_acquire) != fence_value) {
if (--spin_count > 0) {
continue;
}
os::YieldThread();
}
}
template <typename RingIndexTy, bool HwIndexMonotonic, int SizeToCountOffset>
void BlitSdma<RingIndexTy, HwIndexMonotonic, SizeToCountOffset>::BuildCopyCommand(
char* cmd_addr, uint32_t num_copy_command, void* dst, const void* src, size_t size) {
size_t cur_size = 0;
for (uint32_t i = 0; i < num_copy_command; ++i) {
const uint32_t copy_size =
static_cast<uint32_t>(std::min((size - cur_size), kMaxSingleCopySize));
void* cur_dst = static_cast<char*>(dst) + cur_size;
const void* cur_src = static_cast<const char*>(src) + cur_size;
SDMA_PKT_COPY_LINEAR* packet_addr =
reinterpret_cast<SDMA_PKT_COPY_LINEAR*>(cmd_addr);
memset(packet_addr, 0, sizeof(SDMA_PKT_COPY_LINEAR));
packet_addr->HEADER_UNION.op = SDMA_OP_COPY;
packet_addr->HEADER_UNION.sub_op = SDMA_SUBOP_COPY_LINEAR;
packet_addr->COUNT_UNION.count = copy_size + SizeToCountOffset;
packet_addr->SRC_ADDR_LO_UNION.src_addr_31_0 = ptrlow32(cur_src);
packet_addr->SRC_ADDR_HI_UNION.src_addr_63_32 = ptrhigh32(cur_src);
packet_addr->DST_ADDR_LO_UNION.dst_addr_31_0 = ptrlow32(cur_dst);
packet_addr->DST_ADDR_HI_UNION.dst_addr_63_32 = ptrhigh32(cur_dst);
cmd_addr += linear_copy_command_size_;
cur_size += copy_size;
}
assert(cur_size == size);
}
template <typename RingIndexTy, bool HwIndexMonotonic, int SizeToCountOffset>
void BlitSdma<RingIndexTy, HwIndexMonotonic, SizeToCountOffset>::BuildPollCommand(
char* cmd_addr, void* addr, uint32_t reference) {
SDMA_PKT_POLL_REGMEM* packet_addr =
reinterpret_cast<SDMA_PKT_POLL_REGMEM*>(cmd_addr);
memset(packet_addr, 0, sizeof(SDMA_PKT_POLL_REGMEM));
packet_addr->HEADER_UNION.op = SDMA_OP_POLL_REGMEM;
packet_addr->HEADER_UNION.mem_poll = 1;
packet_addr->HEADER_UNION.func = 0x3; // IsEqual.
packet_addr->ADDR_LO_UNION.addr_31_0 = ptrlow32(addr);
packet_addr->ADDR_HI_UNION.addr_63_32 = ptrhigh32(addr);
packet_addr->VALUE_UNION.value = reference;
packet_addr->MASK_UNION.mask = 0xffffffff; // Compare the whole content.
packet_addr->DW5_UNION.interval = 0x04;
packet_addr->DW5_UNION.retry_count = 0xfff; // Retry forever.
}
template <typename RingIndexTy, bool HwIndexMonotonic, int SizeToCountOffset>
void BlitSdma<RingIndexTy, HwIndexMonotonic, SizeToCountOffset>::BuildAtomicDecrementCommand(
char* cmd_addr, void* addr) {
SDMA_PKT_ATOMIC* packet_addr = reinterpret_cast<SDMA_PKT_ATOMIC*>(cmd_addr);
memset(packet_addr, 0, sizeof(SDMA_PKT_ATOMIC));
packet_addr->HEADER_UNION.op = SDMA_OP_ATOMIC;
packet_addr->HEADER_UNION.operation = SDMA_ATOMIC_ADD64;
packet_addr->ADDR_LO_UNION.addr_31_0 = ptrlow32(addr);
packet_addr->ADDR_HI_UNION.addr_63_32 = ptrhigh32(addr);
packet_addr->SRC_DATA_LO_UNION.src_data_31_0 = 0xffffffff;
packet_addr->SRC_DATA_HI_UNION.src_data_63_32 = 0xffffffff;
}
template <typename RingIndexTy, bool HwIndexMonotonic, int SizeToCountOffset>
void BlitSdma<RingIndexTy, HwIndexMonotonic, SizeToCountOffset>::BuildGetGlobalTimestampCommand(
char* cmd_addr, void* write_address) {
SDMA_PKT_TIMESTAMP* packet_addr =
reinterpret_cast<SDMA_PKT_TIMESTAMP*>(cmd_addr);
memset(packet_addr, 0, sizeof(SDMA_PKT_TIMESTAMP));
packet_addr->HEADER_UNION.op = SDMA_OP_TIMESTAMP;
packet_addr->HEADER_UNION.sub_op = SDMA_SUBOP_TIMESTAMP_GET_GLOBAL;
packet_addr->ADDR_LO_UNION.addr_31_0 = ptrlow32(write_address);
packet_addr->ADDR_HI_UNION.addr_63_32 = ptrhigh32(write_address);
}
template <typename RingIndexTy, bool HwIndexMonotonic, int SizeToCountOffset>
void BlitSdma<RingIndexTy, HwIndexMonotonic, SizeToCountOffset>::BuildTrapCommand(char* cmd_addr) {
SDMA_PKT_TRAP* packet_addr =
reinterpret_cast<SDMA_PKT_TRAP*>(cmd_addr);
memset(packet_addr, 0, sizeof(SDMA_PKT_TRAP));
packet_addr->HEADER_UNION.op = SDMA_OP_TRAP;
}
template class BlitSdma<uint32_t, false, 0>;
template class BlitSdma<uint64_t, true, -1>;
} // namespace amd
| 32.067383 | 99 | 0.713494 | [
"object",
"vector"
] |
7db92352df1247b2e6b5ef15dcc885f69b583013 | 15,009 | cpp | C++ | sourceCode/application/logic/mathComputation/linearRegression.cpp | lp-rep/stackprof-1 | 62d9cb96ad7dcdaa26b6383559f542cadc1c7af2 | [
"CECILL-B"
] | 2 | 2022-02-27T20:08:04.000Z | 2022-03-03T13:45:40.000Z | sourceCode/application/logic/mathComputation/linearRegression.cpp | lp-rep/stackprof-1 | 62d9cb96ad7dcdaa26b6383559f542cadc1c7af2 | [
"CECILL-B"
] | 1 | 2021-06-07T17:09:04.000Z | 2021-06-11T11:48:23.000Z | sourceCode/application/logic/mathComputation/linearRegression.cpp | lp-rep/stackprof-1 | 62d9cb96ad7dcdaa26b6383559f542cadc1c7af2 | [
"CECILL-B"
] | 1 | 2021-06-03T21:06:55.000Z | 2021-06-03T21:06:55.000Z | #include <QDebug>
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_fit.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_statistics_double.h>
#include <string.h>
#include <stdio.h>
#include <iostream>
using namespace std;
#include "linearRegression.h"
#include "../toolbox/toolbox_math.h"
#include "../model/core/exportResult.h"
#include "../toolbox/toolbox_conversion.h"
S_MathComp_GSLComputedLinearRegressionParameters::S_MathComp_GSLComputedLinearRegressionParameters() {
clear();
}
void S_MathComp_GSLComputedLinearRegressionParameters::clear() {
_bComputed = false;
_c0_b_intercept = .0;
_c1_a_slope = .0;
_cov00 = .0;
_cov01 = .0;
_cov11 = .0;
_sumsq = .0;
}
S_MathComp_LinearRegression_modelParametersErrors::S_MathComp_LinearRegression_modelParametersErrors() {
clear();
}
void S_MathComp_LinearRegression_modelParametersErrors::clear() {
_b_stdErrorOfTheRegression_computed = false;
_b_stdErrorsOfSlopeAndIntercept_computed = false;
_stdErrorOfTheRegression = .0;
_stdErrorOfTheSlope = .0;
_stdErrorOfIntercept = .0;
}
S_MathComp_LinearRegressionParameters::S_MathComp_LinearRegressionParameters() {
clear();
}
void S_MathComp_LinearRegression_modelParametersErrors::showContent() const {
qDebug() << __FUNCTION__ << "(S_MathComp_LinearRegressionParameters)";
qDebug() << __FUNCTION__ << " _b_stdErrorOfTheRegression_computed : " << _b_stdErrorOfTheRegression_computed;
qDebug() << __FUNCTION__ << " _b_stdErrorsOfSlopeAndIntercept_computed : " << _b_stdErrorsOfSlopeAndIntercept_computed;
qDebug() << __FUNCTION__ << " _stdErrorOfTheRegression : " << _stdErrorOfTheRegression;
qDebug() << __FUNCTION__ << " _stdErrorOfTheSlope : " << _stdErrorOfTheSlope;
qDebug() << __FUNCTION__ << " _stdErrorOfIntercept : " << _stdErrorOfIntercept;
}
void S_MathComp_GSLComputedLinearRegressionParameters::showContent() const {
qDebug() << __FUNCTION__ << "(S_MathComp_GSLComputedLinearRegressionParameters)";
qDebug() << __FUNCTION__ << " _bComputed : " << _bComputed;
qDebug() << __FUNCTION__ << " _c0_b_intercept: " << _c0_b_intercept;
qDebug() << __FUNCTION__ << " _c1_a_slope: " << _c1_a_slope;
qDebug() << __FUNCTION__ << " _cov00: " << _cov00;
qDebug() << __FUNCTION__ << " _cov01: " << _cov01;
qDebug() << __FUNCTION__ << " _cov11: " << _cov11;
qDebug() << __FUNCTION__ << " _sumsq: " << _sumsq;
}
void S_MathComp_LinearRegressionParameters::clear() {
_GSLCompLinRegParameters.clear();
_modelParametersErrors.clear();
}
void S_MathComp_LinearRegressionParameters::showContent() const {
_GSLCompLinRegParameters.showContent();
_modelParametersErrors.showContent();
}
bool S_MathComp_LinearRegressionParameters::linearRegrModel_toQJsonObject(QJsonObject& qjsonObj) const {
if (!_GSLCompLinRegParameters._bComputed) {
qjsonObj.insert("bComputed", false);
qDebug() << __FUNCTION__ << " _GSLCompLinRegParameters._bComputed: " << _GSLCompLinRegParameters._bComputed;
return(false);
}
qjsonObj.insert("bComputed", true);
//y = a * x + b
qjsonObj.insert("slope" , _GSLCompLinRegParameters._c1_a_slope); //@#LP add fixedprecision
qjsonObj.insert("intercept", _GSLCompLinRegParameters._c0_b_intercept); //@#LP add fixedprecision
qjsonObj.insert("sumsq" , _GSLCompLinRegParameters._sumsq); //@#LP add fixedprecision
if (_modelParametersErrors._b_stdErrorsOfSlopeAndIntercept_computed) {
qjsonObj.insert("stdErrorOfSlope" , _modelParametersErrors._stdErrorOfTheSlope); //@#LP add fixedprecision
qjsonObj.insert("stdErrorOfIntercept", _modelParametersErrors._stdErrorOfIntercept); //@#LP add fixedprecision
} else {
qjsonObj.insert("stdErrorOfSlope" , "notComputed");
qjsonObj.insert("stdErrorOfIntercept", "notComputed");
}
if (_modelParametersErrors._b_stdErrorOfTheRegression_computed) {
qjsonObj.insert("stdErrorOfTheRegression", _modelParametersErrors._stdErrorOfTheRegression); //@#LP add fixedprecision
} else {
qjsonObj.insert("stdErrorOfTheRegression", "notComputed");
}
return(true);
}
bool S_MathComp_LinearRegressionParameters::linearRegrModel_toASciiStringlist(
bool bSetLinearRegressionData_asEmpty,
QStringList& qstrList_sideOfLinearRegressionModel) const {
if (bSetLinearRegressionData_asEmpty) {
qstrList_sideOfLinearRegressionModel.push_back("");//_GSLCompLinRegParameters._bComputed as empty
for(int i=0; i < 6; i++) {
qstrList_sideOfLinearRegressionModel.push_back(""); //empty fields from leftSide_a_slope to leftSide_sumsq
}
return(true);
}
qstrList_sideOfLinearRegressionModel.push_back(boolToAsciiBoolString(_GSLCompLinRegParameters._bComputed));
if (!_GSLCompLinRegParameters._bComputed) {
for(int i=0; i < 6; i++) {
qstrList_sideOfLinearRegressionModel.push_back(""); //empty fields from leftSide_a_slope to leftSide_sumsq
}
return(true);
}
//y = a * x + b
qstrList_sideOfLinearRegressionModel.push_back(doubleToQStringPrecision_f_amountOfDecimal(_GSLCompLinRegParameters._c1_a_slope, 14));
qstrList_sideOfLinearRegressionModel.push_back(doubleToQStringPrecision_f_amountOfDecimal(_GSLCompLinRegParameters._c0_b_intercept, 14));
if (_modelParametersErrors._b_stdErrorsOfSlopeAndIntercept_computed) {
qstrList_sideOfLinearRegressionModel.push_back(doubleToQStringPrecision_f_amountOfDecimal(_modelParametersErrors._stdErrorOfTheSlope, 14));
qstrList_sideOfLinearRegressionModel.push_back(doubleToQStringPrecision_f_amountOfDecimal(_modelParametersErrors._stdErrorOfIntercept, 14));
} else {
qstrList_sideOfLinearRegressionModel.push_back("");
qstrList_sideOfLinearRegressionModel.push_back("");
}
if (_modelParametersErrors._b_stdErrorOfTheRegression_computed) {
qstrList_sideOfLinearRegressionModel.push_back(doubleToQStringPrecision_f_amountOfDecimal(_modelParametersErrors._stdErrorOfTheRegression, 14));
} else {
qstrList_sideOfLinearRegressionModel.push_back("");
}
qstrList_sideOfLinearRegressionModel.push_back(doubleToQStringPrecision_f_amountOfDecimal(_GSLCompLinRegParameters._sumsq, 14));
return(true);
}
bool computeLinearRegressionParametersFor(const vector<double>& vectX,
const vector<double>& vectY,
S_MathComp_LinearRegressionParameters &linearRegressionParameters) {
unsigned long int vectXsize = vectX.size();
unsigned long int vectYsize = vectY.size();
linearRegressionParameters.clear();
if (vectXsize != vectYsize) {
qDebug() << __FUNCTION__ << "error: if (vectXsize != vectYsize) {";
return(false);
}
if (vectXsize < 2) {
qDebug() << __FUNCTION__ << "warning: not enough point to compute any line equation: ( " << vectXsize << ")";
return(false);
}
/*fprintf(stdout, "%s: vect:\n", __FUNCTION__);
for (unsigned long int i = 0; i < vectXsize; i++) {
fprintf(stdout, "vectX[%ld] = %f\n", i, vectX[i]);
}*/
gsl_fit_linear (vectX.data(), 1,
vectY.data(), 1,
vectX.size(),
&linearRegressionParameters._GSLCompLinRegParameters._c0_b_intercept,
&linearRegressionParameters._GSLCompLinRegParameters._c1_a_slope,
&linearRegressionParameters._GSLCompLinRegParameters._cov00,
&linearRegressionParameters._GSLCompLinRegParameters._cov01,
&linearRegressionParameters._GSLCompLinRegParameters._cov11,
&linearRegressionParameters._GSLCompLinRegParameters._sumsq);
linearRegressionParameters._GSLCompLinRegParameters._bComputed = true;
qDebug() << __FUNCTION__ << "y = a*x + b <=>" <<
linearRegressionParameters._GSLCompLinRegParameters._c1_a_slope << " * x + " <<
linearRegressionParameters._GSLCompLinRegParameters._c0_b_intercept;
//https://people.duke.edu/~rnau/mathreg.htm :
//'The standard error of the model (denoted again by s) is usually referred to as the standard error of the regression
//(or sometimes the "standard error of the estimate") in this context, and it is equal to the square root of
//{the sum of squared errors divided by n-2}, or equivalently, the standard deviation of the errors multiplied by
//the square root of (n-1)/(n-2), where the latter factor is a number slightly larger than 1:'
if (vectXsize < 3) {
qDebug() << __FUNCTION__ << "warning: Size of data avectors to small to 'compute' errors of the regression";
linearRegressionParameters._modelParametersErrors._b_stdErrorOfTheRegression_computed = false;
linearRegressionParameters._modelParametersErrors._b_stdErrorsOfSlopeAndIntercept_computed = false;
linearRegressionParameters._modelParametersErrors._stdErrorOfTheRegression = .0;
linearRegressionParameters._modelParametersErrors._stdErrorOfTheSlope = .0;
linearRegressionParameters._modelParametersErrors._stdErrorOfIntercept = .0;
return(true);
}
//qDebug() << __FUNCTION__ << "_ fprintf formated .14f:";
double sumsq = linearRegressionParameters._GSLCompLinRegParameters._sumsq;
double stdErrorOfTheRegression = sqrt( (1.0/(vectX.size()-2)) * sumsq);
linearRegressionParameters._modelParametersErrors._stdErrorOfTheRegression = stdErrorOfTheRegression;
linearRegressionParameters._modelParametersErrors._b_stdErrorOfTheRegression_computed = true;
//fprintf(stdout, " stdErrorOfTheRegression:%.14f\n", linearRegressionParameters._modelParametersErrors._stdErrorOfTheRegression);
//'Each of the two model parameters, the slope and intercept, has its own standard error, which is the
//estimated standard deviation of the error in estimating it. (In general, the term "standard error"
//means "standard deviation of the error" in whatever is being estimated.)'
double xMean = gsl_stats_mean (vectX.data(), 1, vectX.size());
double xVariance = gsl_stats_variance(vectX.data(), 1, vectX.size());
//fprintf(stdout, " xMean = %.14f\n", xMean);
//fprintf(stdout, " xVariance = %.14f\n", xVariance);
if (valueIsCloseToZero_deltaLowerThan1ExpMinus14(xVariance)) {
qDebug() << __FUNCTION__ << "warning: xVariance is tool small!";
linearRegressionParameters._modelParametersErrors._b_stdErrorsOfSlopeAndIntercept_computed = false;
linearRegressionParameters._modelParametersErrors._stdErrorOfTheSlope = .0;
linearRegressionParameters._modelParametersErrors._stdErrorOfIntercept = .0;
} else { //if (xVariance > 0.00000000000001) { //@LP avoid divide by zero or over range value
double stdErrorOfIntercept = (stdErrorOfTheRegression / sqrt(vectX.size())) * sqrt ( 1 + ( (xMean*xMean) / xVariance ));
double xStdDev = sqrt(xVariance);
double stdErrorOfTheSlope = (stdErrorOfTheRegression / sqrt(vectX.size())) * (1.0/xStdDev);
//fprintf(stdout, " stdErrorOfTheRegression = %.14f\n", stdErrorOfTheRegression);
//fprintf(stdout, " stdErrorOfTheSlope (a) = %.14f\n", stdErrorOfTheSlope);
//fprintf(stdout, " stdErrorOfIntercept (b) = %.14f\n", stdErrorOfIntercept);
linearRegressionParameters._modelParametersErrors._b_stdErrorsOfSlopeAndIntercept_computed = true;
linearRegressionParameters._modelParametersErrors._stdErrorOfTheSlope = stdErrorOfTheSlope;
linearRegressionParameters._modelParametersErrors._stdErrorOfIntercept = stdErrorOfIntercept;
}
return(true);
}
//use all GSL math parameters
bool computeYForGivenX_usingComputedLinearRegressionParameters_GSLMethod(
const S_MathComp_GSLComputedLinearRegressionParameters &GSLComputedLinearRegressionParameters,
double x, double& computedY) {
if (!GSLComputedLinearRegressionParameters._bComputed) {
qDebug() << __FUNCTION__ << "if (!GSLComputedLinearRegressionParameters._bComputed) {";
return(false);
}
/*
//https://www.gnu.org/software/gsl/doc/html/lls.html?highlight=gsl_fit_linear_est#c.gsl_fit_linear_est
//'This function uses the best-fit linear regression coefficients c0, c1 and
//their covariance cov00, cov01, cov11 to compute the fitted function y and
//its standard deviation y_err for the model Y = c_0 + c_1 X at the point x.'
int gsl_fit_linear_est(double x, double c0, double c1, double cov00, double cov01, double cov11, double * y, double * y_err)
@LP: looking at the source code of this method, it always returns GSL_SUCCESS
*/
double yErr = 0.0;
gsl_fit_linear_est(x,
GSLComputedLinearRegressionParameters._c0_b_intercept,
GSLComputedLinearRegressionParameters._c1_a_slope,
GSLComputedLinearRegressionParameters._cov00,
GSLComputedLinearRegressionParameters._cov01,
GSLComputedLinearRegressionParameters._cov11,
&computedY,
&yErr);
//fprintf(stdout, "%s: yComputed for x= %f : %f\n", __FUNCTION__, x, computedY );
//fprintf(stdout, "%s: yErr = %f\n", __FUNCTION__, yErr);
return(true);
}
//use simpy y = a*x+b
//y = (slope * x) + intercept
bool computeYForGivenX_usingComputedLinearRegressionParameters_slopeInterceptMethod(
const S_MathComp_GSLComputedLinearRegressionParameters &GSLComputedLinearRegressionParameters,
double x, double& computedY) {
if (!GSLComputedLinearRegressionParameters._bComputed) {
qDebug() << __FUNCTION__ << "if (!GSLComputedLinearRegressionParameters._bComputed) {";
return(false);
}
computedY = (GSLComputedLinearRegressionParameters._c1_a_slope * x) + GSLComputedLinearRegressionParameters._c0_b_intercept;
return(true);
}
bool computeXForGivenY_usingComputedLinearRegressionParameters_slopeInterceptMethod(
const S_MathComp_GSLComputedLinearRegressionParameters &GSLComputedLinearRegressionParameters,
double y, double& computedX) {
if (!GSLComputedLinearRegressionParameters._bComputed) {
qDebug() << __FUNCTION__ << "if (!GSLComputedLinearRegressionParameters._bComputed) {";
return(false);
}
if (valueIsCloseToZero_deltaLowerThan1ExpMinus14(GSLComputedLinearRegressionParameters._c1_a_slope)) {
qDebug() << __FUNCTION__ << "warning: _c1_a_slope is very close to zero; the line is considered horizontal";
computedX = GSLComputedLinearRegressionParameters._c0_b_intercept;
return(true);
}
computedX = (y - GSLComputedLinearRegressionParameters._c0_b_intercept) / GSLComputedLinearRegressionParameters._c1_a_slope;
return(true);
}
| 42.882857 | 152 | 0.723299 | [
"vector",
"model"
] |
7dc01e95b4b456788f32daa68dab3ee663b4ed55 | 1,635 | cpp | C++ | aws-cpp-sdk-resiliencehub/source/model/ListUnsupportedAppVersionResourcesResult.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-resiliencehub/source/model/ListUnsupportedAppVersionResourcesResult.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-resiliencehub/source/model/ListUnsupportedAppVersionResourcesResult.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-12-30T04:25:33.000Z | 2021-12-30T04:25:33.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/resiliencehub/model/ListUnsupportedAppVersionResourcesResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::ResilienceHub::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
ListUnsupportedAppVersionResourcesResult::ListUnsupportedAppVersionResourcesResult()
{
}
ListUnsupportedAppVersionResourcesResult::ListUnsupportedAppVersionResourcesResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
ListUnsupportedAppVersionResourcesResult& ListUnsupportedAppVersionResourcesResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("nextToken"))
{
m_nextToken = jsonValue.GetString("nextToken");
}
if(jsonValue.ValueExists("resolutionId"))
{
m_resolutionId = jsonValue.GetString("resolutionId");
}
if(jsonValue.ValueExists("unsupportedResources"))
{
Array<JsonView> unsupportedResourcesJsonList = jsonValue.GetArray("unsupportedResources");
for(unsigned unsupportedResourcesIndex = 0; unsupportedResourcesIndex < unsupportedResourcesJsonList.GetLength(); ++unsupportedResourcesIndex)
{
m_unsupportedResources.push_back(unsupportedResourcesJsonList[unsupportedResourcesIndex].AsObject());
}
}
return *this;
}
| 29.196429 | 148 | 0.786544 | [
"model"
] |
7dc03998cde6f0dac543f3e4dbf365c0975e6f87 | 14,954 | cc | C++ | newtesting.cc | Sarvesh-Sathish/isef2020 | 95a2d51b0592906da2e57413f9e7f20eabaa2b3e | [
"MIT"
] | null | null | null | newtesting.cc | Sarvesh-Sathish/isef2020 | 95a2d51b0592906da2e57413f9e7f20eabaa2b3e | [
"MIT"
] | null | null | null | newtesting.cc | Sarvesh-Sathish/isef2020 | 95a2d51b0592906da2e57413f9e7f20eabaa2b3e | [
"MIT"
] | null | null | null | #include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include "ns3/core-module.h"
#include "ns3/simulator-module.h"
#include "ns3/node-module.h"
#include "ns3/helper-module.h"
#include "ns3/wifi-module.h"
#include "ns3/mobility-module.h"
#include "ns3/mp-internet-stack-helper.h"
#include "ns3/mp-tcp-packet-sink.h"
#include "ns3/mp-tcp-l4-protocol.h"
#include "ns3/mp-tcp-socket-impl.h"
#include "ns3/point-to-point-channel.h"
#include "ns3/point-to-point-net-device.h"
/* Multipath Network Topology
lan 10.1.1.0
___________
/ \
n1 n2
\___________/
lan 10.1.2.0
*/
using namespace ns3;
NS_LOG_COMPONENT_DEFINE("FirstMultipathToplogy");
// The number of bytes to send in this simulation.
static const uint32_t totalTxBytes = 10000000;
static const uint32_t sendBufSize = 14000; //2000000;
static const uint32_t recvBufSize = 2000; //2000000;
static uint32_t currentTxBytes = 0;
static const double simDuration = 360000000.0;
Ptr<Node> client;
Ptr<Node> server;
// Perform series of 1040 byte writes (this is a multiple of 26 since
// we want to detect data splicing in the output stream)
static const uint32_t writeSize = sendBufSize;
uint8_t data[totalTxBytes];
Ptr<MpTcpSocketImpl> lSocket = 0;
/*
PointToPointHelper fstP2Plink;
PointToPointHelper sndP2Plink;
PointToPointHelper trdP2Plink;
*/
//changes
void StartFlow (Ptr<MpTcpSocketImpl>, Ipv4Address, uint16_t);
void WriteUntilBufferFull (Ptr<Socket>, unsigned int);
void connectionSucceeded(Ptr<Socket>);
void connectionFailed(Ptr<Socket>);
void HandlePeerClose (Ptr<Socket>);
void HandlePeerError (Ptr<Socket>);
void CloseConnection (Ptr<Socket>);
int connect(Address &addr);
void variateDelay(PointToPointHelper P2Plink);
static void
CwndTracer (double oldval, double newval)
{
NS_LOG_INFO ("Moving cwnd from " << oldval << " to " << newval);
}
int main(int argc, char *argv[])
{
bool verbose;
CongestionCtrl_t cc = Fully_Coupled;
PacketReorder_t pr = D_SACK;
int arg1 = -1, arg2 = -1, arg3 = -1, arg4 = -1;
int sf = 2; // number of subflows
CommandLine cmd;
cmd.AddValue("verbose", "Tell application to log if true", verbose);
cmd.AddValue("level", "Tell application which log level to use:\n \t - 0 = ERROR \n \t - 1 = WARN \n \t - 2 = DEBUG \n \t - 3 = INFO \n \t - 4 = FUNCTION \n \t - 5 = LOGIC \n \t - 6 = ALL", arg3);
cmd.AddValue("cc", "Tell application which congestion control algorithm to use:\n \t - 0 = Uncoupled_TCPs \n \t - 1 = Linked_Increases \n \t - 2 = RTT_Compensator \n \t - 3 = Fully_Coupled", arg1);
cmd.AddValue("pr", "Tell application which packet reordering algorithm to use:\n \t - 0 = NoPR_Algo \n \t - 1 = Eifel \n \t - 2 = TCP_DOOR \n \t - 3 = D_SACK \n \t - 4 = F_RTO", arg2);
cmd.AddValue("sf", "Tell application the number of subflows to be established between endpoints", arg4);
cmd.Parse (argc, argv);
cc = (arg1==-1 ? Fully_Coupled:(CongestionCtrl_t) arg1);
pr = (arg2==-1 ? D_SACK:(PacketReorder_t) arg2);
sf = (arg4 = -1 ? 2: arg4);
LogComponentEnable("FirstMultipathToplogy", LOG_LEVEL_ALL);
//LogComponentEnable("TcpSocketFactory", LOG_LEVEL_ALL);
//LogComponentEnable("ApplicationContainer", LOG_LEVEL_INFO);
//LogComponentEnable("MpTcpL4Protocol", LOG_LEVEL_ALL);
//LogComponentEnable("TcpL4Protocol", LOG_LEVEL_INFO);
//LogComponentEnable("Packet", LOG_LEVEL_ALL);
//LogComponentEnable("Socket", LOG_LEVEL_ALL);
if(arg3 == 2)
LogComponentEnable("MpTcpSocketImpl", LOG_DEBUG);
else if(arg3 == 6)
LogComponentEnable("MpTcpSocketImpl", LOG_LEVEL_ALL);
else
LogComponentEnable("MpTcpSocketImpl", LOG_WARN);
//LogComponentEnable("TcpSocketImpl", LOG_LEVEL_ALL);
LogComponentEnable("MpTcpPacketSink", LOG_WARN);
LogComponentEnable("MpTcpHeader", LOG_WARN);
//LogComponentEnable("TcpHeader", LOG_LEVEL_ALL);
//LogComponentEnable("Ipv4L3Protocol", LOG_LEVEL_ALL);
//LogComponentEnable("MpTcpTypeDefs", LOG_ERROR);
//LogComponentEnable("RttEstimator", LOG_LEVEL_ALL);
// Creation of the hosts
NodeContainer nodes;
nodes.Create(2);
client = nodes.Get(0);
server = nodes.Get(1);
MpInternetStackHelper stack;
stack.Install(nodes);
vector<Ipv4InterfaceContainer> ipv4Ints;
for(int i=0; i < sf; i++)
{
// Creation of the point to point link between hots
PointToPointHelper p2plink;
p2plink.SetDeviceAttribute ("DataRate", StringValue("5Mbps"));
p2plink.SetChannelAttribute("Delay", StringValue("100ms"));
NetDeviceContainer netDevices;
netDevices = p2plink.Install(nodes);
// Attribution of the IP addresses
std::stringstream netAddr;
netAddr << "10.1." << (i+1) << ".0";
string str = netAddr.str();
Ipv4AddressHelper ipv4addr;
ipv4addr.SetBase(str.c_str(), "255.255.255.0");
Ipv4InterfaceContainer interface = ipv4addr.Assign(netDevices);
ipv4Ints.insert(ipv4Ints.end(), interface);
}
/*
fstP2Plink.SetDeviceAttribute ("DataRate", StringValue("5Mbps"));
fstP2Plink.SetChannelAttribute("Delay", StringValue("100ms"));
NetDeviceContainer fstDevices;
fstDevices = fstP2Plink.Install(nodes);
*/
// Installation of the IPv4 stack on each host
//InternetStackHelper stack;
//stack.Install(nodes);
//Ipv4GlobalRoutingHelper::PopulateRoutingTables();
// Creation of the 2nd point to point link between hosts
/*
sndP2Plink.SetDeviceAttribute ("DataRate", StringValue("5Mbps"));
sndP2Plink.SetChannelAttribute("Delay", StringValue("100ms"));
// Data rate and channel's delay are let in default values
NetDeviceContainer sndDevices;
sndDevices = sndP2Plink.Install(nodes);
*/
// Creation of the 3rd point to point link between hots
/*
trdP2Plink.SetDeviceAttribute ("DataRate", StringValue("3Mbps"));
trdP2Plink.SetChannelAttribute("Delay", StringValue("10ms"));
NetDeviceContainer trdDevices;
trdDevices = trdP2Plink.Install(nodes);
*/
// Enabling PCAP traces to be loged
PointToPointHelper::EnablePcapAll("mptcp");
/*
// Attribution of the IP addresses
Ipv4AddressHelper fstAddrs;
fstAddrs.SetBase("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer fstInt = fstAddrs.Assign(fstDevices);
Ipv4AddressHelper sndAddrs;
sndAddrs.SetBase("10.1.2.0", "255.255.255.0");
Ipv4InterfaceContainer sndInt = sndAddrs.Assign(sndDevices);
*/
/*
Ipv4AddressHelper trdAddrs;
trdAddrs.SetBase("10.1.3.0", "255.255.255.0");
Ipv4InterfaceContainer trdInt = trdAddrs.Assign(trdDevices);
*/
// Configuration of the Client/Server application
uint32_t servPort = 5000;
NS_LOG_INFO ("address " << ipv4Ints[0].GetAddress (1));
ObjectFactory m_sf;
m_sf.SetTypeId("ns3::MpTcpPacketSink");
m_sf.Set("Protocol", StringValue ("ns3::TcpSocketFactory"));
m_sf.Set("Local", AddressValue(InetSocketAddress (ipv4Ints[0].GetAddress (1), servPort)));
m_sf.Set("algopr", UintegerValue ((uint32_t) pr));
Ptr<Application> sapp = m_sf.Create<Application> ();
server->AddApplication(sapp);
/*
Ptr<MpTcpPacketSink> mptcpPktSnk = (Ptr<MpTcpPacketSink>) sapp;
Ptr<MpTcpSocketImpl> sSocket = mptcpPktSnk->getMpTcpSocket ();
sSocket->SetPacketReorderAlgo (pr);
*/
ApplicationContainer Apps;
Apps.Add(sapp);
// Apps.Add(capp);
//ApplicationContainer serverApps = sink.Install(server);
Apps.Start(Seconds(0.0));
Apps.Stop(Seconds(simDuration));
//Ptr<Socket> localSocket = Socket::CreateSocket(client, TcpSocketFactory::GetTypeId());
lSocket = new MpTcpSocketImpl (client);
/*
localSocket->SetNode(client);
Ptr<MpTcpL4Protocol> mptcp = client->GetObject<MpTcpL4Protocol> ();
localSocket->SetMpTcp(mptcp);
*/
//lSocket->SetCongestionCtrlAlgo (Linked_Increases);
//lSocket->SetCongestionCtrlAlgo (RTT_Compensator);
lSocket->SetCongestionCtrlAlgo (cc);
//lSocket->SetCongestionCtrlAlgo (Uncoupled_TCPs);
lSocket->SetDataDistribAlgo (Round_Robin);
//lSocket->SetPacketReorderAlgo (Eifel);
lSocket->SetPacketReorderAlgo (pr);
lSocket->Bind ();
// Trace changes to the congestion window
Config::ConnectWithoutContext ("/NodeList/0/$ns3::MpTcpSocketImpl/subflows/0/CongestionWindow", MakeCallback (&CwndTracer));
// ...and schedule the sending "Application"; This is similar to what an
// ns3::Application subclass would do internally.
Simulator::ScheduleNow (&StartFlow, lSocket, ipv4Ints[0].GetAddress (1), servPort);
// Finally, set up the simulator to run. The 1000 second hard limit is a
// failsafe in case some change above causes the simulation to never end
Simulator::Stop (Seconds(simDuration + 1000.0));
Simulator::Run ();
Simulator::Destroy();
NS_LOG_LOGIC("mpTopology:: simulation ended");
return 0;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//begin implementation of sending "Application"
void StartFlow(Ptr<MpTcpSocketImpl> localSocket, Ipv4Address servAddress, uint16_t servPort)
{
NS_LOG_LOGIC("Starting flow at time " << Simulator::Now ().GetSeconds ());
//localSocket->Connect (InetSocketAddress (servAddress, servPort));//connect
lSocket->SetMaxSubFlowNumber(5);
lSocket->SetMinSubFlowNumber(3);
lSocket->SetSourceAddress(Ipv4Address("10.1.1.1"));
lSocket->allocateSendingBuffer(sendBufSize);
lSocket->allocateRecvingBuffer(recvBufSize);
// the following buffer is uesed by the received to hold out of sequence data
lSocket->SetunOrdBufMaxSize(50);
int connectionState = lSocket->Connect( servAddress, servPort);
//NS_LOG_LOGIC("mpTopology:: connection request sent");
// tell the tcp implementation to call WriteUntilBufferFull again
// if we blocked and new tx buffer space becomes available
if(connectionState == 0)
{
lSocket->SetConnectCallback (MakeCallback (&connectionSucceeded), MakeCallback (&connectionFailed));
lSocket->SetDataSentCallback (MakeCallback (&WriteUntilBufferFull));
lSocket->SetCloseCallbacks (MakeCallback (&HandlePeerClose), MakeCallback(&HandlePeerError));
lSocket->GetSubflow(0)->StartTracing ("CongestionWindow");
}else
{
//localSocket->NotifyConnectionFailed();
NS_LOG_LOGIC("mpTopology:: connection failed");
}
//WriteUntilBufferFull (localSocket);
}
void connectionSucceeded (Ptr<Socket> localSocket)
{
//NS_LOG_FUNCTION_NOARGS();
NS_LOG_INFO("mpTopology: Connection requeste succeed");
Simulator::Schedule (Seconds (1.0), &WriteUntilBufferFull, lSocket, 0);
Simulator::Schedule (Seconds (simDuration), &CloseConnection, lSocket);
//Ptr<MpTcpSocketImpl> lSock = localSocket;
// advertise local addresses
//lSocket->InitiateSubflows();
//WriteUntilBufferFull(lSocket, 0);
}
void connectionFailed (Ptr<Socket> localSocket)
{
//NS_LOG_FUNCTION_NOARGS();
NS_LOG_INFO("mpTopology: Connection requeste failure");
lSocket->Close();
}
void HandlePeerClose (Ptr<Socket> localSocket)
{
//NS_LOG_FUNCTION_NOARGS();
NS_LOG_INFO("mpTopology: Connection closed by peer");
lSocket->Close();
}
void HandlePeerError (Ptr<Socket> localSocket)
{
//NS_LOG_FUNCTION_NOARGS();
NS_LOG_INFO("mpTopology: Connection closed by peer error");
lSocket->Close();
}
void CloseConnection (Ptr<Socket> localSocket)
{
lSocket->Close();
NS_LOG_LOGIC("mpTopology:: currentTxBytes = " << currentTxBytes);
NS_LOG_LOGIC("mpTopology:: totalTxBytes = " << totalTxBytes);
NS_LOG_LOGIC("mpTopology:: connection to remote host has been closed");
}
/*
void variateDelay(PointToPointHelper P2Plink)
{
//NS_LOG_INFO ("variateDelay -> old delay == " << P2Plink.GetDelay());
NS_LOG_INFO ("variateDelay");
std::stringstream strDelay;
int intDelay = rand() % 100;
strDelay << intDelay << "ms";
P2Plink.SetChannelAttribute("Delay", StringValue(strDelay.str()));
NS_LOG_INFO ("New delay == " << strDelay.str());
}
*/
void variateDelay (Ptr<Node> node)
{
//NS_LOG_INFO ("variateDelay");
Ptr<Ipv4L3Protocol> ipv4 = node->GetObject<Ipv4L3Protocol> ();
TimeValue delay;
for(uint32_t i = 0; i < ipv4->GetNInterfaces(); i++)
{
//Ptr<NetDevice> device = m_node->GetDevice(i);
Ptr<Ipv4Interface> interface = ipv4->GetInterface(i);
Ipv4InterfaceAddress interfaceAddr = interface->GetAddress (0);
// do not consider loopback addresses
if(interfaceAddr.GetLocal() == Ipv4Address::GetLoopback())
{
// loopback interface has identifier equal to zero
continue;
}
Ptr<NetDevice> netDev = interface->GetDevice();
Ptr<Channel> P2Plink = netDev->GetChannel();
P2Plink->GetAttribute(string("Delay"), delay);
double oldDelay = delay.Get().GetSeconds();
//NS_LOG_INFO ("variateDelay -> old delay == " << oldDelay);
std::stringstream strDelay;
double newDelay = (rand() % 100) * 0.001;
double err = newDelay - oldDelay;
strDelay << (0.95 * oldDelay + 0.05 * err) << "s";
P2Plink->SetAttribute(string("Delay"), StringValue(strDelay.str()));
P2Plink->GetAttribute(string("Delay"), delay);
//NS_LOG_INFO ("variateDelay -> new delay == " << delay.Get().GetSeconds());
}
}
void WriteUntilBufferFull (Ptr<Socket> localSocket, unsigned int txSpace)
{
//NS_LOG_FUNCTION_NOARGS();
//uint32_t txSpace = localSocket->GetTxAvailable ();
while (currentTxBytes < totalTxBytes && lSocket->GetTxAvailable () > 0)
{
uint32_t left = totalTxBytes - currentTxBytes;
uint32_t toWrite = std::min(writeSize, lSocket->GetTxAvailable ());
toWrite = std::min( toWrite , left );
//NS_LOG_LOGIC("mpTopology:: data already sent ("<< currentTxBytes <<") data buffered ("<< toWrite << ") to be sent subsequentlly");
int amountBuffered = lSocket->FillBuffer (&data[currentTxBytes], toWrite);
currentTxBytes += amountBuffered;
variateDelay(client);
/*
variateDelay(sndP2Plink);
variateDelay(trdP2Plink);
*/
lSocket->SendBufferedData();
}
/*
if ( schedule == true )
{
// we will be called again when new tx space becomes available.
NS_LOG_FUNCTION ("we have to wait a while before trying to send new data");
//Simulator::Schedule (Seconds (2.0), &MpTcpSocketImpl::SendBufferedData, lSocket);
Timer timer = Timer ( Timer::CANCEL_ON_DESTROY );
timer.SetFunction ( &WriteUntilBufferFull );
timer.Schedule ( Seconds (2.01) );
}
*/
//lSocket->SendBufferedData ();
//NS_LOG_LOGIC("mpTopology::WriteUntilBufferFull leaving !");
}
| 36.473171 | 201 | 0.682225 | [
"vector"
] |
7dcaf7da0119fa9fb6cd7b8ff873534002bfb0f7 | 1,758 | cpp | C++ | tool/SVF/tools/WPA/wpa.cpp | SZU-SE/PERIOD | 7636dc7cd8c97ea2fb7c13d6d068efc3872b9d03 | [
"MIT"
] | 16 | 2022-01-14T12:05:49.000Z | 2022-03-10T07:57:26.000Z | tool/SVF/tools/WPA/wpa.cpp | SZU-SE/PERIOD | 7636dc7cd8c97ea2fb7c13d6d068efc3872b9d03 | [
"MIT"
] | 1 | 2022-03-08T13:19:07.000Z | 2022-03-09T06:39:43.000Z | tool/SVF/tools/WPA/wpa.cpp | SZU-SE/PERIOD | 7636dc7cd8c97ea2fb7c13d6d068efc3872b9d03 | [
"MIT"
] | 2 | 2022-01-16T16:55:40.000Z | 2022-03-07T10:20:55.000Z | //===- wpa.cpp -- Whole program analysis -------------------------------------//
//
// SVF: Static Value-Flow Analysis
//
// Copyright (C) <2013-2017> <Yulei Sui>
//
// 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 3 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/>.
//
//===-----------------------------------------------------------------------===//
/*
// Whole Program Pointer Analysis
//
// Author: Yulei Sui,
*/
#include "SVF-FE/LLVMUtil.h"
#include "WPA/WPAPass.h"
using namespace llvm;
using namespace std;
using namespace SVF;
static llvm::cl::opt<std::string> InputFilename(cl::Positional,
llvm::cl::desc("<input bitcode>"), llvm::cl::init("-"));
int main(int argc, char ** argv)
{
int arg_num = 0;
char **arg_value = new char*[argc];
std::vector<std::string> moduleNameVec;
SVFUtil::processArguments(argc, argv, arg_num, arg_value, moduleNameVec);
cl::ParseCommandLineOptions(arg_num, arg_value,
"Whole Program Points-to Analysis\n");
SVFModule* svfModule = LLVMModuleSet::getLLVMModuleSet()->buildSVFModule(moduleNameVec);
WPAPass *wpa = new WPAPass();
wpa->runOnModule(svfModule);
return 0;
}
| 30.842105 | 92 | 0.636519 | [
"vector"
] |
7dcf1440188aae688a1ec01886f3b499a0fa8b28 | 1,683 | cpp | C++ | prayground/shape/plane.cpp | sketchbooks99/PRayGround | 07d1779f2e36ad9ed5fd6df457cdc515b9017300 | [
"MIT"
] | 23 | 2021-08-25T10:40:40.000Z | 2022-03-28T13:02:05.000Z | prayground/shape/plane.cpp | sketchbooks99/PRayGround | 07d1779f2e36ad9ed5fd6df457cdc515b9017300 | [
"MIT"
] | 2 | 2021-12-04T12:50:44.000Z | 2021-12-14T14:55:00.000Z | prayground/shape/plane.cpp | sketchbooks99/PRayGround | 07d1779f2e36ad9ed5fd6df457cdc515b9017300 | [
"MIT"
] | 1 | 2021-04-15T13:13:17.000Z | 2021-04-15T13:13:17.000Z | #include "plane.h"
#include <prayground/core/util.h>
namespace prayground {
// ------------------------------------------------------------------
Plane::Plane()
: m_min{-1.0f, -1.0f}, m_max{1.0f, 1.0f}
{
}
Plane::Plane(const float2& min, const float2& max)
: m_min{ min }, m_max{ max }
{
}
// ------------------------------------------------------------------
constexpr ShapeType Plane::type()
{
return ShapeType::Custom;
}
// ------------------------------------------------------------------
void Plane::copyToDevice()
{
PlaneData data = this->deviceData();
if (!d_data)
CUDA_CHECK( cudaMalloc( &d_data, sizeof(PlaneData) ) );
CUDA_CHECK( cudaMemcpy(
d_data,
&data, sizeof(PlaneData),
cudaMemcpyHostToDevice
));
}
// ------------------------------------------------------------------
OptixBuildInput Plane::createBuildInput()
{
if (d_aabb_buffer) cuda_free(d_aabb_buffer);
return createSingleCustomBuildInput(d_aabb_buffer, this->bound(), m_sbt_index);
}
// ------------------------------------------------------------------
void Plane::free()
{
Shape::free();
cuda_free(d_aabb_buffer);
}
// ------------------------------------------------------------------
AABB Plane::bound() const
{
AABB box{make_float3(m_min.x, -0.01f, m_min.y), make_float3(m_max.x, 0.01f, m_max.y)};
return box;
}
// ------------------------------------------------------------------
Plane::DataType Plane::deviceData() const
{
PlaneData data =
{
.min = m_min,
.max = m_max
};
return data;
}
} // ::prayground | 23.704225 | 91 | 0.42246 | [
"shape"
] |
7dd15aeb462ffda974207b83b9c063ea3c0a67b8 | 6,393 | cpp | C++ | src/lava_lib/reader_bgeo/bgeo/parser/PrimitiveGroup.cpp | cinepost/Falcor | f70bd1d97c064d6f91a017d4409aa2037fd6903a | [
"BSD-3-Clause"
] | 7 | 2018-09-25T23:45:52.000Z | 2021-07-07T04:08:01.000Z | src/lava_lib/reader_bgeo/bgeo/parser/PrimitiveGroup.cpp | cinepost/Falcor | f70bd1d97c064d6f91a017d4409aa2037fd6903a | [
"BSD-3-Clause"
] | 2 | 2021-03-02T10:16:06.000Z | 2021-08-13T10:10:21.000Z | src/lava_lib/reader_bgeo/bgeo/parser/PrimitiveGroup.cpp | cinepost/Lava | f70bd1d97c064d6f91a017d4409aa2037fd6903a | [
"BSD-3-Clause"
] | 3 | 2020-06-07T05:47:48.000Z | 2020-10-03T12:34:54.000Z | /*
* Copyright 2018 Laika, LLC. Authored by Peter Stuart
*
* Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
* http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
* http://opensource.org/licenses/MIT>, at your option. This file may not be
* copied, modified, or distributed except according to those terms.
*/
#include "PrimitiveGroup.h"
#include <cassert>
#include <UT/UT_JSONHandle.h>
#include "util.h"
#include "Detail.h"
namespace ika
{
namespace bgeo
{
namespace parser
{
namespace
{
class BoolArrayHandle : public UT_JSONHandleError
{
public:
BoolArrayHandle(std::vector<bool>& flags)
: m_flags(flags),
m_stack(0)
{
}
/*virtual*/ bool jsonBool(UT_JSONParser& parser, bool value)
{
m_flags.push_back(value);
return true;
}
/*virtual*/ bool jsonInt(UT_JSONParser& parser, int64 value)
{
m_flags.push_back(value);
return true;
}
/*virtual*/ bool jsonBeginArray(UT_JSONParser& parser)
{
if (m_stack > 0)
{
UT_String message;
message.sprintf("Unexpected [ at byte 0x%04lx",
parser.getStreamPosition());
throw ReadError(message);
}
m_stack++;
return true;
}
/*virtual*/ bool jsonEndArray(UT_JSONParser& parser)
{
m_stack--;
if (m_stack < 0)
{
UT_String message;
message.sprintf("Unexpected ] at byte 0x%04lx",
parser.getStreamPosition());
throw ReadError(message);
}
return true;
}
private:
std::vector<bool>& m_flags;
int m_stack;
};
class BoolRleHandle : public UT_JSONHandleError
{
public:
BoolRleHandle(RleVector& rle)
: m_rle(rle),
m_stack(0),
m_count(0),
m_countIsValid(false)
{
}
/*virtual*/ bool jsonBool(UT_JSONParser& parser, bool value)
{
if (!m_countIsValid)
{
UT_String message;
message.sprintf("Invalid RLE unknown count at byte 0x%04lx",
parser.getStreamPosition());
throw ReadError(message);
}
m_rle.push_back(std::make_pair(m_count, value));
m_countIsValid = false;
return true;
}
/*virtual*/ bool jsonInt(UT_JSONParser& parser, int64 value)
{
if (m_countIsValid)
{
m_rle.push_back(std::make_pair(m_count, value));
m_countIsValid = false;
return true;
}
m_count = value;
m_countIsValid = true;
return true;
}
/*virtual*/ bool jsonBeginArray(UT_JSONParser& parser)
{
if (m_stack > 0)
{
UT_String message;
message.sprintf("Unexpected [ at byte 0x%04lx",
parser.getStreamPosition());
throw ReadError(message);
}
m_stack++;
return true;
}
/*virtual*/ bool jsonEndArray(UT_JSONParser& parser)
{
m_stack--;
if (m_stack < 0)
{
UT_String message;
message.sprintf("Unexpected ] at byte 0x%04lx",
parser.getStreamPosition());
throw ReadError(message);
}
return true;
}
private:
RleVector& m_rle;
int m_stack;
int m_count;
bool m_countIsValid;
};
} // anonymous namespace
PrimitiveGroup::PrimitiveGroup(const Detail& detail)
: detail(detail)
{
}
void PrimitiveGroup::load(UT_JSONParser& parser)
{
parseBeginArray(parser);
{
parseBeginArray(parser);
{
parseArrayValueForKey(parser, "name", name);
if (detail.fileVersion.major == 13)
{
UT_String type;
parseArrayValueForKey(parser, "type", type);
assert(type == "primitive");
}
}
parseEndArray(parser);
parseBeginArray(parser);
{
parseArrayKey(parser, "selection");
parseBeginArray(parser);
{
if (detail.fileVersion.major == 13)
{
parseArrayKey(parser, "defaults");
BGEO_CHECK(parser.skipNextObject());
}
parseArrayKey(parser, "unordered");
parseBeginArray(parser);
{
UT_WorkBuffer buffer;
UT_String type;
BGEO_CHECK(parser.parseValue(buffer));
type = buffer.buffer();
if (type == "i8")
{
BoolArrayHandle handle(ingroup);
BGEO_CHECK(parser.parseObject(handle));
}
else
{
BoolRleHandle handle(rleGroup);
BGEO_CHECK(parser.parseObject(handle));
}
}
parseEndArray(parser);
}
parseEndArray(parser);
}
parseEndArray(parser);
}
parseEndArray(parser);
}
void PrimitiveGroup::expandGroup(std::vector<int32_t>& indices) const
{
indices.clear();
if (!ingroup.empty())
{
for (int i = 0; i < ingroup.size(); ++i)
{
if (ingroup[i])
{
indices.push_back(i);
}
}
return;
}
int index = 0;
for (auto rlePair : rleGroup)
{
if (!rlePair.second)
{
index += rlePair.first;
continue;
}
indices.reserve(indices.size() + rlePair.first);
for (int i = 0; i < rlePair.first; ++i, ++index)
{
indices.push_back(index);
}
}
}
std::ostream& operator << (std::ostream& co, const PrimitiveGroup& group)
{
co << group.name << " = ";
if (!group.ingroup.empty())
{
for (auto value : group.ingroup)
{
co << value;
}
}
if (!group.rleGroup.empty())
{
for (auto value : group.rleGroup)
{
co << value.first << "," << (value.second ? "true" : "false");
}
}
return co;
}
} // namespace parser
} // namespace bgeo
} // namespace ika
| 23.079422 | 78 | 0.511184 | [
"vector"
] |
7dd9628394f65fa878d3059b2b0f40829bbfa485 | 2,905 | cpp | C++ | lib/Player.cpp | robhardwick/fmusic | 06960cf92ef58b0ef58f2a79433d225ba0e2f634 | [
"MIT"
] | 15 | 2015-06-30T17:48:13.000Z | 2021-01-07T14:42:30.000Z | lib/Player.cpp | robhardwick/fmusic | 06960cf92ef58b0ef58f2a79433d225ba0e2f634 | [
"MIT"
] | null | null | null | lib/Player.cpp | robhardwick/fmusic | 06960cf92ef58b0ef58f2a79433d225ba0e2f634 | [
"MIT"
] | null | null | null | #include <chrono>
#include "Player.h"
#include "Song.h"
#include "Log.h"
#include "Instrument.h"
using namespace fMusic::Core;
/**
* Initialise player
*/
Player::Player(std::shared_ptr<Log> log)
: log(log),
interval(DEFAULT_INTERVAL) {}
/**
* Stop player execution
*/
Player::~Player() {
stop();
}
/**
* Currently playing
*/
bool Player::isPlaying() {
std::unique_lock<std::mutex> lock(mutex);
return playing;
}
/**
* A song / thread is playing but is paused
*/
bool Player::isPaused() {
std::unique_lock<std::mutex> lock(mutex);
return paused;
}
/**
* Add instrument
*/
void Player::addInstrument(std::shared_ptr<Instrument> instrument) {
instruments.push_back(instrument);
}
/**
* Set interval
*/
void Player::setInterval(int32_t value) {
interval = value;
}
/**
* Start playing specified song
*/
void Player::play(const std::string &str) {
// Stop execution thread, if running
stop();
// Enable playing in execution thread
paused = false;
playing = true;
// Initialise song
song = std::unique_ptr<Song>(new Song(log, str));
// Start execution thread
thread = std::thread(&Player::task, this);
}
/**
* Pause playing
*/
void Player::pause() {
std::unique_lock<std::mutex> lock(mutex);
paused = !paused;
}
/**
* Stop playing
*/
void Player::stop() {
// Check if execution thread is running
if (thread.joinable()) {
// Set playing flag to end thread
std::unique_lock<std::mutex> lock(mutex);
playing = false;
lock.unlock();
// Join thread until it returns
thread.join();
}
}
/**
* Schedule execution every X ms
*/
void Player::task() {
// MIDI message buffer
std::vector<unsigned char> message(3);
// Playing mutex lock
std::unique_lock<std::mutex> lock(mutex);
// Current time as base timeout
std::chrono::high_resolution_clock::time_point start, timeout;
start = timeout = std::chrono::high_resolution_clock::now();
do {
// Only execute if paused is false
if (!paused) {
// Get the time offset in milliseconds
auto time = std::chrono::duration_cast<std::chrono::milliseconds>(timeout - start);
// Attempt to execute song
if (song->execute(time.count(), message)) {
// Iterate over instruments, sending the message to each
for (auto instrument : instruments) {
instrument->message(message);
}
}
}
// Set next execution time
timeout += std::chrono::milliseconds(interval);
// Sleep until next execution
lock.unlock();
std::this_thread::sleep_for(timeout - std::chrono::high_resolution_clock::now());
lock.lock();
// Continue execution while playing is true
} while(playing);
}
| 20.75 | 95 | 0.604819 | [
"vector"
] |
7dde8206e49b72f53e7041ff9b77822ab9480f4d | 2,010 | cpp | C++ | Akel/src/Graphics/entity3d.cpp | NurissGames/Akel | 9580f7eb1d4a0dbe20459bd83a5e681a040c29de | [
"MIT"
] | 3 | 2021-12-01T17:59:30.000Z | 2022-01-22T20:29:08.000Z | Akel/src/Graphics/entity3d.cpp | NurissGames/Akel | 9580f7eb1d4a0dbe20459bd83a5e681a040c29de | [
"MIT"
] | null | null | null | Akel/src/Graphics/entity3d.cpp | NurissGames/Akel | 9580f7eb1d4a0dbe20459bd83a5e681a040c29de | [
"MIT"
] | 1 | 2021-12-01T17:59:32.000Z | 2021-12-01T17:59:32.000Z | // This file is a part of Akel
// Authors : @kbz_8
// Created : 05/03/2022
// Updated : 06/03/2022
#include <Graphics/entity.h>
#include <Core/core.h>
#define R_MASK 0xFF000000
#define G_MASK 0x00FF0000
#define B_MASK 0x0000FF00
#define A_MASK 0x000000FF
namespace Ak
{
Entity3D::Entity3D(Models _model, Maths::Vec3<float> _position, Maths::Vec3<float> _scale, Maths::Vec4<float> _color)
{
model = _model;
position = std::move(_position);
scale = std::move(_scale);
color = std::move(_color);
}
Entity3D::Entity3D(Models _model, Maths::Vec3<float> _position, Maths::Vec3<float> _scale, Colors _color)
{
model = _model;
position = std::move(_position);
scale = std::move(_scale);
uint32_t col_val = static_cast<uint32_t>(_color);
color.SET(static_cast<float>((col_val & R_MASK) >> 24) / 255, static_cast<float>((col_val & G_MASK) >> 16) / 255, static_cast<float>((col_val & B_MASK) >> 8) / 255, static_cast<float>((col_val & A_MASK)) / 255);
switch(model)
{
case Models::quad :
__data.vertexData = {
{position, color},
{{position.X + scale.X, position.Y, position.Z}, color},
{{position.X + scale.X, position.Y + scale.Y, position.Z}, color},
{{position.X, position.Y + scale.Y, position.Z}, color}
};
__data.indexData = {0, 1, 2, 2, 3, 0};
break;
case Models::triangle :
__data.vertexData = {
{{position.X, position.Y + scale.Y, position.Z}, color},
{{position.X + scale.X, position.Y + scale.Y, position.Z}, color},
{{position.X - scale.X, position.Y + scale.Y, position.Z}, color}
};
__data.indexData.clear();
break;
case Models::cube :
break;
default : Core::log::report(ERROR, "Entity 2D : bad model"); break;
}
}
}
| 34.067797 | 219 | 0.561692 | [
"model"
] |
8fbd476c68283b40634466d2b0e36ed976e27da0 | 4,335 | cc | C++ | src/ledger/bin/storage/impl/commit_impl_unittest.cc | yanyushr/fuchsia | 98e70672a81a206d235503e398f37b7b65581f79 | [
"BSD-3-Clause"
] | 1 | 2019-10-09T10:50:57.000Z | 2019-10-09T10:50:57.000Z | src/ledger/bin/storage/impl/commit_impl_unittest.cc | bootingman/fuchsia2 | 04012f0aa1edd1d4108a2ac647a65e59730fc4c2 | [
"BSD-3-Clause"
] | null | null | null | src/ledger/bin/storage/impl/commit_impl_unittest.cc | bootingman/fuchsia2 | 04012f0aa1edd1d4108a2ac647a65e59730fc4c2 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2016 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/ledger/bin/storage/impl/commit_impl.h"
#include <tuple>
#include "gtest/gtest.h"
#include "src/ledger/bin/storage/fake/fake_page_storage.h"
#include "src/ledger/bin/storage/impl/commit_random_impl.h"
#include "src/ledger/bin/storage/impl/storage_test_utils.h"
#include "src/ledger/bin/storage/public/constants.h"
#include "src/lib/fxl/macros.h"
namespace storage {
namespace {
class CommitImplTest : public StorageTest {
public:
CommitImplTest() : page_storage_(&environment_, "page_id") {}
~CommitImplTest() override {}
protected:
PageStorage* GetStorage() override { return &page_storage_; }
bool CheckCommitEquals(const Commit& expected, const Commit& commit) {
return std::forward_as_tuple(expected.GetId(), expected.GetTimestamp(),
expected.GetParentIds(),
expected.GetRootIdentifier()) ==
std::forward_as_tuple(commit.GetId(), commit.GetTimestamp(),
commit.GetParentIds(),
commit.GetRootIdentifier());
}
bool CheckCommitStorageBytes(const std::unique_ptr<const Commit>& commit) {
std::unique_ptr<const Commit> copy;
Status status = CommitImpl::FromStorageBytes(
&page_storage_, commit->GetId(), commit->GetStorageBytes().ToString(),
©);
EXPECT_EQ(Status::OK, status);
return CheckCommitEquals(*commit, *copy);
}
fake::FakePageStorage page_storage_;
private:
FXL_DISALLOW_COPY_AND_ASSIGN(CommitImplTest);
};
TEST_F(CommitImplTest, CommitStorageBytes) {
ObjectIdentifier root_node_identifier =
RandomObjectIdentifier(environment_.random());
std::vector<std::unique_ptr<const Commit>> parents;
// A commit with one parent.
parents.emplace_back(
std::make_unique<CommitRandomImpl>(environment_.random()));
std::unique_ptr<const Commit> commit = CommitImpl::FromContentAndParents(
environment_.clock(), &page_storage_, root_node_identifier,
std::move(parents));
EXPECT_TRUE(CheckCommitStorageBytes(commit));
// A commit with two parents.
parents = std::vector<std::unique_ptr<const Commit>>();
parents.emplace_back(
std::make_unique<CommitRandomImpl>(environment_.random()));
parents.emplace_back(
std::make_unique<CommitRandomImpl>(environment_.random()));
std::unique_ptr<const Commit> commit2 = CommitImpl::FromContentAndParents(
environment_.clock(), &page_storage_, root_node_identifier,
std::move(parents));
EXPECT_TRUE(CheckCommitStorageBytes(commit2));
}
TEST_F(CommitImplTest, CloneCommit) {
ObjectIdentifier root_node_identifier =
RandomObjectIdentifier(environment_.random());
std::vector<std::unique_ptr<const Commit>> parents;
parents.emplace_back(
std::make_unique<CommitRandomImpl>(environment_.random()));
std::unique_ptr<const Commit> commit = CommitImpl::FromContentAndParents(
environment_.clock(), &page_storage_, root_node_identifier,
std::move(parents));
std::unique_ptr<const Commit> copy;
Status status =
CommitImpl::FromStorageBytes(&page_storage_, commit->GetId(),
commit->GetStorageBytes().ToString(), ©);
ASSERT_EQ(Status::OK, status);
std::unique_ptr<const Commit> clone = commit->Clone();
EXPECT_TRUE(CheckCommitEquals(*copy, *clone));
}
TEST_F(CommitImplTest, MergeCommitTimestamp) {
ObjectIdentifier root_node_identifier =
RandomObjectIdentifier(environment_.random());
std::vector<std::unique_ptr<const Commit>> parents;
parents.emplace_back(
std::make_unique<CommitRandomImpl>(environment_.random()));
parents.emplace_back(
std::make_unique<CommitRandomImpl>(environment_.random()));
EXPECT_NE(parents[0]->GetTimestamp(), parents[1]->GetTimestamp());
auto max_timestamp =
std::max(parents[0]->GetTimestamp(), parents[1]->GetTimestamp());
std::unique_ptr<const Commit> commit = CommitImpl::FromContentAndParents(
environment_.clock(), &page_storage_, root_node_identifier,
std::move(parents));
EXPECT_EQ(max_timestamp, commit->GetTimestamp());
}
} // namespace
} // namespace storage
| 36.428571 | 80 | 0.713264 | [
"vector"
] |
8fbdb9b65782e11a7ef5dbae7b87a28e2a34274e | 1,701 | hxx | C++ | include/idocp/robot/contact_surface.hxx | KY-Lin22/idocp | 8cacfea7bb2184023eb15316aea07154a62d59bb | [
"BSD-3-Clause"
] | 1 | 2021-09-04T07:43:04.000Z | 2021-09-04T07:43:04.000Z | include/idocp/robot/contact_surface.hxx | KY-Lin22/idocp | 8cacfea7bb2184023eb15316aea07154a62d59bb | [
"BSD-3-Clause"
] | null | null | null | include/idocp/robot/contact_surface.hxx | KY-Lin22/idocp | 8cacfea7bb2184023eb15316aea07154a62d59bb | [
"BSD-3-Clause"
] | null | null | null | #ifndef IDOCP_CONTACT_SURFACE_HXX_
#define IDOCP_CONTACT_SURFACE_HXX_
#include "idocp/robot/contact_surface.hpp"
#include <stdexcept>
#include <iostream>
namespace idocp {
inline ContactSurface::ContactSurface(const Eigen::Vector3d& origin,
const Eigen::Vector3d& normal_vector)
: origin_(origin),
normal_vector_(normal_vector) {
try {
if (normal_vector.squaredNorm() != 1.0) {
throw std::out_of_range(
"invalid argment: norm of normal vector must be 1");
}
}
catch(const std::exception& e) {
std::cerr << e.what() << '\n';
std::exit(EXIT_FAILURE);
}
}
inline ContactSurface::ContactSurface()
: origin_(Eigen::Vector3d::Zero()),
normal_vector_(Eigen::Vector3d::Zero()) {
normal_vector_.coeffRef(2) = 1;
}
inline ContactSurface::~ContactSurface() {
}
inline bool ContactSurface::doesPenetrate(
const Eigen::Vector3d& coordinate) const {
if (coordinate.coeff(2) < 0) {
return true;
}
else {
return false;
}
}
inline double ContactSurface::normalContactForce(
const Eigen::Vector3d& f) const {
return f.dot(normal_vector_);
}
inline void ContactSurface::setOrigin(const Eigen::Vector3d& origin) {
origin_ = origin;
}
inline void ContactSurface::setNormalVector(
const Eigen::Vector3d& normal_vector) {
try {
if (normal_vector.squaredNorm() != 1.0) {
throw std::out_of_range(
"invalid argment: norm of normal vector must be 1");
}
}
catch(const std::exception& e) {
std::cerr << e.what() << '\n';
std::exit(EXIT_FAILURE);
}
normal_vector_ = normal_vector;
}
} // namespace idocp
#endif // IDOCP_CONTACT_SURFACE_HXX_ | 21.807692 | 75 | 0.663139 | [
"vector"
] |
8fc56e643beb7a4087518d7c885f07a7ad2a76c5 | 9,393 | cc | C++ | app/oxs/ext/mindriver.cc | ViennaNovoFlop/ViennaNovoFlop-dev | f8c4d6c06590a0d9a3890d81e9b0b4dcb7ea9e00 | [
"TCL",
"SWL",
"MIT",
"X11",
"BSD-3-Clause"
] | null | null | null | app/oxs/ext/mindriver.cc | ViennaNovoFlop/ViennaNovoFlop-dev | f8c4d6c06590a0d9a3890d81e9b0b4dcb7ea9e00 | [
"TCL",
"SWL",
"MIT",
"X11",
"BSD-3-Clause"
] | null | null | null | app/oxs/ext/mindriver.cc | ViennaNovoFlop/ViennaNovoFlop-dev | f8c4d6c06590a0d9a3890d81e9b0b4dcb7ea9e00 | [
"TCL",
"SWL",
"MIT",
"X11",
"BSD-3-Clause"
] | null | null | null | /* FILE: mindriver.cc -*-Mode: c++-*-
*
* Example minimization Oxs_Driver class.
*
*/
#include <string>
#include "nb.h"
#include "mindriver.h"
#include "director.h"
#include "simstate.h"
#include "minevolver.h"
#include "key.h"
#include "mesh.h"
#include "energy.h" // Needed to make MSVC++ 5 happy
OC_USE_STRING;
// Oxs_Ext registration support
OXS_EXT_REGISTER(Oxs_MinDriver);
/* End includes */
// Constructor
Oxs_MinDriver::Oxs_MinDriver(
const char* name, // Child instance id
Oxs_Director* newdtr, // App director
const char* argstr) // MIF input block parameters
: Oxs_Driver(name,newdtr,argstr),
max_mxHxm_output_obj_ptr(NULL), total_energy_output_obj_ptr(NULL)
{
// Process arguments
// Get evolver name specification
OXS_GET_INIT_EXT_OBJECT("evolver",Oxs_MinEvolver,evolver_obj);
evolver_key.Set(evolver_obj.GetPtr());
// Dependency lock on Oxs_MinEvolver object is
// held until *this is destroyed.
if(!HasInitValue("stopping_mxHxm")) {
stopping_mxHxm.push_back(0.0); // Default is no control
} else {
GetGroupedRealListInitValue("stopping_mxHxm",stopping_mxHxm);
}
VerifyAllInitArgsUsed();
// Reserve space for initial state (see GetInitialState() below)
director->ReserveSimulationStateRequest(1);
}
Oxs_ConstKey<Oxs_SimState>
Oxs_MinDriver::GetInitialState() const
{
Oxs_Key<Oxs_SimState> initial_state;
director->GetNewSimulationState(initial_state);
Oxs_SimState& istate = initial_state.GetWriteReference();
SetStartValues(istate);
istate.stage_start_time = -1.; // Dummy value
istate.stage_elapsed_time = -1.; // Dummy value
istate.last_timestep = -1.; // Dummy value
const Oxs_SimState& fstate = initial_state.GetReadReference();
/// Release write lock. The read lock will be automatically
/// released when the key "initial_state" is destroyed.
fstate.AddDerivedData("Last energy",0.);
return initial_state;
}
OC_BOOL Oxs_MinDriver::Init()
{
Oxs_Driver::Init(); // Run init routine in parent.
/// This will call Oxs_MinDriver::GetInitialState().
// Get pointer to output object providing max mxHxm data
const Oxs_MinEvolver* evolver = evolver_key.GetPtr();
if(evolver==NULL) {
throw Oxs_ExtError(this,"PROGRAMMING ERROR: No evolver found?");
}
String output_name = String(evolver->InstanceName());
output_name += String(":Max mxHxm");
max_mxHxm_output_obj_ptr
= director->FindOutputObjectExact(output_name.c_str());
if(max_mxHxm_output_obj_ptr==NULL) {
String msg = String("Unable to identify unique \"")
+ output_name + String("\" object.");
throw Oxs_ExtError(this,msg.c_str());
}
output_name = String(evolver->InstanceName());
output_name += String(":Total energy");
total_energy_output_obj_ptr
= director->FindOutputObjectExact(output_name.c_str());
if(total_energy_output_obj_ptr==NULL) {
String msg = String("Unable to identify unique \"")
+ output_name + String("\" object.");
throw Oxs_ExtError(this,msg.c_str());
}
return 1;
}
Oxs_MinDriver::~Oxs_MinDriver()
{}
void Oxs_MinDriver::StageRequestCount
(unsigned int& min,
unsigned int& max) const
{ // Number of stages wanted by driver
Oxs_Driver::StageRequestCount(min,max);
unsigned int count = static_cast<unsigned int>(stopping_mxHxm.size());
if(count>min) min=count;
if(count>1 && count<max) max=count;
// Treat length 1 lists as imposing no upper constraint.
}
OC_BOOL
Oxs_MinDriver::ChildIsStageDone(const Oxs_SimState& state) const
{
OC_UINT4m stage_index = state.stage_number;
// Max mxHxm check
Tcl_Interp* mif_interp = director->GetMifInterp();
if(max_mxHxm_output_obj_ptr == NULL ||
max_mxHxm_output_obj_ptr->Output(&state,mif_interp,0,NULL) != TCL_OK) {
String msg=String("Unable to obtain Max mxHxm output: ");
if(max_mxHxm_output_obj_ptr==NULL) {
msg += String("PROGRAMMING ERROR: max_mxHxm_output_obj_ptr not set."
" Driver Init() probably not called.");
} else {
msg += String(Tcl_GetStringResult(mif_interp));
}
throw Oxs_ExtError(this,msg.c_str());
}
OC_BOOL err;
OC_REAL8m max_mxHxm = Nb_Atof(Tcl_GetStringResult(mif_interp),err);
if(err) {
String msg=String("Error detected in StageDone method"
" --- Invalid Max dm/dt output: ");
msg += String(Tcl_GetStringResult(mif_interp));
throw Oxs_ExtError(this,msg.c_str());
}
OC_REAL8m stop_mxHxm=0.;
if(stage_index >= stopping_mxHxm.size()) {
stop_mxHxm = stopping_mxHxm[stopping_mxHxm.size()-1];
} else {
stop_mxHxm = stopping_mxHxm[stage_index];
}
if(stop_mxHxm>0.0 && max_mxHxm <= stop_mxHxm) {
return 1; // Stage done
}
// If control gets here, then stage not done
return 0;
}
OC_BOOL
Oxs_MinDriver::ChildIsRunDone(const Oxs_SimState& /* state */) const
{
// No child-specific checks at this time...
return 0; // Run not done
}
void Oxs_MinDriver::FillStateMemberData
(const Oxs_SimState& old_state,
Oxs_SimState& new_state) const
{
Oxs_Driver::FillStateMemberData(old_state,new_state);
// Copy over values from old_state for time indexes, since
// with mindriver time is not advanced. Perhaps the time index
// variables should be moved over to the WOO area in simstate?
new_state.stage_start_time = old_state.stage_start_time;
new_state.stage_elapsed_time = old_state.stage_elapsed_time;
new_state.last_timestep = old_state.last_timestep;
}
void Oxs_MinDriver::FillStateDerivedData
(const Oxs_SimState& old_state,
const Oxs_SimState& new_state) const
{
Oxs_Driver::FillStateDerivedData(old_state,new_state);
// Keep track of energy from previous state. This is used
// by "Delta E" output.
OC_REAL8m old_energy;
if(!old_state.GetDerivedData("Total energy",old_energy)) {
// Energy field not filled in old state. Try calling output
// object, which should call necessary update functions.
Tcl_Interp* mif_interp = director->GetMifInterp();
if(total_energy_output_obj_ptr == NULL ||
total_energy_output_obj_ptr->Output(&old_state,mif_interp,0,NULL)
!= TCL_OK) {
String msg =
String("Error in FillState:"
" Unable to obtain \"Total energy\" output: ");
if(total_energy_output_obj_ptr==NULL) {
msg += String("PROGRAMMING ERROR:"
" total_energy_output_obj_ptr not set."
" Driver Init() probably not called.");
} else {
msg += String(Tcl_GetStringResult(mif_interp));
}
throw Oxs_ExtError(this,msg.c_str());
}
OC_BOOL err;
old_energy = Nb_Atof(Tcl_GetStringResult(mif_interp),err);
if(err) {
String msg=String("Error detected in FillState method"
" --- Invalid \"Total energy\" output: ");
msg += String(Tcl_GetStringResult(mif_interp));
throw Oxs_ExtError(this,msg.c_str());
}
}
new_state.AddDerivedData("Last energy",old_energy);
}
void Oxs_MinDriver::FillNewStageStateDerivedData
(const Oxs_SimState& old_state,
int new_stage_number,
const Oxs_SimState& new_state) const
{
Oxs_Driver::FillNewStageStateDerivedData(old_state,new_stage_number,
new_state);
OC_REAL8m old_energy;
if(!old_state.GetDerivedData("Total energy",old_energy)) {
// Energy field not filled in old state. Try calling output
// object, which should call necessary update functions.
Tcl_Interp* mif_interp = director->GetMifInterp();
if(total_energy_output_obj_ptr == NULL ||
total_energy_output_obj_ptr->Output(&old_state,mif_interp,0,NULL)
!= TCL_OK) {
String msg =
String("Error in FillNewStageState:"
" Unable to obtain \"Total energy\" output: ");
if(total_energy_output_obj_ptr==NULL) {
msg += String("PROGRAMMING ERROR:"
" total_energy_output_obj_ptr not set."
" Driver Init() probably not called.");
} else {
msg += String(Tcl_GetStringResult(mif_interp));
}
throw Oxs_ExtError(this,msg.c_str());
}
OC_BOOL err;
old_energy = Nb_Atof(Tcl_GetStringResult(mif_interp),err);
if(err) {
String msg=String("Error detected in FillNewStageState method"
" --- Invalid \"Total energy\" output: ");
msg += String(Tcl_GetStringResult(mif_interp));
throw Oxs_ExtError(this,msg.c_str());
}
}
new_state.AddDerivedData("Last energy",old_energy);
}
OC_BOOL
Oxs_MinDriver::Step
(Oxs_ConstKey<Oxs_SimState> base_state,
const Oxs_DriverStepInfo& stepinfo,
Oxs_Key<Oxs_SimState>& next_state)
{ // Returns true if step was successful, false if
// unable to step as requested.
// Put write lock on evolver in order to get a non-const
// pointer. Use a temporary variable, temp_key, so
// write lock is automatically removed when temp_key
// is destroyed.
Oxs_Key<Oxs_MinEvolver> temp_key = evolver_key;
Oxs_MinEvolver& evolver = temp_key.GetWriteReference();
return evolver.Step(this,base_state,stepinfo,next_state);
}
OC_BOOL
Oxs_MinDriver::InitNewStage
(Oxs_ConstKey<Oxs_SimState> state,
Oxs_ConstKey<Oxs_SimState> prevstate)
{
// Put write lock on evolver in order to get a non-const
// pointer. Use a temporary variable, temp_key, so
// write lock is automatically removed when temp_key
// is destroyed.
Oxs_Key<Oxs_MinEvolver> temp_key = evolver_key;
Oxs_MinEvolver& evolver = temp_key.GetWriteReference();
return evolver.InitNewStage(this,state,prevstate);
}
| 32.278351 | 76 | 0.712765 | [
"mesh",
"object"
] |
8fcb2252eeb69964e20ab8f26ce0702eccfe6c33 | 5,675 | hpp | C++ | include/efslam/io/carmen/CarmenProcessor.hpp | Pandinosaurus/Evidential-FastSLAM | 0af895592077bf24b9c3c2db92a3e0e1c962c37b | [
"BSD-3-Clause"
] | 17 | 2016-09-13T08:52:07.000Z | 2022-01-12T10:24:14.000Z | include/efslam/io/carmen/CarmenProcessor.hpp | Pandinosaurus/Evidential-FastSLAM | 0af895592077bf24b9c3c2db92a3e0e1c962c37b | [
"BSD-3-Clause"
] | null | null | null | include/efslam/io/carmen/CarmenProcessor.hpp | Pandinosaurus/Evidential-FastSLAM | 0af895592077bf24b9c3c2db92a3e0e1c962c37b | [
"BSD-3-Clause"
] | 7 | 2017-02-16T14:12:05.000Z | 2021-06-22T12:32:45.000Z | /*
* Software License Agreement (BSD License)
*
* Evidential FastSLAM - An evidential approach to SLAM
* Copyright (c) 2013-2016, Joachim Clemens, Thomas Reineking, Tobias Kluth
* 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 Evidential FastSLAM 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 "efslam/utils/Convenience.h"
#include "efslam/utils/Config.h"
#include "efslam/utils/Log.h"
namespace efs {
template<typename SLAM>
CarmenProcessor<SLAM>::CarmenProcessor( SLAM *slam, std::istream &inputStream, std::istream *gtInputStream ) :
m_slam( slam ),
m_reader( inputStream ),
m_laserStartAngle( DEG2RAD( Config::getDouble( "LASER_START_ANGLE", -90.0 ) ) ),
m_laserAngularRes( DEG2RAD( Config::getDouble( "LASER_ANGULAR_RES", 1.0 ) ) ),
m_first( true )
{
if( gtInputStream )
m_gtReader = new CarmenGtReader( *gtInputStream );
else
m_gtReader = nullptr;
}
template<typename SLAM>
CarmenProcessor<SLAM>::~CarmenProcessor() {
if( m_gtReader )
delete m_gtReader;
}
template<typename SLAM>
bool
CarmenProcessor<SLAM>::processNext( bool *scanProcessed ) {
PoseSE2 pose;
std::vector<double> scan;
std::string timestamp;
if( m_reader.nextReading( &pose, &scan, ×tamp ) ) {
if( m_first ) {
m_lastPose = pose;
m_first = false;
}
// Process odometry
m_slam->processOdom( m_lastPose, pose );
m_lastPose = pose;
if( m_slam->scanRequired() ) {
// Convert laser scan to 2D point cloud
typename Scan::Ptr scanPointCloud( new Scan );
scanPointCloud->reserve( scan.size() );
for( size_t i = 0; i < scan.size(); i++ ) {
PointType p;
double angle = m_laserStartAngle + m_laserAngularRes*i;
p[0] = scan[i] * cos( angle );
p[1] = scan[i] * sin( angle );
//cout << p.transpose() << endl;
scanPointCloud->push_back( p );
}
// Process scan
m_slam->processScan( scanPointCloud );
// Save timestamp
m_timestamps.push_back( timestamp );
// Find GT pose and calc error
if( m_gtReader ) {
PoseSE2 gtPose;
std::string gtTimestamp;
bool found = false;
while( !found && m_gtReader->nextPose( >Pose, >Timestamp ) ) {
if( gtTimestamp == timestamp )
found = true;
}
if( found ) {
// TODO: Other error calculation?
/*
// Error between absolute pose
PoseSE2 estPose = m_slam->pose( m_slam->bestParticleIdx() );
double error = 0;
for( size_t i = 0; i < 2; i++ )
error += SQR( estPose.pos[i] - gtPose.pos[i] );
error = sqrt( error );
*/
/*
// Relative diff between last and current pose for current best particle
Trajectory estTraj = m_slam->trajectory( m_slam->bestParticleIdx(), (size_t) 2 );
PoseSE2 &estPose = estTraj[1],
estPoseDiff = estTraj[0].compoundInv( estTraj[1] ),
gtPoseDiff = m_lastGtPose.compoundInv( gtPose );
double error = 0;
for( size_t i = 0; i < 2; i++ )
error += SQR( estPoseDiff.pos[i] - gtPoseDiff.pos[i] );
error = sqrt( error );
*/
// Relative diff between last and current pose for current and last best particle
PoseSE2 estPose = m_slam->pose( m_slam->bestParticleIdx() ),
estPoseDiff = m_lastEstPose.compoundInv( estPose ),
gtPoseDiff = m_lastGtPose.compoundInv( gtPose );
double error = 0;
for( size_t i = 0; i < 2; i++ )
error += SQR( estPoseDiff.pos()[i] - gtPoseDiff.pos()[i] );
error = sqrt( error );
m_gtTrajectory.push_back( gtPose );
m_poseError.push_back( error );
m_lastGtPose = gtPose;
m_lastEstPose = estPose;
l_inf( "Estimated pose: \t" << estPose );
l_inf( "Ground truth pose:\t" << gtPose );
l_inf( "Pose error: \t" << error );
} else {
l_wrn( "No GT pose for timestamp " << timestamp << ". Unable to compute error.");
}
}
if( scanProcessed )
*scanProcessed = true;
} else {
if( scanProcessed )
*scanProcessed = false;
}
return true;
} else {
return false;
}
}
template<typename SLAM>
uint64_t
CarmenProcessor<SLAM>::processAll() {
uint64_t count = 0;
bool scanProcessed;
while( processNext( &scanProcessed ) ) {
if( scanProcessed )
count++;
}
return count;
}
} /* namespace efs */
| 29.557292 | 110 | 0.669604 | [
"vector"
] |
8fd44f89304428d553d3ada02a1e28a742226325 | 376 | cpp | C++ | internals/wip/program/types/list_strict_test.cpp | polytypic/algebraic.cpp | 77813838eb775e7640506a0a3d10a3b5d2130421 | [
"MIT"
] | 2 | 2018-12-16T21:32:21.000Z | 2021-12-11T20:54:36.000Z | internals/wip/program/types/list_strict_test.cpp | polytypic/algebraic.cpp | 77813838eb775e7640506a0a3d10a3b5d2130421 | [
"MIT"
] | null | null | null | internals/wip/program/types/list_strict_test.cpp | polytypic/algebraic.cpp | 77813838eb775e7640506a0a3d10a3b5d2130421 | [
"MIT"
] | null | null | null | #include "list_strict.hpp"
#include "generics/pretty.hpp"
#include "util/test_runner.hpp"
#include "core/structures.hpp"
#include <iostream>
static auto list_strict_test = test_runner([]() {
auto xs = list(3, 1, 4);
auto ys = reverse(reverse(xs));
auto zs = map<append>([](auto &x) { return 0.5 + x; }, ys);
std::cerr << render(120, pretty(zs)) << std::endl;
});
| 22.117647 | 61 | 0.646277 | [
"render"
] |
8fe01c598be7285bf563b8a9b8d024783884b187 | 33,543 | cpp | C++ | tests/EQ/RobertBristowJohnsonFilter.cpp | AudioTK/AudioTK | dba42eea68534501efe74692b74edf4792cca231 | [
"BSD-3-Clause"
] | 23 | 2021-02-04T10:47:46.000Z | 2022-03-25T03:45:00.000Z | tests/EQ/RobertBristowJohnsonFilter.cpp | AudioTK/AudioTK | dba42eea68534501efe74692b74edf4792cca231 | [
"BSD-3-Clause"
] | 2 | 2021-02-01T15:45:06.000Z | 2021-09-13T19:39:05.000Z | tests/EQ/RobertBristowJohnsonFilter.cpp | AudioTK/AudioTK | dba42eea68534501efe74692b74edf4792cca231 | [
"BSD-3-Clause"
] | 2 | 2021-04-12T03:28:12.000Z | 2021-12-17T00:47:11.000Z | /**
* \ file RobertBristowJohnsonFilter.cpp
*/
#include <ATK/EQ/RobertBristowJohnsonFilter.h>
#include <ATK/EQ/IIRFilter.h>
#include <ATK/Mock/FFTCheckerFilter.h>
#include <ATK/Mock/SimpleSinusGeneratorFilter.h>
#include <gtest/gtest.h>
constexpr gsl::index PROCESSSIZE = 1024*64;
TEST(IIRFilter, RobertBristowJohnsonLowPassCoefficients_Q_test)
{
ATK::IIRFilter<ATK::RobertBristowJohnsonLowPassCoefficients<double> > filter;
filter.set_Q(20);
ASSERT_EQ(filter.get_Q(), 20);
}
TEST(IIRFilter, RobertBristowJohnsonLowPassCoefficients_Q_range_test)
{
ATK::IIRFilter<ATK::RobertBristowJohnsonLowPassCoefficients<double> > filter;
ASSERT_THROW(filter.set_Q(0), std::out_of_range);
}
TEST(IIRFilter, RobertBristowJohnsonHighPassCoefficients_Q_test)
{
ATK::IIRFilter<ATK::RobertBristowJohnsonHighPassCoefficients<double> > filter;
filter.set_Q(20);
ASSERT_EQ(filter.get_Q(), 20);
}
TEST(IIRFilter, RobertBristowJohnsonHighPassCoefficients_Q_range_test)
{
ATK::IIRFilter<ATK::RobertBristowJohnsonHighPassCoefficients<double> > filter;
ASSERT_THROW(filter.set_Q(0), std::out_of_range);
}
TEST(IIRFilter, RobertBristowJohnsonBandPassCoefficients_Q_test)
{
ATK::IIRFilter<ATK::RobertBristowJohnsonBandPassCoefficients<double> > filter;
filter.set_Q(20);
ASSERT_EQ(filter.get_Q(), 20);
}
TEST(IIRFilter, RobertBristowJohnsonBandPassCoefficients_Q_range_test)
{
ATK::IIRFilter<ATK::RobertBristowJohnsonBandPassCoefficients<double> > filter;
ASSERT_THROW(filter.set_Q(0), std::out_of_range);
}
TEST(IIRFilter, RobertBristowJohnsonBandPass2Coefficients_Q_test)
{
ATK::IIRFilter<ATK::RobertBristowJohnsonBandPass2Coefficients<double> > filter;
filter.set_Q(20);
ASSERT_EQ(filter.get_Q(), 20);
}
TEST(IIRFilter, RobertBristowJohnsonBandPass2Coefficients_Q_range_test)
{
ATK::IIRFilter<ATK::RobertBristowJohnsonBandPass2Coefficients<double> > filter;
ASSERT_THROW(filter.set_Q(0), std::out_of_range);
}
TEST(IIRFilter, RobertBristowJohnsonBandStopCoefficients_Q_test)
{
ATK::IIRFilter<ATK::RobertBristowJohnsonBandStopCoefficients<double> > filter;
filter.set_Q(20);
ASSERT_EQ(filter.get_Q(), 20);
}
TEST(IIRFilter, RobertBristowJohnsonBandStopCoefficients_Q_range_test)
{
ATK::IIRFilter<ATK::RobertBristowJohnsonBandStopCoefficients<double> > filter;
ASSERT_THROW(filter.set_Q(0), std::out_of_range);
}
TEST(IIRFilter, RobertBristowJohnsonAllPassCoefficients_Q_test)
{
ATK::IIRFilter<ATK::RobertBristowJohnsonAllPassCoefficients<double> > filter;
filter.set_Q(20);
ASSERT_EQ(filter.get_Q(), 20);
}
TEST(IIRFilter, RobertBristowJohnsonAllPassCoefficients_Q_range_test)
{
ATK::IIRFilter<ATK::RobertBristowJohnsonAllPassCoefficients<double> > filter;
ASSERT_THROW(filter.set_Q(0), std::out_of_range);
}
TEST(IIRFilter, RobertBristowJohnsonBandPassPeakCoefficients_Q_test)
{
ATK::IIRFilter<ATK::RobertBristowJohnsonBandPassPeakCoefficients<double> > filter;
filter.set_Q(20);
ASSERT_EQ(filter.get_Q(), 20);
}
TEST(IIRFilter, RobertBristowJohnsonBandPassPeakCoefficients_Q_range_test)
{
ATK::IIRFilter<ATK::RobertBristowJohnsonBandPassPeakCoefficients<double> > filter;
ASSERT_THROW(filter.set_Q(0), std::out_of_range);
}
TEST(IIRFilter, RobertBristowJohnsonBandPassPeakCoefficients_gain_test)
{
ATK::IIRFilter<ATK::RobertBristowJohnsonBandPassPeakCoefficients<double> > filter;
filter.set_gain(20);
ASSERT_EQ(filter.get_gain(), 20);
}
TEST(IIRFilter, RobertBristowJohnsonBandPassPeakCoefficients_gain_range_test)
{
ATK::IIRFilter<ATK::RobertBristowJohnsonBandPassPeakCoefficients<double> > filter;
ASSERT_THROW(filter.set_gain(0), std::out_of_range);
}
TEST(IIRFilter, RobertBristowJohnsonLowShelvingCoefficients_Q_test)
{
ATK::IIRFilter<ATK::RobertBristowJohnsonLowShelvingCoefficients<double> > filter;
filter.set_Q(20);
ASSERT_EQ(filter.get_Q(), 20);
}
TEST(IIRFilter, RobertBristowJohnsonLowShelvingCoefficients_Q_range_test)
{
ATK::IIRFilter<ATK::RobertBristowJohnsonLowShelvingCoefficients<double> > filter;
ASSERT_THROW(filter.set_Q(0), std::out_of_range);
}
TEST(IIRFilter, RobertBristowJohnsonLowShelvingCoefficients_gain_test)
{
ATK::IIRFilter<ATK::RobertBristowJohnsonLowShelvingCoefficients<double> > filter;
filter.set_gain(20);
ASSERT_EQ(filter.get_gain(), 20);
}
TEST(IIRFilter, RobertBristowJohnsonLowShelvingCoefficients_gain_range_test)
{
ATK::IIRFilter<ATK::RobertBristowJohnsonLowShelvingCoefficients<double> > filter;
ASSERT_THROW(filter.set_gain(0), std::out_of_range);
}
TEST(IIRFilter, RobertBristowJohnsonHighShelvingCoefficients_Q_test)
{
ATK::IIRFilter<ATK::RobertBristowJohnsonHighShelvingCoefficients<double> > filter;
filter.set_Q(20);
ASSERT_EQ(filter.get_Q(), 20);
}
TEST(IIRFilter, RobertBristowJohnsonHighShelvingCoefficients_Q_range_test)
{
ATK::IIRFilter<ATK::RobertBristowJohnsonHighShelvingCoefficients<double> > filter;
ASSERT_THROW(filter.set_Q(0), std::out_of_range);
}
TEST(IIRFilter, RobertBristowJohnsonHighShelvingCoefficients_gain_test)
{
ATK::IIRFilter<ATK::RobertBristowJohnsonHighShelvingCoefficients<double> > filter;
filter.set_gain(20);
ASSERT_EQ(filter.get_gain(), 20);
}
TEST(IIRFilter, RobertBristowJohnsonHighShelvingCoefficients_gain_range_test)
{
ATK::IIRFilter<ATK::RobertBristowJohnsonHighShelvingCoefficients<double> > filter;
ASSERT_THROW(filter.set_gain(0), std::out_of_range);
}
TEST(IIRFilter, RobertBristowJohnsonLowPassCoefficients_1k_test)
{
ATK::SimpleSinusGeneratorFilter<double> generator;
generator.set_output_sampling_rate(1024*64);
generator.set_amplitude(1);
generator.set_frequency(1000);
ATK::IIRFilter<ATK::RobertBristowJohnsonLowPassCoefficients<double> > filter;
filter.set_input_sampling_rate(1024*64);
filter.set_output_sampling_rate(1024*64);
filter.set_cut_frequency(100);
ATK::FFTCheckerFilter<double> checker;
checker.set_input_sampling_rate(1024*64);
std::vector<std::pair<int, double> > frequency_checks;
frequency_checks.push_back(std::make_pair(100, 0));
frequency_checks.push_back(std::make_pair(1000, 0.10017263357405178));
frequency_checks.push_back(std::make_pair(10000, 0));
checker.set_checks(frequency_checks);
checker.set_input_port(0, &filter, 0);
filter.set_input_port(0, &generator, 0);
filter.process(1024*64);
checker.process(PROCESSSIZE);
}
TEST(IIRFilter, RobertBristowJohnsonLowPassCoefficients_100_test)
{
ATK::SimpleSinusGeneratorFilter<double> generator;
generator.set_output_sampling_rate(1024*64);
generator.set_amplitude(1);
generator.set_frequency(100);
ATK::IIRFilter<ATK::RobertBristowJohnsonLowPassCoefficients<double> > filter;
filter.set_input_sampling_rate(1024*64);
filter.set_output_sampling_rate(1024*64);
filter.set_cut_frequency(100);
ATK::FFTCheckerFilter<double> checker;
checker.set_input_sampling_rate(1024*64);
std::vector<std::pair<int, double> > frequency_checks;
frequency_checks.push_back(std::make_pair(10, 0));
frequency_checks.push_back(std::make_pair(100, 1.));
frequency_checks.push_back(std::make_pair(1000, 0));
checker.set_checks(frequency_checks);
checker.set_input_port(0, &filter, 0);
filter.set_input_port(0, &generator, 0);
filter.process(1024*64);
checker.process(PROCESSSIZE);
}
TEST(IIRFilter, RobertBristowJohnsonLowPassCoefficients_2k_test)
{
ATK::SimpleSinusGeneratorFilter<double> generator;
generator.set_output_sampling_rate(1024*64);
generator.set_amplitude(1);
generator.set_frequency(2000);
ATK::IIRFilter<ATK::RobertBristowJohnsonLowPassCoefficients<double> > filter;
filter.set_input_sampling_rate(1024*64);
filter.set_output_sampling_rate(1024*64);
filter.set_cut_frequency(100);
ATK::FFTCheckerFilter<double> checker;
checker.set_input_sampling_rate(1024*64);
std::vector<std::pair<int, double> > frequency_checks;
frequency_checks.push_back(std::make_pair(100, 0));
frequency_checks.push_back(std::make_pair(1000, 0));
frequency_checks.push_back(std::make_pair(2000, 0.04987802660970978));
checker.set_checks(frequency_checks);
checker.set_input_port(0, &filter, 0);
filter.set_input_port(0, &generator, 0);
filter.process(1024*64);
checker.process(PROCESSSIZE);
}
TEST(IIRFilter, RobertBristowJohnsonLowPassCoefficients_200_test)
{
ATK::SimpleSinusGeneratorFilter<double> generator;
generator.set_output_sampling_rate(1024*64);
generator.set_amplitude(1);
generator.set_frequency(200);
ATK::IIRFilter<ATK::RobertBristowJohnsonLowPassCoefficients<double> > filter;
filter.set_input_sampling_rate(1024*64);
filter.set_output_sampling_rate(1024*64);
filter.set_cut_frequency(100);
ATK::FFTCheckerFilter<double> checker;
checker.set_input_sampling_rate(1024*64);
std::vector<std::pair<int, double> > frequency_checks;
frequency_checks.push_back(std::make_pair(100, 0));
frequency_checks.push_back(std::make_pair(200, 0.5266273548331198));
frequency_checks.push_back(std::make_pair(1000, 0));
checker.set_checks(frequency_checks);
checker.set_input_port(0, &filter, 0);
filter.set_input_port(0, &generator, 0);
filter.process(1024*64);
checker.process(PROCESSSIZE);
}
TEST(IIRFilter, RobertBristowJohnsonHighPassCoefficients_1k_test)
{
ATK::SimpleSinusGeneratorFilter<double> generator;
generator.set_output_sampling_rate(1024*64);
generator.set_amplitude(1);
generator.set_frequency(1000);
ATK::IIRFilter<ATK::RobertBristowJohnsonHighPassCoefficients<double> > filter;
filter.set_input_sampling_rate(1024*64);
filter.set_output_sampling_rate(1024*64);
filter.set_cut_frequency(100);
ATK::FFTCheckerFilter<double> checker;
checker.set_input_sampling_rate(1024*64);
std::vector<std::pair<int, double> > frequency_checks;
frequency_checks.push_back(std::make_pair(100, 0));
frequency_checks.push_back(std::make_pair(1000, 1.0024866672050896));
frequency_checks.push_back(std::make_pair(10000, 0));
checker.set_checks(frequency_checks);
checker.set_input_port(0, &filter, 0);
filter.set_input_port(0, &generator, 0);
filter.process(1024*64);
checker.process(PROCESSSIZE);
}
TEST(IIRFilter, RobertBristowJohnsonHighPassCoefficients_100_test)
{
ATK::SimpleSinusGeneratorFilter<double> generator;
generator.set_output_sampling_rate(1024*64);
generator.set_amplitude(1);
generator.set_frequency(100);
ATK::IIRFilter<ATK::RobertBristowJohnsonHighPassCoefficients<double> > filter;
filter.set_input_sampling_rate(1024*64);
filter.set_output_sampling_rate(1024*64);
filter.set_cut_frequency(100);
ATK::FFTCheckerFilter<double> checker;
checker.set_input_sampling_rate(1024*64);
std::vector<std::pair<int, double> > frequency_checks;
frequency_checks.push_back(std::make_pair(10, 0));
frequency_checks.push_back(std::make_pair(100, 1.));
frequency_checks.push_back(std::make_pair(1000, 0));
checker.set_checks(frequency_checks);
checker.set_input_port(0, &filter, 0);
filter.set_input_port(0, &generator, 0);
filter.process(1024*64);
checker.process(PROCESSSIZE);
}
TEST(IIRFilter, RobertBristowJohnsonHighPassCoefficients_2k_test)
{
ATK::SimpleSinusGeneratorFilter<double> generator;
generator.set_output_sampling_rate(1024*64);
generator.set_amplitude(1);
generator.set_frequency(2000);
ATK::IIRFilter<ATK::RobertBristowJohnsonHighPassCoefficients<double> > filter;
filter.set_input_sampling_rate(1024*64);
filter.set_output_sampling_rate(1024*64);
filter.set_cut_frequency(100);
ATK::FFTCheckerFilter<double> checker;
checker.set_input_sampling_rate(1024*64);
std::vector<std::pair<int, double> > frequency_checks;
frequency_checks.push_back(std::make_pair(100, 0));
frequency_checks.push_back(std::make_pair(1000, 0));
frequency_checks.push_back(std::make_pair(2000, 1.0006206013284984));
checker.set_checks(frequency_checks);
checker.set_input_port(0, &filter, 0);
filter.set_input_port(0, &generator, 0);
filter.process(1024*64);
checker.process(PROCESSSIZE);
}
TEST(IIRFilter, RobertBristowJohnsonHighPassCoefficients_200_test)
{
ATK::SimpleSinusGeneratorFilter<double> generator;
generator.set_output_sampling_rate(1024*64);
generator.set_amplitude(1);
generator.set_frequency(200);
ATK::IIRFilter<ATK::RobertBristowJohnsonHighPassCoefficients<double> > filter;
filter.set_input_sampling_rate(1024*64);
filter.set_output_sampling_rate(1024*64);
filter.set_cut_frequency(100);
ATK::FFTCheckerFilter<double> checker;
checker.set_input_sampling_rate(1024*64);
std::vector<std::pair<int, double> > frequency_checks;
frequency_checks.push_back(std::make_pair(100, 0));
frequency_checks.push_back(std::make_pair(200, 1.0532789138212624));
frequency_checks.push_back(std::make_pair(1000, 0));
checker.set_checks(frequency_checks);
checker.set_input_port(0, &filter, 0);
filter.set_input_port(0, &generator, 0);
filter.process(1024*64);
checker.process(PROCESSSIZE);
}
TEST(IIRFilter, RobertBristowJohnsonBandPassCoefficients_1k_test)
{
ATK::SimpleSinusGeneratorFilter<double> generator;
generator.set_output_sampling_rate(1024 * 64);
generator.set_amplitude(1);
generator.set_frequency(1000);
ATK::IIRFilter<ATK::RobertBristowJohnsonBandPassCoefficients<double> > filter;
filter.set_input_sampling_rate(1024 * 64);
filter.set_output_sampling_rate(1024 * 64);
filter.set_Q(1);
filter.set_cut_frequency(100);
ATK::FFTCheckerFilter<double> checker;
checker.set_input_sampling_rate(1024 * 64);
std::vector<std::pair<int, double> > frequency_checks;
frequency_checks.push_back(std::make_pair(100, 0));
frequency_checks.push_back(std::make_pair(1000, 0.3168938774681514));
frequency_checks.push_back(std::make_pair(10000, 0));
checker.set_checks(frequency_checks);
checker.set_input_port(0, &filter, 0);
filter.set_input_port(0, &generator, 0);
filter.process(1024 * 64);
checker.process(PROCESSSIZE);
}
TEST(IIRFilter, RobertBristowJohnsonBandPassCoefficients_100_test)
{
ATK::SimpleSinusGeneratorFilter<double> generator;
generator.set_output_sampling_rate(1024 * 64);
generator.set_amplitude(1);
generator.set_frequency(100);
ATK::IIRFilter<ATK::RobertBristowJohnsonBandPassCoefficients<double> > filter;
filter.set_input_sampling_rate(1024 * 64);
filter.set_output_sampling_rate(1024 * 64);
filter.set_Q(1);
filter.set_cut_frequency(100);
ATK::FFTCheckerFilter<double> checker;
checker.set_input_sampling_rate(1024 * 64);
std::vector<std::pair<int, double> > frequency_checks;
frequency_checks.push_back(std::make_pair(10, 0));
frequency_checks.push_back(std::make_pair(100, 1.));
frequency_checks.push_back(std::make_pair(1000, 0));
checker.set_checks(frequency_checks);
checker.set_input_port(0, &filter, 0);
filter.set_input_port(0, &generator, 0);
filter.process(1024 * 64);
checker.process(PROCESSSIZE);
}
TEST(IIRFilter, RobertBristowJohnsonBandPassCoefficients_2k_test)
{
ATK::SimpleSinusGeneratorFilter<double> generator;
generator.set_output_sampling_rate(1024 * 64);
generator.set_amplitude(1);
generator.set_frequency(2000);
ATK::IIRFilter<ATK::RobertBristowJohnsonBandPassCoefficients<double> > filter;
filter.set_input_sampling_rate(1024 * 64);
filter.set_output_sampling_rate(1024 * 64);
filter.set_Q(1);
filter.set_cut_frequency(100);
ATK::FFTCheckerFilter<double> checker;
checker.set_input_sampling_rate(1024 * 64);
std::vector<std::pair<int, double> > frequency_checks;
frequency_checks.push_back(std::make_pair(100, 0));
frequency_checks.push_back(std::make_pair(1000, 0));
frequency_checks.push_back(std::make_pair(2000, 0.22340318032490636));
checker.set_checks(frequency_checks);
checker.set_input_port(0, &filter, 0);
filter.set_input_port(0, &generator, 0);
filter.process(1024 * 64);
checker.process(PROCESSSIZE);
}
TEST(IIRFilter, RobertBristowJohnsonBandPass2Coefficients_1k_test)
{
ATK::SimpleSinusGeneratorFilter<double> generator;
generator.set_output_sampling_rate(1024 * 64);
generator.set_amplitude(1);
generator.set_frequency(1000);
ATK::IIRFilter<ATK::RobertBristowJohnsonBandPass2Coefficients<double> > filter;
filter.set_input_sampling_rate(1024 * 64);
filter.set_output_sampling_rate(1024 * 64);
filter.set_Q(1);
filter.set_cut_frequency(100);
ATK::FFTCheckerFilter<double> checker;
checker.set_input_sampling_rate(1024 * 64);
std::vector<std::pair<int, double> > frequency_checks;
frequency_checks.push_back(std::make_pair(100, 0));
frequency_checks.push_back(std::make_pair(1000, 0.3168938774681514));
frequency_checks.push_back(std::make_pair(10000, 0));
checker.set_checks(frequency_checks);
checker.set_input_port(0, &filter, 0);
filter.set_input_port(0, &generator, 0);
filter.process(1024 * 64);
checker.process(PROCESSSIZE);
}
TEST(IIRFilter, RobertBristowJohnsonBandPass2Coefficients_100_test)
{
ATK::SimpleSinusGeneratorFilter<double> generator;
generator.set_output_sampling_rate(1024 * 64);
generator.set_amplitude(1);
generator.set_frequency(100);
ATK::IIRFilter<ATK::RobertBristowJohnsonBandPass2Coefficients<double> > filter;
filter.set_input_sampling_rate(1024 * 64);
filter.set_output_sampling_rate(1024 * 64);
filter.set_Q(1);
filter.set_cut_frequency(100);
ATK::FFTCheckerFilter<double> checker;
checker.set_input_sampling_rate(1024 * 64);
std::vector<std::pair<int, double> > frequency_checks;
frequency_checks.push_back(std::make_pair(10, 0));
frequency_checks.push_back(std::make_pair(100, 1.));
frequency_checks.push_back(std::make_pair(1000, 0));
checker.set_checks(frequency_checks);
checker.set_input_port(0, &filter, 0);
filter.set_input_port(0, &generator, 0);
filter.process(1024 * 64);
checker.process(PROCESSSIZE);
}
TEST(IIRFilter, RobertBristowJohnsonBandPass2Coefficients_2k_test)
{
ATK::SimpleSinusGeneratorFilter<double> generator;
generator.set_output_sampling_rate(1024 * 64);
generator.set_amplitude(1);
generator.set_frequency(2000);
ATK::IIRFilter<ATK::RobertBristowJohnsonBandPass2Coefficients<double> > filter;
filter.set_input_sampling_rate(1024 * 64);
filter.set_output_sampling_rate(1024 * 64);
filter.set_Q(1);
filter.set_cut_frequency(100);
ATK::FFTCheckerFilter<double> checker;
checker.set_input_sampling_rate(1024 * 64);
std::vector<std::pair<int, double> > frequency_checks;
frequency_checks.push_back(std::make_pair(100, 0));
frequency_checks.push_back(std::make_pair(1000, 0));
frequency_checks.push_back(std::make_pair(2000, 0.22340318032490636));
checker.set_checks(frequency_checks);
checker.set_input_port(0, &filter, 0);
filter.set_input_port(0, &generator, 0);
filter.process(1024 * 64);
checker.process(PROCESSSIZE);
}
TEST(IIRFilter, RobertBristowJohnsonBandStopCoefficients_1k_test)
{
ATK::SimpleSinusGeneratorFilter<double> generator;
generator.set_output_sampling_rate(1024 * 64);
generator.set_amplitude(1);
generator.set_frequency(1000);
ATK::IIRFilter<ATK::RobertBristowJohnsonBandStopCoefficients<double> > filter;
filter.set_input_sampling_rate(1024 * 64);
filter.set_output_sampling_rate(1024 * 64);
filter.set_Q(1);
filter.set_cut_frequency(100);
ATK::FFTCheckerFilter<double> checker;
checker.set_input_sampling_rate(1024 * 64);
std::vector<std::pair<int, double> > frequency_checks;
frequency_checks.push_back(std::make_pair(100, 0));
frequency_checks.push_back(std::make_pair(1000, 0.9974692784275677));
frequency_checks.push_back(std::make_pair(10000, 0));
checker.set_checks(frequency_checks);
checker.set_input_port(0, &filter, 0);
filter.set_input_port(0, &generator, 0);
filter.process(1024 * 64);
checker.process(PROCESSSIZE);
}
TEST(IIRFilter, RobertBristowJohnsonBandStopCoefficients_100_test)
{
ATK::SimpleSinusGeneratorFilter<double> generator;
generator.set_output_sampling_rate(1024 * 64);
generator.set_amplitude(1);
generator.set_frequency(100);
ATK::IIRFilter<ATK::RobertBristowJohnsonBandStopCoefficients<double> > filter;
filter.set_input_sampling_rate(1024 * 64);
filter.set_output_sampling_rate(1024 * 64);
filter.set_Q(1);
filter.set_cut_frequency(100);
ATK::FFTCheckerFilter<double> checker;
checker.set_input_sampling_rate(1024 * 64);
std::vector<std::pair<int, double> > frequency_checks;
frequency_checks.push_back(std::make_pair(10, 0));
frequency_checks.push_back(std::make_pair(100, 6.701459011526403e-07));
frequency_checks.push_back(std::make_pair(1000, 0));
checker.set_checks(frequency_checks);
checker.set_input_port(0, &filter, 0);
filter.set_input_port(0, &generator, 0);
filter.process(1024 * 64);
checker.process(PROCESSSIZE);
}
TEST(IIRFilter, RobertBristowJohnsonBandStopCoefficients_2k_test)
{
ATK::SimpleSinusGeneratorFilter<double> generator;
generator.set_output_sampling_rate(1024 * 64);
generator.set_amplitude(1);
generator.set_frequency(2000);
ATK::IIRFilter<ATK::RobertBristowJohnsonBandStopCoefficients<double> > filter;
filter.set_input_sampling_rate(1024 * 64);
filter.set_output_sampling_rate(1024 * 64);
filter.set_Q(1);
filter.set_cut_frequency(100);
ATK::FFTCheckerFilter<double> checker;
checker.set_input_sampling_rate(1024 * 64);
std::vector<std::pair<int, double> > frequency_checks;
frequency_checks.push_back(std::make_pair(100, 0));
frequency_checks.push_back(std::make_pair(1000, 0));
frequency_checks.push_back(std::make_pair(2000, 0.9993766908751316));
checker.set_checks(frequency_checks);
checker.set_input_port(0, &filter, 0);
filter.set_input_port(0, &generator, 0);
filter.process(1024 * 64);
checker.process(PROCESSSIZE);
}
TEST(IIRFilter, RobertBristowJohnsonAllPassCoefficients_1k_test)
{
ATK::SimpleSinusGeneratorFilter<double> generator;
generator.set_output_sampling_rate(1024 * 64);
generator.set_amplitude(1);
generator.set_frequency(1000);
ATK::IIRFilter<ATK::RobertBristowJohnsonAllPassCoefficients<double> > filter;
filter.set_input_sampling_rate(1024 * 64);
filter.set_output_sampling_rate(1024 * 64);
filter.set_Q(.1);
filter.set_cut_frequency(100);
ATK::FFTCheckerFilter<double> checker;
checker.set_input_sampling_rate(1024 * 64);
std::vector<std::pair<int, double> > frequency_checks;
frequency_checks.push_back(std::make_pair(100, 0));
frequency_checks.push_back(std::make_pair(1000, 1));
frequency_checks.push_back(std::make_pair(10000, 0));
checker.set_checks(frequency_checks);
checker.set_input_port(0, &filter, 0);
filter.set_input_port(0, &generator, 0);
filter.process(1024 * 64);
checker.process(PROCESSSIZE);
}
TEST(IIRFilter, RobertBristowJohnsonAllPassCoefficients_100_test)
{
ATK::SimpleSinusGeneratorFilter<double> generator;
generator.set_output_sampling_rate(1024 * 64);
generator.set_amplitude(1);
generator.set_frequency(100);
ATK::IIRFilter<ATK::RobertBristowJohnsonAllPassCoefficients<double> > filter;
filter.set_input_sampling_rate(1024 * 64);
filter.set_output_sampling_rate(1024 * 64);
filter.set_Q(.1);
filter.set_cut_frequency(100);
ATK::FFTCheckerFilter<double> checker;
checker.set_input_sampling_rate(1024 * 64);
std::vector<std::pair<int, double> > frequency_checks;
frequency_checks.push_back(std::make_pair(10, 0));
frequency_checks.push_back(std::make_pair(100, 1));
frequency_checks.push_back(std::make_pair(1000, 0));
checker.set_checks(frequency_checks);
checker.set_input_port(0, &filter, 0);
filter.set_input_port(0, &generator, 0);
filter.process(1024 * 64);
checker.process(PROCESSSIZE);
}
TEST(IIRFilter, RobertBristowJohnsonAllPassCoefficients_2k_test)
{
ATK::SimpleSinusGeneratorFilter<double> generator;
generator.set_output_sampling_rate(1024 * 64);
generator.set_amplitude(1);
generator.set_frequency(2000);
ATK::IIRFilter<ATK::RobertBristowJohnsonAllPassCoefficients<double> > filter;
filter.set_input_sampling_rate(1024 * 64);
filter.set_output_sampling_rate(1024 * 64);
filter.set_Q(.1);
filter.set_cut_frequency(100);
ATK::FFTCheckerFilter<double> checker;
checker.set_input_sampling_rate(1024 * 64);
std::vector<std::pair<int, double> > frequency_checks;
frequency_checks.push_back(std::make_pair(100, 0));
frequency_checks.push_back(std::make_pair(1000, 0));
frequency_checks.push_back(std::make_pair(2000, 1));
checker.set_checks(frequency_checks);
checker.set_input_port(0, &filter, 0);
filter.set_input_port(0, &generator, 0);
filter.process(1024 * 64);
checker.process(PROCESSSIZE);
}
TEST(IIRFilter, RobertBristowJohnsonBandPassPeakCoefficients_1k_test)
{
ATK::SimpleSinusGeneratorFilter<double> generator;
generator.set_output_sampling_rate(1024 * 64);
generator.set_amplitude(1);
generator.set_frequency(1000);
ATK::IIRFilter<ATK::RobertBristowJohnsonBandPassPeakCoefficients<double> > filter;
filter.set_input_sampling_rate(1024 * 64);
filter.set_output_sampling_rate(1024 * 64);
filter.set_Q(1);
filter.set_cut_frequency(100);
filter.set_gain(2);
ATK::FFTCheckerFilter<double> checker;
checker.set_input_sampling_rate(1024 * 64);
std::vector<std::pair<int, double> > frequency_checks;
frequency_checks.push_back(std::make_pair(100, 0));
frequency_checks.push_back(std::make_pair(1000, 1.0093931154905567));
frequency_checks.push_back(std::make_pair(10000, 0));
checker.set_checks(frequency_checks);
checker.set_input_port(0, &filter, 0);
filter.set_input_port(0, &generator, 0);
filter.process(1024 * 64);
checker.process(PROCESSSIZE);
}
TEST(IIRFilter, RobertBristowJohnsonBandPassPeakCoefficients_100_test)
{
ATK::SimpleSinusGeneratorFilter<double> generator;
generator.set_output_sampling_rate(1024 * 64);
generator.set_amplitude(1);
generator.set_frequency(100);
ATK::IIRFilter<ATK::RobertBristowJohnsonBandPassPeakCoefficients<double> > filter;
filter.set_input_sampling_rate(1024 * 64);
filter.set_output_sampling_rate(1024 * 64);
filter.set_Q(1);
filter.set_cut_frequency(100);
filter.set_gain(2);
ATK::FFTCheckerFilter<double> checker;
checker.set_input_sampling_rate(1024 * 64);
std::vector<std::pair<int, double> > frequency_checks;
frequency_checks.push_back(std::make_pair(10, 0));
frequency_checks.push_back(std::make_pair(100, 2.));
frequency_checks.push_back(std::make_pair(1000, 0));
checker.set_checks(frequency_checks);
checker.set_input_port(0, &filter, 0);
filter.set_input_port(0, &generator, 0);
filter.process(1024 * 64);
checker.process(PROCESSSIZE);
}
TEST(IIRFilter, RobertBristowJohnsonBandPassPeakCoefficients_2k_test)
{
ATK::SimpleSinusGeneratorFilter<double> generator;
generator.set_output_sampling_rate(1024 * 64);
generator.set_amplitude(1);
generator.set_frequency(2000);
ATK::IIRFilter<ATK::RobertBristowJohnsonBandPassPeakCoefficients<double> > filter;
filter.set_input_sampling_rate(1024 * 64);
filter.set_output_sampling_rate(1024 * 64);
filter.set_Q(1);
filter.set_cut_frequency(100);
filter.set_gain(2);
ATK::FFTCheckerFilter<double> checker;
checker.set_input_sampling_rate(1024 * 64);
std::vector<std::pair<int, double> > frequency_checks;
frequency_checks.push_back(std::make_pair(100, 0));
frequency_checks.push_back(std::make_pair(1000, 0));
frequency_checks.push_back(std::make_pair(2000, 1.0018333926095173));
checker.set_checks(frequency_checks);
checker.set_input_port(0, &filter, 0);
filter.set_input_port(0, &generator, 0);
filter.process(1024 * 64);
checker.process(PROCESSSIZE);
}
TEST(IIRFilter, RobertBristowJohnsonLowShelvingCoefficients_1k_test)
{
ATK::SimpleSinusGeneratorFilter<double> generator;
generator.set_output_sampling_rate(1024*64);
generator.set_amplitude(1);
generator.set_frequency(1000);
ATK::IIRFilter<ATK::RobertBristowJohnsonLowShelvingCoefficients<double> > filter;
filter.set_input_sampling_rate(1024*64);
filter.set_output_sampling_rate(1024*64);
filter.set_cut_frequency(100);
filter.set_gain(.5);
ATK::FFTCheckerFilter<double> checker;
checker.set_input_sampling_rate(1024*64);
std::vector<std::pair<int, double> > frequency_checks;
frequency_checks.push_back(std::make_pair(100, 0));
frequency_checks.push_back(std::make_pair(1000, 1.0037031041980957));
frequency_checks.push_back(std::make_pair(10000, 0));
checker.set_checks(frequency_checks);
checker.set_input_port(0, &filter, 0);
filter.set_input_port(0, &generator, 0);
filter.process(1024*64);
checker.process(PROCESSSIZE);
}
TEST(IIRFilter, RobertBristowJohnsonLowShelvingCoefficients_100_test)
{
ATK::SimpleSinusGeneratorFilter<double> generator;
generator.set_output_sampling_rate(1024*64);
generator.set_amplitude(1);
generator.set_frequency(100);
ATK::IIRFilter<ATK::RobertBristowJohnsonLowShelvingCoefficients<double> > filter;
filter.set_input_sampling_rate(1024*64);
filter.set_output_sampling_rate(1024*64);
filter.set_cut_frequency(100);
filter.set_gain(.5);
ATK::FFTCheckerFilter<double> checker;
checker.set_input_sampling_rate(1024*64);
std::vector<std::pair<int, double> > frequency_checks;
frequency_checks.push_back(std::make_pair(10, 0));
frequency_checks.push_back(std::make_pair(100, 0.7071067811865296));
frequency_checks.push_back(std::make_pair(1000, 0));
checker.set_checks(frequency_checks);
checker.set_input_port(0, &filter, 0);
filter.set_input_port(0, &generator, 0);
filter.process(1024*64);
checker.process(PROCESSSIZE);
}
TEST(IIRFilter, RobertBristowJohnsonLowShelvingCoefficients_200_test)
{
ATK::SimpleSinusGeneratorFilter<double> generator;
generator.set_output_sampling_rate(1024*64);
generator.set_amplitude(1);
generator.set_frequency(200);
ATK::IIRFilter<ATK::RobertBristowJohnsonLowShelvingCoefficients<double> > filter;
filter.set_input_sampling_rate(1024*64);
filter.set_output_sampling_rate(1024*64);
filter.set_cut_frequency(100);
filter.set_gain(.5);
ATK::FFTCheckerFilter<double> checker;
checker.set_input_sampling_rate(1024*64);
std::vector<std::pair<int, double> > frequency_checks;
frequency_checks.push_back(std::make_pair(100, 0));
frequency_checks.push_back(std::make_pair(200, 1.0439000773319405));
frequency_checks.push_back(std::make_pair(1000, 0));
checker.set_checks(frequency_checks);
checker.set_input_port(0, &filter, 0);
filter.set_input_port(0, &generator, 0);
filter.process(1024*64);
checker.process(PROCESSSIZE);
}
TEST(IIRFilter, RobertBristowJohnsonHighShelvingCoefficients_1k_test)
{
ATK::SimpleSinusGeneratorFilter<double> generator;
generator.set_output_sampling_rate(1024*64);
generator.set_amplitude(1);
generator.set_frequency(1000);
ATK::IIRFilter<ATK::RobertBristowJohnsonHighShelvingCoefficients<double> > filter;
filter.set_input_sampling_rate(1024*64);
filter.set_output_sampling_rate(1024*64);
filter.set_cut_frequency(1000);
filter.set_gain(.5);
ATK::FFTCheckerFilter<double> checker;
checker.set_input_sampling_rate(1024*64);
std::vector<std::pair<int, double> > frequency_checks;
frequency_checks.push_back(std::make_pair(100, 0));
frequency_checks.push_back(std::make_pair(1000, 0.7071067811865515));
frequency_checks.push_back(std::make_pair(10000, 0));
checker.set_checks(frequency_checks);
checker.set_input_port(0, &filter, 0);
filter.set_input_port(0, &generator, 0);
filter.process(1024*64);
checker.process(PROCESSSIZE);
}
TEST(IIRFilter, RobertBristowJohnsonHighShelvingCoefficients_10k_test)
{
ATK::SimpleSinusGeneratorFilter<double> generator;
generator.set_output_sampling_rate(1024*64);
generator.set_amplitude(1);
generator.set_frequency(10000);
ATK::IIRFilter<ATK::RobertBristowJohnsonHighShelvingCoefficients<double> > filter;
filter.set_input_sampling_rate(1024*64);
filter.set_output_sampling_rate(1024*64);
filter.set_cut_frequency(1000);
filter.set_gain(.5);
ATK::FFTCheckerFilter<double> checker;
checker.set_input_sampling_rate(1024*64);
std::vector<std::pair<int, double> > frequency_checks;
frequency_checks.push_back(std::make_pair(100, 0));
frequency_checks.push_back(std::make_pair(10000, 0.4984228523764117));
frequency_checks.push_back(std::make_pair(1000, 0));
checker.set_checks(frequency_checks);
checker.set_input_port(0, &filter, 0);
filter.set_input_port(0, &generator, 0);
filter.process(1024*64);
checker.process(PROCESSSIZE);
}
TEST(IIRFilter, RobertBristowJohnsonHighShelvingCoefficients_500_test)
{
ATK::SimpleSinusGeneratorFilter<double> generator;
generator.set_output_sampling_rate(1024*64);
generator.set_amplitude(1);
generator.set_frequency(500);
ATK::IIRFilter<ATK::RobertBristowJohnsonHighShelvingCoefficients<double> > filter;
filter.set_input_sampling_rate(1024*64);
filter.set_output_sampling_rate(1024*64);
filter.set_cut_frequency(1000);
filter.set_gain(.5);
ATK::FFTCheckerFilter<double> checker;
checker.set_input_sampling_rate(1024*64);
std::vector<std::pair<int, double> > frequency_checks;
frequency_checks.push_back(std::make_pair(100, 0));
frequency_checks.push_back(std::make_pair(1000, 0));
frequency_checks.push_back(std::make_pair(500, 1.0439302711974656));
checker.set_checks(frequency_checks);
checker.set_input_port(0, &filter, 0);
filter.set_input_port(0, &generator, 0);
filter.process(1024*64);
checker.process(PROCESSSIZE);
}
| 33.342942 | 84 | 0.780401 | [
"vector"
] |
8fe9ae866f3149b3cecca33f4a5cf5d3b0b342a8 | 6,832 | cpp | C++ | src/Lib/sctp/SctpH264RtpPolicyManager.cpp | miseri/rtp_plus_plus | 244ddd86f40f15247dd39ae7f9283114c2ef03a2 | [
"BSD-3-Clause"
] | 1 | 2021-07-14T08:15:05.000Z | 2021-07-14T08:15:05.000Z | src/Lib/sctp/SctpH264RtpPolicyManager.cpp | 7956968/rtp_plus_plus | 244ddd86f40f15247dd39ae7f9283114c2ef03a2 | [
"BSD-3-Clause"
] | null | null | null | src/Lib/sctp/SctpH264RtpPolicyManager.cpp | 7956968/rtp_plus_plus | 244ddd86f40f15247dd39ae7f9283114c2ef03a2 | [
"BSD-3-Clause"
] | 2 | 2021-07-14T08:15:02.000Z | 2021-07-14T08:56:10.000Z | #include "CorePch.h"
#include <rtp++/media/h264/H264NalUnitTypes.h>
#include <rtp++/media/h264/SvcExtensionHeader.h>
#include <rtp++/sctp/SctpH264RtpPolicyManager.h>
namespace rtp_plus_plus
{
using namespace media::h264;
using media::MediaSample;
namespace sctp
{
SctpH264RtpPolicyManager::SctpH264RtpPolicyManager()
:m_uiLastAuIndex(0),
m_uiLevelIndex(0)
{
}
void SctpH264RtpPolicyManager::setPolicy(const SctpRtpPolicy &sctpPolicy)
{
m_sctpPolicy = sctpPolicy;
}
uint32_t SctpH264RtpPolicyManager::getRtpChannelForAvcMedia(const MediaSample& mediaSample)
{
const std::vector<PolicyDescriptor>& policies = m_sctpPolicy.getAdditionalRtpPolicies();
// first check if there is a policy for the NAL type
for (const PolicyDescriptor& desc: policies)
{
if (desc.FrameType == FRAME_TYPE_NALU)
{
NalUnitType eType = getNalUnitType(mediaSample);
if (eType == desc.NaluType)
return desc.Channel_Id;
}
}
// otherwise check if there is a rule for AVC frame type
int32_t iFrameType = determineAvcFrameType(mediaSample);
for (const PolicyDescriptor& desc: policies)
{
if (desc.FrameType == iFrameType)
{
return desc.Channel_Id;
}
}
// else use default RTP policy
return m_sctpPolicy.getRtpPolicy().Channel_Id;
}
uint32_t SctpH264RtpPolicyManager::getRtpChannelForAvcMedia(const std::vector<MediaSample>& vMediaSamples)
{
const std::vector<PolicyDescriptor>& policies = m_sctpPolicy.getAdditionalRtpPolicies();
int32_t iMostImportantFrameType = determineAvcAccessUnitImportance(vMediaSamples);
for (const PolicyDescriptor& desc: policies)
{
if (desc.FrameType == iMostImportantFrameType)
{
return desc.Channel_Id;
}
}
// else use default RTP policy
return m_sctpPolicy.getRtpPolicy().Channel_Id;
}
bool areDQTSet(const PolicyDescriptor& desc)
{
return (desc.D_L_ID != TYPE_NOT_SET && desc.Q_T_ID != TYPE_NOT_SET && desc.T_ID != TYPE_NOT_SET);
}
bool areDQTSet(int32_t iD, int32_t iQ,int32_t iT)
{
return (iD != TYPE_NOT_SET && iQ != TYPE_NOT_SET && iT != TYPE_NOT_SET);
}
const uint32_t LEVEL[] = {0, 2, 1, 2};
uint32_t SctpH264RtpPolicyManager::getRtpChannelForSvcMedia(const MediaSample& mediaSample, uint32_t uiAccessUnitNumber)
{
if (uiAccessUnitNumber != m_uiLastAuIndex)
{
m_uiLevelIndex = (m_uiLevelIndex + 1)%4;
m_uiLastAuIndex = uiAccessUnitNumber;
}
uint32_t uiTemporalLevel = LEVEL[m_uiLevelIndex];
const std::vector<PolicyDescriptor>& policies = m_sctpPolicy.getAdditionalRtpPolicies();
NalUnitType eType = getNalUnitType(mediaSample);
// first check if there is a policy for the NAL type
for (int i = policies.size() - 1; i >= 0 ; --i)
{
const PolicyDescriptor& desc = policies[i];
if (desc.Layer == LAYER_TYPE_NALU)
{
if (eType == desc.NaluType)
{
// check if the descriptor is for all types, or only specific ones
if (areDQTSet(desc))
{
// Must match on DQT
// get DQT of media sample if possible
int32_t iD = 0, iQ = 0, iT = 0;
determineSvcLayer(mediaSample, iD, iQ, iT);
if (areDQTSet(iD, iQ, iT))
{
if (desc.D_L_ID == iD &&
desc.Q_T_ID == iQ &&
desc.T_ID == iT)
{
// MATCH on DQT
return desc.Channel_Id;
}
}
}
else
{
// match suffices
return desc.Channel_Id;
}
}
}
}
// Look for DQT match
int32_t iD = 0, iQ = 0, iT = 0;
int32_t iLayer = determineSvcLayer(mediaSample, iD, iQ, iT);
// HACK: override and use predefined T
iT = uiTemporalLevel;
for (int i = policies.size() - 1; i >= 0 ; --i)
{
const PolicyDescriptor& desc = policies[i];
if (iD != -1 && iQ != -1 && iT != -1)
{
if (desc.D_L_ID == iD &&
desc.Q_T_ID == iQ &&
desc.T_ID == iT)
{
return desc.Channel_Id;
}
}
}
// just try match on layer
for (int i = policies.size() - 1; i >= 0 ; --i)
{
const PolicyDescriptor& desc = policies[i];
if (desc.Layer == iLayer)
{
return desc.Channel_Id;
}
}
// else use default RTP policy
VLOG(2) << "No rule found for NALU: "
<< eType << " Layer:" << iLayer
<< " DQT: " << iD << ":" << iQ << ":" << iT;
return m_sctpPolicy.getRtpPolicy().Channel_Id;
}
int32_t SctpH264RtpPolicyManager::determineAvcFrameType(const MediaSample& mediaSample)
{
using namespace media::h264;
NalUnitType eType = getNalUnitType(mediaSample);
VLOG(15) << "NAL Unit Type: " << eType;
switch (eType)
{
case NUT_CODED_SLICE_OF_A_NON_IDR_PICTURE:
case NUT_SUPPLEMENTAL_ENHANCEMENT_INFORMATION_SEI:
{
return sctp::FRAME_TYPE_P;
break;
}
case NUT_CODED_SLICE_OF_AN_IDR_PICTURE:
case NUT_SEQUENCE_PARAMETER_SET:
case NUT_PICTURE_PARAMETER_SET:
case NUT_SUBSET_SEQUENCE_PARAMETER_SET:
{
return sctp::FRAME_TYPE_I;
break;
}
case NUT_ACCESS_UNIT_DELIMITER:
case NUT_PREFIX_NAL_UNIT:
default:
{
return sctp::FRAME_TYPE_B;
break;
}
}
}
int32_t SctpH264RtpPolicyManager::determineAvcAccessUnitImportance(const std::vector<MediaSample>& vMediaSamples)
{
// start with least importance
int iMaxFrameImportance = sctp::FRAME_TYPE_B;
for (size_t i = 0; i < vMediaSamples.size(); ++i)
{
int32_t iFrameImportance = determineAvcFrameType(vMediaSamples[i]);
VLOG(2) << "NAL Unit Type: " << media::h264::getNalUnitType(vMediaSamples[i]) << " Frame type: " << iFrameImportance;
if (iFrameImportance < iMaxFrameImportance)
{
iMaxFrameImportance = iFrameImportance;
}
}
return iMaxFrameImportance;
}
int32_t SctpH264RtpPolicyManager::determineSvcLayer(const MediaSample& mediaSample, int32_t& iD, int32_t& iQ, int32_t& iT)
{
using namespace media::h264;
NalUnitType eType = getNalUnitType(mediaSample);
switch (eType)
{
case NUT_PREFIX_NAL_UNIT:
{
boost::optional<svc::SvcExtensionHeader> pSvcHeader = svc::extractSvcExtensionHeader(mediaSample);
if (pSvcHeader)
{
iD = pSvcHeader->dependency_id;
iQ = pSvcHeader->quality_id;
iT = pSvcHeader->temporal_id;
}
return LAYER_TYPE_BL;
break;
}
case NUT_CODED_SLICE_EXT:
case NUT_RESERVED_21: /* SVC encoder not updated to latest version of standard */
{
boost::optional<svc::SvcExtensionHeader> pSvcHeader = svc::extractSvcExtensionHeader(mediaSample);
if (pSvcHeader)
{
iD = pSvcHeader->dependency_id;
iQ = pSvcHeader->quality_id;
iT = pSvcHeader->temporal_id;
}
return LAYER_TYPE_EL;
break;
}
default:
{
return LAYER_TYPE_BL;
}
}
}
}
}
| 27.111111 | 122 | 0.655591 | [
"vector"
] |
8feeb614c16c90204a023b964036363fc8dcec74 | 164,156 | cpp | C++ | runtime/test/TestValidateModel.cpp | aosp-goes-brrbrr/packages_modules_NeuralNetworks | 87a14e21ce905ce7c4584fe9a53e4397a4d33c67 | [
"Apache-2.0"
] | null | null | null | runtime/test/TestValidateModel.cpp | aosp-goes-brrbrr/packages_modules_NeuralNetworks | 87a14e21ce905ce7c4584fe9a53e4397a4d33c67 | [
"Apache-2.0"
] | null | null | null | runtime/test/TestValidateModel.cpp | aosp-goes-brrbrr/packages_modules_NeuralNetworks | 87a14e21ce905ce7c4584fe9a53e4397a4d33c67 | [
"Apache-2.0"
] | 2 | 2021-11-28T11:20:31.000Z | 2021-11-28T11:28:38.000Z | /*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include "NeuralNetworks.h"
namespace {
class ValidateModelTest : public ::testing::Test {
protected:
virtual void SetUp() {}
};
TEST_F(ValidateModelTest, MaskRCNN2Go) {
ANeuralNetworksModel* model = nullptr;
ASSERT_EQ(ANeuralNetworksModel_create(&model), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_0{};
operand_0.type = ANEURALNETWORKS_BOOL;
operand_0.scale = 0;
operand_0.zeroPoint = 0;
operand_0.dimensionCount = 0;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_0), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_1{};
operand_1.type = ANEURALNETWORKS_BOOL;
operand_1.scale = 0;
operand_1.zeroPoint = 0;
operand_1.dimensionCount = 0;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_1), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_2{};
operand_2.type = ANEURALNETWORKS_TENSOR_FLOAT32;
operand_2.scale = 0;
operand_2.zeroPoint = 0;
operand_2.dimensionCount = 4;
const uint32_t dimensions_2[] = {1, 3, 0, 0};
operand_2.dimensions = dimensions_2;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_2), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_3{};
operand_3.type = ANEURALNETWORKS_TENSOR_FLOAT32;
operand_3.scale = 0;
operand_3.zeroPoint = 0;
operand_3.dimensionCount = 2;
const uint32_t dimensions_3[] = {1, 3};
operand_3.dimensions = dimensions_3;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_3), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_4{};
operand_4.type = ANEURALNETWORKS_TENSOR_FLOAT32;
operand_4.scale = 0;
operand_4.zeroPoint = 0;
operand_4.dimensionCount = 2;
const uint32_t dimensions_4[] = {1, 2};
operand_4.dimensions = dimensions_4;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_4), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_5{};
operand_5.type = ANEURALNETWORKS_TENSOR_QUANT16_ASYMM;
operand_5.scale = 0.125;
operand_5.zeroPoint = 0;
operand_5.dimensionCount = 2;
const uint32_t dimensions_5[] = {1, 2};
operand_5.dimensions = dimensions_5;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_5), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_6{};
operand_6.type = ANEURALNETWORKS_TENSOR_INT32;
operand_6.scale = 0;
operand_6.zeroPoint = 0;
operand_6.dimensionCount = 1;
const uint32_t dimensions_6[] = {4};
operand_6.dimensions = dimensions_6;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_6), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_7{};
operand_7.type = ANEURALNETWORKS_TENSOR_FLOAT32;
operand_7.scale = 0;
operand_7.zeroPoint = 0;
operand_7.dimensionCount = 4;
const uint32_t dimensions_7[] = {1, 0, 0, 3};
operand_7.dimensions = dimensions_7;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_7), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_8{};
operand_8.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_8.scale = 0.9891946315765381;
operand_8.zeroPoint = 0;
operand_8.dimensionCount = 4;
const uint32_t dimensions_8[] = {1, 0, 0, 3};
operand_8.dimensions = dimensions_8;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_8), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_9{};
operand_9.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_9.scale = 5.880743992747739e-05;
operand_9.zeroPoint = 95;
operand_9.dimensionCount = 4;
const uint32_t dimensions_9[] = {16, 3, 3, 3};
operand_9.dimensions = dimensions_9;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_9), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_10{};
operand_10.type = ANEURALNETWORKS_TENSOR_INT32;
operand_10.scale = 5.81720050831791e-05;
operand_10.zeroPoint = 0;
operand_10.dimensionCount = 1;
const uint32_t dimensions_10[] = {16};
operand_10.dimensions = dimensions_10;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_10), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_11{};
operand_11.type = ANEURALNETWORKS_INT32;
operand_11.scale = 0;
operand_11.zeroPoint = 0;
operand_11.dimensionCount = 0;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_11), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_12{};
operand_12.type = ANEURALNETWORKS_INT32;
operand_12.scale = 0;
operand_12.zeroPoint = 0;
operand_12.dimensionCount = 0;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_12), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_13{};
operand_13.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_13.scale = 0.01966476067900658;
operand_13.zeroPoint = 0;
operand_13.dimensionCount = 4;
const uint32_t dimensions_13[] = {1, 0, 0, 16};
operand_13.dimensions = dimensions_13;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_13), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_14{};
operand_14.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_14.scale = 0.01236020401120186;
operand_14.zeroPoint = 94;
operand_14.dimensionCount = 4;
const uint32_t dimensions_14[] = {16, 1, 1, 16};
operand_14.dimensions = dimensions_14;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_14), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_15{};
operand_15.type = ANEURALNETWORKS_TENSOR_INT32;
operand_15.scale = 0.0002430604654364288;
operand_15.zeroPoint = 0;
operand_15.dimensionCount = 1;
const uint32_t dimensions_15[] = {16};
operand_15.dimensions = dimensions_15;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_15), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_16{};
operand_16.type = ANEURALNETWORKS_INT32;
operand_16.scale = 0;
operand_16.zeroPoint = 0;
operand_16.dimensionCount = 0;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_16), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_17{};
operand_17.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_17.scale = 0.01199939660727978;
operand_17.zeroPoint = 0;
operand_17.dimensionCount = 4;
const uint32_t dimensions_17[] = {1, 0, 0, 16};
operand_17.dimensions = dimensions_17;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_17), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_18{};
operand_18.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_18.scale = 0.006678132340312004;
operand_18.zeroPoint = 124;
operand_18.dimensionCount = 4;
const uint32_t dimensions_18[] = {1, 3, 3, 16};
operand_18.dimensions = dimensions_18;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_18), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_19{};
operand_19.type = ANEURALNETWORKS_TENSOR_INT32;
operand_19.scale = 8.013355545699596e-05;
operand_19.zeroPoint = 0;
operand_19.dimensionCount = 1;
const uint32_t dimensions_19[] = {16};
operand_19.dimensions = dimensions_19;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_19), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_20{};
operand_20.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_20.scale = 0.01280416082590818;
operand_20.zeroPoint = 136;
operand_20.dimensionCount = 4;
const uint32_t dimensions_20[] = {1, 0, 0, 16};
operand_20.dimensions = dimensions_20;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_20), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_21{};
operand_21.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_21.scale = 0.02433430217206478;
operand_21.zeroPoint = 111;
operand_21.dimensionCount = 4;
const uint32_t dimensions_21[] = {16, 1, 1, 16};
operand_21.dimensions = dimensions_21;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_21), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_22{};
operand_22.type = ANEURALNETWORKS_TENSOR_INT32;
operand_22.scale = 0.0003115803119726479;
operand_22.zeroPoint = 0;
operand_22.dimensionCount = 1;
const uint32_t dimensions_22[] = {16};
operand_22.dimensions = dimensions_22;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_22), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_23{};
operand_23.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_23.scale = 0.04481548070907593;
operand_23.zeroPoint = 132;
operand_23.dimensionCount = 4;
const uint32_t dimensions_23[] = {1, 0, 0, 16};
operand_23.dimensions = dimensions_23;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_23), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_24{};
operand_24.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_24.scale = 0.04634242877364159;
operand_24.zeroPoint = 128;
operand_24.dimensionCount = 4;
const uint32_t dimensions_24[] = {1, 0, 0, 16};
operand_24.dimensions = dimensions_24;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_24), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_25{};
operand_25.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_25.scale = 0.005194671452045441;
operand_25.zeroPoint = 158;
operand_25.dimensionCount = 4;
const uint32_t dimensions_25[] = {96, 1, 1, 16};
operand_25.dimensions = dimensions_25;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_25), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_26{};
operand_26.type = ANEURALNETWORKS_TENSOR_INT32;
operand_26.scale = 0.0002407336869509891;
operand_26.zeroPoint = 0;
operand_26.dimensionCount = 1;
const uint32_t dimensions_26[] = {96};
operand_26.dimensions = dimensions_26;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_26), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_27{};
operand_27.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_27.scale = 0.01568881794810295;
operand_27.zeroPoint = 0;
operand_27.dimensionCount = 4;
const uint32_t dimensions_27[] = {1, 0, 0, 96};
operand_27.dimensions = dimensions_27;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_27), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_28{};
operand_28.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_28.scale = 0.001355677493847907;
operand_28.zeroPoint = 127;
operand_28.dimensionCount = 4;
const uint32_t dimensions_28[] = {1, 3, 3, 96};
operand_28.dimensions = dimensions_28;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_28), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_29{};
operand_29.type = ANEURALNETWORKS_TENSOR_INT32;
operand_29.scale = 2.126897743437439e-05;
operand_29.zeroPoint = 0;
operand_29.dimensionCount = 1;
const uint32_t dimensions_29[] = {96};
operand_29.dimensions = dimensions_29;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_29), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_30{};
operand_30.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_30.scale = 0.01245978008955717;
operand_30.zeroPoint = 123;
operand_30.dimensionCount = 4;
const uint32_t dimensions_30[] = {1, 0, 0, 96};
operand_30.dimensions = dimensions_30;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_30), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_31{};
operand_31.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_31.scale = 0.01157373003661633;
operand_31.zeroPoint = 134;
operand_31.dimensionCount = 4;
const uint32_t dimensions_31[] = {32, 1, 1, 96};
operand_31.dimensions = dimensions_31;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_31), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_32{};
operand_32.type = ANEURALNETWORKS_TENSOR_INT32;
operand_32.scale = 0.000144206132972613;
operand_32.zeroPoint = 0;
operand_32.dimensionCount = 1;
const uint32_t dimensions_32[] = {32};
operand_32.dimensions = dimensions_32;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_32), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_33{};
operand_33.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_33.scale = 0.01940538175404072;
operand_33.zeroPoint = 135;
operand_33.dimensionCount = 4;
const uint32_t dimensions_33[] = {1, 0, 0, 32};
operand_33.dimensions = dimensions_33;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_33), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_34{};
operand_34.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_34.scale = 0.003280390985310078;
operand_34.zeroPoint = 129;
operand_34.dimensionCount = 4;
const uint32_t dimensions_34[] = {192, 1, 1, 32};
operand_34.dimensions = dimensions_34;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_34), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_35{};
operand_35.type = ANEURALNETWORKS_TENSOR_INT32;
operand_35.scale = 6.365723675116897e-05;
operand_35.zeroPoint = 0;
operand_35.dimensionCount = 1;
const uint32_t dimensions_35[] = {192};
operand_35.dimensions = dimensions_35;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_35), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_36{};
operand_36.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_36.scale = 0.005680288188159466;
operand_36.zeroPoint = 0;
operand_36.dimensionCount = 4;
const uint32_t dimensions_36[] = {1, 0, 0, 192};
operand_36.dimensions = dimensions_36;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_36), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_37{};
operand_37.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_37.scale = 0.002816423308104277;
operand_37.zeroPoint = 131;
operand_37.dimensionCount = 4;
const uint32_t dimensions_37[] = {1, 3, 3, 192};
operand_37.dimensions = dimensions_37;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_37), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_38{};
operand_38.type = ANEURALNETWORKS_TENSOR_INT32;
operand_38.scale = 1.599809547769837e-05;
operand_38.zeroPoint = 0;
operand_38.dimensionCount = 1;
const uint32_t dimensions_38[] = {192};
operand_38.dimensions = dimensions_38;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_38), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_39{};
operand_39.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_39.scale = 0.002300027292221785;
operand_39.zeroPoint = 111;
operand_39.dimensionCount = 4;
const uint32_t dimensions_39[] = {1, 0, 0, 192};
operand_39.dimensions = dimensions_39;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_39), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_40{};
operand_40.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_40.scale = 0.02601869031786919;
operand_40.zeroPoint = 133;
operand_40.dimensionCount = 4;
const uint32_t dimensions_40[] = {32, 1, 1, 192};
operand_40.dimensions = dimensions_40;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_40), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_41{};
operand_41.type = ANEURALNETWORKS_TENSOR_INT32;
operand_41.scale = 5.984370000078343e-05;
operand_41.zeroPoint = 0;
operand_41.dimensionCount = 1;
const uint32_t dimensions_41[] = {32};
operand_41.dimensions = dimensions_41;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_41), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_42{};
operand_42.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_42.scale = 0.01957281865179539;
operand_42.zeroPoint = 126;
operand_42.dimensionCount = 4;
const uint32_t dimensions_42[] = {1, 0, 0, 32};
operand_42.dimensions = dimensions_42;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_42), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_43{};
operand_43.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_43.scale = 0.028990238904953;
operand_43.zeroPoint = 123;
operand_43.dimensionCount = 4;
const uint32_t dimensions_43[] = {1, 0, 0, 32};
operand_43.dimensions = dimensions_43;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_43), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_44{};
operand_44.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_44.scale = 0.002658893587067723;
operand_44.zeroPoint = 135;
operand_44.dimensionCount = 4;
const uint32_t dimensions_44[] = {192, 1, 1, 32};
operand_44.dimensions = dimensions_44;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_44), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_45{};
operand_45.type = ANEURALNETWORKS_TENSOR_INT32;
operand_45.scale = 7.708196062594652e-05;
operand_45.zeroPoint = 0;
operand_45.dimensionCount = 1;
const uint32_t dimensions_45[] = {192};
operand_45.dimensions = dimensions_45;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_45), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_46{};
operand_46.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_46.scale = 0.009067215956747532;
operand_46.zeroPoint = 0;
operand_46.dimensionCount = 4;
const uint32_t dimensions_46[] = {1, 0, 0, 192};
operand_46.dimensions = dimensions_46;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_46), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_47{};
operand_47.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_47.scale = 0.001217219163663685;
operand_47.zeroPoint = 125;
operand_47.dimensionCount = 4;
const uint32_t dimensions_47[] = {1, 3, 3, 192};
operand_47.dimensions = dimensions_47;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_47), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_48{};
operand_48.type = ANEURALNETWORKS_TENSOR_INT32;
operand_48.scale = 1.103678914660122e-05;
operand_48.zeroPoint = 0;
operand_48.dimensionCount = 1;
const uint32_t dimensions_48[] = {192};
operand_48.dimensions = dimensions_48;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_48), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_49{};
operand_49.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_49.scale = 0.003552014008164406;
operand_49.zeroPoint = 130;
operand_49.dimensionCount = 4;
const uint32_t dimensions_49[] = {1, 0, 0, 192};
operand_49.dimensions = dimensions_49;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_49), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_50{};
operand_50.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_50.scale = 0.01093960553407669;
operand_50.zeroPoint = 125;
operand_50.dimensionCount = 4;
const uint32_t dimensions_50[] = {48, 1, 1, 192};
operand_50.dimensions = dimensions_50;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_50), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_51{};
operand_51.type = ANEURALNETWORKS_TENSOR_INT32;
operand_51.scale = 3.885763362632133e-05;
operand_51.zeroPoint = 0;
operand_51.dimensionCount = 1;
const uint32_t dimensions_51[] = {48};
operand_51.dimensions = dimensions_51;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_51), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_52{};
operand_52.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_52.scale = 0.01332638971507549;
operand_52.zeroPoint = 115;
operand_52.dimensionCount = 4;
const uint32_t dimensions_52[] = {1, 0, 0, 48};
operand_52.dimensions = dimensions_52;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_52), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_53{};
operand_53.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_53.scale = 0.003872227622196078;
operand_53.zeroPoint = 110;
operand_53.dimensionCount = 4;
const uint32_t dimensions_53[] = {288, 1, 1, 48};
operand_53.dimensions = dimensions_53;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_53), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_54{};
operand_54.type = ANEURALNETWORKS_TENSOR_INT32;
operand_54.scale = 5.160281580174342e-05;
operand_54.zeroPoint = 0;
operand_54.dimensionCount = 1;
const uint32_t dimensions_54[] = {288};
operand_54.dimensions = dimensions_54;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_54), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_55{};
operand_55.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_55.scale = 0.005248025059700012;
operand_55.zeroPoint = 0;
operand_55.dimensionCount = 4;
const uint32_t dimensions_55[] = {1, 0, 0, 288};
operand_55.dimensions = dimensions_55;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_55), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_56{};
operand_56.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_56.scale = 0.001976602710783482;
operand_56.zeroPoint = 121;
operand_56.dimensionCount = 4;
const uint32_t dimensions_56[] = {1, 3, 3, 288};
operand_56.dimensions = dimensions_56;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_56), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_57{};
operand_57.type = ANEURALNETWORKS_TENSOR_INT32;
operand_57.scale = 1.037326001096517e-05;
operand_57.zeroPoint = 0;
operand_57.dimensionCount = 1;
const uint32_t dimensions_57[] = {288};
operand_57.dimensions = dimensions_57;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_57), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_58{};
operand_58.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_58.scale = 0.001622712821699679;
operand_58.zeroPoint = 128;
operand_58.dimensionCount = 4;
const uint32_t dimensions_58[] = {1, 0, 0, 288};
operand_58.dimensions = dimensions_58;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_58), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_59{};
operand_59.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_59.scale = 0.01881795562803745;
operand_59.zeroPoint = 132;
operand_59.dimensionCount = 4;
const uint32_t dimensions_59[] = {48, 1, 1, 288};
operand_59.dimensions = dimensions_59;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_59), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_60{};
operand_60.type = ANEURALNETWORKS_TENSOR_INT32;
operand_60.scale = 3.053613909287378e-05;
operand_60.zeroPoint = 0;
operand_60.dimensionCount = 1;
const uint32_t dimensions_60[] = {48};
operand_60.dimensions = dimensions_60;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_60), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_61{};
operand_61.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_61.scale = 0.01099279243499041;
operand_61.zeroPoint = 126;
operand_61.dimensionCount = 4;
const uint32_t dimensions_61[] = {1, 0, 0, 48};
operand_61.dimensions = dimensions_61;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_61), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_62{};
operand_62.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_62.scale = 0.01927739381790161;
operand_62.zeroPoint = 118;
operand_62.dimensionCount = 4;
const uint32_t dimensions_62[] = {1, 0, 0, 48};
operand_62.dimensions = dimensions_62;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_62), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_63{};
operand_63.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_63.scale = 0.00215660990215838;
operand_63.zeroPoint = 111;
operand_63.dimensionCount = 4;
const uint32_t dimensions_63[] = {288, 1, 1, 48};
operand_63.dimensions = dimensions_63;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_63), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_64{};
operand_64.type = ANEURALNETWORKS_TENSOR_INT32;
operand_64.scale = 4.157381772529334e-05;
operand_64.zeroPoint = 0;
operand_64.dimensionCount = 1;
const uint32_t dimensions_64[] = {288};
operand_64.dimensions = dimensions_64;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_64), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_65{};
operand_65.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_65.scale = 0.004311998840421438;
operand_65.zeroPoint = 0;
operand_65.dimensionCount = 4;
const uint32_t dimensions_65[] = {1, 0, 0, 288};
operand_65.dimensions = dimensions_65;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_65), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_66{};
operand_66.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_66.scale = 0.001798613811843097;
operand_66.zeroPoint = 128;
operand_66.dimensionCount = 4;
const uint32_t dimensions_66[] = {1, 3, 3, 288};
operand_66.dimensions = dimensions_66;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_66), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_67{};
operand_67.type = ANEURALNETWORKS_TENSOR_INT32;
operand_67.scale = 7.755620572424959e-06;
operand_67.zeroPoint = 0;
operand_67.dimensionCount = 1;
const uint32_t dimensions_67[] = {288};
operand_67.dimensions = dimensions_67;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_67), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_68{};
operand_68.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_68.scale = 0.001595283509232104;
operand_68.zeroPoint = 122;
operand_68.dimensionCount = 4;
const uint32_t dimensions_68[] = {1, 0, 0, 288};
operand_68.dimensions = dimensions_68;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_68), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_69{};
operand_69.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_69.scale = 0.02731921337544918;
operand_69.zeroPoint = 136;
operand_69.dimensionCount = 4;
const uint32_t dimensions_69[] = {48, 1, 1, 288};
operand_69.dimensions = dimensions_69;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_69), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_70{};
operand_70.type = ANEURALNETWORKS_TENSOR_INT32;
operand_70.scale = 4.358188743935898e-05;
operand_70.zeroPoint = 0;
operand_70.dimensionCount = 1;
const uint32_t dimensions_70[] = {48};
operand_70.dimensions = dimensions_70;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_70), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_71{};
operand_71.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_71.scale = 0.01208362448960543;
operand_71.zeroPoint = 120;
operand_71.dimensionCount = 4;
const uint32_t dimensions_71[] = {1, 0, 0, 48};
operand_71.dimensions = dimensions_71;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_71), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_72{};
operand_72.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_72.scale = 0.02560163103044033;
operand_72.zeroPoint = 107;
operand_72.dimensionCount = 4;
const uint32_t dimensions_72[] = {1, 0, 0, 48};
operand_72.dimensions = dimensions_72;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_72), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_73{};
operand_73.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_73.scale = 0.003050966653972864;
operand_73.zeroPoint = 125;
operand_73.dimensionCount = 4;
const uint32_t dimensions_73[] = {288, 1, 1, 48};
operand_73.dimensions = dimensions_73;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_73), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_74{};
operand_74.type = ANEURALNETWORKS_TENSOR_INT32;
operand_74.scale = 7.810971874278039e-05;
operand_74.zeroPoint = 0;
operand_74.dimensionCount = 1;
const uint32_t dimensions_74[] = {288};
operand_74.dimensions = dimensions_74;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_74), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_75{};
operand_75.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_75.scale = 0.01042873691767454;
operand_75.zeroPoint = 0;
operand_75.dimensionCount = 4;
const uint32_t dimensions_75[] = {1, 0, 0, 288};
operand_75.dimensions = dimensions_75;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_75), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_76{};
operand_76.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_76.scale = 0.00121846969705075;
operand_76.zeroPoint = 117;
operand_76.dimensionCount = 4;
const uint32_t dimensions_76[] = {1, 3, 3, 288};
operand_76.dimensions = dimensions_76;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_76), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_77{};
operand_77.type = ANEURALNETWORKS_TENSOR_INT32;
operand_77.scale = 1.270709981326945e-05;
operand_77.zeroPoint = 0;
operand_77.dimensionCount = 1;
const uint32_t dimensions_77[] = {288};
operand_77.dimensions = dimensions_77;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_77), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_78{};
operand_78.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_78.scale = 0.002883265493437648;
operand_78.zeroPoint = 137;
operand_78.dimensionCount = 4;
const uint32_t dimensions_78[] = {1, 0, 0, 288};
operand_78.dimensions = dimensions_78;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_78), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_79{};
operand_79.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_79.scale = 0.009875123389065266;
operand_79.zeroPoint = 131;
operand_79.dimensionCount = 4;
const uint32_t dimensions_79[] = {96, 1, 1, 288};
operand_79.dimensions = dimensions_79;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_79), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_80{};
operand_80.type = ANEURALNETWORKS_TENSOR_INT32;
operand_80.scale = 2.847260293492582e-05;
operand_80.zeroPoint = 0;
operand_80.dimensionCount = 1;
const uint32_t dimensions_80[] = {96};
operand_80.dimensions = dimensions_80;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_80), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_81{};
operand_81.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_81.scale = 0.009474765509366989;
operand_81.zeroPoint = 115;
operand_81.dimensionCount = 4;
const uint32_t dimensions_81[] = {1, 0, 0, 96};
operand_81.dimensions = dimensions_81;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_81), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_82{};
operand_82.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_82.scale = 0.00323105463758111;
operand_82.zeroPoint = 121;
operand_82.dimensionCount = 4;
const uint32_t dimensions_82[] = {576, 1, 1, 96};
operand_82.dimensions = dimensions_82;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_82), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_83{};
operand_83.type = ANEURALNETWORKS_TENSOR_INT32;
operand_83.scale = 3.061348616029136e-05;
operand_83.zeroPoint = 0;
operand_83.dimensionCount = 1;
const uint32_t dimensions_83[] = {576};
operand_83.dimensions = dimensions_83;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_83), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_84{};
operand_84.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_84.scale = 0.004371246788650751;
operand_84.zeroPoint = 0;
operand_84.dimensionCount = 4;
const uint32_t dimensions_84[] = {1, 0, 0, 576};
operand_84.dimensions = dimensions_84;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_84), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_85{};
operand_85.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_85.scale = 0.001316901994869113;
operand_85.zeroPoint = 132;
operand_85.dimensionCount = 4;
const uint32_t dimensions_85[] = {1, 3, 3, 576};
operand_85.dimensions = dimensions_85;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_85), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_86{};
operand_86.type = ANEURALNETWORKS_TENSOR_INT32;
operand_86.scale = 5.75650346945622e-06;
operand_86.zeroPoint = 0;
operand_86.dimensionCount = 1;
const uint32_t dimensions_86[] = {576};
operand_86.dimensions = dimensions_86;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_86), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_87{};
operand_87.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_87.scale = 0.001160673331469297;
operand_87.zeroPoint = 136;
operand_87.dimensionCount = 4;
const uint32_t dimensions_87[] = {1, 0, 0, 576};
operand_87.dimensions = dimensions_87;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_87), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_88{};
operand_88.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_88.scale = 0.01717966049909592;
operand_88.zeroPoint = 138;
operand_88.dimensionCount = 4;
const uint32_t dimensions_88[] = {96, 1, 1, 576};
operand_88.dimensions = dimensions_88;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_88), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_89{};
operand_89.type = ANEURALNETWORKS_TENSOR_INT32;
operand_89.scale = 1.993997466342989e-05;
operand_89.zeroPoint = 0;
operand_89.dimensionCount = 1;
const uint32_t dimensions_89[] = {96};
operand_89.dimensions = dimensions_89;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_89), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_90{};
operand_90.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_90.scale = 0.006981693673878908;
operand_90.zeroPoint = 120;
operand_90.dimensionCount = 4;
const uint32_t dimensions_90[] = {1, 0, 0, 96};
operand_90.dimensions = dimensions_90;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_90), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_91{};
operand_91.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_91.scale = 0.01042260229587555;
operand_91.zeroPoint = 124;
operand_91.dimensionCount = 4;
const uint32_t dimensions_91[] = {1, 0, 0, 96};
operand_91.dimensions = dimensions_91;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_91), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_92{};
operand_92.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_92.scale = 0.002388325287029147;
operand_92.zeroPoint = 120;
operand_92.dimensionCount = 4;
const uint32_t dimensions_92[] = {576, 1, 1, 96};
operand_92.dimensions = dimensions_92;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_92), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_93{};
operand_93.type = ANEURALNETWORKS_TENSOR_INT32;
operand_93.scale = 2.489256439730525e-05;
operand_93.zeroPoint = 0;
operand_93.dimensionCount = 1;
const uint32_t dimensions_93[] = {576};
operand_93.dimensions = dimensions_93;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_93), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_94{};
operand_94.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_94.scale = 0.003468555863946676;
operand_94.zeroPoint = 0;
operand_94.dimensionCount = 4;
const uint32_t dimensions_94[] = {1, 0, 0, 576};
operand_94.dimensions = dimensions_94;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_94), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_95{};
operand_95.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_95.scale = 0.001293058856390417;
operand_95.zeroPoint = 135;
operand_95.dimensionCount = 4;
const uint32_t dimensions_95[] = {1, 3, 3, 576};
operand_95.dimensions = dimensions_95;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_95), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_96{};
operand_96.type = ANEURALNETWORKS_TENSOR_INT32;
operand_96.scale = 4.485046702029649e-06;
operand_96.zeroPoint = 0;
operand_96.dimensionCount = 1;
const uint32_t dimensions_96[] = {576};
operand_96.dimensions = dimensions_96;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_96), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_97{};
operand_97.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_97.scale = 0.001004486111924052;
operand_97.zeroPoint = 121;
operand_97.dimensionCount = 4;
const uint32_t dimensions_97[] = {1, 0, 0, 576};
operand_97.dimensions = dimensions_97;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_97), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_98{};
operand_98.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_98.scale = 0.02229274623095989;
operand_98.zeroPoint = 132;
operand_98.dimensionCount = 4;
const uint32_t dimensions_98[] = {96, 1, 1, 576};
operand_98.dimensions = dimensions_98;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_98), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_99{};
operand_99.type = ANEURALNETWORKS_TENSOR_INT32;
operand_99.scale = 2.239275454485323e-05;
operand_99.zeroPoint = 0;
operand_99.dimensionCount = 1;
const uint32_t dimensions_99[] = {96};
operand_99.dimensions = dimensions_99;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_99), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_100{};
operand_100.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_100.scale = 0.00858442485332489;
operand_100.zeroPoint = 128;
operand_100.dimensionCount = 4;
const uint32_t dimensions_100[] = {1, 0, 0, 96};
operand_100.dimensions = dimensions_100;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_100), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_101{};
operand_101.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_101.scale = 0.01262346189469099;
operand_101.zeroPoint = 130;
operand_101.dimensionCount = 4;
const uint32_t dimensions_101[] = {1, 0, 0, 96};
operand_101.dimensions = dimensions_101;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_101), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_102{};
operand_102.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_102.scale = 0.001790200243704021;
operand_102.zeroPoint = 143;
operand_102.dimensionCount = 4;
const uint32_t dimensions_102[] = {576, 1, 1, 96};
operand_102.dimensions = dimensions_102;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_102), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_103{};
operand_103.type = ANEURALNETWORKS_TENSOR_INT32;
operand_103.scale = 2.259852408315055e-05;
operand_103.zeroPoint = 0;
operand_103.dimensionCount = 1;
const uint32_t dimensions_103[] = {576};
operand_103.dimensions = dimensions_103;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_103), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_104{};
operand_104.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_104.scale = 0.003789969952777028;
operand_104.zeroPoint = 0;
operand_104.dimensionCount = 4;
const uint32_t dimensions_104[] = {1, 0, 0, 576};
operand_104.dimensions = dimensions_104;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_104), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_105{};
operand_105.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_105.scale = 0.001565286540426314;
operand_105.zeroPoint = 133;
operand_105.dimensionCount = 4;
const uint32_t dimensions_105[] = {1, 3, 3, 576};
operand_105.dimensions = dimensions_105;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_105), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_106{};
operand_106.type = ANEURALNETWORKS_TENSOR_INT32;
operand_106.scale = 5.932388830842683e-06;
operand_106.zeroPoint = 0;
operand_106.dimensionCount = 1;
const uint32_t dimensions_106[] = {576};
operand_106.dimensions = dimensions_106;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_106), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_107{};
operand_107.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_107.scale = 0.001188441878184676;
operand_107.zeroPoint = 107;
operand_107.dimensionCount = 4;
const uint32_t dimensions_107[] = {1, 0, 0, 576};
operand_107.dimensions = dimensions_107;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_107), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_108{};
operand_108.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_108.scale = 0.03223617374897003;
operand_108.zeroPoint = 131;
operand_108.dimensionCount = 4;
const uint32_t dimensions_108[] = {96, 1, 1, 576};
operand_108.dimensions = dimensions_108;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_108), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_109{};
operand_109.type = ANEURALNETWORKS_TENSOR_INT32;
operand_109.scale = 3.83108199457638e-05;
operand_109.zeroPoint = 0;
operand_109.dimensionCount = 1;
const uint32_t dimensions_109[] = {96};
operand_109.dimensions = dimensions_109;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_109), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_110{};
operand_110.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_110.scale = 0.01084044575691223;
operand_110.zeroPoint = 130;
operand_110.dimensionCount = 4;
const uint32_t dimensions_110[] = {1, 0, 0, 96};
operand_110.dimensions = dimensions_110;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_110), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_111{};
operand_111.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_111.scale = 0.01627451553940773;
operand_111.zeroPoint = 133;
operand_111.dimensionCount = 4;
const uint32_t dimensions_111[] = {1, 0, 0, 96};
operand_111.dimensions = dimensions_111;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_111), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_112{};
operand_112.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_112.scale = 0.001678385655395687;
operand_112.zeroPoint = 135;
operand_112.dimensionCount = 4;
const uint32_t dimensions_112[] = {576, 1, 1, 96};
operand_112.dimensions = dimensions_112;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_112), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_113{};
operand_113.type = ANEURALNETWORKS_TENSOR_INT32;
operand_113.scale = 2.731491440499667e-05;
operand_113.zeroPoint = 0;
operand_113.dimensionCount = 1;
const uint32_t dimensions_113[] = {576};
operand_113.dimensions = dimensions_113;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_113), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_114{};
operand_114.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_114.scale = 0.004788670688867569;
operand_114.zeroPoint = 0;
operand_114.dimensionCount = 4;
const uint32_t dimensions_114[] = {1, 0, 0, 576};
operand_114.dimensions = dimensions_114;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_114), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_115{};
operand_115.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_115.scale = 0.001882086275145411;
operand_115.zeroPoint = 130;
operand_115.dimensionCount = 4;
const uint32_t dimensions_115[] = {1, 3, 3, 576};
operand_115.dimensions = dimensions_115;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_115), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_116{};
operand_116.type = ANEURALNETWORKS_TENSOR_INT32;
operand_116.scale = 9.012691407406237e-06;
operand_116.zeroPoint = 0;
operand_116.dimensionCount = 1;
const uint32_t dimensions_116[] = {576};
operand_116.dimensions = dimensions_116;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_116), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_117{};
operand_117.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_117.scale = 0.001888960134238005;
operand_117.zeroPoint = 131;
operand_117.dimensionCount = 4;
const uint32_t dimensions_117[] = {1, 0, 0, 576};
operand_117.dimensions = dimensions_117;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_117), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_118{};
operand_118.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_118.scale = 0.006059954408556223;
operand_118.zeroPoint = 131;
operand_118.dimensionCount = 4;
const uint32_t dimensions_118[] = {128, 1, 1, 576};
operand_118.dimensions = dimensions_118;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_118), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_119{};
operand_119.type = ANEURALNETWORKS_TENSOR_INT32;
operand_119.scale = 1.144701218436239e-05;
operand_119.zeroPoint = 0;
operand_119.dimensionCount = 1;
const uint32_t dimensions_119[] = {128};
operand_119.dimensions = dimensions_119;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_119), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_120{};
operand_120.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_120.scale = 0.004614091943949461;
operand_120.zeroPoint = 131;
operand_120.dimensionCount = 4;
const uint32_t dimensions_120[] = {1, 0, 0, 128};
operand_120.dimensions = dimensions_120;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_120), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_121{};
operand_121.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_121.scale = 0.007414539344608784;
operand_121.zeroPoint = 126;
operand_121.dimensionCount = 4;
const uint32_t dimensions_121[] = {768, 1, 1, 128};
operand_121.dimensions = dimensions_121;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_121), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_122{};
operand_122.type = ANEURALNETWORKS_TENSOR_INT32;
operand_122.scale = 3.42113635269925e-05;
operand_122.zeroPoint = 0;
operand_122.dimensionCount = 1;
const uint32_t dimensions_122[] = {768};
operand_122.dimensions = dimensions_122;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_122), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_123{};
operand_123.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_123.scale = 0.002970855450257659;
operand_123.zeroPoint = 0;
operand_123.dimensionCount = 4;
const uint32_t dimensions_123[] = {1, 0, 0, 768};
operand_123.dimensions = dimensions_123;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_123), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_124{};
operand_124.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_124.scale = 0.00154426705557853;
operand_124.zeroPoint = 127;
operand_124.dimensionCount = 4;
const uint32_t dimensions_124[] = {1, 3, 3, 768};
operand_124.dimensions = dimensions_124;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_124), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_125{};
operand_125.type = ANEURALNETWORKS_TENSOR_INT32;
operand_125.scale = 4.58779413747834e-06;
operand_125.zeroPoint = 0;
operand_125.dimensionCount = 1;
const uint32_t dimensions_125[] = {768};
operand_125.dimensions = dimensions_125;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_125), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_126{};
operand_126.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_126.scale = 0.001004609395749867;
operand_126.zeroPoint = 119;
operand_126.dimensionCount = 4;
const uint32_t dimensions_126[] = {1, 0, 0, 768};
operand_126.dimensions = dimensions_126;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_126), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_127{};
operand_127.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_127.scale = 0.01107242610305548;
operand_127.zeroPoint = 127;
operand_127.dimensionCount = 4;
const uint32_t dimensions_127[] = {128, 1, 1, 768};
operand_127.dimensions = dimensions_127;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_127), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_128{};
operand_128.type = ANEURALNETWORKS_TENSOR_INT32;
operand_128.scale = 1.112346308218548e-05;
operand_128.zeroPoint = 0;
operand_128.dimensionCount = 1;
const uint32_t dimensions_128[] = {128};
operand_128.dimensions = dimensions_128;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_128), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_129{};
operand_129.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_129.scale = 0.004491065628826618;
operand_129.zeroPoint = 121;
operand_129.dimensionCount = 4;
const uint32_t dimensions_129[] = {1, 0, 0, 128};
operand_129.dimensions = dimensions_129;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_129), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_130{};
operand_130.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_130.scale = 0.007918111048638821;
operand_130.zeroPoint = 132;
operand_130.dimensionCount = 4;
const uint32_t dimensions_130[] = {1, 0, 0, 128};
operand_130.dimensions = dimensions_130;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_130), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_131{};
operand_131.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_131.scale = 0.004637615289539099;
operand_131.zeroPoint = 126;
operand_131.dimensionCount = 4;
const uint32_t dimensions_131[] = {768, 1, 1, 128};
operand_131.dimensions = dimensions_131;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_131), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_132{};
operand_132.type = ANEURALNETWORKS_TENSOR_INT32;
operand_132.scale = 3.672115417430177e-05;
operand_132.zeroPoint = 0;
operand_132.dimensionCount = 1;
const uint32_t dimensions_132[] = {768};
operand_132.dimensions = dimensions_132;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_132), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_133{};
operand_133.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_133.scale = 0.003131674602627754;
operand_133.zeroPoint = 0;
operand_133.dimensionCount = 4;
const uint32_t dimensions_133[] = {1, 0, 0, 768};
operand_133.dimensions = dimensions_133;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_133), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_134{};
operand_134.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_134.scale = 0.001537951757200062;
operand_134.zeroPoint = 130;
operand_134.dimensionCount = 4;
const uint32_t dimensions_134[] = {1, 3, 3, 768};
operand_134.dimensions = dimensions_134;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_134), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_135{};
operand_135.type = ANEURALNETWORKS_TENSOR_INT32;
operand_135.scale = 4.816364707949106e-06;
operand_135.zeroPoint = 0;
operand_135.dimensionCount = 1;
const uint32_t dimensions_135[] = {768};
operand_135.dimensions = dimensions_135;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_135), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_136{};
operand_136.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_136.scale = 0.001004835939966142;
operand_136.zeroPoint = 121;
operand_136.dimensionCount = 4;
const uint32_t dimensions_136[] = {1, 0, 0, 768};
operand_136.dimensions = dimensions_136;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_136), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_137{};
operand_137.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_137.scale = 0.01529518887400627;
operand_137.zeroPoint = 131;
operand_137.dimensionCount = 4;
const uint32_t dimensions_137[] = {128, 1, 1, 768};
operand_137.dimensions = dimensions_137;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_137), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_138{};
operand_138.type = ANEURALNETWORKS_TENSOR_INT32;
operand_138.scale = 1.536915442557074e-05;
operand_138.zeroPoint = 0;
operand_138.dimensionCount = 1;
const uint32_t dimensions_138[] = {128};
operand_138.dimensions = dimensions_138;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_138), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_139{};
operand_139.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_139.scale = 0.005413023289293051;
operand_139.zeroPoint = 121;
operand_139.dimensionCount = 4;
const uint32_t dimensions_139[] = {1, 0, 0, 128};
operand_139.dimensions = dimensions_139;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_139), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_140{};
operand_140.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_140.scale = 0.01041953638195992;
operand_140.zeroPoint = 122;
operand_140.dimensionCount = 4;
const uint32_t dimensions_140[] = {1, 0, 0, 128};
operand_140.dimensions = dimensions_140;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_140), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_141{};
operand_141.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_141.scale = 0.002339381724596024;
operand_141.zeroPoint = 119;
operand_141.dimensionCount = 4;
const uint32_t dimensions_141[] = {768, 1, 1, 128};
operand_141.dimensions = dimensions_141;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_141), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_142{};
operand_142.type = ANEURALNETWORKS_TENSOR_INT32;
operand_142.scale = 2.437527291476727e-05;
operand_142.zeroPoint = 0;
operand_142.dimensionCount = 1;
const uint32_t dimensions_142[] = {768};
operand_142.dimensions = dimensions_142;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_142), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_143{};
operand_143.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_143.scale = 0.002237820532172918;
operand_143.zeroPoint = 0;
operand_143.dimensionCount = 4;
const uint32_t dimensions_143[] = {1, 0, 0, 768};
operand_143.dimensions = dimensions_143;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_143), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_144{};
operand_144.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_144.scale = 0.0007936766487546265;
operand_144.zeroPoint = 133;
operand_144.dimensionCount = 4;
const uint32_t dimensions_144[] = {1, 3, 3, 768};
operand_144.dimensions = dimensions_144;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_144), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_145{};
operand_145.type = ANEURALNETWORKS_TENSOR_INT32;
operand_145.scale = 1.776105818862561e-06;
operand_145.zeroPoint = 0;
operand_145.dimensionCount = 1;
const uint32_t dimensions_145[] = {768};
operand_145.dimensions = dimensions_145;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_145), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_146{};
operand_146.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_146.scale = 0.001001776661723852;
operand_146.zeroPoint = 115;
operand_146.dimensionCount = 4;
const uint32_t dimensions_146[] = {1, 0, 0, 768};
operand_146.dimensions = dimensions_146;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_146), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_147{};
operand_147.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_147.scale = 0.02992645651102066;
operand_147.zeroPoint = 122;
operand_147.dimensionCount = 4;
const uint32_t dimensions_147[] = {128, 1, 1, 768};
operand_147.dimensions = dimensions_147;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_147), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_148{};
operand_148.type = ANEURALNETWORKS_TENSOR_INT32;
operand_148.scale = 2.997962474182714e-05;
operand_148.zeroPoint = 0;
operand_148.dimensionCount = 1;
const uint32_t dimensions_148[] = {128};
operand_148.dimensions = dimensions_148;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_148), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_149{};
operand_149.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_149.scale = 0.006007113959640265;
operand_149.zeroPoint = 138;
operand_149.dimensionCount = 4;
const uint32_t dimensions_149[] = {1, 0, 0, 128};
operand_149.dimensions = dimensions_149;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_149), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_150{};
operand_150.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_150.scale = 0.01333596650511026;
operand_150.zeroPoint = 128;
operand_150.dimensionCount = 4;
const uint32_t dimensions_150[] = {1, 0, 0, 128};
operand_150.dimensions = dimensions_150;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_150), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_151{};
operand_151.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_151.scale = 0.002114560455083847;
operand_151.zeroPoint = 131;
operand_151.dimensionCount = 4;
const uint32_t dimensions_151[] = {768, 1, 1, 128};
operand_151.dimensions = dimensions_151;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_151), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_152{};
operand_152.type = ANEURALNETWORKS_TENSOR_INT32;
operand_152.scale = 2.819970904965885e-05;
operand_152.zeroPoint = 0;
operand_152.dimensionCount = 1;
const uint32_t dimensions_152[] = {768};
operand_152.dimensions = dimensions_152;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_152), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_153{};
operand_153.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_153.scale = 0.002463524229824543;
operand_153.zeroPoint = 0;
operand_153.dimensionCount = 4;
const uint32_t dimensions_153[] = {1, 0, 0, 768};
operand_153.dimensions = dimensions_153;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_153), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_154{};
operand_154.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_154.scale = 0.0009068828076124191;
operand_154.zeroPoint = 125;
operand_154.dimensionCount = 4;
const uint32_t dimensions_154[] = {1, 3, 3, 768};
operand_154.dimensions = dimensions_154;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_154), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_155{};
operand_155.type = ANEURALNETWORKS_TENSOR_INT32;
operand_155.scale = 2.234127578049083e-06;
operand_155.zeroPoint = 0;
operand_155.dimensionCount = 1;
const uint32_t dimensions_155[] = {768};
operand_155.dimensions = dimensions_155;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_155), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_156{};
operand_156.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_156.scale = 0.001002233359031379;
operand_156.zeroPoint = 132;
operand_156.dimensionCount = 4;
const uint32_t dimensions_156[] = {1, 0, 0, 768};
operand_156.dimensions = dimensions_156;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_156), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_157{};
operand_157.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_157.scale = 0.0339314192533493;
operand_157.zeroPoint = 113;
operand_157.dimensionCount = 4;
const uint32_t dimensions_157[] = {128, 1, 1, 768};
operand_157.dimensions = dimensions_157;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_157), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_158{};
operand_158.type = ANEURALNETWORKS_TENSOR_INT32;
operand_158.scale = 3.400720015633851e-05;
operand_158.zeroPoint = 0;
operand_158.dimensionCount = 1;
const uint32_t dimensions_158[] = {128};
operand_158.dimensions = dimensions_158;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_158), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_159{};
operand_159.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_159.scale = 0.007420019246637821;
operand_159.zeroPoint = 135;
operand_159.dimensionCount = 4;
const uint32_t dimensions_159[] = {1, 0, 0, 128};
operand_159.dimensions = dimensions_159;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_159), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_160{};
operand_160.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_160.scale = 0.01803975738584995;
operand_160.zeroPoint = 134;
operand_160.dimensionCount = 4;
const uint32_t dimensions_160[] = {1, 0, 0, 128};
operand_160.dimensions = dimensions_160;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_160), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_161{};
operand_161.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_161.scale = 0.001758694183081388;
operand_161.zeroPoint = 134;
operand_161.dimensionCount = 4;
const uint32_t dimensions_161[] = {768, 1, 1, 128};
operand_161.dimensions = dimensions_161;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_161), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_162{};
operand_162.type = ANEURALNETWORKS_TENSOR_INT32;
operand_162.scale = 3.172641663695686e-05;
operand_162.zeroPoint = 0;
operand_162.dimensionCount = 1;
const uint32_t dimensions_162[] = {768};
operand_162.dimensions = dimensions_162;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_162), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_163{};
operand_163.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_163.scale = 0.003602873533964157;
operand_163.zeroPoint = 0;
operand_163.dimensionCount = 4;
const uint32_t dimensions_163[] = {1, 0, 0, 768};
operand_163.dimensions = dimensions_163;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_163), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_164{};
operand_164.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_164.scale = 0.00123634107876569;
operand_164.zeroPoint = 134;
operand_164.dimensionCount = 4;
const uint32_t dimensions_164[] = {1, 3, 3, 768};
operand_164.dimensions = dimensions_164;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_164), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_165{};
operand_165.type = ANEURALNETWORKS_TENSOR_INT32;
operand_165.scale = 4.45438035967527e-06;
operand_165.zeroPoint = 0;
operand_165.dimensionCount = 1;
const uint32_t dimensions_165[] = {768};
operand_165.dimensions = dimensions_165;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_165), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_166{};
operand_166.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_166.scale = 0.001004456076771021;
operand_166.zeroPoint = 114;
operand_166.dimensionCount = 4;
const uint32_t dimensions_166[] = {1, 0, 0, 768};
operand_166.dimensions = dimensions_166;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_166), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_167{};
operand_167.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_167.scale = 0.04360251501202583;
operand_167.zeroPoint = 125;
operand_167.dimensionCount = 4;
const uint32_t dimensions_167[] = {128, 1, 1, 768};
operand_167.dimensions = dimensions_167;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_167), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_168{};
operand_168.type = ANEURALNETWORKS_TENSOR_INT32;
operand_168.scale = 4.379680831334554e-05;
operand_168.zeroPoint = 0;
operand_168.dimensionCount = 1;
const uint32_t dimensions_168[] = {128};
operand_168.dimensions = dimensions_168;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_168), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_169{};
operand_169.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_169.scale = 0.01710499450564384;
operand_169.zeroPoint = 129;
operand_169.dimensionCount = 4;
const uint32_t dimensions_169[] = {1, 0, 0, 128};
operand_169.dimensions = dimensions_169;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_169), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_170{};
operand_170.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_170.scale = 0.02661834843456745;
operand_170.zeroPoint = 134;
operand_170.dimensionCount = 4;
const uint32_t dimensions_170[] = {1, 0, 0, 128};
operand_170.dimensions = dimensions_170;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_170), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_171{};
operand_171.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_171.scale = 0.003064587479457259;
operand_171.zeroPoint = 115;
operand_171.dimensionCount = 4;
const uint32_t dimensions_171[] = {15, 1, 1, 128};
operand_171.dimensions = dimensions_171;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_171), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_172{};
operand_172.type = ANEURALNETWORKS_TENSOR_INT32;
operand_172.scale = 8.157426054822281e-05;
operand_172.zeroPoint = 0;
operand_172.dimensionCount = 1;
const uint32_t dimensions_172[] = {15};
operand_172.dimensions = dimensions_172;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_172), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_173{};
operand_173.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_173.scale = 0.08332997560501099;
operand_173.zeroPoint = 148;
operand_173.dimensionCount = 4;
const uint32_t dimensions_173[] = {1, 0, 0, 15};
operand_173.dimensions = dimensions_173;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_173), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_174{};
operand_174.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_174.scale = 0.0009250070434063673;
operand_174.zeroPoint = 131;
operand_174.dimensionCount = 4;
const uint32_t dimensions_174[] = {60, 1, 1, 128};
operand_174.dimensions = dimensions_174;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_174), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_175{};
operand_175.type = ANEURALNETWORKS_TENSOR_INT32;
operand_175.scale = 2.462215888954233e-05;
operand_175.zeroPoint = 0;
operand_175.dimensionCount = 1;
const uint32_t dimensions_175[] = {60};
operand_175.dimensions = dimensions_175;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_175), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_176{};
operand_176.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_176.scale = 0.008264735341072083;
operand_176.zeroPoint = 137;
operand_176.dimensionCount = 4;
const uint32_t dimensions_176[] = {1, 0, 0, 60};
operand_176.dimensions = dimensions_176;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_176), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_177{};
operand_177.type = ANEURALNETWORKS_TENSOR_QUANT16_SYMM;
operand_177.scale = 0.125;
operand_177.zeroPoint = 0;
operand_177.dimensionCount = 2;
const uint32_t dimensions_177[] = {15, 4};
operand_177.dimensions = dimensions_177;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_177), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_178{};
operand_178.type = ANEURALNETWORKS_FLOAT32;
operand_178.scale = 0;
operand_178.zeroPoint = 0;
operand_178.dimensionCount = 0;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_178), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_179{};
operand_179.type = ANEURALNETWORKS_INT32;
operand_179.scale = 0;
operand_179.zeroPoint = 0;
operand_179.dimensionCount = 0;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_179), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_180{};
operand_180.type = ANEURALNETWORKS_INT32;
operand_180.scale = 0;
operand_180.zeroPoint = 0;
operand_180.dimensionCount = 0;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_180), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_181{};
operand_181.type = ANEURALNETWORKS_FLOAT32;
operand_181.scale = 0;
operand_181.zeroPoint = 0;
operand_181.dimensionCount = 0;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_181), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_182{};
operand_182.type = ANEURALNETWORKS_FLOAT32;
operand_182.scale = 0;
operand_182.zeroPoint = 0;
operand_182.dimensionCount = 0;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_182), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_183{};
operand_183.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_183.scale = 0.08332997560501099;
operand_183.zeroPoint = 148;
operand_183.dimensionCount = 1;
const uint32_t dimensions_183[] = {0};
operand_183.dimensions = dimensions_183;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_183), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_184{};
operand_184.type = ANEURALNETWORKS_TENSOR_QUANT16_ASYMM;
operand_184.scale = 0.125;
operand_184.zeroPoint = 0;
operand_184.dimensionCount = 2;
const uint32_t dimensions_184[] = {0, 4};
operand_184.dimensions = dimensions_184;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_184), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_185{};
operand_185.type = ANEURALNETWORKS_TENSOR_INT32;
operand_185.scale = 0;
operand_185.zeroPoint = 0;
operand_185.dimensionCount = 1;
const uint32_t dimensions_185[] = {0};
operand_185.dimensions = dimensions_185;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_185), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_186{};
operand_186.type = ANEURALNETWORKS_INT32;
operand_186.scale = 0;
operand_186.zeroPoint = 0;
operand_186.dimensionCount = 0;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_186), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_187{};
operand_187.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_187.scale = 0.009147729724645615;
operand_187.zeroPoint = 121;
operand_187.dimensionCount = 4;
const uint32_t dimensions_187[] = {0, 6, 6, 128};
operand_187.dimensions = dimensions_187;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_187), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_188{};
operand_188.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_188.scale = 0.003680879715830088;
operand_188.zeroPoint = 146;
operand_188.dimensionCount = 4;
const uint32_t dimensions_188[] = {512, 1, 1, 128};
operand_188.dimensions = dimensions_188;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_188), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_189{};
operand_189.type = ANEURALNETWORKS_TENSOR_INT32;
operand_189.scale = 3.367169483681209e-05;
operand_189.zeroPoint = 0;
operand_189.dimensionCount = 1;
const uint32_t dimensions_189[] = {512};
operand_189.dimensions = dimensions_189;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_189), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_190{};
operand_190.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_190.scale = 0.003791309893131256;
operand_190.zeroPoint = 0;
operand_190.dimensionCount = 4;
const uint32_t dimensions_190[] = {0, 6, 6, 512};
operand_190.dimensions = dimensions_190;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_190), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_191{};
operand_191.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_191.scale = 0.001269564847461879;
operand_191.zeroPoint = 138;
operand_191.dimensionCount = 4;
const uint32_t dimensions_191[] = {1, 3, 3, 512};
operand_191.dimensions = dimensions_191;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_191), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_192{};
operand_192.type = ANEURALNETWORKS_TENSOR_INT32;
operand_192.scale = 4.813313807972008e-06;
operand_192.zeroPoint = 0;
operand_192.dimensionCount = 1;
const uint32_t dimensions_192[] = {512};
operand_192.dimensions = dimensions_192;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_192), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_193{};
operand_193.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_193.scale = 0.001495834090746939;
operand_193.zeroPoint = 103;
operand_193.dimensionCount = 4;
const uint32_t dimensions_193[] = {0, 3, 3, 512};
operand_193.dimensions = dimensions_193;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_193), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_194{};
operand_194.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_194.scale = 0.008620671927928925;
operand_194.zeroPoint = 120;
operand_194.dimensionCount = 4;
const uint32_t dimensions_194[] = {128, 1, 1, 512};
operand_194.dimensions = dimensions_194;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_194), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_195{};
operand_195.type = ANEURALNETWORKS_TENSOR_INT32;
operand_195.scale = 1.289509418711532e-05;
operand_195.zeroPoint = 0;
operand_195.dimensionCount = 1;
const uint32_t dimensions_195[] = {128};
operand_195.dimensions = dimensions_195;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_195), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_196{};
operand_196.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_196.scale = 0.004329186864197254;
operand_196.zeroPoint = 133;
operand_196.dimensionCount = 4;
const uint32_t dimensions_196[] = {0, 3, 3, 128};
operand_196.dimensions = dimensions_196;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_196), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_197{};
operand_197.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_197.scale = 0.003237461671233177;
operand_197.zeroPoint = 129;
operand_197.dimensionCount = 4;
const uint32_t dimensions_197[] = {768, 1, 1, 128};
operand_197.dimensions = dimensions_197;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_197), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_198{};
operand_198.type = ANEURALNETWORKS_TENSOR_INT32;
operand_198.scale = 1.401557619828964e-05;
operand_198.zeroPoint = 0;
operand_198.dimensionCount = 1;
const uint32_t dimensions_198[] = {768};
operand_198.dimensions = dimensions_198;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_198), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_199{};
operand_199.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_199.scale = 0.00272013433277607;
operand_199.zeroPoint = 0;
operand_199.dimensionCount = 4;
const uint32_t dimensions_199[] = {0, 3, 3, 768};
operand_199.dimensions = dimensions_199;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_199), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_200{};
operand_200.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_200.scale = 0.001447727903723717;
operand_200.zeroPoint = 140;
operand_200.dimensionCount = 4;
const uint32_t dimensions_200[] = {1, 3, 3, 768};
operand_200.dimensions = dimensions_200;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_200), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_201{};
operand_201.type = ANEURALNETWORKS_TENSOR_INT32;
operand_201.scale = 3.938014287996339e-06;
operand_201.zeroPoint = 0;
operand_201.dimensionCount = 1;
const uint32_t dimensions_201[] = {768};
operand_201.dimensions = dimensions_201;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_201), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_202{};
operand_202.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_202.scale = 0.001003918354399502;
operand_202.zeroPoint = 128;
operand_202.dimensionCount = 4;
const uint32_t dimensions_202[] = {0, 3, 3, 768};
operand_202.dimensions = dimensions_202;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_202), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_203{};
operand_203.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_203.scale = 0.02241912484169006;
operand_203.zeroPoint = 132;
operand_203.dimensionCount = 4;
const uint32_t dimensions_203[] = {128, 1, 1, 768};
operand_203.dimensions = dimensions_203;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_203), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_204{};
operand_204.type = ANEURALNETWORKS_TENSOR_INT32;
operand_204.scale = 2.250697070849128e-05;
operand_204.zeroPoint = 0;
operand_204.dimensionCount = 1;
const uint32_t dimensions_204[] = {128};
operand_204.dimensions = dimensions_204;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_204), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_205{};
operand_205.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_205.scale = 0.004013048950582743;
operand_205.zeroPoint = 123;
operand_205.dimensionCount = 4;
const uint32_t dimensions_205[] = {0, 3, 3, 128};
operand_205.dimensions = dimensions_205;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_205), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_206{};
operand_206.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_206.scale = 0.005564078688621521;
operand_206.zeroPoint = 132;
operand_206.dimensionCount = 4;
const uint32_t dimensions_206[] = {0, 3, 3, 128};
operand_206.dimensions = dimensions_206;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_206), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_207{};
operand_207.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_207.scale = 0.002945196582004428;
operand_207.zeroPoint = 130;
operand_207.dimensionCount = 4;
const uint32_t dimensions_207[] = {768, 1, 1, 128};
operand_207.dimensions = dimensions_207;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_207), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_208{};
operand_208.type = ANEURALNETWORKS_TENSOR_INT32;
operand_208.scale = 1.638730645936448e-05;
operand_208.zeroPoint = 0;
operand_208.dimensionCount = 1;
const uint32_t dimensions_208[] = {768};
operand_208.dimensions = dimensions_208;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_208), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_209{};
operand_209.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_209.scale = 0.002767552156001329;
operand_209.zeroPoint = 0;
operand_209.dimensionCount = 4;
const uint32_t dimensions_209[] = {0, 3, 3, 768};
operand_209.dimensions = dimensions_209;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_209), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_210{};
operand_210.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_210.scale = 0.001267897896468639;
operand_210.zeroPoint = 111;
operand_210.dimensionCount = 4;
const uint32_t dimensions_210[] = {1, 3, 3, 768};
operand_210.dimensions = dimensions_210;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_210), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_211{};
operand_211.type = ANEURALNETWORKS_TENSOR_INT32;
operand_211.scale = 3.508973350108135e-06;
operand_211.zeroPoint = 0;
operand_211.dimensionCount = 1;
const uint32_t dimensions_211[] = {768};
operand_211.dimensions = dimensions_211;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_211), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_212{};
operand_212.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_212.scale = 0.001003496232442558;
operand_212.zeroPoint = 103;
operand_212.dimensionCount = 4;
const uint32_t dimensions_212[] = {0, 3, 3, 768};
operand_212.dimensions = dimensions_212;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_212), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_213{};
operand_213.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_213.scale = 0.04008430987596512;
operand_213.zeroPoint = 130;
operand_213.dimensionCount = 4;
const uint32_t dimensions_213[] = {128, 1, 1, 768};
operand_213.dimensions = dimensions_213;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_213), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_214{};
operand_214.type = ANEURALNETWORKS_TENSOR_INT32;
operand_214.scale = 4.022445500595495e-05;
operand_214.zeroPoint = 0;
operand_214.dimensionCount = 1;
const uint32_t dimensions_214[] = {128};
operand_214.dimensions = dimensions_214;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_214), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_215{};
operand_215.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_215.scale = 0.007019979413598776;
operand_215.zeroPoint = 127;
operand_215.dimensionCount = 4;
const uint32_t dimensions_215[] = {0, 3, 3, 128};
operand_215.dimensions = dimensions_215;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_215), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_216{};
operand_216.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_216.scale = 0.008132008835673332;
operand_216.zeroPoint = 113;
operand_216.dimensionCount = 4;
const uint32_t dimensions_216[] = {0, 3, 3, 128};
operand_216.dimensions = dimensions_216;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_216), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_217{};
operand_217.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_217.scale = 0.002510206308215857;
operand_217.zeroPoint = 121;
operand_217.dimensionCount = 4;
const uint32_t dimensions_217[] = {768, 1, 1, 128};
operand_217.dimensions = dimensions_217;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_217), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_218{};
operand_218.type = ANEURALNETWORKS_TENSOR_INT32;
operand_218.scale = 2.041302104771603e-05;
operand_218.zeroPoint = 0;
operand_218.dimensionCount = 1;
const uint32_t dimensions_218[] = {768};
operand_218.dimensions = dimensions_218;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_218), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_219{};
operand_219.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_219.scale = 0.002694383496418595;
operand_219.zeroPoint = 0;
operand_219.dimensionCount = 4;
const uint32_t dimensions_219[] = {0, 3, 3, 768};
operand_219.dimensions = dimensions_219;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_219), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_220{};
operand_220.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_220.scale = 0.0008893656777217984;
operand_220.zeroPoint = 133;
operand_220.dimensionCount = 4;
const uint32_t dimensions_220[] = {1, 3, 3, 768};
operand_220.dimensions = dimensions_220;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_220), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_221{};
operand_221.type = ANEURALNETWORKS_TENSOR_INT32;
operand_221.scale = 2.3962923023646e-06;
operand_221.zeroPoint = 0;
operand_221.dimensionCount = 1;
const uint32_t dimensions_221[] = {768};
operand_221.dimensions = dimensions_221;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_221), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_222{};
operand_222.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_222.scale = 0.001002407167106867;
operand_222.zeroPoint = 131;
operand_222.dimensionCount = 4;
const uint32_t dimensions_222[] = {0, 3, 3, 768};
operand_222.dimensions = dimensions_222;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_222), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_223{};
operand_223.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_223.scale = 0.05506842583417892;
operand_223.zeroPoint = 153;
operand_223.dimensionCount = 4;
const uint32_t dimensions_223[] = {160, 1, 1, 768};
operand_223.dimensions = dimensions_223;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_223), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_224{};
operand_224.type = ANEURALNETWORKS_TENSOR_INT32;
operand_224.scale = 5.520098784472793e-05;
operand_224.zeroPoint = 0;
operand_224.dimensionCount = 1;
const uint32_t dimensions_224[] = {160};
operand_224.dimensions = dimensions_224;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_224), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_225{};
operand_225.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_225.scale = 0.005563139915466309;
operand_225.zeroPoint = 126;
operand_225.dimensionCount = 4;
const uint32_t dimensions_225[] = {0, 3, 3, 160};
operand_225.dimensions = dimensions_225;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_225), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_226{};
operand_226.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_226.scale = 0.02526126243174076;
operand_226.zeroPoint = 112;
operand_226.dimensionCount = 4;
const uint32_t dimensions_226[] = {160, 1, 1, 160};
operand_226.dimensions = dimensions_226;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_226), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_227{};
operand_227.type = ANEURALNETWORKS_TENSOR_INT32;
operand_227.scale = 0.0001405319344485179;
operand_227.zeroPoint = 0;
operand_227.dimensionCount = 1;
const uint32_t dimensions_227[] = {160};
operand_227.dimensions = dimensions_227;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_227), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_228{};
operand_228.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_228.scale = 0.04058342799544334;
operand_228.zeroPoint = 0;
operand_228.dimensionCount = 4;
const uint32_t dimensions_228[] = {0, 3, 3, 160};
operand_228.dimensions = dimensions_228;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_228), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_229{};
operand_229.type = ANEURALNETWORKS_INT32;
operand_229.scale = 0;
operand_229.zeroPoint = 0;
operand_229.dimensionCount = 0;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_229), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_230{};
operand_230.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_230.scale = 0.04058342799544334;
operand_230.zeroPoint = 0;
operand_230.dimensionCount = 4;
const uint32_t dimensions_230[] = {0, 1, 1, 160};
operand_230.dimensions = dimensions_230;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_230), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_231{};
operand_231.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_231.scale = 0.005672636907547712;
operand_231.zeroPoint = 136;
operand_231.dimensionCount = 2;
const uint32_t dimensions_231[] = {81, 160};
operand_231.dimensions = dimensions_231;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_231), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_232{};
operand_232.type = ANEURALNETWORKS_TENSOR_INT32;
operand_232.scale = 0.0002302150533068925;
operand_232.zeroPoint = 0;
operand_232.dimensionCount = 1;
const uint32_t dimensions_232[] = {81};
operand_232.dimensions = dimensions_232;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_232), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_233{};
operand_233.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_233.scale = 0.08092430979013443;
operand_233.zeroPoint = 80;
operand_233.dimensionCount = 2;
const uint32_t dimensions_233[] = {0, 81};
operand_233.dimensions = dimensions_233;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_233), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_234{};
operand_234.type = ANEURALNETWORKS_FLOAT32;
operand_234.scale = 0;
operand_234.zeroPoint = 0;
operand_234.dimensionCount = 0;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_234), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_235{};
operand_235.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_235.scale = 0.00390625;
operand_235.zeroPoint = 0;
operand_235.dimensionCount = 2;
const uint32_t dimensions_235[] = {0, 81};
operand_235.dimensions = dimensions_235;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_235), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_236{};
operand_236.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_236.scale = 0.0006408203043974936;
operand_236.zeroPoint = 139;
operand_236.dimensionCount = 2;
const uint32_t dimensions_236[] = {324, 160};
operand_236.dimensions = dimensions_236;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_236), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_237{};
operand_237.type = ANEURALNETWORKS_TENSOR_INT32;
operand_237.scale = 2.600668449304067e-05;
operand_237.zeroPoint = 0;
operand_237.dimensionCount = 1;
const uint32_t dimensions_237[] = {324};
operand_237.dimensions = dimensions_237;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_237), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_238{};
operand_238.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_238.scale = 0.004951907321810722;
operand_238.zeroPoint = 131;
operand_238.dimensionCount = 2;
const uint32_t dimensions_238[] = {0, 324};
operand_238.dimensions = dimensions_238;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_238), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_239{};
operand_239.type = ANEURALNETWORKS_TENSOR_QUANT16_ASYMM;
operand_239.scale = 0.125;
operand_239.zeroPoint = 0;
operand_239.dimensionCount = 2;
const uint32_t dimensions_239[] = {0, 324};
operand_239.dimensions = dimensions_239;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_239), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_240{};
operand_240.type = ANEURALNETWORKS_FLOAT32;
operand_240.scale = 0;
operand_240.zeroPoint = 0;
operand_240.dimensionCount = 0;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_240), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_241{};
operand_241.type = ANEURALNETWORKS_FLOAT32;
operand_241.scale = 0;
operand_241.zeroPoint = 0;
operand_241.dimensionCount = 0;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_241), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_242{};
operand_242.type = ANEURALNETWORKS_FLOAT32;
operand_242.scale = 0;
operand_242.zeroPoint = 0;
operand_242.dimensionCount = 0;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_242), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_243{};
operand_243.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_243.scale = 0.00390625;
operand_243.zeroPoint = 0;
operand_243.dimensionCount = 1;
const uint32_t dimensions_243[] = {0};
operand_243.dimensions = dimensions_243;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_243), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_244{};
operand_244.type = ANEURALNETWORKS_TENSOR_QUANT16_ASYMM;
operand_244.scale = 0.125;
operand_244.zeroPoint = 0;
operand_244.dimensionCount = 2;
const uint32_t dimensions_244[] = {0, 4};
operand_244.dimensions = dimensions_244;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_244), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_245{};
operand_245.type = ANEURALNETWORKS_TENSOR_INT32;
operand_245.scale = 0;
operand_245.zeroPoint = 0;
operand_245.dimensionCount = 1;
const uint32_t dimensions_245[] = {0};
operand_245.dimensions = dimensions_245;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_245), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_246{};
operand_246.type = ANEURALNETWORKS_TENSOR_INT32;
operand_246.scale = 0;
operand_246.zeroPoint = 0;
operand_246.dimensionCount = 1;
const uint32_t dimensions_246[] = {0};
operand_246.dimensions = dimensions_246;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_246), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_247{};
operand_247.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_247.scale = 0.009006229229271412;
operand_247.zeroPoint = 119;
operand_247.dimensionCount = 4;
const uint32_t dimensions_247[] = {0, 6, 6, 128};
operand_247.dimensions = dimensions_247;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_247), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_248{};
operand_248.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_248.scale = 0.002211635699495673;
operand_248.zeroPoint = 132;
operand_248.dimensionCount = 4;
const uint32_t dimensions_248[] = {512, 1, 1, 128};
operand_248.dimensions = dimensions_248;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_248), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_249{};
operand_249.type = ANEURALNETWORKS_TENSOR_INT32;
operand_249.scale = 1.991849785554223e-05;
operand_249.zeroPoint = 0;
operand_249.dimensionCount = 1;
const uint32_t dimensions_249[] = {512};
operand_249.dimensions = dimensions_249;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_249), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_250{};
operand_250.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_250.scale = 0.002592636970803142;
operand_250.zeroPoint = 0;
operand_250.dimensionCount = 4;
const uint32_t dimensions_250[] = {0, 6, 6, 512};
operand_250.dimensions = dimensions_250;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_250), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_251{};
operand_251.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_251.scale = 0.001000639051198959;
operand_251.zeroPoint = 148;
operand_251.dimensionCount = 4;
const uint32_t dimensions_251[] = {1, 3, 3, 512};
operand_251.dimensions = dimensions_251;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_251), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_252{};
operand_252.type = ANEURALNETWORKS_TENSOR_INT32;
operand_252.scale = 2.5942936190404e-06;
operand_252.zeroPoint = 0;
operand_252.dimensionCount = 1;
const uint32_t dimensions_252[] = {512};
operand_252.dimensions = dimensions_252;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_252), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_253{};
operand_253.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_253.scale = 0.001002595527097583;
operand_253.zeroPoint = 116;
operand_253.dimensionCount = 4;
const uint32_t dimensions_253[] = {0, 6, 6, 512};
operand_253.dimensions = dimensions_253;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_253), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_254{};
operand_254.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_254.scale = 0.01961961947381496;
operand_254.zeroPoint = 135;
operand_254.dimensionCount = 4;
const uint32_t dimensions_254[] = {128, 1, 1, 512};
operand_254.dimensions = dimensions_254;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_254), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_255{};
operand_255.type = ANEURALNETWORKS_TENSOR_INT32;
operand_255.scale = 1.967054413398728e-05;
operand_255.zeroPoint = 0;
operand_255.dimensionCount = 1;
const uint32_t dimensions_255[] = {128};
operand_255.dimensions = dimensions_255;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_255), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_256{};
operand_256.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_256.scale = 0.003791325259953737;
operand_256.zeroPoint = 133;
operand_256.dimensionCount = 4;
const uint32_t dimensions_256[] = {0, 6, 6, 128};
operand_256.dimensions = dimensions_256;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_256), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_257{};
operand_257.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_257.scale = 0.009337191469967365;
operand_257.zeroPoint = 121;
operand_257.dimensionCount = 4;
const uint32_t dimensions_257[] = {0, 6, 6, 128};
operand_257.dimensions = dimensions_257;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_257), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_258{};
operand_258.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_258.scale = 0.002133074915036559;
operand_258.zeroPoint = 128;
operand_258.dimensionCount = 4;
const uint32_t dimensions_258[] = {768, 1, 1, 128};
operand_258.dimensions = dimensions_258;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_258), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_259{};
operand_259.type = ANEURALNETWORKS_TENSOR_INT32;
operand_259.scale = 1.991692988667637e-05;
operand_259.zeroPoint = 0;
operand_259.dimensionCount = 1;
const uint32_t dimensions_259[] = {768};
operand_259.dimensions = dimensions_259;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_259), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_260{};
operand_260.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_260.scale = 0.002098787110298872;
operand_260.zeroPoint = 0;
operand_260.dimensionCount = 4;
const uint32_t dimensions_260[] = {0, 6, 6, 768};
operand_260.dimensions = dimensions_260;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_260), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_261{};
operand_261.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_261.scale = 0.0008608275675214827;
operand_261.zeroPoint = 124;
operand_261.dimensionCount = 4;
const uint32_t dimensions_261[] = {1, 3, 3, 768};
operand_261.dimensions = dimensions_261;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_261), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_262{};
operand_262.type = ANEURALNETWORKS_TENSOR_INT32;
operand_262.scale = 1.806693830985751e-06;
operand_262.zeroPoint = 0;
operand_262.dimensionCount = 1;
const uint32_t dimensions_262[] = {768};
operand_262.dimensions = dimensions_262;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_262), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_263{};
operand_263.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_263.scale = 0.001001805765554309;
operand_263.zeroPoint = 150;
operand_263.dimensionCount = 4;
const uint32_t dimensions_263[] = {0, 6, 6, 768};
operand_263.dimensions = dimensions_263;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_263), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_264{};
operand_264.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_264.scale = 0.0244825966656208;
operand_264.zeroPoint = 125;
operand_264.dimensionCount = 4;
const uint32_t dimensions_264[] = {128, 1, 1, 768};
operand_264.dimensions = dimensions_264;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_264), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_265{};
operand_265.type = ANEURALNETWORKS_TENSOR_INT32;
operand_265.scale = 2.452680564601906e-05;
operand_265.zeroPoint = 0;
operand_265.dimensionCount = 1;
const uint32_t dimensions_265[] = {128};
operand_265.dimensions = dimensions_265;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_265), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_266{};
operand_266.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_266.scale = 0.003958381246775389;
operand_266.zeroPoint = 126;
operand_266.dimensionCount = 4;
const uint32_t dimensions_266[] = {0, 6, 6, 128};
operand_266.dimensions = dimensions_266;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_266), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_267{};
operand_267.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_267.scale = 0.009366916492581367;
operand_267.zeroPoint = 121;
operand_267.dimensionCount = 4;
const uint32_t dimensions_267[] = {0, 6, 6, 128};
operand_267.dimensions = dimensions_267;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_267), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_268{};
operand_268.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_268.scale = 0.002321642125025392;
operand_268.zeroPoint = 121;
operand_268.dimensionCount = 4;
const uint32_t dimensions_268[] = {768, 1, 1, 128};
operand_268.dimensions = dimensions_268;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_268), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_269{};
operand_269.type = ANEURALNETWORKS_TENSOR_INT32;
operand_269.scale = 2.17466258618515e-05;
operand_269.zeroPoint = 0;
operand_269.dimensionCount = 1;
const uint32_t dimensions_269[] = {768};
operand_269.dimensions = dimensions_269;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_269), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_270{};
operand_270.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_270.scale = 0.002672255504876375;
operand_270.zeroPoint = 0;
operand_270.dimensionCount = 4;
const uint32_t dimensions_270[] = {0, 6, 6, 768};
operand_270.dimensions = dimensions_270;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_270), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_271{};
operand_271.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_271.scale = 0.0008156994008459151;
operand_271.zeroPoint = 131;
operand_271.dimensionCount = 4;
const uint32_t dimensions_271[] = {1, 3, 3, 768};
operand_271.dimensions = dimensions_271;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_271), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_272{};
operand_272.type = ANEURALNETWORKS_TENSOR_INT32;
operand_272.scale = 2.179757075282396e-06;
operand_272.zeroPoint = 0;
operand_272.dimensionCount = 1;
const uint32_t dimensions_272[] = {768};
operand_272.dimensions = dimensions_272;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_272), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_273{};
operand_273.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_273.scale = 0.00100218434818089;
operand_273.zeroPoint = 104;
operand_273.dimensionCount = 4;
const uint32_t dimensions_273[] = {0, 6, 6, 768};
operand_273.dimensions = dimensions_273;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_273), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_274{};
operand_274.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_274.scale = 0.02847485058009624;
operand_274.zeroPoint = 121;
operand_274.dimensionCount = 4;
const uint32_t dimensions_274[] = {128, 1, 1, 768};
operand_274.dimensions = dimensions_274;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_274), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_275{};
operand_275.type = ANEURALNETWORKS_TENSOR_INT32;
operand_275.scale = 2.853704972949345e-05;
operand_275.zeroPoint = 0;
operand_275.dimensionCount = 1;
const uint32_t dimensions_275[] = {128};
operand_275.dimensions = dimensions_275;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_275), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_276{};
operand_276.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_276.scale = 0.005113502498716116;
operand_276.zeroPoint = 134;
operand_276.dimensionCount = 4;
const uint32_t dimensions_276[] = {0, 6, 6, 128};
operand_276.dimensions = dimensions_276;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_276), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_277{};
operand_277.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_277.scale = 0.009635390713810921;
operand_277.zeroPoint = 126;
operand_277.dimensionCount = 4;
const uint32_t dimensions_277[] = {0, 6, 6, 128};
operand_277.dimensions = dimensions_277;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_277), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_278{};
operand_278.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_278.scale = 0.002073407173156738;
operand_278.zeroPoint = 138;
operand_278.dimensionCount = 4;
const uint32_t dimensions_278[] = {768, 1, 1, 128};
operand_278.dimensions = dimensions_278;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_278), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_279{};
operand_279.type = ANEURALNETWORKS_TENSOR_INT32;
operand_279.scale = 1.997808794840239e-05;
operand_279.zeroPoint = 0;
operand_279.dimensionCount = 1;
const uint32_t dimensions_279[] = {768};
operand_279.dimensions = dimensions_279;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_279), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_280{};
operand_280.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_280.scale = 0.00225812871940434;
operand_280.zeroPoint = 0;
operand_280.dimensionCount = 4;
const uint32_t dimensions_280[] = {0, 6, 6, 768};
operand_280.dimensions = dimensions_280;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_280), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_281{};
operand_281.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_281.scale = 0.0009067427599802613;
operand_281.zeroPoint = 116;
operand_281.dimensionCount = 4;
const uint32_t dimensions_281[] = {1, 3, 3, 768};
operand_281.dimensions = dimensions_281;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_281), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_282{};
operand_282.type = ANEURALNETWORKS_TENSOR_INT32;
operand_282.scale = 2.047542011496262e-06;
operand_282.zeroPoint = 0;
operand_282.dimensionCount = 1;
const uint32_t dimensions_282[] = {768};
operand_282.dimensions = dimensions_282;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_282), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_283{};
operand_283.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_283.scale = 0.001002039294689894;
operand_283.zeroPoint = 121;
operand_283.dimensionCount = 4;
const uint32_t dimensions_283[] = {0, 6, 6, 768};
operand_283.dimensions = dimensions_283;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_283), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_284{};
operand_284.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_284.scale = 0.0345500223338604;
operand_284.zeroPoint = 134;
operand_284.dimensionCount = 4;
const uint32_t dimensions_284[] = {128, 1, 1, 768};
operand_284.dimensions = dimensions_284;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_284), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_285{};
operand_285.type = ANEURALNETWORKS_TENSOR_INT32;
operand_285.scale = 3.462047970970161e-05;
operand_285.zeroPoint = 0;
operand_285.dimensionCount = 1;
const uint32_t dimensions_285[] = {128};
operand_285.dimensions = dimensions_285;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_285), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_286{};
operand_286.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_286.scale = 0.005219598766416311;
operand_286.zeroPoint = 129;
operand_286.dimensionCount = 4;
const uint32_t dimensions_286[] = {0, 6, 6, 128};
operand_286.dimensions = dimensions_286;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_286), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_287{};
operand_287.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_287.scale = 0.01011695526540279;
operand_287.zeroPoint = 125;
operand_287.dimensionCount = 4;
const uint32_t dimensions_287[] = {0, 6, 6, 128};
operand_287.dimensions = dimensions_287;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_287), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_288{};
operand_288.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_288.scale = 0.002151809399947524;
operand_288.zeroPoint = 134;
operand_288.dimensionCount = 4;
const uint32_t dimensions_288[] = {384, 1, 1, 128};
operand_288.dimensions = dimensions_288;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_288), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_289{};
operand_289.type = ANEURALNETWORKS_TENSOR_INT32;
operand_289.scale = 2.176975976908579e-05;
operand_289.zeroPoint = 0;
operand_289.dimensionCount = 1;
const uint32_t dimensions_289[] = {384};
operand_289.dimensions = dimensions_289;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_289), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_290{};
operand_290.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_290.scale = 0.003372935345396399;
operand_290.zeroPoint = 0;
operand_290.dimensionCount = 4;
const uint32_t dimensions_290[] = {0, 6, 6, 384};
operand_290.dimensions = dimensions_290;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_290), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_291{};
operand_291.type = ANEURALNETWORKS_FLOAT32;
operand_291.scale = 0;
operand_291.zeroPoint = 0;
operand_291.dimensionCount = 0;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_291), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_292{};
operand_292.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_292.scale = 0.003372935345396399;
operand_292.zeroPoint = 0;
operand_292.dimensionCount = 4;
const uint32_t dimensions_292[] = {0, 12, 12, 384};
operand_292.dimensions = dimensions_292;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_292), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_293{};
operand_293.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_293.scale = 0.001229611807502806;
operand_293.zeroPoint = 134;
operand_293.dimensionCount = 4;
const uint32_t dimensions_293[] = {1, 3, 3, 384};
operand_293.dimensions = dimensions_293;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_293), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_294{};
operand_294.type = ANEURALNETWORKS_TENSOR_INT32;
operand_294.scale = 4.147401341469958e-06;
operand_294.zeroPoint = 0;
operand_294.dimensionCount = 1;
const uint32_t dimensions_294[] = {384};
operand_294.dimensions = dimensions_294;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_294), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_295{};
operand_295.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_295.scale = 0.001418625121004879;
operand_295.zeroPoint = 129;
operand_295.dimensionCount = 4;
const uint32_t dimensions_295[] = {0, 12, 12, 384};
operand_295.dimensions = dimensions_295;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_295), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_296{};
operand_296.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_296.scale = 0.06397756934165955;
operand_296.zeroPoint = 123;
operand_296.dimensionCount = 4;
const uint32_t dimensions_296[] = {64, 1, 1, 384};
operand_296.dimensions = dimensions_296;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_296), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_297{};
operand_297.type = ANEURALNETWORKS_TENSOR_INT32;
operand_297.scale = 9.076018613995984e-05;
operand_297.zeroPoint = 0;
operand_297.dimensionCount = 1;
const uint32_t dimensions_297[] = {64};
operand_297.dimensions = dimensions_297;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_297), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_298{};
operand_298.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_298.scale = 0.04541563242673874;
operand_298.zeroPoint = 145;
operand_298.dimensionCount = 4;
const uint32_t dimensions_298[] = {0, 12, 12, 64};
operand_298.dimensions = dimensions_298;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_298), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_299{};
operand_299.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_299.scale = 0.003162507666274905;
operand_299.zeroPoint = 127;
operand_299.dimensionCount = 4;
const uint32_t dimensions_299[] = {81, 1, 1, 64};
operand_299.dimensions = dimensions_299;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_299), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_300{};
operand_300.type = ANEURALNETWORKS_TENSOR_INT32;
operand_300.scale = 0.000143627286888659;
operand_300.zeroPoint = 0;
operand_300.dimensionCount = 1;
const uint32_t dimensions_300[] = {81};
operand_300.dimensions = dimensions_300;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_300), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_301{};
operand_301.type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
operand_301.scale = 0.08356435596942902;
operand_301.zeroPoint = 135;
operand_301.dimensionCount = 4;
const uint32_t dimensions_301[] = {0, 12, 12, 81};
operand_301.dimensions = dimensions_301;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_301), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_302{};
operand_302.type = ANEURALNETWORKS_TENSOR_FLOAT32;
operand_302.scale = 0;
operand_302.zeroPoint = 0;
operand_302.dimensionCount = 4;
const uint32_t dimensions_302[] = {0, 12, 12, 81};
operand_302.dimensions = dimensions_302;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_302), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_303{};
operand_303.type = ANEURALNETWORKS_TENSOR_INT32;
operand_303.scale = 0;
operand_303.zeroPoint = 0;
operand_303.dimensionCount = 1;
const uint32_t dimensions_303[] = {4};
operand_303.dimensions = dimensions_303;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_303), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_304{};
operand_304.type = ANEURALNETWORKS_TENSOR_FLOAT32;
operand_304.scale = 0;
operand_304.zeroPoint = 0;
operand_304.dimensionCount = 4;
const uint32_t dimensions_304[] = {0, 81, 12, 12};
operand_304.dimensions = dimensions_304;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_304), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_305{};
operand_305.type = ANEURALNETWORKS_TENSOR_FLOAT32;
operand_305.scale = 0;
operand_305.zeroPoint = 0;
operand_305.dimensionCount = 4;
const uint32_t dimensions_305[] = {0, 81, 12, 12};
operand_305.dimensions = dimensions_305;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_305), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_306{};
operand_306.type = ANEURALNETWORKS_TENSOR_INT32;
operand_306.scale = 0;
operand_306.zeroPoint = 0;
operand_306.dimensionCount = 1;
const uint32_t dimensions_306[] = {2};
operand_306.dimensions = dimensions_306;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_306), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_307{};
operand_307.type = ANEURALNETWORKS_TENSOR_INT32;
operand_307.scale = 0;
operand_307.zeroPoint = 0;
operand_307.dimensionCount = 1;
const uint32_t dimensions_307[] = {2};
operand_307.dimensions = dimensions_307;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_307), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_308{};
operand_308.type = ANEURALNETWORKS_TENSOR_FLOAT32;
operand_308.scale = 0;
operand_308.zeroPoint = 0;
operand_308.dimensionCount = 2;
const uint32_t dimensions_308[] = {1, 1};
operand_308.dimensions = dimensions_308;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_308), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType operand_309{};
operand_309.type = ANEURALNETWORKS_TENSOR_FLOAT32;
operand_309.scale = 0;
operand_309.zeroPoint = 0;
operand_309.dimensionCount = 1;
const uint32_t dimensions_309[] = {0};
operand_309.dimensions = dimensions_309;
ASSERT_EQ(ANeuralNetworksModel_addOperand(model, &operand_309), ANEURALNETWORKS_NO_ERROR);
#include "generated/maskrcnn/maskrcnn2go_quantized_const_data.cpp"
const uint32_t input_0[] = {2, 6};
const uint32_t output_0[] = {7};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_TRANSPOSE, 2, input_0, 1,
output_0),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_1[] = {7};
const uint32_t output_1[] = {8};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_QUANTIZE, 1, input_1, 1,
output_1),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_2[] = {8, 9, 10, 11, 11, 11, 11, 12, 12, 11, 0};
const uint32_t output_2[] = {13};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_2, 1,
output_2),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_3[] = {13, 14, 15, 16, 16, 16, 16, 11, 11, 11, 0};
const uint32_t output_3[] = {17};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_3, 1,
output_3),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_4[] = {17, 18, 19, 11, 11, 11, 11, 11, 11, 11, 16, 0};
const uint32_t output_4[] = {20};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_DEPTHWISE_CONV_2D, 12,
input_4, 1, output_4),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_5[] = {20, 21, 22, 16, 16, 16, 16, 11, 11, 16, 0};
const uint32_t output_5[] = {23};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_5, 1,
output_5),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_6[] = {23, 13, 16};
const uint32_t output_6[] = {24};
ASSERT_EQ(
ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_ADD, 3, input_6, 1, output_6),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_7[] = {24, 25, 26, 16, 16, 16, 16, 11, 11, 11, 0};
const uint32_t output_7[] = {27};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_7, 1,
output_7),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_8[] = {27, 28, 29, 11, 11, 11, 11, 12, 12, 11, 16, 0};
const uint32_t output_8[] = {30};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_DEPTHWISE_CONV_2D, 12,
input_8, 1, output_8),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_9[] = {30, 31, 32, 16, 16, 16, 16, 11, 11, 16, 0};
const uint32_t output_9[] = {33};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_9, 1,
output_9),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_10[] = {33, 34, 35, 16, 16, 16, 16, 11, 11, 11, 0};
const uint32_t output_10[] = {36};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_10, 1,
output_10),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_11[] = {36, 37, 38, 11, 11, 11, 11, 11, 11, 11, 16, 0};
const uint32_t output_11[] = {39};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_DEPTHWISE_CONV_2D, 12,
input_11, 1, output_11),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_12[] = {39, 40, 41, 16, 16, 16, 16, 11, 11, 16, 0};
const uint32_t output_12[] = {42};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_12, 1,
output_12),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_13[] = {42, 33, 16};
const uint32_t output_13[] = {43};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_ADD, 3, input_13, 1,
output_13),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_14[] = {43, 44, 45, 16, 16, 16, 16, 11, 11, 11, 0};
const uint32_t output_14[] = {46};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_14, 1,
output_14),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_15[] = {46, 47, 48, 11, 11, 11, 11, 12, 12, 11, 16, 0};
const uint32_t output_15[] = {49};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_DEPTHWISE_CONV_2D, 12,
input_15, 1, output_15),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_16[] = {49, 50, 51, 16, 16, 16, 16, 11, 11, 16, 0};
const uint32_t output_16[] = {52};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_16, 1,
output_16),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_17[] = {52, 53, 54, 16, 16, 16, 16, 11, 11, 11, 0};
const uint32_t output_17[] = {55};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_17, 1,
output_17),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_18[] = {55, 56, 57, 11, 11, 11, 11, 11, 11, 11, 16, 0};
const uint32_t output_18[] = {58};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_DEPTHWISE_CONV_2D, 12,
input_18, 1, output_18),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_19[] = {58, 59, 60, 16, 16, 16, 16, 11, 11, 16, 0};
const uint32_t output_19[] = {61};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_19, 1,
output_19),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_20[] = {61, 52, 16};
const uint32_t output_20[] = {62};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_ADD, 3, input_20, 1,
output_20),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_21[] = {62, 63, 64, 16, 16, 16, 16, 11, 11, 11, 0};
const uint32_t output_21[] = {65};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_21, 1,
output_21),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_22[] = {65, 66, 67, 11, 11, 11, 11, 11, 11, 11, 16, 0};
const uint32_t output_22[] = {68};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_DEPTHWISE_CONV_2D, 12,
input_22, 1, output_22),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_23[] = {68, 69, 70, 16, 16, 16, 16, 11, 11, 16, 0};
const uint32_t output_23[] = {71};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_23, 1,
output_23),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_24[] = {71, 62, 16};
const uint32_t output_24[] = {72};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_ADD, 3, input_24, 1,
output_24),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_25[] = {72, 73, 74, 16, 16, 16, 16, 11, 11, 11, 0};
const uint32_t output_25[] = {75};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_25, 1,
output_25),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_26[] = {75, 76, 77, 11, 11, 11, 11, 12, 12, 11, 16, 0};
const uint32_t output_26[] = {78};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_DEPTHWISE_CONV_2D, 12,
input_26, 1, output_26),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_27[] = {78, 79, 80, 16, 16, 16, 16, 11, 11, 16, 0};
const uint32_t output_27[] = {81};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_27, 1,
output_27),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_28[] = {81, 82, 83, 16, 16, 16, 16, 11, 11, 11, 0};
const uint32_t output_28[] = {84};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_28, 1,
output_28),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_29[] = {84, 85, 86, 11, 11, 11, 11, 11, 11, 11, 16, 0};
const uint32_t output_29[] = {87};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_DEPTHWISE_CONV_2D, 12,
input_29, 1, output_29),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_30[] = {87, 88, 89, 16, 16, 16, 16, 11, 11, 16, 0};
const uint32_t output_30[] = {90};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_30, 1,
output_30),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_31[] = {90, 81, 16};
const uint32_t output_31[] = {91};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_ADD, 3, input_31, 1,
output_31),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_32[] = {91, 92, 93, 16, 16, 16, 16, 11, 11, 11, 0};
const uint32_t output_32[] = {94};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_32, 1,
output_32),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_33[] = {94, 95, 96, 11, 11, 11, 11, 11, 11, 11, 16, 0};
const uint32_t output_33[] = {97};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_DEPTHWISE_CONV_2D, 12,
input_33, 1, output_33),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_34[] = {97, 98, 99, 16, 16, 16, 16, 11, 11, 16, 0};
const uint32_t output_34[] = {100};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_34, 1,
output_34),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_35[] = {100, 91, 16};
const uint32_t output_35[] = {101};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_ADD, 3, input_35, 1,
output_35),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_36[] = {101, 102, 103, 16, 16, 16, 16, 11, 11, 11, 0};
const uint32_t output_36[] = {104};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_36, 1,
output_36),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_37[] = {104, 105, 106, 11, 11, 11, 11, 11, 11, 11, 16, 0};
const uint32_t output_37[] = {107};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_DEPTHWISE_CONV_2D, 12,
input_37, 1, output_37),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_38[] = {107, 108, 109, 16, 16, 16, 16, 11, 11, 16, 0};
const uint32_t output_38[] = {110};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_38, 1,
output_38),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_39[] = {110, 101, 16};
const uint32_t output_39[] = {111};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_ADD, 3, input_39, 1,
output_39),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_40[] = {111, 112, 113, 16, 16, 16, 16, 11, 11, 11, 0};
const uint32_t output_40[] = {114};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_40, 1,
output_40),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_41[] = {114, 115, 116, 11, 11, 11, 11, 11, 11, 11, 16, 0};
const uint32_t output_41[] = {117};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_DEPTHWISE_CONV_2D, 12,
input_41, 1, output_41),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_42[] = {117, 118, 119, 16, 16, 16, 16, 11, 11, 16, 0};
const uint32_t output_42[] = {120};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_42, 1,
output_42),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_43[] = {120, 121, 122, 16, 16, 16, 16, 11, 11, 11, 0};
const uint32_t output_43[] = {123};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_43, 1,
output_43),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_44[] = {123, 124, 125, 11, 11, 11, 11, 11, 11, 11, 16, 0};
const uint32_t output_44[] = {126};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_DEPTHWISE_CONV_2D, 12,
input_44, 1, output_44),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_45[] = {126, 127, 128, 16, 16, 16, 16, 11, 11, 16, 0};
const uint32_t output_45[] = {129};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_45, 1,
output_45),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_46[] = {129, 120, 16};
const uint32_t output_46[] = {130};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_ADD, 3, input_46, 1,
output_46),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_47[] = {130, 131, 132, 16, 16, 16, 16, 11, 11, 11, 0};
const uint32_t output_47[] = {133};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_47, 1,
output_47),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_48[] = {133, 134, 135, 11, 11, 11, 11, 11, 11, 11, 16, 0};
const uint32_t output_48[] = {136};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_DEPTHWISE_CONV_2D, 12,
input_48, 1, output_48),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_49[] = {136, 137, 138, 16, 16, 16, 16, 11, 11, 16, 0};
const uint32_t output_49[] = {139};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_49, 1,
output_49),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_50[] = {139, 130, 16};
const uint32_t output_50[] = {140};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_ADD, 3, input_50, 1,
output_50),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_51[] = {140, 141, 142, 16, 16, 16, 16, 11, 11, 11, 0};
const uint32_t output_51[] = {143};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_51, 1,
output_51),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_52[] = {143, 144, 145, 11, 11, 11, 11, 11, 11, 11, 16, 0};
const uint32_t output_52[] = {146};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_DEPTHWISE_CONV_2D, 12,
input_52, 1, output_52),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_53[] = {146, 147, 148, 16, 16, 16, 16, 11, 11, 16, 0};
const uint32_t output_53[] = {149};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_53, 1,
output_53),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_54[] = {149, 140, 16};
const uint32_t output_54[] = {150};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_ADD, 3, input_54, 1,
output_54),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_55[] = {150, 151, 152, 16, 16, 16, 16, 11, 11, 11, 0};
const uint32_t output_55[] = {153};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_55, 1,
output_55),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_56[] = {153, 154, 155, 11, 11, 11, 11, 11, 11, 11, 16, 0};
const uint32_t output_56[] = {156};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_DEPTHWISE_CONV_2D, 12,
input_56, 1, output_56),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_57[] = {156, 157, 158, 16, 16, 16, 16, 11, 11, 16, 0};
const uint32_t output_57[] = {159};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_57, 1,
output_57),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_58[] = {159, 150, 16};
const uint32_t output_58[] = {160};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_ADD, 3, input_58, 1,
output_58),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_59[] = {160, 161, 162, 16, 16, 16, 16, 11, 11, 11, 0};
const uint32_t output_59[] = {163};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_59, 1,
output_59),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_60[] = {163, 164, 165, 11, 11, 11, 11, 11, 11, 11, 16, 0};
const uint32_t output_60[] = {166};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_DEPTHWISE_CONV_2D, 12,
input_60, 1, output_60),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_61[] = {166, 167, 168, 16, 16, 16, 16, 11, 11, 16, 0};
const uint32_t output_61[] = {169};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_61, 1,
output_61),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_62[] = {169, 160, 16};
const uint32_t output_62[] = {170};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_ADD, 3, input_62, 1,
output_62),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_63[] = {170, 171, 172, 16, 16, 16, 16, 11, 11, 16, 0};
const uint32_t output_63[] = {173};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_63, 1,
output_63),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_64[] = {170, 174, 175, 16, 16, 16, 16, 11, 11, 16, 0};
const uint32_t output_64[] = {176};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_64, 1,
output_64),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_65[] = {173, 176, 177, 5, 178, 178, 179, 180, 181, 182, 0};
const uint32_t output_65[] = {183, 184, 185};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_GENERATE_PROPOSALS, 11,
input_65, 3, output_65),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_66[] = {140, 184, 185, 186, 186, 178, 178, 16, 16, 0};
const uint32_t output_66[] = {187};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_ROI_ALIGN, 10, input_66, 1,
output_66),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_67[] = {187, 188, 189, 16, 16, 16, 16, 11, 11, 11, 0};
const uint32_t output_67[] = {190};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_67, 1,
output_67),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_68[] = {190, 191, 192, 11, 11, 11, 11, 12, 12, 11, 16, 0};
const uint32_t output_68[] = {193};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_DEPTHWISE_CONV_2D, 12,
input_68, 1, output_68),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_69[] = {193, 194, 195, 16, 16, 16, 16, 11, 11, 16, 0};
const uint32_t output_69[] = {196};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_69, 1,
output_69),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_70[] = {196, 197, 198, 16, 16, 16, 16, 11, 11, 11, 0};
const uint32_t output_70[] = {199};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_70, 1,
output_70),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_71[] = {199, 200, 201, 11, 11, 11, 11, 11, 11, 11, 16, 0};
const uint32_t output_71[] = {202};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_DEPTHWISE_CONV_2D, 12,
input_71, 1, output_71),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_72[] = {202, 203, 204, 16, 16, 16, 16, 11, 11, 16, 0};
const uint32_t output_72[] = {205};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_72, 1,
output_72),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_73[] = {205, 196, 16};
const uint32_t output_73[] = {206};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_ADD, 3, input_73, 1,
output_73),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_74[] = {206, 207, 208, 16, 16, 16, 16, 11, 11, 11, 0};
const uint32_t output_74[] = {209};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_74, 1,
output_74),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_75[] = {209, 210, 211, 11, 11, 11, 11, 11, 11, 11, 16, 0};
const uint32_t output_75[] = {212};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_DEPTHWISE_CONV_2D, 12,
input_75, 1, output_75),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_76[] = {212, 213, 214, 16, 16, 16, 16, 11, 11, 16, 0};
const uint32_t output_76[] = {215};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_76, 1,
output_76),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_77[] = {215, 206, 16};
const uint32_t output_77[] = {216};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_ADD, 3, input_77, 1,
output_77),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_78[] = {216, 217, 218, 16, 16, 16, 16, 11, 11, 11, 0};
const uint32_t output_78[] = {219};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_78, 1,
output_78),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_79[] = {219, 220, 221, 11, 11, 11, 11, 11, 11, 11, 16, 0};
const uint32_t output_79[] = {222};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_DEPTHWISE_CONV_2D, 12,
input_79, 1, output_79),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_80[] = {222, 223, 224, 16, 16, 16, 16, 11, 11, 16, 0};
const uint32_t output_80[] = {225};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_80, 1,
output_80),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_81[] = {225, 226, 227, 16, 16, 16, 16, 11, 11, 11, 0};
const uint32_t output_81[] = {228};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_81, 1,
output_81),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_82[] = {228, 16, 16, 16, 16, 11, 11, 229, 229, 16, 0};
const uint32_t output_82[] = {230};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_AVERAGE_POOL_2D, 11,
input_82, 1, output_82),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_83[] = {230, 231, 232, 16};
const uint32_t output_83[] = {233};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_FULLY_CONNECTED, 4, input_83,
1, output_83),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_84[] = {233, 234};
const uint32_t output_84[] = {235};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_SOFTMAX, 2, input_84, 1,
output_84),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_85[] = {230, 236, 237, 16};
const uint32_t output_85[] = {238};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_FULLY_CONNECTED, 4, input_85,
1, output_85),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_86[] = {184, 238, 185, 5};
const uint32_t output_86[] = {239};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_AXIS_ALIGNED_BBOX_TRANSFORM,
4, input_86, 1, output_86),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_87[] = {235, 239, 185, 240, 180, 11, 241, 242, 182};
const uint32_t output_87[] = {243, 244, 245, 246};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_BOX_WITH_NMS_LIMIT, 9,
input_87, 4, output_87),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_88[] = {140, 244, 246, 186, 186, 178, 178, 16, 16, 0};
const uint32_t output_88[] = {247};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_ROI_ALIGN, 10, input_88, 1,
output_88),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_89[] = {247, 248, 249, 16, 16, 16, 16, 11, 11, 11, 0};
const uint32_t output_89[] = {250};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_89, 1,
output_89),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_90[] = {250, 251, 252, 11, 11, 11, 11, 11, 11, 11, 16, 0};
const uint32_t output_90[] = {253};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_DEPTHWISE_CONV_2D, 12,
input_90, 1, output_90),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_91[] = {253, 254, 255, 16, 16, 16, 16, 11, 11, 16, 0};
const uint32_t output_91[] = {256};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_91, 1,
output_91),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_92[] = {256, 247, 16};
const uint32_t output_92[] = {257};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_ADD, 3, input_92, 1,
output_92),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_93[] = {257, 258, 259, 16, 16, 16, 16, 11, 11, 11, 0};
const uint32_t output_93[] = {260};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_93, 1,
output_93),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_94[] = {260, 261, 262, 11, 11, 11, 11, 11, 11, 11, 16, 0};
const uint32_t output_94[] = {263};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_DEPTHWISE_CONV_2D, 12,
input_94, 1, output_94),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_95[] = {263, 264, 265, 16, 16, 16, 16, 11, 11, 16, 0};
const uint32_t output_95[] = {266};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_95, 1,
output_95),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_96[] = {266, 257, 16};
const uint32_t output_96[] = {267};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_ADD, 3, input_96, 1,
output_96),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_97[] = {267, 268, 269, 16, 16, 16, 16, 11, 11, 11, 0};
const uint32_t output_97[] = {270};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_97, 1,
output_97),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_98[] = {270, 271, 272, 11, 11, 11, 11, 11, 11, 11, 16, 0};
const uint32_t output_98[] = {273};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_DEPTHWISE_CONV_2D, 12,
input_98, 1, output_98),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_99[] = {273, 274, 275, 16, 16, 16, 16, 11, 11, 16, 0};
const uint32_t output_99[] = {276};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_99, 1,
output_99),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_100[] = {276, 267, 16};
const uint32_t output_100[] = {277};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_ADD, 3, input_100, 1,
output_100),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_101[] = {277, 278, 279, 16, 16, 16, 16, 11, 11, 11, 0};
const uint32_t output_101[] = {280};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_101, 1,
output_101),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_102[] = {280, 281, 282, 11, 11, 11, 11, 11, 11, 11, 16, 0};
const uint32_t output_102[] = {283};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_DEPTHWISE_CONV_2D, 12,
input_102, 1, output_102),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_103[] = {283, 284, 285, 16, 16, 16, 16, 11, 11, 16, 0};
const uint32_t output_103[] = {286};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_103, 1,
output_103),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_104[] = {286, 277, 16};
const uint32_t output_104[] = {287};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_ADD, 3, input_104, 1,
output_104),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_105[] = {287, 288, 289, 16, 16, 16, 16, 11, 11, 11, 0};
const uint32_t output_105[] = {290};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_105, 1,
output_105),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_106[] = {290, 291, 291, 0};
const uint32_t output_106[] = {292};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_RESIZE_NEAREST_NEIGHBOR, 4,
input_106, 1, output_106),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_107[] = {292, 293, 294, 11, 11, 11, 11, 11, 11, 11, 16, 0};
const uint32_t output_107[] = {295};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_DEPTHWISE_CONV_2D, 12,
input_107, 1, output_107),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_108[] = {295, 296, 297, 16, 16, 16, 16, 11, 11, 16, 0};
const uint32_t output_108[] = {298};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_108, 1,
output_108),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_109[] = {298, 299, 300, 16, 16, 16, 16, 11, 11, 16, 0};
const uint32_t output_109[] = {301};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_CONV_2D, 11, input_109, 1,
output_109),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_110[] = {301};
const uint32_t output_110[] = {302};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_DEQUANTIZE, 1, input_110, 1,
output_110),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_111[] = {302, 303};
const uint32_t output_111[] = {304};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_TRANSPOSE, 2, input_111, 1,
output_111),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_112[] = {304};
const uint32_t output_112[] = {305};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_LOGISTIC, 1, input_112, 1,
output_112),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_113[] = {3, 306, 307};
const uint32_t output_113[] = {308};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_SLICE, 3, input_113, 1,
output_113),
ANEURALNETWORKS_NO_ERROR);
const uint32_t input_114[] = {243};
const uint32_t output_114[] = {309};
ASSERT_EQ(ANeuralNetworksModel_addOperation(model, ANEURALNETWORKS_DEQUANTIZE, 1, input_114, 1,
output_114),
ANEURALNETWORKS_NO_ERROR);
const uint32_t model_inputs[] = {2, 3, 4, 5};
const uint32_t model_outputs[] = {309, 244, 245, 305};
ASSERT_EQ(
ANeuralNetworksModel_identifyInputsAndOutputs(model, 4, model_inputs, 4, model_outputs),
ANEURALNETWORKS_NO_ERROR);
ASSERT_EQ(ANeuralNetworksModel_finish(model), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksCompilation* compilation = nullptr;
ASSERT_EQ(ANeuralNetworksCompilation_create(model, &compilation), ANEURALNETWORKS_NO_ERROR);
ASSERT_EQ(ANeuralNetworksCompilation_finish(compilation), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksExecution* execution = nullptr;
ASSERT_EQ(ANeuralNetworksExecution_create(compilation, &execution), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType input_operand_0{};
input_operand_0.type = ANEURALNETWORKS_TENSOR_FLOAT32;
input_operand_0.scale = 0;
input_operand_0.zeroPoint = 0;
input_operand_0.dimensionCount = 4;
const uint32_t input_dimensions_0[] = {1, 3, 462, 320};
input_operand_0.dimensions = input_dimensions_0;
ASSERT_EQ(ANeuralNetworksExecution_setInput(execution, 0, &input_operand_0,
execution_input_buffer_0, 1774080),
ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType input_operand_1{};
input_operand_1.type = ANEURALNETWORKS_TENSOR_FLOAT32;
input_operand_1.scale = 0;
input_operand_1.zeroPoint = 0;
input_operand_1.dimensionCount = 2;
const uint32_t input_dimensions_1[] = {1, 3};
input_operand_1.dimensions = input_dimensions_1;
const uint8_t execution_input_buffer_1[] = {0, 0, 231, 67, 0, 0, 160, 67, 198, 235, 56, 63};
ASSERT_EQ(ANeuralNetworksExecution_setInput(execution, 1, &input_operand_1,
execution_input_buffer_1, 12),
ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType input_operand_2{};
input_operand_2.type = ANEURALNETWORKS_TENSOR_FLOAT32;
input_operand_2.scale = 0;
input_operand_2.zeroPoint = 0;
input_operand_2.dimensionCount = 2;
const uint32_t input_dimensions_2[] = {1, 2};
input_operand_2.dimensions = input_dimensions_2;
const uint8_t execution_input_buffer_2[] = {0, 0, 231, 67, 0, 0, 160, 67};
ASSERT_EQ(ANeuralNetworksExecution_setInput(execution, 2, &input_operand_2,
execution_input_buffer_2, 8),
ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksOperandType input_operand_3{};
input_operand_3.type = ANEURALNETWORKS_TENSOR_FLOAT32;
input_operand_3.scale = 0;
input_operand_3.zeroPoint = 0;
input_operand_3.dimensionCount = 2;
const uint32_t input_dimensions_3[] = {1, 2};
input_operand_3.dimensions = input_dimensions_3;
const uint8_t execution_input_buffer_3[] = {112, 14, 0, 10};
ASSERT_EQ(ANeuralNetworksExecution_setInput(execution, 3, &input_operand_3,
execution_input_buffer_3, 4),
ANEURALNETWORKS_NO_ERROR);
static uint8_t execution_output_buffer_0[462];
ASSERT_EQ(
ANeuralNetworksExecution_setOutput(execution, 0, NULL, execution_output_buffer_0, 462),
ANEURALNETWORKS_NO_ERROR);
static uint8_t execution_output_buffer_1[924];
ASSERT_EQ(
ANeuralNetworksExecution_setOutput(execution, 1, NULL, execution_output_buffer_1, 924),
ANEURALNETWORKS_NO_ERROR);
static uint8_t execution_output_buffer_2[462];
ASSERT_EQ(
ANeuralNetworksExecution_setOutput(execution, 2, NULL, execution_output_buffer_2, 462),
ANEURALNETWORKS_NO_ERROR);
static uint8_t execution_output_buffer_3[5388768];
ASSERT_EQ(ANeuralNetworksExecution_setOutput(execution, 3, NULL, execution_output_buffer_3,
5388768),
ANEURALNETWORKS_NO_ERROR);
ASSERT_EQ(ANeuralNetworksExecution_compute(execution), ANEURALNETWORKS_NO_ERROR);
ANeuralNetworksExecution_free(execution);
ANeuralNetworksCompilation_free(compilation);
ANeuralNetworksModel_free(model);
}
} // namespace
| 52.412516 | 100 | 0.725542 | [
"model"
] |
8fef1336dd7b75449230836c345dc6d9ee999ff3 | 2,755 | hh | C++ | userFiles/ctrl/io/ctrl_options/CtrlOptions.hh | mharding01/augmented-neuromuscular-RT-running | 7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834 | [
"MIT"
] | null | null | null | userFiles/ctrl/io/ctrl_options/CtrlOptions.hh | mharding01/augmented-neuromuscular-RT-running | 7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834 | [
"MIT"
] | null | null | null | userFiles/ctrl/io/ctrl_options/CtrlOptions.hh | mharding01/augmented-neuromuscular-RT-running | 7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834 | [
"MIT"
] | null | null | null | /*!
* \author Nicolas Van der Noot
* \file CtrlOptions.hh
* \brief CtrlOptions class
*/
#ifndef _CTRL_OPTIONS_HH_
#define _CTRL_OPTIONS_HH_
#ifdef ROBOTRAN_SIMU
#include "user_realtime.h"
#endif
enum{CTRL_DEFAULT, CTRL_REFLEX, CTRL_CPG, CTRL_STIM_TEST, CTRL_REFLEX_WANG};
enum{COMAN_DEFAULT, COMAN_SHORT_FEET, COMAN_FLEX_CAT_1, COMAN_FLEX_CAT_2};
/*! \brief controller options
*/
class CtrlOptions
{
public:
CtrlOptions();
~CtrlOptions();
int get_flag_coman() const { return flag_coman; }
int get_flag_ctrl() const { return flag_ctrl; }
int is_flag_3D() const { return flag_3D; }
int is_r_first_swing() const { return r_first_swing; }
int is_upper_motion() const { return upper_motion; }
int is_torque_limit() const { return torque_limit; }
int is_extra_knee() const { return extra_knee; }
int is_cpg_range() const { return cpg_range; }
int is_extra_ham_reflex() const { return extra_ham_reflex; }
int is_extra_ta_reflex() const { return extra_ta_reflex; }
int is_opti() const { return opti; }
int is_muscle_noise() const { return muscle_noise; }
int is_print() const { return print; }
int is_ctrl_two_parts() const { return ctrl_two_parts; }
int is_Qq_match_wang() const { return flag_Qq_match_wang; }
int is_initial_pos() const { return flag_initial_pos; }
int is_apply_Qq_wang() const { return apply_Qq_wang; }
private:
int flag_coman; ///< flag corresponding to the COMAN model used
int flag_ctrl; ///< flag corresponding to the controller type
int flag_3D; ///< 1 if 3D walking, 0 otherwise
int r_first_swing; ///< 1 if right leg first in swing, 0 otherwise
int upper_motion; ///< 1 for upper-body motion, 0 otherwise
int torque_limit; ///< 1 to limit the torque outputs, 0 otherwise
int extra_knee; ///< 1 for the extra swing knee CPG stimulation
int cpg_range; ///< 1 for CPG range speed, 0 for fixed CPG speed
int extra_ham_reflex; ///< extra reflex to flex the knee in early swing
int extra_ta_reflex; ///< extra reflex to flex the foot in late swing
int opti; ///< 1 to run an optimization, 0 otherwise
int muscle_noise; ///< 1 to add noise on the muscle stimulations, 0 otherwise
int print; ///< 1 to print comments, 0 otherwise
int ctrl_two_parts; ///< 1 for ctrl in two parts : first with know results and after with opti's results, 0 otherwise
int flag_Qq_match_wang; ///< 1 to find param from Qq wang with driven joints for position, 0 otherwise
int flag_initial_pos; ///< 1 to optimize initial positions and velocities for joints, 0 otherwise
int apply_Qq_wang; ///< 1 to apply Wang torque (with opti shifting and sclaling) in leg pitch articulations, 0 otherwise
};
#endif
| 34.4375 | 123 | 0.716515 | [
"model",
"3d"
] |
8ff495b65f8996ac67fc9a9c7314647ab07e03e4 | 7,445 | cpp | C++ | Notification/NotificationWidget.cpp | devonchenc/NovaImage | 3d17166f9705ba23b89f1aefd31ac2db97385b1c | [
"MIT"
] | null | null | null | Notification/NotificationWidget.cpp | devonchenc/NovaImage | 3d17166f9705ba23b89f1aefd31ac2db97385b1c | [
"MIT"
] | null | null | null | Notification/NotificationWidget.cpp | devonchenc/NovaImage | 3d17166f9705ba23b89f1aefd31ac2db97385b1c | [
"MIT"
] | null | null | null | #include "NotificationWidget.h"
#include <QString>
#include <QGuiApplication>
#include <QMessageBox>
#include <QDesktopWidget>
#include <QPropertyAnimation>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QPainter>
#include <QScreen>
#include <QGraphicsOpacityEffect>
namespace NotificationWidgetDetails
{
static std::vector<std::pair<QMessageBox::Icon, NotificationParams::Type>> notificationIconsConvertor =
{
std::make_pair(QMessageBox::Information, NotificationParams::Information),
std::make_pair(QMessageBox::Warning, NotificationParams::Warning),
std::make_pair(QMessageBox::Critical, NotificationParams::Critical)
};
QMessageBox::Icon Convert(const NotificationParams::Type& type)
{
using IconNode = std::pair<QMessageBox::Icon, NotificationParams::Type>;
auto iter = std::find_if(notificationIconsConvertor.begin(), notificationIconsConvertor.end(), [type](const IconNode& node)
{
return node.second == type;
});
Q_ASSERT(iter != notificationIconsConvertor.end());
return iter->first;
}
QString ColorToHTML(const QColor& color)
{
QString ret = QString("#%1%2%3%4")
.arg(color.alpha(), 2, 16, QChar('0'))
.arg(color.red(), 2, 16, QChar('0'))
.arg(color.green(), 2, 16, QChar('0'))
.arg(color.blue(), 2, 16, QChar('0'));
return ret;
}
} //namespace NotificationWidgetDetails
NotificationWidget::NotificationWidget(const NotificationParams& params, QWidget* parent)
: QWidget(parent)
{
setWindowFlags(Qt::FramelessWindowHint | Qt::Tool | Qt::WindowStaysOnTopHint);
setAttribute(Qt::WA_TranslucentBackground); // Indicates that the background will be transparent
setAttribute(Qt::WA_ShowWithoutActivating); // At the show, the widget does not get the focus automatically
_effect = new QGraphicsOpacityEffect(this);
_effect->setOpacity(0.85);
setGraphicsEffect(_effect);
initUI(params);
QRect geometry = QGuiApplication::primaryScreen()->availableGeometry();
setFixedWidth(geometry.width() / 6);
setMaximumHeight(geometry.height() / 3);
}
void NotificationWidget::onCloseButtonClicked()
{
emit closeButtonClicked(this);
}
void NotificationWidget::onDetailsButtonClicked()
{
emit detailsButtonClicked(this);
}
void NotificationWidget::initUI(const NotificationParams& params)
{
QHBoxLayout* titleLayout = new QHBoxLayout;
titleLayout->setSpacing(12);
QFontMetrics fm(font());
int fontHeight = fm.height() * 2;
QLabel* iconLabel = new QLabel();
QMessageBox::Icon icon = NotificationWidgetDetails::Convert(params.type);
QPixmap image = QMessageBox::standardIcon(icon).scaled(QSize(fontHeight, fontHeight), Qt::KeepAspectRatio, Qt::SmoothTransformation);
iconLabel->setPixmap(image);
iconLabel->setScaledContents(false);
titleLayout->addWidget(iconLabel);
if (params.title.isEmpty() == false)
{
QString title = params.title;
QLabel* labelTitle = new QLabel(title);
labelTitle->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);
labelTitle->setStyleSheet("font-weight: bold;");
titleLayout->addWidget(labelTitle);
}
QLabel* messageLabel = new QLabel(params.message);
messageLabel->setMinimumHeight(30);
messageLabel->setMaximumHeight(30);
messageLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
messageLabel->setWordWrap(true);
QHBoxLayout* mesLayout = new QHBoxLayout;
mesLayout->addSpacing(20);
mesLayout->addWidget(messageLabel);
QVBoxLayout* messageLayout = new QVBoxLayout();
messageLayout->setSpacing(5);
messageLayout->addItem(titleLayout);
messageLayout->addLayout(mesLayout);
QHBoxLayout* mainLayout = new QHBoxLayout;
mainLayout->setContentsMargins(10, 10, 10, 10);
mainLayout->addItem(messageLayout);
QPalette palette;
QColor baseColor = palette.color(QPalette::Midlight);
QColor buttonColor = baseColor;
buttonColor.setAlpha(0);
QColor pressedColor = baseColor;
pressedColor.setAlpha(255);
QString styleSheet = QString("QPushButton {"
"border-radius: 1px;"
"background-color: " +
NotificationWidgetDetails::ColorToHTML(buttonColor) + ";"
"padding: 5px;"
"}"
"QPushButton:pressed {"
"background-color: " +
NotificationWidgetDetails::ColorToHTML(pressedColor) + ";"
"}");
QVBoxLayout* buttonsLayout = new QVBoxLayout();
buttonsLayout->setContentsMargins(0, 0, 0, 0);
buttonsLayout->setSpacing(5);
{
_closeButton = new QPushButton(tr("Close"));
_closeButton->setStyleSheet(styleSheet);
_closeButton->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred));
buttonsLayout->addWidget(_closeButton);
connect(_closeButton, &QPushButton::clicked, this, &NotificationWidget::onCloseButtonClicked);
}
if (params.callback)
{
_detailsButton = new QPushButton(params.detailsButtonText);
_detailsButton->setStyleSheet(styleSheet);
_detailsButton->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred));
buttonsLayout->addWidget(_detailsButton);
connect(_detailsButton, &QPushButton::clicked, this, &NotificationWidget::onDetailsButtonClicked);
}
mainLayout->addItem(buttonsLayout);
setLayout(mainLayout);
}
void NotificationWidget::paintEvent(QPaintEvent*)
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
QRect roundedRect;
const int radius = 10;
roundedRect.setX(rect().x() + radius / 2);
roundedRect.setY(rect().y() + radius / 2);
roundedRect.setWidth(rect().width() - radius);
roundedRect.setHeight(rect().height() - radius);
QPalette palette;
QColor rectColor = palette.color(QPalette::Window);
painter.setBrush(QBrush(rectColor));
QPen roundedRectPen(Qt::black);
painter.setPen(roundedRectPen);
painter.drawRoundedRect(roundedRect, radius, radius);
QPen pen(Qt::gray, 1);
painter.setPen(pen);
QRect closeButtonGeometry = _closeButton->geometry();
//horizontal line
if (_detailsButton != nullptr)
{
QRect detailsButtonGeometry = _detailsButton->geometry();
int y = (closeButtonGeometry.bottom() + detailsButtonGeometry.top()) / 2;
QPoint left(qMin(closeButtonGeometry.left(), detailsButtonGeometry.left()), y);
QPoint right(qMax(closeButtonGeometry.right(), detailsButtonGeometry.right()), y);
painter.drawLine(left, right);
}
//vertical line
//close button and details button have Preferred size policy
int x = closeButtonGeometry.left() - pen.width();
QPoint top(x, roundedRect.top() + roundedRectPen.width());
QPoint bottom(x, roundedRect.bottom() - roundedRectPen.width());
painter.drawLine(top, bottom);
}
| 37.984694 | 137 | 0.658294 | [
"geometry",
"vector"
] |
8ffde503b8f8dfad026295724a903978b40d0f13 | 2,506 | cpp | C++ | chapter_7/chapter_7_main.cpp | bdolinar/ray_tracer_challenge_cpp | 96e746b58ca4a173583ecbccfcde714a22b12935 | [
"BSD-2-Clause"
] | null | null | null | chapter_7/chapter_7_main.cpp | bdolinar/ray_tracer_challenge_cpp | 96e746b58ca4a173583ecbccfcde714a22b12935 | [
"BSD-2-Clause"
] | null | null | null | chapter_7/chapter_7_main.cpp | bdolinar/ray_tracer_challenge_cpp | 96e746b58ca4a173583ecbccfcde714a22b12935 | [
"BSD-2-Clause"
] | null | null | null |
#include <fstream>
#include <raytracer/camera.h>
#include <raytracer/canvas.h>
#include <raytracer/intersection.h>
#include <raytracer/light.h>
#include <raytracer/material.h>
#include <raytracer/ray.h>
#include <raytracer/sphere.h>
#include <raytracer/transform.h>
int main(int argc, char* argv[])
{
World world;
Material floorMaterial;
floorMaterial.set_color(Color(1, 0.9, 0.9));
floorMaterial.set_specular(0);
auto floor = Sphere::new_ptr();
floor->set_transform(scaling(10, 0.01, 10));
floor->set_material(floorMaterial);
auto leftWall = Sphere::new_ptr();
auto leftWallTransform = translation(0, 0, 5) * rotation_y(-M_PI_4) * rotation_x(M_PI_2) * scaling(10, 0.01, 10);
leftWall->set_transform(leftWallTransform);
leftWall->set_material(floorMaterial);
auto rightWall = Sphere::new_ptr();
auto rightWallTransform = translation(0, 0, 5) * rotation_y(M_PI_4) * rotation_x(M_PI_2) * scaling(10, 0.01, 10);
rightWall->set_transform(rightWallTransform);
rightWall->set_material(floorMaterial);
auto middle = Sphere::new_ptr();
middle->set_transform(translation(-0.5, 1, 0.5));
Material middleMaterial;
middleMaterial.set_color(Color(0.1, 1, 0.5));
middleMaterial.set_diffuse(0.7);
middleMaterial.set_specular(0.3);
middle->set_material(middleMaterial);
auto right = Sphere::new_ptr();
right->set_transform(translation(1.5, 0.5, -0.5) * scaling(0.5, 0.5, 0.5));
Material rightMaterial;
rightMaterial.set_color(Color(0.5, 1, 0.1));
rightMaterial.set_diffuse(0.7);
rightMaterial.set_specular(0.3);
right->set_material(rightMaterial);
auto left = Sphere::new_ptr();
left->set_transform(translation(-1.5, 0.33, -0.75) * scaling(0.33, 0.33, 0.33));
Material leftMaterial;
leftMaterial.set_color(Color(1, 0.8, 0.1));
leftMaterial.set_diffuse(0.7);
leftMaterial.set_specular(0.3);
left->set_material(leftMaterial);
world.add_object(std::move(floor));
world.add_object(std::move(leftWall));
world.add_object(std::move(rightWall));
world.add_object(std::move(middle));
world.add_object(std::move(right));
world.add_object(std::move(left));
world.set_light(Light::new_ptr(point(-10, 10, -10), Color(1, 1, 1)));
Camera camera(200, 100, M_PI/3);
camera.set_transform(view_transform(point(0, 1.5, -5), point(0, 1, 0), vector(0, 1, 0)));
auto canvas = camera.render(world);
std::ofstream outfile;
outfile.open ("output.ppm");
canvas.to_ppm_file(outfile);
return 0;
}
| 32.973684 | 115 | 0.702314 | [
"render",
"vector",
"transform"
] |
8fff445919d5e2655aaf321428d6b478d8a49714 | 1,968 | cpp | C++ | LeetCode/C++/General/Easy/ValidWordSquare/main.cpp | busebd12/InterviewPreparation | e68c41f16f7790e44b10a229548186e13edb5998 | [
"MIT"
] | null | null | null | LeetCode/C++/General/Easy/ValidWordSquare/main.cpp | busebd12/InterviewPreparation | e68c41f16f7790e44b10a229548186e13edb5998 | [
"MIT"
] | null | null | null | LeetCode/C++/General/Easy/ValidWordSquare/main.cpp | busebd12/InterviewPreparation | e68c41f16f7790e44b10a229548186e13edb5998 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <string>
#include <deque>
using namespace std;
/*
* Approaches:
*
* 1) Store each row in a deque and then for each element in the column check to see if it matches
* the corresponding element in the row. The edge cases to watch out for are if the column size does
* not match the row size or if the number of rows and columns are not the same.
*
* Time complexity: O(n * (n + m)) [where n is the number of rows in the vector and m is the number of columns]
* Space complexity: O(n)
*
* 2) Same logic just without extra space and more efficient
*
* Time complexity: O(n * m) [where n is the number of rows and m is the number of columns]
* Space complexity: O(1)
*/
bool validWordSquare(vector<string>& words)
{
if(words.empty())
{
return true;
}
if(words.size()==1)
{
return true;
}
int n=int(words.size());
if(n > words[0].size())
{
return false;
}
for(int i=0;i<n;++i)
{
deque<char> dq;
for(int j=0;j<words[i].size();++j)
{
dq.push_back(words[i][j]);
}
for(int k=0;k<words[i].size();++k)
{
if(k >= n || k >= words[i].size())
{
break;
}
if(words[k][i]!=dq.front())
{
return false;
}
else
{
dq.pop_front();
}
}
if(!dq.empty())
{
return false;
}
}
return true;
}
bool validWordSquare(vector<string> & words)
{
for(int i=0;i<words.size();i++)
{
for(int j=0;j<words[i].size();j++)
{
if(words.size() <= j || words[j].size() <= i)
{
return false;
}
if(words[i][j]!=words[j][i])
{
return false;
}
}
}
return true;
} | 20.5 | 111 | 0.483232 | [
"vector"
] |
891381c587c06bebde889a50b7cfed729d15a794 | 4,012 | cpp | C++ | MasterSim/src/MSIM_FMUManager.cpp | ghorwin/MasterSim | 281b71e228435ca8fa02319bf2ce86b66b8b2b45 | [
"BSD-3-Clause"
] | 5 | 2021-11-17T07:12:54.000Z | 2022-03-16T15:06:39.000Z | MasterSim/src/MSIM_FMUManager.cpp | ghorwin/MasterSim | 281b71e228435ca8fa02319bf2ce86b66b8b2b45 | [
"BSD-3-Clause"
] | 25 | 2021-09-09T07:39:13.000Z | 2022-01-23T13:00:19.000Z | MasterSim/src/MSIM_FMUManager.cpp | ghorwin/MasterSim | 281b71e228435ca8fa02319bf2ce86b66b8b2b45 | [
"BSD-3-Clause"
] | null | null | null | #include "MSIM_FMUManager.h"
#include <memory> // for std::autoptr
#include <cstdlib>
#include <IBK_messages.h>
#include <IBK_Exception.h>
#include "MSIM_FMU.h"
namespace MASTER_SIM {
FMUManager::~FMUManager() {
for (std::vector<FMU*>::iterator it = m_fmus.begin(); it != m_fmus.end(); ++it) {
delete *it;
}
m_fmus.clear();
}
void FMUManager::importFMU(const IBK::Path & fmuTargetDirectory, const IBK::Path & fmuFilePath) {
const char * const FUNC_ID = "[FMUManager::importFMU]";
// generate unique file path
IBK::Path extractionPath = generateFilePath(fmuTargetDirectory, fmuFilePath);
IBK::IBK_Message(IBK::FormatString("%1\n").arg(fmuFilePath.filename()), IBK::MSG_PROGRESS, FUNC_ID, IBK::VL_STANDARD);
IBK::MessageIndentor indent; (void)indent;
IBK::IBK_Message(IBK::FormatString("%1\n").arg(fmuFilePath), IBK::MSG_PROGRESS, FUNC_ID, IBK::VL_INFO);
importFMUAt(fmuFilePath, extractionPath);
}
void FMUManager::importFMUAt(const IBK::Path & fmuFilePath, const IBK::Path & unzipPath) {
const char * const FUNC_ID = "[FMUManager::importFMUAt]";
if (!fmuFilePath.exists())
throw IBK::Exception(IBK::FormatString("FMU file '%1' not found.").arg(fmuFilePath), FUNC_ID);
if (m_unzipFMUs) {
IBK::IBK_Message(IBK::FormatString("Unzipping FMU\n"), IBK::MSG_PROGRESS, FUNC_ID, IBK::VL_DETAILED);
IBK::IBK_Message(IBK::FormatString(" into directory: %1\n").arg(unzipPath), IBK::MSG_PROGRESS, FUNC_ID, IBK::VL_DETAILED);
// check if target directory exists
if (unzipPath.exists()) {
IBK::IBK_Message(IBK::FormatString(" Directory exists, unzipping will overwrite files!"), IBK::MSG_WARNING, FUNC_ID, IBK::VL_INFO);
}
// extract FMU into target directory
FMU::unzipFMU(fmuFilePath, unzipPath);
}
// create FMU instance
#if __cplusplus >= 199711L
std::unique_ptr<FMU> fmu(new FMU(fmuFilePath, unzipPath));
#else
std::auto_ptr<FMU> fmu(new FMU(fmuFilePath, unzipPath));
#endif
try {
// parse modelDescription.xml so that we get the model identifyer
IBK::IBK_Message(IBK::FormatString("Reading modelDescription.xml\n"), IBK::MSG_PROGRESS, FUNC_ID, IBK::VL_INFO);
fmu->readModelDescription();
IBK::IBK_Message(IBK::FormatString("Importing shared library\n"), IBK::MSG_PROGRESS, FUNC_ID, IBK::VL_INFO);
if (fmu->m_modelDescription.m_fmuType & ModelDescription::CS_v2) {
IBK::IBK_Message(IBK::FormatString(" CoSimulation Interface v2\n"), IBK::MSG_PROGRESS, FUNC_ID, IBK::VL_INFO);
fmu->import(ModelDescription::CS_v2);
}
else if (fmu->m_modelDescription.m_fmuType & ModelDescription::CS_v1) {
IBK::IBK_Message(IBK::FormatString(" CoSimulation Interface v1\n"), IBK::MSG_PROGRESS, FUNC_ID, IBK::VL_INFO);
fmu->import(ModelDescription::CS_v1);
}
else {
throw IBK::Exception("FMU does provide CoSimulation interface (neither version 1 or 2).", FUNC_ID);
}
}
catch (IBK::Exception & ex) {
throw IBK::Exception(ex, "Import of FMU failed.", FUNC_ID);
}
// import successful, remember FMU instance
m_fmus.push_back(fmu.release());
}
FMU * FMUManager::fmuByPath(const IBK::Path & fmuFilePath) {
const char * const FUNC_ID = "[FMUManager::fmuByPath]";
for (unsigned int i=0; i<m_fmus.size(); ++i) {
if (m_fmus[i]->fmuFilePath() == fmuFilePath) {
return m_fmus[i];
}
}
throw IBK::Exception(IBK::FormatString("FMU with file path '%1' has not been imported, yet.").arg(fmuFilePath), FUNC_ID);
}
IBK::Path FMUManager::generateFilePath(const IBK::Path & fmuBaseDirectory, const IBK::Path & fmuFilePath) {
IBK::Path pBase = fmuBaseDirectory / fmuFilePath.filename().withoutExtension();
IBK::Path p = pBase;
// Ensure uniqueness of path by checking already instantiated FMUs
unsigned int counter = 1;
bool found = true;
while (found) {
found = false;
for (unsigned int i=0; i<m_fmus.size(); ++i) {
if (m_fmus[i]->fmuDir() == p) {
found = true;
break;
}
}
if (found) {
p = IBK::Path(IBK::FormatString("%1_%2").arg(pBase).arg(++counter).str());
}
}
return p;
}
} // namespace MASTER_SIM
| 32.617886 | 135 | 0.706879 | [
"vector",
"model"
] |
8919f82e49d910f72533ecd87928ae9eeba8c6a0 | 2,623 | cpp | C++ | venv/lib/python3.6/site-packages/pachi_py/pachi/dcnn.cpp | marcusfrancis/cartpole-bot | 009dede4a7551501b2817eafc8765a9060e33161 | [
"Python-2.0",
"OLDAP-2.7"
] | null | null | null | venv/lib/python3.6/site-packages/pachi_py/pachi/dcnn.cpp | marcusfrancis/cartpole-bot | 009dede4a7551501b2817eafc8765a9060e33161 | [
"Python-2.0",
"OLDAP-2.7"
] | null | null | null | venv/lib/python3.6/site-packages/pachi_py/pachi/dcnn.cpp | marcusfrancis/cartpole-bot | 009dede4a7551501b2817eafc8765a9060e33161 | [
"Python-2.0",
"OLDAP-2.7"
] | null | null | null | #define DEBUG
#include <assert.h>
#include <ctype.h>
#include <math.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#define CPU_ONLY 1
#include <caffe/caffe.hpp>
using namespace caffe;
extern "C" {
#include "debug.h"
#include "board.h"
#include "dcnn.h"
static shared_ptr<Net<float> > net;
bool
using_dcnn(struct board *b)
{
return (real_board_size(b) == 19 && net);
}
/* Make caffe quiet */
void
dcnn_quiet_caffe(int argc, char *argv[])
{
if (DEBUGL(7) || getenv("GLOG_minloglevel"))
return;
setenv("GLOG_minloglevel", "2", 1);
execvp(argv[0], argv); /* Sucks that we have to do this */
}
void
dcnn_init()
{
if (net)
return;
struct stat s;
const char *model_file = "golast19.prototxt";
const char *trained_file = "golast.trained";
if (stat(model_file, &s) != 0 || stat(trained_file, &s) != 0) {
if (DEBUGL(1))
fprintf(stderr, "No dcnn files found, will not use dcnn code.\n");
return;
}
Caffe::set_mode(Caffe::CPU);
/* Load the network. */
net.reset(new Net<float>(model_file, TEST));
net->CopyTrainedLayersFrom(trained_file);
if (DEBUGL(1))
fprintf(stderr, "Initialized dcnn.\n");
}
void
dcnn_get_moves(struct board *b, enum stone color, float result[])
{
assert(real_board_size(b) == 19);
int size = 19;
int dsize = 13 * size * size;
float *data = new float[dsize];
for (int i = 0; i < dsize; i++)
data[i] = 0.0;
for (int j = 0; j < size; j++) {
for(int k = 0; k < size; k++) {
int p = size * j + k;
coord_t c = coord_xy(b, j+1, k+1);
group_t g = group_at(b, c);
enum stone bc = board_at(b, c);
int libs = board_group_info(b, g).libs - 1;
if (libs > 3) libs = 3;
if (bc == S_NONE)
data[8*size*size + p] = 1.0;
else if (bc == color)
data[(0+libs)*size*size + p] = 1.0;
else if (bc == stone_other(color))
data[(4+libs)*size*size + p] = 1.0;
if (c == b->last_move.coord)
data[9*size*size + p] = 1.0;
else if (c == b->last_move2.coord)
data[10*size*size + p] = 1.0;
else if (c == b->last_move3.coord)
data[11*size*size + p] = 1.0;
else if (c == b->last_move4.coord)
data[12*size*size + p] = 1.0;
}
}
Blob<float> *blob = new Blob<float>(1,13,size,size);
blob->set_cpu_data(data);
vector<Blob<float>*> bottom;
bottom.push_back(blob);
assert(net);
const vector<Blob<float>*>& rr = net->Forward(bottom);
for (int i = 0; i < size * size; i++) {
result[i] = rr[0]->cpu_data()[i];
if (result[i] < 0.00001)
result[i] = 0.00001;
}
delete[] data;
delete blob;
}
} /* extern "C" */
| 21.325203 | 69 | 0.605414 | [
"vector"
] |
891ce512050f0a5120e7d4fbcead382affb90520 | 61,873 | cpp | C++ | src/pipol_tracker_lib/peopleTracker.cpp | andreucm/pipol_tracker | 5056dd3858cdb5139373862da220082191301d2c | [
"MIT"
] | 19 | 2015-02-17T09:22:33.000Z | 2022-03-21T02:49:55.000Z | src/pipol_tracker_lib/peopleTracker.cpp | cdondrup/pipol_tracker | 5056dd3858cdb5139373862da220082191301d2c | [
"MIT"
] | null | null | null | src/pipol_tracker_lib/peopleTracker.cpp | cdondrup/pipol_tracker | 5056dd3858cdb5139373862da220082191301d2c | [
"MIT"
] | 11 | 2015-03-17T14:27:59.000Z | 2022-02-07T21:57:24.000Z | #include "peopleTracker.h"
CpeopleTracker::CpeopleTracker()
{
nextTargetId = 1;
followMeTargetId = -1;//initially there is no folloMe target Id
for (unsigned int ii=0; ii<NUM_DETECTORS; ii++) nextDetectionId[ii] = 1;
setDefaultParameters();
}
CpeopleTracker::~CpeopleTracker()
{
laserDetSet.clear();
bodyDetSet.clear();
body3dDetSet.clear();
targetList.clear();
}
void CpeopleTracker::setDefaultParameters()
{
//tracker params
params.minDistanceBetweenPeople = MINIMUN_DISTANCE_BETWEEN_PEOPLE;
params.minAssociationProb = MINIMUM_ASSOCIATION_PROB;
params.maxDetectionDistance = MAX_DETECTION_DISTANCE_ACCEPTED;
params.minDetectionDistance = MIN_DETECTION_DISTANCE_ACCEPTED;
params.maxDetectionAzimut = MAX_DETECTION_AZIMUT_ACCEPTED;
params.maxConsecutiveUncorrected = MAX_CONSECUTIVE_UNCORRECTED_ITERATIONS;
params.minIterationsToBeTarget = MINIMUM_ITERATIONS_TO_BE_TARGET;
params.minAppearanceRegionSize = MINIMUM_APPEARANCE_REGION_SIZE;
params.iterationsToBeVisuallyConfirmed = MINIMUM_ITERATIONS_TO_BE_VISUALLY_CONFIRMED;
params.iterationsToBeFriend = MINIMUM_ITERATIONS_TO_BE_FRIEND;
//particle filter params (for each created filter)
filterParams.numParticles = DEFAULT_NP;
filterParams.initDeltaXY = INIT_DELTA_XY;
filterParams.initDeltaVxy = INIT_DELTA_VXY;
filterParams.sigmaResamplingXY = SIGMA_FIXED_RESAMPLING_XY;
filterParams.sigmaRatioResamplingVxy = SIGMA_RATIO_RESAMPLING_VXY;
filterParams.sigmaMinResamplingVxy = SIGMA_MIN_RESAMPLING_VXY;
filterParams.personRadiusLegs = PERSON_RADIUS_LEGS;
filterParams.personRadiusBody = PERSON_RADIUS_BODY;
filterParams.matchingLegsAlpha = MATCHING_LEGS_ALPHA;
filterParams.matchingLegsBeta = MATCHING_LEGS_BETA;
filterParams.matchingBearingAlpha = MATCHING_BODY_ALPHA;
filterParams.matchingBearingBeta = MATCHING_BODY_BETA;
filterParams.matchingBody3dAlpha = MATCHING_BODY3D_ALPHA;
filterParams.matchingBody3dBeta = MATCHING_BODY3D_BETA;
}
void CpeopleTracker::setParameters(const trackerParameters & tp)
{
params.minDistanceBetweenPeople = tp.minDistanceBetweenPeople;
params.minAssociationProb = tp.minAssociationProb;
params.maxDetectionDistance = tp.maxDetectionDistance;
params.minDetectionDistance = tp.minDetectionDistance;
params.maxDetectionAzimut = tp.maxDetectionAzimut;
params.maxConsecutiveUncorrected = tp.maxConsecutiveUncorrected;
params.minIterationsToBeTarget = tp.minIterationsToBeTarget;
params.minAppearanceRegionSize = tp.minAppearanceRegionSize;
params.iterationsToBeVisuallyConfirmed = tp.iterationsToBeVisuallyConfirmed;
params.iterationsToBeFriend = tp.iterationsToBeFriend;
std::cout << std::endl <<
"TRACKER PARAMETERS ***********************************" << std::endl <<
"params.minDistanceBetweenPeople: " << params.minDistanceBetweenPeople << std::endl <<
"params.minAssociationProb: " << params.minAssociationProb << std::endl <<
"params.maxDetectionDistance: " << params.maxDetectionDistance << std::endl <<
"params.minDetectionDistance: " << params.minDetectionDistance << std::endl <<
"params.maxDetectionAzimut: " << params.maxDetectionAzimut << std::endl <<
"params.maxConsecutiveUncorrected: " << params.maxConsecutiveUncorrected << std::endl <<
"params.minIterationsToBeTarget: " << params.minIterationsToBeTarget << std::endl <<
"params.minAppearanceRegionSize: " << params.minAppearanceRegionSize << std::endl <<
"params.iterationsToBeVisuallyConfirmed: " << params.iterationsToBeVisuallyConfirmed << std::endl <<
"params.iterationsToBeFriend: " << params.iterationsToBeFriend << std::endl <<
"******************************************************" << std::endl << std::endl;
}
void CpeopleTracker::setFilterParameters(const pFilterParameters & pfp)
{
filterParams.numParticles = pfp.numParticles;
filterParams.initDeltaXY = pfp.initDeltaXY;
filterParams.initDeltaVxy = pfp.initDeltaVxy;
filterParams.sigmaResamplingXY = pfp.sigmaResamplingXY;
filterParams.sigmaRatioResamplingVxy = pfp.sigmaRatioResamplingVxy;
filterParams.sigmaMinResamplingVxy = pfp.sigmaMinResamplingVxy;
filterParams.personRadiusLegs = pfp.personRadiusLegs;
filterParams.personRadiusBody = pfp.personRadiusBody;
filterParams.matchingLegsAlpha = pfp.matchingLegsAlpha;
filterParams.matchingLegsBeta = pfp.matchingLegsBeta;
filterParams.matchingBearingAlpha = pfp.matchingBearingAlpha;
filterParams.matchingBearingBeta = pfp.matchingBearingBeta;
filterParams.matchingBody3dAlpha = pfp.matchingBody3dAlpha;
filterParams.matchingBody3dBeta = pfp.matchingBody3dBeta;
}
void CpeopleTracker::setFollowMeTargetId(int fmtid)
{
this->followMeTargetId = fmtid;
std::cout << "**********************************" << std::endl;
std::cout << "FOLLOW ME TARGET ID SET TO: " << this->followMeTargetId << std::endl;
std::cout << "**********************************" << std::endl;
}
int CpeopleTracker::getFollowMeTargetId()
{
return this->followMeTargetId;
}
bool CpeopleTracker::checkTLDinit()
{
std::list<CpersonTarget>::iterator iiT;
CtimeStamp tsNow;
bool tldInitConditionMeet = false;
//check init condition over the set of targets that are VISUALLY_CONFIRMED
tsNow.setToNow();
for (iiT=targetList.begin();iiT!=targetList.end();iiT++)
{
if ( ( iiT->isStatus(VISUALLY_CONFIRMED) ) && ( (tsNow.get()-iiT->getTsInit()) > 9 ) )
{
tldInitConditionMeet = true;
//followMeTargetId = iiT->getId();
break;
}
}
return tldInitConditionMeet;
}
void CpeopleTracker::initTLD()
{
std::list<CpersonTarget>::iterator iiT;
filterEstimate tgEst;
Cpoint3d tgPoint;
//camera intrinsic params
cv::Matx33d camK(525, 0, 319.5,
0, 525, 239.5,
0, 0, 1);
//select followMeTargetId
for (iiT=targetList.begin();iiT!=targetList.end();iiT++)
{
if ( iiT->getId() == this->followMeTargetId ) break;
}
//gets target point of iiT
iiT->getEstimate(tgEst);
tgPoint = tgEst.position;
tgPoint.setZ(1.2);//120cm will be the central point of the bounding box
// Computes the estimated bbox to initialize TLD. Now it is hardcoded ... to do
tldBox.x = 140;
tldBox.y = 140;
tldBox.width = 140;
tldBox.height = 200;
}
void CpeopleTracker::getTLDbb(unsigned int & bbx, unsigned int & bby, unsigned int & bbw, unsigned int & bbh)
{
bbx = tldBox.x;
bby = tldBox.y;
bbw = tldBox.width;
bbh = tldBox.height;
}
void CpeopleTracker::addDetection(Cpoint3dObservation & newDet)
{
double dist;
double azimut;
dist = newDet.point.norm();
azimut = fabs(atan2(newDet.point.getY(),newDet.point.getX()));
if ( (dist >= params.minDetectionDistance) && (dist <= params.maxDetectionDistance) && (azimut < params.maxDetectionAzimut) )
{
newDet.setId(nextDetectionId[LEGS]);
laserDetSet.push_back(newDet);
nextDetectionId[LEGS]++;
}
}
void CpeopleTracker::addDetection(CbodyObservation & newDet)
{
newDet.setId(nextDetectionId[BODY]);
bodyDetSet.push_back(newDet);
nextDetectionId[BODY]++;
}
void CpeopleTracker::addDetection(CfaceObservation & newDet)
{
newDet.setId(nextDetectionId[FACE]);
faceDetSet.push_back(newDet);
nextDetectionId[FACE]++;
}
void CpeopleTracker::addDetectionBody3d(Cpoint3dObservation & newDet)
{
newDet.setId(nextDetectionId[BODY3D]);
body3dDetSet.push_back(newDet);
nextDetectionId[BODY3D]++;
}
void CpeopleTracker::setTLDdetection(CbodyObservation & newDet)
{
tldDetection.timeStamp.set(newDet.timeStamp.get());
tldDetection.direction = newDet.direction;
tldDetection.rgbEigen = newDet.rgbEigen;
tldDetection.bbX = newDet.bbX;
tldDetection.bbY = newDet.bbY;
tldDetection.bbW = newDet.bbW;
tldDetection.bbH = newDet.bbH;
}
void CpeopleTracker::getTLDdetection(CbodyObservation & det)
{
det.timeStamp.set(tldDetection.timeStamp.get());
det.direction = tldDetection.direction;
det.bbX = tldDetection.bbX;
det.bbY = tldDetection.bbY;
det.bbW = tldDetection.bbW;
det.bbH = tldDetection.bbH;
}
// double CpeopleTracker::getTldAngle()
// {
// //std::cout << "tldX: " << tldDetection.direction.getX() << "; tldY: " << tldDetection.direction.getY() << std::endl;
// return atan2(tldDetection.direction.getY(),tldDetection.direction.getX());
// }
void CpeopleTracker::resetDetectionSets(int detId)
{
switch (detId)
{
case LEGS:
laserDetSet.clear();
nextDetectionId[LEGS] = 1;
break;
case BODY:
bodyDetSet.clear();
nextDetectionId[BODY] = 1;
break;
case FACE:
faceDetSet.clear();
nextDetectionId[FACE] = 1;
break;
case BODY3D:
body3dDetSet.clear();
nextDetectionId[BODY3D] = 1;
break;
case TLD:
tldDetection.bbW = 0;
break;
default:
break;
}
}
void CpeopleTracker::computeOcclusions()
{
std::list<CpersonTarget>::iterator iiT, jjT;
Cline iiLine;
Cpoint jjTpoint;
filterEstimate fEst;
bool occlusionFound;
double ddij;
//for each target iiT, compute potential occlusions caused by other targets jjT
for (iiT=targetList.begin();iiT!=targetList.end();iiT++)
{
//builds iiLine, from the robot to target ii
iiT->getEstimate(fEst);
iiLine.set_point_coord(0,0,fEst.position.getX(),fEst.position.getY());
//resets flag
occlusionFound = false;
//jjT targets will cause potential occlusions
for (jjT=targetList.begin();jjT!=targetList.end();jjT++)
{
if (iiT!=jjT)
{
jjT->getEstimate(fEst);
jjTpoint.set_point(fEst.position.getX(),fEst.position.getY());
ddij = iiLine.d2point(&jjTpoint);
if ( ddij < jjT->getPersonRadius()*1.2 )
{
occlusionFound = true;
break; //iterate to the next target iiT if an occlusion is found
}
}
}
//set status and probability of occlusion for target iiT (ToDo: improve step function with a smoother one)
if ( occlusionFound )
{
iiT->pOcclusion = 1; //0.9
iiT->setStatus(IN_OCCLUSION,true);
}
else
{
iiT->pOcclusion = 0;
iiT->setStatus(IN_OCCLUSION,false);
}
}
}
void CpeopleTracker::dataAssociationTree()
{
std::list<Cpoint3dObservation>::iterator iiL;//leg detections
std::list<CbodyObservation>::iterator iiB; //body2D detections
std::list<CfaceObservation>::iterator iiF; //face detections
std::list<Cpoint3dObservation>::iterator iiB3; //body3d detections
std::list<CpersonTarget>::iterator jjT; //targets
double matchingValue;
unsigned int ii, jj, kk; //ii: detections, jj: targets, kk: auxiliar
std::vector<std::pair<unsigned int, unsigned int> > associations;
std::vector<bool> associated_mask;
//Resize decision vectors
for (jjT=targetList.begin();jjT!=targetList.end();jjT++)
jjT->resizeAssociationDecisions(laserDetSet.size(), bodyDetSet.size(), faceDetSet.size(), body3dDetSet.size());
//LEG DETECTOR
if( laserDetSet.size() != 0 )
{
//resets tree
tree_.reset();
//Resizes input tree tables
tree_.resize(laserDetSet.size(), targetList.size());//Score table is sized Nd x (Nt+1), to consider void target
//set matching scores to tree_ score table
for (iiL=laserDetSet.begin(),ii=0;iiL!=laserDetSet.end();iiL++,ii++) //detections start
{
//Set matching values for all targets except void target. It is not required to set scores for void target, they are not used to compute p_{i,N_t+1}
for (jjT=targetList.begin(),jj=0;jjT!=targetList.end();jjT++,jj++)
{
matchingValue = jjT->legMatchingFunction(iiL->point);
tree_.setScore(ii,jj,matchingValue);
}
}
//Decides best association event according to the tree
tree_.solve(associations, associated_mask);
//sets association vectors
for(kk=0; kk<associations.size(); kk++)
{
setAssociationDecision(LEGS, associations.at(kk).second, associations.at(kk).first);
}
//mark detections as associated or not ( required to create new targets at createFilters() )
for (iiL=laserDetSet.begin(),ii=0;iiL!=laserDetSet.end();iiL++,ii++)
{
//check if d_i is associated or not
if ( associated_mask.at(ii) == true ) iiL->setAssociated(true);
else iiL->setAssociated(false);
}
//resets association pairs and unassociated vector
associations.clear();
//unassociated.clear();
}
//BODY2D DETECTOR
if( bodyDetSet.size() != 0 )
{
//resets tree
tree_.reset();
//Resizes input tree tables
tree_.resize(bodyDetSet.size(), targetList.size());//Score table is sized Nd x (Nt+1), to consider void target
//set matching scores to tree_ score table
for (iiB=bodyDetSet.begin(),ii=0;iiB!=bodyDetSet.end();iiB++,ii++) //detections start
{
//Set matching values for all targets except void target. It is not required to set scores for void target, they are not used to compute p_{i,N_t+1}
for (jjT=targetList.begin(),jj=0;jjT!=targetList.end();jjT++,jj++)
{
matchingValue = jjT->bodyMatchingFunction(iiB->direction);
tree_.setScore(ii,jj,matchingValue);
}
}
//Decides best association event according to the tree
tree_.solve(associations, associated_mask);
//sets association vectors
for(kk=0; kk<associations.size(); kk++)
{
setAssociationDecision(BODY, associations.at(kk).second, associations.at(kk).first);
}
//resets association pairs and unassociated vector
associations.clear();
//unassociated.clear();
}
//FACE DETECTOR
if( faceDetSet.size() != 0 )
{
//resets tree
tree_.reset();
//Resizes input tree tables
tree_.resize(faceDetSet.size(), targetList.size());//Score table is sized Nd x (Nt+1), to consider void target
//set matching scores to tree_ score table
for (iiF=faceDetSet.begin(),ii=0;iiF!=faceDetSet.end();iiF++,ii++) //detections start
{
//Set matching values for all targets except void target. It is not required to set scores for void target, they are not used to compute p_{i,N_t+1}
for (jjT=targetList.begin(),jj=0;jjT!=targetList.end();jjT++,jj++)
{
matchingValue = jjT->faceMatchingFunction(iiF->faceLoc);
tree_.setScore(ii,jj,matchingValue);
}
}
//Decides best event according to the tree
tree_.solve(associations, associated_mask);
//sets association vectors
for(kk=0; kk<associations.size(); kk++)
{
setAssociationDecision(FACE, associations.at(kk).second, associations.at(kk).first);
}
//resets association pairs and unassociated vector
associations.clear();
//unassociated.clear();
}
//BODY3D DETECTOR
if( body3dDetSet.size() != 0 )
{
//resets tree
tree_.reset();
//Resizes input tree tables
tree_.resize(body3dDetSet.size(), targetList.size());//Score table is sized Nd x (Nt+1), to consider void target
//set matching scores to tree_ score table
for (iiB3=body3dDetSet.begin(),ii=0;iiB3!=body3dDetSet.end();iiB3++,ii++) //detections start
{
//Set matching values for all targets except void target. It is not required to set scores for void target, they are not used to compute p_{i,N_t+1}
for (jjT=targetList.begin(),jj=0;jjT!=targetList.end();jjT++,jj++)
{
matchingValue = jjT->body3dMatchingFunction(iiB3->point);
tree_.setScore(ii,jj,matchingValue);
}
}
//Decides best event according to the tree
tree_.solve(associations, associated_mask);
//sets association vectors
for(kk=0; kk<associations.size(); kk++)
{
setAssociationDecision(BODY3D, associations.at(kk).second, associations.at(kk).first);
}
//resets association pairs and unassociated vector
associations.clear();
//unassociated.clear();
}
}
void CpeopleTracker::dataAssociationNN()
{
std::list<Cpoint3dObservation>::iterator iiL;//leg detections
std::list<CbodyObservation>::iterator iiB; //body2D detections
std::list<CfaceObservation>::iterator iiF; //face detections
std::list<Cpoint3dObservation>::iterator iiB3; //body3d detections
std::list<CpersonTarget>::iterator jjT; //targets
double sqd;//euclidean distance squared
unsigned int ii, jj, kk; //ii: detections, jj: targets, kk: auxiliar
std::vector<std::pair<unsigned int, unsigned int> > associations;
std::vector<bool> associated_mask;
//Resize decision vectors
for (jjT=targetList.begin();jjT!=targetList.end();jjT++)
jjT->resizeAssociationDecisions(laserDetSet.size(), bodyDetSet.size(), faceDetSet.size(), body3dDetSet.size());
//LEG DETECTOR
if( laserDetSet.size() != 0 )
{
//resets nnls
nnls_.reset();
//Resizes input nnls tables
nnls_.resize(laserDetSet.size(), targetList.size());//Score table is sized Nd x Nt
//set matching scores to tree_ score table
for (iiL=laserDetSet.begin(),ii=0;iiL!=laserDetSet.end();iiL++,ii++) //detections start
{
//Set sq distances between detections and targets
for (jjT=targetList.begin(),jj=0;jjT!=targetList.end();jjT++,jj++)
{
sqd = jjT->d2point2(iiL->point);
nnls_.setScore(ii,jj,sqd);
}
}
//Decides best association event according to the nnls
nnls_.solve(associations, associated_mask);
//sets association vectors
for(kk=0; kk<associations.size(); kk++)
{
setAssociationDecision(LEGS, associations.at(kk).second, associations.at(kk).first);
}
//mark detections as associated or not ( required to create new targets at createFilters() )
for (iiL=laserDetSet.begin(),ii=0;iiL!=laserDetSet.end();iiL++,ii++)
{
//check if d_i is associated or not
if ( associated_mask.at(ii) == true ) iiL->setAssociated(true);
else iiL->setAssociated(false);
}
//resets association pairs and unassociated vector
associations.clear();
}
//BODY2D DETECTOR
if( bodyDetSet.size() != 0 )
{
//resets nnls
nnls_.reset();
//Resizes input nnls tables
nnls_.resize(bodyDetSet.size(), targetList.size());//Score table is sized Nd x Nt
//set matching scores to tree_ score table
for (iiB=bodyDetSet.begin(),ii=0;iiB!=bodyDetSet.end();iiB++,ii++) //detections start
{
//Set matching values for all targets except void target. It is not required to set scores for void target, they are not used to compute p_{i,N_t+1}
for (jjT=targetList.begin(),jj=0;jjT!=targetList.end();jjT++,jj++)
{
sqd = fabs(jjT->getAzimuth() - iiB->direction.getAzimuth());
nnls_.setScore(ii,jj,sqd);
}
}
//Decides best association event according to the tree
nnls_.solve(associations, associated_mask);
//sets association vectors
for(kk=0; kk<associations.size(); kk++)
{
setAssociationDecision(BODY, associations.at(kk).second, associations.at(kk).first);
}
//resets association pairs and unassociated vector
associations.clear();
}
//FACE DETECTOR
if( faceDetSet.size() != 0 )
{
//resets nnls
nnls_.reset();
//Resizes input nnls tables
nnls_.resize(faceDetSet.size(), targetList.size());//Score table is sized Nd x Nt
//set matching scores to tree_ score table
for (iiF=faceDetSet.begin(),ii=0;iiF!=faceDetSet.end();iiF++,ii++) //detections start
{
//Set matching values for all targets except void target. It is not required to set scores for void target, they are not used to compute p_{i,N_t+1}
for (jjT=targetList.begin(),jj=0;jjT!=targetList.end();jjT++,jj++)
{
sqd = jjT->d2point2( Cpoint3d(iiF->faceLoc.getX(), iiF->faceLoc.getY(), 0) );
nnls_.setScore(ii,jj,sqd);
}
}
//Decides best event according to the tree
nnls_.solve(associations, associated_mask);
//sets association vectors
for(kk=0; kk<associations.size(); kk++)
{
setAssociationDecision(FACE, associations.at(kk).second, associations.at(kk).first);
}
//resets association pairs and unassociated vector
associations.clear();
}
//BODY3D DETECTOR
if( body3dDetSet.size() != 0 )
{
//resets nnls
nnls_.reset();
//Resizes input nnls tables
nnls_.resize(body3dDetSet.size(), targetList.size());//Score table is sized Nd x Nt
//set matching scores to tree_ score table
for (iiB3=body3dDetSet.begin(),ii=0;iiB3!=body3dDetSet.end();iiB3++,ii++) //detections start
{
//Set matching values for all targets except void target. It is not required to set scores for void target, they are not used to compute p_{i,N_t+1}
for (jjT=targetList.begin(),jj=0;jjT!=targetList.end();jjT++,jj++)
{
sqd = jjT->d2point2(iiB3->point);
nnls_.setScore(ii,jj,sqd);
}
}
//Decides best event according to the tree
nnls_.solve(associations, associated_mask);
//sets association vectors
for(kk=0; kk<associations.size(); kk++)
{
setAssociationDecision(BODY3D, associations.at(kk).second, associations.at(kk).first);
}
//resets association pairs and unassociated vector
associations.clear();
}
}
void CpeopleTracker::setAssociationDecision(unsigned int _detector_id, unsigned int _tj, unsigned int _di)
{
unsigned int jj = 0;
for (std::list<CpersonTarget>::iterator jjT=targetList.begin(); jjT!=targetList.end(); jjT++,jj++)
{
if (jj == _tj) jjT->aDecisions[_detector_id].at(_di) = true;
}
}
void CpeopleTracker::updateTargetStatus()
{
for (std::list<CpersonTarget>::iterator iiT=targetList.begin(); iiT!=targetList.end(); iiT++)
{
iiT->updateStatus( params.maxConsecutiveUncorrected, params.minIterationsToBeTarget,
params.iterationsToBeVisuallyConfirmed, params.iterationsToBeFriend );
}
}
void CpeopleTracker::createFilters()
{
CpersonTarget *newTarget;
std::list<Cpoint3dObservation>::iterator iiD;
std::list<CpersonTarget>::iterator jjT;
std::list<CpersonTarget> newFilters;
double assocProb;
bool associated;
unsigned int ii;
Cline iiLine;
Cpoint jjTpoint;
filterEstimate fEst;
double ddij;
bool detectionInOcclusion;
//check for unassociated detections of LEG detector & create new filters for unassociated LEG detections
//createNewFilters();
for (iiD=laserDetSet.begin(),ii=0;iiD!=laserDetSet.end();iiD++,ii++)
{
// associated = false;
// for (jjT=targetList.begin();jjT!=targetList.end();jjT++)
// {
// assocProb = jjT->aProbs[LEGS].at(ii);
// //std::cout << "Det: " << ii << "; Filter: " << jjT->getTargetId() << std::endl;
// //std::cout << " assocP = " << assocProb << std::endl;
// if ( assocProb > params.minAssociationProb ) //iiD detection has been associated, at least, to filter jjT
// {
// associated = true;
// break;
// }
// }
// if (!associated) //iiD has not been associated to any target/filter, so we launch a new filter
if ( !iiD->isAssociated() ) //iiD has not been associated to any target/filter, so we launch a new filter
{
//first check if some target is causing occlusion of iiD detection
detectionInOcclusion = false;
iiLine.set_point_coord(0,0,iiD->point.getX(),iiD->point.getY());
for (jjT=targetList.begin();jjT!=targetList.end();jjT++)
{
jjT->getEstimate(fEst);
jjTpoint.set_point(fEst.position.getX(),fEst.position.getY());
ddij = iiLine.d2point(&jjTpoint);
if ( ddij < jjT->getPersonRadius()*1.2 )
{
detectionInOcclusion = true;
break; //iterate to the next target iiT if an occlusion is found
}
}
//if no occlusion, then initialize a new target by creating a new filter
if (!detectionInOcclusion)
{
newTarget = new CpersonTarget(nextTargetId);
newTarget->setParameters(filterParams);
nextTargetId++;
newTarget->init(*iiD);
newTarget->updateEstimate();
newFilters.push_back(*newTarget);
delete newTarget;
//std::cout << "createFilters(): new target with id: "<< newTarget->getTargetId() << std::endl;
}
}
}
targetList.splice(targetList.end(),newFilters);//adds new filters to the targetList maintained by this Tracker
newFilters.clear();
}
void CpeopleTracker::deleteFilters()
{
std::list<CpersonTarget>::iterator iiF, jjF;//, auxF;
Cpoint3dCov iiTrckPos, jjTrckPos;
double dist;
bool incrementToBeRemoved_ii;
//Delete filters that have status=TO_BE_REMOVED
for (iiF=targetList.begin();iiF!=targetList.end();iiF++)
{
if ( iiF->isStatus(TO_BE_REMOVED) )
{
targetList.erase(iiF);
break;
}
}
//update toBeRemovedCounters of each filter
for (iiF=targetList.begin();iiF!=targetList.end();iiF++)
{
iiF->getPositionEstimate(iiTrckPos);
incrementToBeRemoved_ii = false;
for (jjF=targetList.begin();jjF!=targetList.end();jjF++)
{
jjF->getPositionEstimate(jjTrckPos);
dist = iiTrckPos.d2point(jjTrckPos);
if ( dist < params.minDistanceBetweenPeople )
{
if ( iiF->getMaxStatus() < jjF->getMaxStatus() ) //ii has lower status than jj
{
incrementToBeRemoved_ii = true;
break;
}
if ( (iiF->getMaxStatus() == jjF->getMaxStatus()) && (iiF->getId() > jjF->getId()) ) //same status & ii is newer-> increment counter of filter ii
{
incrementToBeRemoved_ii = true;
break;
}
}
}
if (incrementToBeRemoved_ii) iiF->incrementToBeRemovedCounter();
else iiF->resetToBeRemovedCounter();
}
/*
//removes filters that are closer between them. Keeps id of the oldest (lower id)
iiF=targetList.begin();
while(iiF!=targetList.end())
{
iiFilterDeleted = false;
iiF->getPositionEstimate(iiTrckPos);
jjF = iiF;
jjF++;
while(jjF!=targetList.end())
{
jjFilterDeleted = false;
jjF->getPositionEstimate(jjTrckPos);
dist = iiTrckPos.d2point(jjTrckPos);
if ( dist < params.minDistanceBetweenPeople )
{
if( jjF->getId() > iiF->getId() ) //jj is newer-> remove filter jj
{
auxF = jjF;
jjF++;
targetList.erase(auxF);
jjFilterDeleted = true;
}
else //ii is newer -> remove filter ii
{
auxF = iiF;
iiF++;
targetList.erase(auxF);
iiFilterDeleted = true;
break;
}
}
if (!jjFilterDeleted) jjF++;
}
if (!iiFilterDeleted) iiF++;
}
*/
}
void CpeopleTracker::updateFilterEstimates()
{
std::list<CpersonTarget>::iterator iiF;
for (iiF=targetList.begin();iiF!=targetList.end();iiF++)
{
iiF->updateEstimate();
iiF->setMotionMode();
}
}
void CpeopleTracker::addEstimatesToTracks()
{
std::list<CpersonTarget>::iterator iiF;
for (iiF=targetList.begin();iiF!=targetList.end();iiF++)
{
iiF->addEstimateToTrack();
}
}
void CpeopleTracker::propagateFilters(CodometryObservation & odoIncrement)
{
std::list<CpersonTarget>::iterator iiF;
for (iiF=targetList.begin();iiF!=targetList.end();iiF++)
{
iiF->predictPset(odoIncrement);
}
}
void CpeopleTracker::propagateFilters()
{
std::list<CpersonTarget>::iterator iiF;
for (iiF=targetList.begin();iiF!=targetList.end();iiF++)
{
iiF->predictPset();
}
}
void CpeopleTracker::correctFilters()
{
std::list<CpersonTarget>::iterator iiT;
std::list<Cpoint3dObservation>::iterator jjL, jjB3d;
std::list<CbodyObservation>::iterator jjB;
std::list<CfaceObservation>::iterator jjF;
unsigned int numP,ii,jj;
bool associated_legs = false, associated_body = false, associated_face = false, associated_body3d = false;
vector<double> ww_fusion, ww_legs, ww_body, ww_face, ww_body3d;
// bool targetOccluded;
for (iiT=targetList.begin(),ii=0;iiT!=targetList.end();iiT++,ii++)
{
numP = iiT->getNP();
//LEGS
// ww_legs.reserve(numP);//init vector sizes
// for (jj=0; jj<numP; jj++) ww_legs.push_back(0);//reset values //ALERT: do a resize before and here reset to 1's (without push_back) to avoid case !associated_legs
ww_legs.resize(numP);//init vector sizes
for (jj=0; jj<numP; jj++) ww_legs.at(jj) = 0;//reset values
associated_legs = false;
for (jjL=laserDetSet.begin(),jj=0;jjL!=laserDetSet.end();jjL++,jj++)
{
if ( iiT->aDecisions[LEGS].at(jj) ) //leg detection jj is associated with filter ii
{
associated_legs = true;
iiT->computeWeights(*jjL, ww_legs);
}
}
if (!associated_legs) //if target iiT does not associate with any leg detection
{
for (ii=0; ii<numP; ii++) ww_legs.at(ii) = 1;//leg detection does not "shape" particle set
}
//BODY
// ww_body.reserve(numP);//init vector sizes
// for (jj=0; jj<numP; jj++) ww_body.push_back(0);//reset values //ALERT: do a resize before, and here reset to 1's (without push_back) to avoid case !associated_body
ww_body.resize(numP);//init vector sizes
for (jj=0; jj<numP; jj++) ww_body.at(jj) = 0;//reset values
associated_body = false;
for (jjB=bodyDetSet.begin(),jj=0;jjB!=bodyDetSet.end();jjB++,jj++)
{
if ( iiT->aDecisions[BODY].at(jj) ) //body detection jj is associated with filter ii
{
associated_body = true;
iiT->computeWeights(*jjB, ww_body);
}
}
if (!associated_body)
{
for (ii=0; ii<numP; ii++) ww_body.at(ii) = 1;//jj-th body detection does not correct ii-th particle set
}
//FACE
// ww_face.reserve(numP);//init vector sizes
// for (jj=0; jj<numP; jj++) ww_face.push_back(0);//reset values //ALERT: do a resize before, and here reset to 1's (without push_back) to avoid case !associated_body
ww_face.resize(numP);//init vector sizes
for (jj=0; jj<numP; jj++) ww_face.at(jj) = 0;//reset values
associated_face = false;
for (jjF=faceDetSet.begin(),jj=0;jjF!=faceDetSet.end();jjF++,jj++)
{
if ( iiT->aDecisions[FACE].at(jj) ) //face detection jj is associated with target ii
{
associated_face = true;
iiT->computeWeights(*jjF, ww_face);
}
}
if (!associated_face)
{
for (ii=0; ii<numP; ii++) ww_face.at(ii) = 1;//face detector does not correct ii-th target
}
ww_body3d.resize(numP);//init vector sizes
for (jj=0; jj<numP; jj++) ww_body3d.at(jj) = 0;//reset values
associated_body3d = false;
for (jjB3d=body3dDetSet.begin(),jj=0;jjB3d!=body3dDetSet.end();jjB3d++,jj++)
{
if ( iiT->aDecisions[BODY3D].at(jj) ) //face detection jj is associated with target ii
{
associated_body3d = true;
iiT->computeWeightsBody3d(*jjB3d, ww_body3d);
}
}
if (!associated_body3d)
{
for (ii=0; ii<numP; ii++) ww_body3d.at(ii) = 1;//face detector does not correct ii-th target
}
//Check whether the iiT target has been associated to some detection or not
if ( (associated_legs) || (associated_body) || (associated_face) || (associated_body3d) )
{
ww_fusion.clear();
//ww_fusion.reserve(numP);
ww_fusion.resize(numP);
for (ii=0; ii<numP; ii++)
{
//ww_fusion.push_back( ww_legs.at(ii)*ww_body.at(ii)*ww_face.at(ii) );
ww_fusion.at(ii) = ww_legs.at(ii)*ww_body.at(ii)*ww_face.at(ii)*ww_body3d.at(ii);
}
iiT->setWeights(ww_fusion);
}
//check if it is occluded
// if ( iiT->pOcclusion > 0.5 ) targetOccluded = 1;
// else targetOccluded = 0;
//update target counters
// iiT->updateCounters( (associated_legs || associated_body || associated_face) , (associated_body || associated_face) , targetOccluded );
iiT->updateCounters(
(associated_legs || associated_body || associated_face || associated_body3d),
(associated_body || associated_face || associated_body3d),
iiT->isStatus(IN_OCCLUSION) );
}
}
void CpeopleTracker::resampleFilters()
{
std::list<CpersonTarget>::iterator iiF;
for (iiF=targetList.begin();iiF!=targetList.end();iiF++)
{
iiF->resamplePset();
}
}
std::list<CpersonTarget> & CpeopleTracker::getTargetList()
{
return targetList;
}
std::list<Cpoint3dObservation> & CpeopleTracker::getLaserDetSet()
{
return laserDetSet;
}
std::list<CbodyObservation> & CpeopleTracker::getBodyDetSet()
{
return bodyDetSet;
}
std::list<Cpoint3dObservation> & CpeopleTracker::getBody3dDetSet()
{
return body3dDetSet;
}
void CpeopleTracker::setCurrentImage(cv::Mat & inImg)
{
this->img = inImg.clone();
}
void CpeopleTracker::getCurrentImage(cv::Mat & outImg)
{
outImg = this->img.clone();
}
void CpeopleTracker::markBodies()
{
cv::Rect_<int> bb;
std::list<CbodyObservation>::iterator jjB;
for (jjB=bodyDetSet.begin();jjB!=bodyDetSet.end();jjB++)
{
//sets the bounding box of the detection jj
bb.x = jjB->bbX;
bb.y = jjB->bbY;
bb.width = jjB->bbW;
bb.height = jjB->bbH;
//draws a cyan bounding box on the image according to detection jj
cv::rectangle(img, bb, cv::Scalar(0,255,255), 3);
}
}
void CpeopleTracker::markFaces()
{
cv::Rect_<int> bb;
std::list<CfaceObservation>::iterator iiF;
//for each face detection
for (iiF=faceDetSet.begin();iiF!=faceDetSet.end();iiF++)
{
//sets the bounding box of the detection iiF
bb.x = iiF->bbX;
bb.y = iiF->bbY;
bb.width = iiF->bbW;
bb.height = iiF->bbH;
//draws a yellow bounding box on the image according to detection iiF
cv::rectangle(img, bb, cv::Scalar(255,255,0), 3);
}
}
void CpeopleTracker::printDetectionSets()
{
std::list<Cpoint3dObservation>::iterator iiLd;
std::list<CbodyObservation>::iterator iiBd;
std::list<CfaceObservation>::iterator iiF;
std::cout << "Laser Leg Detections: "<< std::endl;
for (iiLd=laserDetSet.begin();iiLd!=laserDetSet.end();iiLd++)
{
std::cout << iiLd->getId() << " ";
iiLd->timeStamp.print();
iiLd->point.printPoint();
}
std::cout << "Camera Body Detections: "<< std::endl;
for (iiBd=bodyDetSet.begin();iiBd!=bodyDetSet.end();iiBd++)
{
std::cout << iiBd->getId() << " ";
iiBd->timeStamp.print();
iiBd->direction.printPoint();
iiBd->rgbEigen.printPoint();
}
std::cout << "Camera Face Detections: "<< std::endl;
for (iiF=faceDetSet.begin();iiF!=faceDetSet.end();iiF++)
{
std::cout << iiF->getId() << " ";
iiF->timeStamp.print();
iiF->faceLoc.printPoint();
}
}
void CpeopleTracker::printPeopleSet()
{
std::list<CpersonTarget>::iterator iiF;
std::cout << std::endl;
for (iiF=targetList.begin();iiF!=targetList.end();iiF++)
{
iiF->print();
//iiF->printParticleSet();
}
}
// void CpeopleTracker::initSingleTarget()
// {
// std::list<Cpoint3dObservation>::iterator jjL;
// double dd, angle;
// CpersonTarget *newTarget;
//
// if (targetList.size() == 0)
// {
// for (jjL=laserDetSet.begin();jjL!=laserDetSet.end();jjL++)
// {
// dd = jjL->point.norm();
// angle = fabs( atan2(jjL->point.getY(),jjL->point.getX()) );
// if ( (dd<1) && (angle<20*M_PI/180.0) )
// {
// newTarget = new CpersonTarget(nextTargetId);
// newTarget->setParameters(filterParams);
// nextTargetId++;
// newTarget->init(*jjL);
// newTarget->updateEstimate();
// targetList.push_back(*newTarget);
// break;
// }
// }
// }
// }
// void CpeopleTracker::correctFiltersSingleTarget()
// {
// std::list<CpersonTarget>::iterator iiF;
// std::list<Cpoint3dObservation>::iterator jjL, kkL;
// std::list<CbodyObservation>::iterator jjB, kkB;
// double dd, dMin, delta, deltaMin, estimatedAngle, detectedAngle;
// vector<double> ww_fusion, ww_legs, ww_body;
// unsigned int ii, numP;
// bool associated_legs=false, associated_body=false;
//
// //legs
// for (iiF=targetList.begin();iiF!=targetList.end();iiF++)
// {
// dMin = 1.5*params.minDistanceBetweenPeople;
// associated_legs = false;
// numP = iiF->getNP();
// ww_legs.reserve(numP);//init vector sizes
// for (ii=0; ii<numP; ii++) ww_legs.push_back(0);//reset values
// targetState & filterEstimate = iiF->getEstimate();
// for (jjL=laserDetSet.begin();jjL!=laserDetSet.end();jjL++)
// {
// dd = filterEstimate.position.d2point(jjL->point);
// if( dd < dMin)
// {
// dMin = dd;
// kkL = jjL;
// associated_legs = true;
// }
// }
// if (associated_legs)
// iiF->computeWeights(*kkL, ww_legs);
// else
// for (ii=0; ii<numP; ii++) ww_legs.at(ii) = 1;
// }
//
// //body
// for (iiF=targetList.begin();iiF!=targetList.end();iiF++)
// {
// deltaMin = 10*M_PI/180.0;
// associated_body = false;
// numP = iiF->getNP();
// ww_body.reserve(numP);//init vector sizes
// for (ii=0; ii<numP; ii++) ww_body.push_back(0);//reset values
// targetState & filterEstimate = iiF->getEstimate();
// estimatedAngle = atan2(filterEstimate.position.getY(),filterEstimate.position.getX());
// for (jjB=bodyDetSet.begin();jjB!=bodyDetSet.end();jjB++)
// {
// detectedAngle = atan2(jjB->direction.getY(),jjB->direction.getX());
// delta = fabs(detectedAngle-estimatedAngle);
// if( delta < deltaMin)
// {
// deltaMin = delta;
// kkB = jjB;
// associated_body = true;
// }
// }
// if (associated_body)
// iiF->computeWeights(*kkB, ww_body);
// else
// for (ii=0; ii<numP; ii++) ww_body.at(ii) = 1;
// }
//
// //fusion
// if ( (associated_legs) || (associated_body) ) // || (associated_face) )
// {
// ww_fusion.clear();
// ww_fusion.reserve(numP);
// for (ii=0; ii<numP; ii++)
// {
// ww_fusion.push_back( ww_legs.at(ii)*ww_body.at(ii) );
// }
// iiF = targetList.begin();
// iiF->setWeights(ww_fusion);
// }
// }
/*
void CpeopleTracker::removeCrossAssociatedParticles()
{
std::list<CpersonTarget>::iterator iiF, jjF;
std::list<CpersonParticle> * pList;
std::list<CpersonParticle>::iterator kkP;
Cpoint3dCov iiEstimate, jjEstimate;
double dist, dM1, dM2;
for (iiF=targetList.begin();iiF!=targetList.end();iiF++)
{
pList = iiF->getParticleList();
iiF->getPositionEstimate(iiEstimate);
for (jjF=targetList.begin();jjF!=targetList.end();jjF++)
{
if (iiF->getTargetId() != jjF->getTargetId()) //evaluate when different id
{
jjF->getPositionEstimate(jjEstimate);
dist = iiEstimate.d2point(jjEstimate);
if ( dist < params.minDistanceBetweenPeople ) //evaluate only if filters ii and jj are closer enough
{
for (kkP = pList->begin(); kkP!=pList->end(); kkP++) //particle kk belongs to ii filter
{
//dM1 = iiEstimate.mahalanobisDistance2D(kkP->position);//mahalanobis between filter estimate ii and particle kk
//dM2 = jjEstimate.mahalanobisDistance2D(kkP->position);//mahalanobis between filter estimate jj and particle kk
dM1 = iiEstimate.d2point(kkP->position);
dM2 = jjEstimate.d2point(kkP->position);
//std::cout << "removeCrossAssociatedParticles(): ";
if(dM2 < dM1) //particle kk is closer to another filter (jj) than to that it belongs to (ii)
{
//std::cout << "(" << dM1 << "," << dM2 << "); " << std::endl;
kkP->setW(0.0);
}
//std::cout << std::endl;
}
}
}
}
}
}
*/
/*
void CpeopleTracker::computeTargetAppearance()
{
cv::Rect_<int> bb;
std::list<CbodyObservation>::iterator jjB;
std::list<CpersonTarget>::iterator iiF;
unsigned int ii,jj;
std::vector<HsHistogram> detApps;
double mValue; //matching value
std::ostringstream label;
cv::Scalar labelColor;
//for each body detection
detApps.resize(bodyDetSet.size());
for (jjB=bodyDetSet.begin(),jj=0;jjB!=bodyDetSet.end();jjB++,jj++)
{
//sets the bounding box of the detection jj
bb.x = jjB->bbX;
bb.y = jjB->bbY;
bb.width = jjB->bbW;
bb.height = jjB->bbH;
//draws a red bounding box on the image according to detection jj
//cv::rectangle(img, bb, cv::Scalar(0,0,255), 3);
//computes an appearance of the bounding box
detApps[jj].addAppearance(this->img,bb);
//For each target "FRIEND_IN_SIGHT"
for (iiF=targetList.begin(),ii=0;iiF!=targetList.end();iiF++,ii++)
{
if ( iiF->isStatus(FRIEND_IN_SIGHT) )
{
//computes matching value
mValue = iiF->appearanceHistHS.match(&detApps[jj]);
//if target iiF associated to jj body detection
if ( iiF->aDecisions[BODY].at(jj) == true )
{
//draw a blue bounding box
cv::rectangle(img, bb, cv::Scalar(255,0,0), 3);
//Add appearance to the target model
iiF->appearanceHistHS.addAppearance(img,bb);
//set label color to blue
labelColor = cv::Scalar(255,0,0);
}
else
{
//set label color to red
labelColor = cv::Scalar(0,0,255);
}
//Display matching values
label.str("");
label << mValue;
cv::putText(img,label.str(),cv::Point(bb.x+bb.width,bb.y+ii*20),cv::FONT_HERSHEY_SIMPLEX,0.4,labelColor,1);
//std::cout << "Matching appearance of target/detection " << iiF->getId() << "/" << jj << ": " << mValue << std::endl;
}
}
}
}
*/
// void CpeopleTracker::setOnBoardCamPose(Cposition3d & camP)
// {
// this->camINbase = camP;
// std::cout << "CpeopleTracker: Camera pose in base link is: ";
// this->camINbase.printPosition();
// }
// void CpeopleTracker::setOnBoardCamCalMatrix()
// {
// std::cout << "CpeopleTracker: Camera calibration matrix is: " << std::endl;
// }
// void CpeopleTracker::markTld()
// {
// cv::Rect_<int> bb;
// std::ostringstream label;
//
// label.precision(2);
//
// //draws a yellow bounding box on image according to current tld detection
// if ( tldDetection.bbW > 0 )
// {
// bb.x = tldDetection.bbX;
// bb.y = tldDetection.bbY;
// bb.width = tldDetection.bbW;
// bb.height = tldDetection.bbH;
// cv::rectangle(img, bb, cv::Scalar(20,180,240), 3);
// label.str("");
// label << tldDetection.rgbEigen.getX();//confidence stored in the rgbEigen.X field
// cv::putText(img,label.str(),cv::Point(bb.x+bb.width,bb.y),cv::FONT_HERSHEY_SIMPLEX,0.6,cv::Scalar(20,180,240),1);
// //std::cout << "markTld(): bb: " << bb.x << "," << bb.y << "," << bb.width << "," << bb.height << std::endl;
// }
// }
/*
void CpeopleTracker::updateAssociationTablesOld()
{
std::list<Cpoint3dObservation>::iterator jjL, kkL, llL, jjB3d, kkB3d;
std::list<CbodyObservation>::iterator jjB, kkB;
std::list<CfaceObservation>::iterator jjF, kkF;
std::list<CpersonTarget>::iterator iiT, llT;
double matchingValue, assocProb;
unsigned int ii = 0;
unsigned int jj = 0;
unsigned int ll = 0;
decisionElement de;
std::list<decisionElement> deList;
std::list<decisionElement>::iterator k1E, k2E;
//resets matching and association tables
for (iiT=targetList.begin();iiT!=targetList.end();iiT++)
{
iiT->resetMatchScores();
iiT->resetAssociationProbs();
//iiT->resetAssociationDecisions(); already done just some lines below at resize call.
}
//Resizes aDecisions vectors
for (iiT=targetList.begin();iiT!=targetList.end();iiT++)
iiT->resizeAssociationDecisions(laserDetSet.size(), bodyDetSet.size(), faceDetSet.size(), body3dDetSet.size());
//1A. LEG DETECTOR. Matching: for each LEG detection, compute matching score to each target
for (jjL=laserDetSet.begin();jjL!=laserDetSet.end();jjL++)
{
for (iiT=targetList.begin();iiT!=targetList.end();iiT++)
{
matchingValue = iiT->legMatchingFunction(jjL->point);
iiT->matchScores[LEGS].push_back(matchingValue);
//std::cout << "LD" << jjL->getId() << ", T" << iiT->getId() << ": match: " << matchingValue << std::endl;
}
}
//1B. LEG DETECTOR. Association Probability: for each leg detection, computes association probability to each target
for (iiT=targetList.begin();iiT!=targetList.end();iiT++) //target ii
{
for (jjL=laserDetSet.begin(),jj=0;jjL!=laserDetSet.end();jjL++,jj++) //detection jj
{
assocProb = 1;
for (llL=laserDetSet.begin(),ll=0;llL!=laserDetSet.end();llL++,ll++)
{
if( llL==jjL ) //contribution of the positive event
{
assocProb *= iiT->matchScores[LEGS].at(ll);
}
else //product of all negative matching events , target ii against other detections
{
assocProb *= ( 1 - iiT->matchScores[LEGS].at(ll));
}
}
for (llT=targetList.begin();llT!=targetList.end();llT++)
{
if( llT!=iiT ) //product of all negative matching events, detection jj against other targets
{
assocProb *= ( 1 - llT->matchScores[LEGS].at(jj));
}
}
iiT->aProbs[LEGS].push_back(assocProb);//associates ii target with jj detection
}
}
//1C. LEG DETECTOR. Association decision: for each leg detection decides to which target is associated
//1C-a. First, build a list
deList.clear();
for (iiT=targetList.begin(),ii=0;iiT!=targetList.end();iiT++, ii++)
{
for (jjL=laserDetSet.begin(),jj=0;jjL!=laserDetSet.end();jjL++, jj++)
{
if (iiT->aProbs[LEGS].at(jj) > params.minAssociationProb)
{
de.aProb = iiT->aProbs[LEGS].at(jj);
de.targetIdx = ii;
de.detectionIdx = jj;
de.assigned = false;
deList.push_back(de);
}
}
}
//1C-b. Sorts the list following aProbs field
deList.sort();
//1C-c. Sets Association decisions starting from the highest probabilistic event
for (k1E = deList.begin(); k1E != deList.end(); k1E++ )
{
if ( !k1E->assigned )
{
ii = k1E->targetIdx;
jj = k1E->detectionIdx;
setAssociationDecision(LEGS,ii,jj); //sets association decision
}
for (k2E = k1E; k2E != deList.end(); k2E++ )
{
if ( (k2E->targetIdx == ii) || (k2E->detectionIdx == jj) )
{
k2E->assigned = true; //Mark target ii and detection jj as assigned
}
}
}
//2A. BODY DETECTOR. Matching: for each BODY detection, compute matching score to each filter
for (jjB=bodyDetSet.begin();jjB!=bodyDetSet.end();jjB++)
{
for (iiT=targetList.begin();iiT!=targetList.end();iiT++)
{
matchingValue = iiT->bodyMatchingFunction(jjB->direction);
iiT->matchScores[BODY].push_back(matchingValue);
}
}
//2B. BODY DETECTOR. Association Probability: for each body detection, computes association probability to each filter
for (jjB=bodyDetSet.begin();jjB!=bodyDetSet.end();jjB++)
{
for (iiT=targetList.begin();iiT!=targetList.end();iiT++)
{
assocProb = 1;
for (kkB=bodyDetSet.begin(),ii=0;kkB!=bodyDetSet.end();kkB++,ii++)
{
if(kkB!=jjB) //product of all negative matching events
{
assocProb *= ( 1 - iiT->matchScores[BODY].at(ii));
}
else //contribution of the positive event
{
assocProb *= iiT->matchScores[BODY].at(ii);
}
}
iiT->aProbs[BODY].push_back((1-iiT->pOcclusion)*assocProb);
}
}
//2C. BODY DETECTOR. Association decision: for each body detection decides to which target is associated
//2C-a. First, build a list
deList.clear();
for (iiT=targetList.begin(),ii=0;iiT!=targetList.end();iiT++, ii++)
{
for (jjB=bodyDetSet.begin(),jj=0;jjB!=bodyDetSet.end();jjB++, jj++)
{
if (iiT->aProbs[BODY].at(jj) > params.minAssociationProb)
{
de.aProb = iiT->aProbs[BODY].at(jj);
de.targetIdx = ii;
de.detectionIdx = jj;
de.assigned = false;
deList.push_back(de);
//debug
//std::cout << "LINE: "<< __LINE__ << ", aProb: " << de.aProb << std::endl;
//std::cout << "params.minAssociationProb: " << params.minAssociationProb << std::endl;
}
}
}
//2C-b. Sorts the list following aProbs field
deList.sort();
//2C-c. Sets Association decisions starting from the highest probabilistic event
for (k1E = deList.begin(); k1E != deList.end(); k1E++ )
{
if ( !k1E->assigned )
{
ii = k1E->targetIdx;
jj = k1E->detectionIdx;
setAssociationDecision(BODY,ii,jj); //sets association decision
//std::cout << "BODY associated: t" << ii << ", d" << jj << std::endl;
}
for (k2E = k1E; k2E != deList.end(); k2E++ )
{
if ( (k2E->targetIdx == ii) || (k2E->detectionIdx == jj) )
{
k2E->assigned = true; //Mark target ii and detection jj as assigned
}
}
}
//3A. FACE DETECTOR. Matching: for each FACE detection, compute matching score to each target
for (jjF=faceDetSet.begin();jjF!=faceDetSet.end();jjF++)
{
for (iiT=targetList.begin();iiT!=targetList.end();iiT++)
{
matchingValue = iiT->faceMatchingFunction(jjF->faceLoc);
iiT->matchScores[FACE].push_back(matchingValue);
}
}
//3B. FACE DETECTOR. Association Probability: for each face detection, computes association probability to each target
for (jjF=faceDetSet.begin();jjF!=faceDetSet.end();jjF++)
{
for (iiT=targetList.begin();iiT!=targetList.end();iiT++)
{
assocProb = 1;
for (kkF=faceDetSet.begin(),ii=0;kkF!=faceDetSet.end();kkF++,ii++)
{
if(kkF!=jjF) //product of all negative matching events
{
assocProb *= ( 1 - iiT->matchScores[FACE].at(ii));
}
else //contribution of the positive event
{
assocProb *= iiT->matchScores[FACE].at(ii);
}
}
iiT->aProbs[FACE].push_back(assocProb);
}
}
//3C. FACE DETECTOR. Association decision: for each face detection decides to which target is associated
//3C-a. First, build a list
deList.clear();
for (iiT=targetList.begin(),ii=0;iiT!=targetList.end();iiT++, ii++)
{
for (jjF=faceDetSet.begin(),jj=0;jjF!=faceDetSet.end();jjF++, jj++)
{
if (iiT->aProbs[FACE].at(jj) > params.minAssociationProb)
{
de.aProb = iiT->aProbs[FACE].at(jj);
de.targetIdx = ii;
de.detectionIdx = jj;
de.assigned = false;
deList.push_back(de);
}
}
}
//3C-b. Sorts the list following aProbs field
deList.sort();
//3C-c. Sets Association decisions starting from the highest probabilistic event
for (k1E = deList.begin(); k1E != deList.end(); k1E++ )
{
if ( !k1E->assigned )
{
ii = k1E->targetIdx;
jj = k1E->detectionIdx;
setAssociationDecision(FACE,ii,jj); //sets association decision
//std::cout << "FACE associated: t" << ii << ", d" << jj << std::endl;
}
for (k2E = k1E; k2E != deList.end(); k2E++ )
{
if ( (k2E->targetIdx == ii) || (k2E->detectionIdx == jj) )
{
k2E->assigned = true; //Mark target ii and detection jj as assigned
}
}
}
//4A. BODY3D DETECTOR. Matching: for each BODY3D detection, compute matching score to each target
for (jjB3d=body3dDetSet.begin();jjB3d!=body3dDetSet.end();jjB3d++)
{
for (iiT=targetList.begin();iiT!=targetList.end();iiT++)
{
//debugging
//std::cout << "B3dD" << jjB3d->getId() << ", T" << iiT->getId() << std::endl;
//jjB3d->point.printPoint();
//iiT->print();
matchingValue = iiT->body3dMatchingFunction(jjB3d->point);
iiT->matchScores[BODY3D].push_back(matchingValue);
//std::cout << "B3dD" << jjB3d->getId() << ", T" << iiT->getId() << ": match: " << matchingValue << std::endl;
}
}
//4B. BODY3D DETECTOR. Association Probability: for each body3d detection, computes association probability to each target
for (jjB3d=body3dDetSet.begin();jjB3d!=body3dDetSet.end();jjB3d++)
{
for (iiT=targetList.begin();iiT!=targetList.end();iiT++)
{
assocProb = 1;
for (kkB3d=body3dDetSet.begin(),ii=0;kkB3d!=body3dDetSet.end();kkB3d++,ii++)
{
if(kkB3d!=jjB3d) //product of all negative matching events
{
assocProb *= ( 1 - iiT->matchScores[BODY3D].at(ii));
}
else //contribution of the positive event
{
assocProb *= iiT->matchScores[BODY3D].at(ii);
}
}
//iiT->aProbs[BODY3D].push_back((1-iiT->pOcclusion)*assocProb);
iiT->aProbs[BODY3D].push_back(assocProb);
}
}
//4C. BODY3D DETECTOR. Association decision: for each body3d detection decides to which target is associated
//4C-a. First, build a list
deList.clear();
for (iiT=targetList.begin(),ii=0;iiT!=targetList.end();iiT++, ii++)
{
for (jjB3d=body3dDetSet.begin(),jj=0;jjB3d!=body3dDetSet.end();jjB3d++, jj++)
{
if (iiT->aProbs[BODY3D].at(jj) > params.minAssociationProb)
{
de.aProb = iiT->aProbs[BODY3D].at(jj);
de.targetIdx = ii;
de.detectionIdx = jj;
de.assigned = false;
deList.push_back(de);
}
}
}
//4C-b. Sorts the list following aProbs field
deList.sort();
//4C-c. Sets Association decisions starting from the highest probabilistic event
for (k1E = deList.begin(); k1E != deList.end(); k1E++ )
{
if ( !k1E->assigned )
{
ii = k1E->targetIdx;
jj = k1E->detectionIdx;
setAssociationDecision(BODY3D,ii,jj); //sets association decision
//std::cout << "BODY associated: t" << ii << ", d" << jj << std::endl;
}
for (k2E = k1E; k2E != deList.end(); k2E++ )
{
if ( (k2E->targetIdx == ii) || (k2E->detectionIdx == jj) )
{
k2E->assigned = true; //Mark target ii and detection jj as assigned
}
}
}
//frees memory allocated
deList.clear();
//debug
//for (iiT=targetList.begin();iiT!=targetList.end();iiT++) iiT->printTables();
}
*/
| 37.362923 | 208 | 0.561586 | [
"shape",
"vector",
"model"
] |
8925fd81071df3be192a86a26752b78754a4c6d7 | 1,467 | cc | C++ | leetcode/ac/90.cc | Shuo626/algorithm-killer | 9ca31226b89f096277b9067207001704068a2f89 | [
"MIT"
] | null | null | null | leetcode/ac/90.cc | Shuo626/algorithm-killer | 9ca31226b89f096277b9067207001704068a2f89 | [
"MIT"
] | null | null | null | leetcode/ac/90.cc | Shuo626/algorithm-killer | 9ca31226b89f096277b9067207001704068a2f89 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> tmp;
vector<vector<int>> resultCab;
vector<int> _nums;
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<int> none;
resultCab.push_back(none);
_nums = nums;
for (int i = 1; i <= nums.size(); i++) {
C(i, nums.size());
}
return resultCab;
}
void C(int a, int b) {
dfs(1, 0, a, b);
}
void dfs(int step, int start, int a, int b) {
if (step > a) {
updateResult();
return;
}
for (int i = start; i < b; i++) {
tmp.push_back(_nums[i]);
dfs(step + 1, i + 1, a, b);
tmp.pop_back();
}
}
void updateResult() {
if (!checkSame()) {
resultCab.push_back(tmp);
}
}
bool checkSame() {
for (vector<int>& result: resultCab) {
if (result == tmp) {
return true;
}
}
return false;
}
};
int main() {
vector<int> nums;
nums.push_back(1);
nums.push_back(2);
nums.push_back(3);
Solution solution;
vector<vector<int>> result = solution.subsetsWithDup(nums);
for (vector<int>& nn: result) {
for (int& n: nn) {
cout << n;
}
cout << endl;
}
} | 18.56962 | 63 | 0.464213 | [
"vector"
] |
892a529ca0904f010b6c7f59783ffb4202e3f9d7 | 1,752 | cpp | C++ | src/display/line_display.cpp | corenting/chronos-cli | b277486e00db5bce46e855f411954e144b43bb28 | [
"MIT"
] | null | null | null | src/display/line_display.cpp | corenting/chronos-cli | b277486e00db5bce46e855f411954e144b43bb28 | [
"MIT"
] | null | null | null | src/display/line_display.cpp | corenting/chronos-cli | b277486e00db5bce46e855f411954e144b43bb28 | [
"MIT"
] | null | null | null | #include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>
#include "line_display.h"
void LineDisplay::Print(std::vector<Event> events) {
int latestDisplayedDay = -1;
bool first = true;
for (auto event : events) {
if (event.GetStart().date().day_of_week() > latestDisplayedDay) {
// Facet for date display
boost::posix_time::time_facet *dateFacet(new boost::posix_time::time_facet("%a %d %b %Y"));
std::cout.imbue(std::locale(std::cout.getloc(), dateFacet));
if (first) {
first = false;
} else {
std::cout << std::endl;
}
std::cout << event.GetStart() << std::endl;
latestDisplayedDay = event.GetStart().date().day_of_week();
//Facet for time display
boost::posix_time::time_facet *timeFacet(new boost::posix_time::time_facet("%H:%M"));
std::cout.imbue(std::locale(std::cout.getloc(), timeFacet));
}
std::cout << event.GetStart() << " - " << event.GetEnd() << " - "
<< Display::TruncateString(event.GetName(), 45);
if (event.GetRoomsList().size() != 0 || event.GetTeachersList().size() != 0) {
std::cout << " - ";
}
if (event.GetRoomsList().size() != 0) {
std::cout << Display::TruncateString(Display::GetListAsString(event.GetRoomsList()), 45);
if (event.GetTeachersList().size() != 0) {
std::cout << " - ";
}
}
if (event.GetTeachersList().size() != 0) {
std::cout << Display::TruncateString(Display::GetListAsString(event.GetTeachersList()), 45);
}
std::cout << std::endl;
}
} | 38.933333 | 104 | 0.538813 | [
"vector"
] |
9f16c3cee75df3ad5815e7c2f12a0e8882b9a378 | 951 | cpp | C++ | C++/base_4/mem_fun_1.cpp | liangjisheng/C-Cpp | 8b33ba1f43580a7bdded8bb4ce3d92983ccedb81 | [
"MIT"
] | 5 | 2019-09-17T09:12:15.000Z | 2021-05-29T10:54:39.000Z | C++/base_4/mem_fun_1.cpp | liangjisheng/C-Cpp | 8b33ba1f43580a7bdded8bb4ce3d92983ccedb81 | [
"MIT"
] | null | null | null | C++/base_4/mem_fun_1.cpp | liangjisheng/C-Cpp | 8b33ba1f43580a7bdded8bb4ce3d92983ccedb81 | [
"MIT"
] | 2 | 2021-07-26T06:36:12.000Z | 2022-01-23T15:20:30.000Z |
/***********************************************************
* @name: mem_fun_1.cpp
* @brief: mem_fun
* @author: Jisheng Liang
* @date: 2018/6/30 15:34:06
* @version: 1.0
**********************************************************/
#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
using namespace std;
struct Car {
int id;
Car(int id) { this->id = id; }
void display() const { cout << "car " << id << endl; }
};
int main()
{
vector<Car*> pcars;
vector<Car> cars;
for (int i = 0; i < 5; i++)
pcars.push_back(new Car(i));
for (int i = 5; i < 10; i++)
cars.push_back(Car(i));
cout << "elements in pcars:" << endl;
for_each(pcars.begin(), pcars.end(), std::mem_fun(&Car::display));
cout << "elements in cars: " << endl;
for_each(cars.begin(), cars.end(), std::mem_fun_ref(&Car::display));
for (size_t i = 0; i < pcars.size(); i++)
delete pcars[i], pcars[i] = NULL;
getchar();
return 0;
}
| 21.133333 | 69 | 0.526814 | [
"vector"
] |
9f19fe6259bd4b9b0d869eda7333a58b1f862c34 | 3,687 | hpp | C++ | config/include/config/config.hpp | DEIS-Tools/model-utilities | a1a38f7f8adcedc0b175fa7d3d06e4551688903a | [
"MIT"
] | null | null | null | config/include/config/config.hpp | DEIS-Tools/model-utilities | a1a38f7f8adcedc0b175fa7d3d06e4551688903a | [
"MIT"
] | 6 | 2019-11-14T13:49:39.000Z | 2019-12-04T09:36:21.000Z | config/include/config/config.hpp | DEIS-Tools/model-utilities | a1a38f7f8adcedc0b175fa7d3d06e4551688903a | [
"MIT"
] | 2 | 2019-11-20T18:01:34.000Z | 2020-05-05T07:18:37.000Z | /*Copyright 2019 Anders Madsen, Emil Jørgensen Njor, Emil Stenderup Bækdahl, Frederik Baymler
*Mathiesen, Nikolaj Jensen Ulrik, Simon Mejlby Virenfeldt
*
*Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
*associated documentation files (the "Software"), to deal in the Software without restriction,
*including without limitation the rights to use, copy, modify, merge, publish, distribute,
*sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
*furnished to do so, subject to the following conditions:
*
*The above copyright notice and this permission notice shall be included in all copies or
*substantial portions of the Software.
*
*THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
*NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
*NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
*DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
*OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef CONFIG_HPP
#define CONFIG_HPP
#include "util/json.hpp"
#include "util/meta.hpp"
#include <string>
#include <type_traits>
#include <vector>
namespace config {
using Action = std::pair<std::string, int>;
class FileNotOpenedException : public std::exception {
std::string message;
public:
FileNotOpenedException(const std::string &path) : message("Could not open file: " + path){};
const char *what() const noexcept { return message.c_str(); }
};
class ReadException : public std::exception {
std::string message;
public:
ReadException(bool fail, bool bad)
: message("Invalid stream state: " + std::to_string(fail) + ", " + std::to_string(bad)){};
const char *what() const noexcept { return message.c_str(); }
};
class InvalidValueException : public std::exception {
std::string message;
public:
InvalidValueException(const std::string &str) : message("Invalid value: " + str){};
const char *what() const noexcept { return message.c_str(); }
};
class InvalidKeyException : public std::exception {
std::string message;
public:
InvalidKeyException(const std::string &key) : message("Key not found: " + key){};
const char *what() const noexcept { return message.c_str(); };
};
template <typename T>
T convert_from_json(const Json::Value &value);
class Config {
Json::Value json;
public:
Config(){};
Config(const std::string &file_path);
void load_from_file(const std::string &file_path);
void write_to_file(const std::string &file_path);
template <typename T>
T get(const std::string &key);
template <typename T>
T get(const std::string &key1, const std::string &key2);
int getSize(const std::string &key);
template <typename T>
void set(const std::string &key, T value)
{
// if we can just assign the value to json[key] (of type Json::Value &),
// simply assign.
if constexpr (std::is_assignable<Json::Value &, T>::value) {
json[key] = value;
}
// if it is a container, dump container to a Json::array.
else if constexpr (meta::is_container<T>::value) {
Json::Value arr{Json::arrayValue};
for (auto &it : value) {
arr.append(it);
}
json[key] = arr;
}
// otherwise abort; we don't know what to do;
else {
meta::unsupported<T> _;
}
}
};
} // namespace config
#endif
| 33.518182 | 100 | 0.678872 | [
"vector"
] |
9f1d983a80561a9a74eeda61f143aa7d274b098a | 151,162 | cpp | C++ | src/core/qgsvectorfilewriter.cpp | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | null | null | null | src/core/qgsvectorfilewriter.cpp | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | null | null | null | src/core/qgsvectorfilewriter.cpp | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | 1 | 2021-12-25T08:40:30.000Z | 2021-12-25T08:40:30.000Z | /***************************************************************************
qgsvectorfilewriter.cpp
generic vector file writer
-------------------
begin : Sat Jun 16 2004
copyright : (C) 2004 by Tim Sutton
email : tim at linfiniti.com
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#include "qgsapplication.h"
#include "qgsfields.h"
#include "qgsfeature.h"
#include "qgsfeatureiterator.h"
#include "qgsgeometry.h"
#include "qgslogger.h"
#include "qgsmessagelog.h"
#include "qgscoordinatereferencesystem.h"
#include "qgsvectorfilewriter.h"
#include "qgsrenderer.h"
#include "qgssymbollayer.h"
#include "qgsvectordataprovider.h"
#include "qgsvectorlayer.h"
#include "qgslocalec.h"
#include "qgsexception.h"
#include "qgssettings.h"
#include "qgsgeometryengine.h"
#include "qgsproviderregistry.h"
#include "qgsexpressioncontextutils.h"
#include <QFile>
#include <QFileInfo>
#include <QDir>
#include <QTextCodec>
#include <QTextStream>
#include <QSet>
#include <QMetaType>
#include <cassert>
#include <cstdlib> // size_t
#include <limits> // std::numeric_limits
#include <ogr_srs_api.h>
#include <cpl_error.h>
#include <cpl_conv.h>
#include <cpl_string.h>
#include <gdal.h>
// Thin wrapper around OGROpen() to workaround a bug in GDAL < 2.3.1
// where a existing BNA file is wrongly reported to be openable in update mode
// but attempting to add features in it crashes the BNA driver.
static OGRDataSourceH myOGROpen( const char *pszName, int bUpdate, OGRSFDriverH *phDriver )
{
OGRSFDriverH hDriver = nullptr;
OGRDataSourceH hDS = OGROpen( pszName, bUpdate, &hDriver );
if ( hDS && bUpdate )
{
QString drvName = OGR_Dr_GetName( hDriver );
if ( drvName == "BNA" )
{
OGR_DS_Destroy( hDS );
if ( phDriver )
*phDriver = nullptr;
return nullptr;
}
}
if ( phDriver )
*phDriver = hDriver;
return hDS;
}
QgsField QgsVectorFileWriter::FieldValueConverter::fieldDefinition( const QgsField &field )
{
return field;
}
QVariant QgsVectorFileWriter::FieldValueConverter::convert( int /*fieldIdxInLayer*/, const QVariant &value )
{
return value;
}
QgsVectorFileWriter::FieldValueConverter *QgsVectorFileWriter::FieldValueConverter::clone() const
{
return new FieldValueConverter( *this );
}
QgsVectorFileWriter::QgsVectorFileWriter(
const QString &vectorFileName,
const QString &fileEncoding,
const QgsFields &fields,
QgsWkbTypes::Type geometryType,
const QgsCoordinateReferenceSystem &srs,
const QString &driverName,
const QStringList &datasourceOptions,
const QStringList &layerOptions,
QString *newFilename,
SymbologyExport symbologyExport,
QgsFeatureSink::SinkFlags sinkFlags,
QString *newLayer
)
: mError( NoError )
, mWkbType( geometryType )
, mSymbologyExport( symbologyExport )
, mSymbologyScale( 1.0 )
{
init( vectorFileName, fileEncoding, fields, geometryType,
srs, driverName, datasourceOptions, layerOptions, newFilename, nullptr,
QString(), CreateOrOverwriteFile, newLayer, sinkFlags );
}
QgsVectorFileWriter::QgsVectorFileWriter( const QString &vectorFileName,
const QString &fileEncoding,
const QgsFields &fields,
QgsWkbTypes::Type geometryType,
const QgsCoordinateReferenceSystem &srs,
const QString &driverName,
const QStringList &datasourceOptions,
const QStringList &layerOptions,
QString *newFilename,
QgsVectorFileWriter::SymbologyExport symbologyExport,
FieldValueConverter *fieldValueConverter,
const QString &layerName,
ActionOnExistingFile action,
QString *newLayer )
: mError( NoError )
, mWkbType( geometryType )
, mSymbologyExport( symbologyExport )
, mSymbologyScale( 1.0 )
{
init( vectorFileName, fileEncoding, fields, geometryType, srs, driverName,
datasourceOptions, layerOptions, newFilename, fieldValueConverter,
layerName, action, newLayer, nullptr );
}
bool QgsVectorFileWriter::supportsFeatureStyles( const QString &driverName )
{
if ( driverName == QLatin1String( "MapInfo MIF" ) )
{
return true;
}
#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(2,3,0)
GDALDriverH gdalDriver = GDALGetDriverByName( driverName.toLocal8Bit().constData() );
if ( !gdalDriver )
return false;
char **driverMetadata = GDALGetMetadata( gdalDriver, nullptr );
if ( !driverMetadata )
return false;
return CSLFetchBoolean( driverMetadata, GDAL_DCAP_FEATURE_STYLES, false );
#else
return driverName == QLatin1String( "DXF" ) || driverName == QLatin1String( "KML" ) || driverName == QLatin1String( "MapInfo File" );
#endif
}
void QgsVectorFileWriter::init( QString vectorFileName,
QString fileEncoding,
const QgsFields &fields,
QgsWkbTypes::Type geometryType,
QgsCoordinateReferenceSystem srs,
const QString &driverName,
QStringList datasourceOptions,
QStringList layerOptions,
QString *newFilename,
FieldValueConverter *fieldValueConverter,
const QString &layerNameIn,
ActionOnExistingFile action,
QString *newLayer, SinkFlags sinkFlags )
{
mRenderContext.setRendererScale( mSymbologyScale );
if ( vectorFileName.isEmpty() )
{
mErrorMessage = QObject::tr( "Empty filename given" );
mError = ErrCreateDataSource;
return;
}
if ( driverName == QLatin1String( "MapInfo MIF" ) )
{
mOgrDriverName = QStringLiteral( "MapInfo File" );
}
else if ( driverName == QLatin1String( "SpatiaLite" ) )
{
mOgrDriverName = QStringLiteral( "SQLite" );
if ( !datasourceOptions.contains( QStringLiteral( "SPATIALITE=YES" ) ) )
{
datasourceOptions.append( QStringLiteral( "SPATIALITE=YES" ) );
}
}
else if ( driverName == QLatin1String( "DBF file" ) )
{
mOgrDriverName = QStringLiteral( "ESRI Shapefile" );
if ( !layerOptions.contains( QStringLiteral( "SHPT=NULL" ) ) )
{
layerOptions.append( QStringLiteral( "SHPT=NULL" ) );
}
srs = QgsCoordinateReferenceSystem();
}
else
{
mOgrDriverName = driverName;
}
// find driver in OGR
OGRSFDriverH poDriver;
QgsApplication::registerOgrDrivers();
poDriver = OGRGetDriverByName( mOgrDriverName.toLocal8Bit().constData() );
if ( !poDriver )
{
mErrorMessage = QObject::tr( "OGR driver for '%1' not found (OGR error: %2)" )
.arg( driverName,
QString::fromUtf8( CPLGetLastErrorMsg() ) );
mError = ErrDriverNotFound;
return;
}
MetaData metadata;
bool metadataFound = driverMetadata( driverName, metadata );
if ( mOgrDriverName == QLatin1String( "ESRI Shapefile" ) )
{
if ( layerOptions.join( QString() ).toUpper().indexOf( QLatin1String( "ENCODING=" ) ) == -1 )
{
layerOptions.append( "ENCODING=" + convertCodecNameForEncodingOption( fileEncoding ) );
}
if ( driverName == QLatin1String( "ESRI Shapefile" ) && !vectorFileName.endsWith( QLatin1String( ".shp" ), Qt::CaseInsensitive ) )
{
vectorFileName += QLatin1String( ".shp" );
}
else if ( driverName == QLatin1String( "DBF file" ) && !vectorFileName.endsWith( QLatin1String( ".dbf" ), Qt::CaseInsensitive ) )
{
vectorFileName += QLatin1String( ".dbf" );
}
if ( action == CreateOrOverwriteFile || action == CreateOrOverwriteLayer )
deleteShapeFile( vectorFileName );
}
else
{
if ( metadataFound )
{
QStringList allExts = metadata.ext.split( ' ', QString::SkipEmptyParts );
bool found = false;
const auto constAllExts = allExts;
for ( const QString &ext : constAllExts )
{
if ( vectorFileName.endsWith( '.' + ext, Qt::CaseInsensitive ) )
{
found = true;
break;
}
}
if ( !found )
{
vectorFileName += '.' + allExts[0];
}
}
if ( action == CreateOrOverwriteFile )
{
if ( vectorFileName.endsWith( QLatin1String( ".gdb" ), Qt::CaseInsensitive ) )
{
QDir dir( vectorFileName );
if ( dir.exists() )
{
QFileInfoList fileList = dir.entryInfoList(
QDir::NoDotAndDotDot | QDir::System | QDir::Hidden | QDir::AllDirs | QDir::Files, QDir::DirsFirst );
const auto constFileList = fileList;
for ( const QFileInfo &info : constFileList )
{
QFile::remove( info.absoluteFilePath() );
}
}
QDir().rmdir( vectorFileName );
}
else
{
QFile::remove( vectorFileName );
}
}
}
if ( metadataFound && !metadata.compulsoryEncoding.isEmpty() )
{
if ( fileEncoding.compare( metadata.compulsoryEncoding, Qt::CaseInsensitive ) != 0 )
{
QgsDebugMsg( QStringLiteral( "forced %1 encoding for %2" ).arg( metadata.compulsoryEncoding, driverName ) );
fileEncoding = metadata.compulsoryEncoding;
}
}
char **options = nullptr;
if ( !datasourceOptions.isEmpty() )
{
options = new char *[ datasourceOptions.size() + 1 ];
for ( int i = 0; i < datasourceOptions.size(); i++ )
{
QgsDebugMsg( QStringLiteral( "-dsco=%1" ).arg( datasourceOptions[i] ) );
options[i] = CPLStrdup( datasourceOptions[i].toLocal8Bit().constData() );
}
options[ datasourceOptions.size()] = nullptr;
}
mAttrIdxToOgrIdx.remove( 0 );
// create the data source
if ( action == CreateOrOverwriteFile )
mDS.reset( OGR_Dr_CreateDataSource( poDriver, vectorFileName.toUtf8().constData(), options ) );
else
mDS.reset( myOGROpen( vectorFileName.toUtf8().constData(), TRUE, nullptr ) );
if ( options )
{
for ( int i = 0; i < datasourceOptions.size(); i++ )
CPLFree( options[i] );
delete [] options;
options = nullptr;
}
if ( !mDS )
{
mError = ErrCreateDataSource;
if ( action == CreateOrOverwriteFile )
mErrorMessage = QObject::tr( "Creation of data source failed (OGR error: %1)" )
.arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
else
mErrorMessage = QObject::tr( "Opening of data source in update mode failed (OGR error: %1)" )
.arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
return;
}
QString layerName( layerNameIn );
if ( layerName.isEmpty() )
layerName = QFileInfo( vectorFileName ).baseName();
if ( action == CreateOrOverwriteLayer )
{
const int layer_count = OGR_DS_GetLayerCount( mDS.get() );
for ( int i = 0; i < layer_count; i++ )
{
OGRLayerH hLayer = OGR_DS_GetLayer( mDS.get(), i );
if ( EQUAL( OGR_L_GetName( hLayer ), layerName.toUtf8().constData() ) )
{
if ( OGR_DS_DeleteLayer( mDS.get(), i ) != OGRERR_NONE )
{
mError = ErrCreateLayer;
mErrorMessage = QObject::tr( "Overwriting of existing layer failed (OGR error: %1)" )
.arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
return;
}
break;
}
}
}
if ( action == CreateOrOverwriteFile )
{
QgsDebugMsg( QStringLiteral( "Created data source" ) );
}
else
{
QgsDebugMsg( QStringLiteral( "Opened data source in update mode" ) );
}
// use appropriate codec
mCodec = QTextCodec::codecForName( fileEncoding.toLocal8Bit().constData() );
if ( !mCodec )
{
QgsDebugMsg( "error finding QTextCodec for " + fileEncoding );
QgsSettings settings;
QString enc = settings.value( QStringLiteral( "UI/encoding" ), "System" ).toString();
mCodec = QTextCodec::codecForName( enc.toLocal8Bit().constData() );
if ( !mCodec )
{
QgsDebugMsg( "error finding QTextCodec for " + enc );
mCodec = QTextCodec::codecForLocale();
Q_ASSERT( mCodec );
}
}
// consider spatial reference system of the layer
if ( srs.isValid() )
{
QString srsWkt = srs.toWkt();
QgsDebugMsg( "WKT to save as is " + srsWkt );
mOgrRef = OSRNewSpatialReference( srsWkt.toLocal8Bit().constData() );
}
// datasource created, now create the output layer
OGRwkbGeometryType wkbType = ogrTypeFromWkbType( geometryType );
// Remove FEATURE_DATASET layer option (used for ESRI File GDB driver) if its value is not set
int optIndex = layerOptions.indexOf( QStringLiteral( "FEATURE_DATASET=" ) );
if ( optIndex != -1 )
{
layerOptions.removeAt( optIndex );
}
if ( !layerOptions.isEmpty() )
{
options = new char *[ layerOptions.size() + 1 ];
for ( int i = 0; i < layerOptions.size(); i++ )
{
QgsDebugMsg( QStringLiteral( "-lco=%1" ).arg( layerOptions[i] ) );
options[i] = CPLStrdup( layerOptions[i].toLocal8Bit().constData() );
}
options[ layerOptions.size()] = nullptr;
}
// disable encoding conversion of OGR Shapefile layer
CPLSetConfigOption( "SHAPE_ENCODING", "" );
if ( action == CreateOrOverwriteFile || action == CreateOrOverwriteLayer )
{
mLayer = OGR_DS_CreateLayer( mDS.get(), layerName.toUtf8().constData(), mOgrRef, wkbType, options );
if ( newLayer && mLayer )
*newLayer = OGR_L_GetName( mLayer );
}
else if ( driverName == QLatin1String( "DGN" ) )
{
mLayer = OGR_DS_GetLayerByName( mDS.get(), "elements" );
}
else
{
mLayer = OGR_DS_GetLayerByName( mDS.get(), layerName.toUtf8().constData() );
}
if ( options )
{
for ( int i = 0; i < layerOptions.size(); i++ )
CPLFree( options[i] );
delete [] options;
options = nullptr;
}
QgsSettings settings;
if ( !settings.value( QStringLiteral( "qgis/ignoreShapeEncoding" ), true ).toBool() )
{
CPLSetConfigOption( "SHAPE_ENCODING", nullptr );
}
if ( srs.isValid() )
{
if ( mOgrDriverName == QLatin1String( "ESRI Shapefile" ) )
{
QString layerName = vectorFileName.left( vectorFileName.indexOf( QLatin1String( ".shp" ), Qt::CaseInsensitive ) );
QFile prjFile( layerName + ".qpj" );
if ( prjFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
{
QTextStream prjStream( &prjFile );
prjStream << srs.toWkt().toLocal8Bit().constData() << endl;
prjFile.close();
}
else
{
QgsDebugMsg( "Couldn't open file " + layerName + ".qpj" );
}
}
}
if ( !mLayer )
{
if ( action == CreateOrOverwriteFile || action == CreateOrOverwriteLayer )
mErrorMessage = QObject::tr( "Creation of layer failed (OGR error: %1)" )
.arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
else
mErrorMessage = QObject::tr( "Opening of layer failed (OGR error: %1)" )
.arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
mError = ErrCreateLayer;
return;
}
OGRFeatureDefnH defn = OGR_L_GetLayerDefn( mLayer );
QgsDebugMsg( QStringLiteral( "created layer" ) );
// create the fields
QgsDebugMsg( "creating " + QString::number( fields.size() ) + " fields" );
mFields = fields;
mAttrIdxToOgrIdx.clear();
QSet<int> existingIdxs;
mFieldValueConverter = fieldValueConverter;
switch ( action )
{
case CreateOrOverwriteFile:
case CreateOrOverwriteLayer:
case AppendToLayerAddFields:
{
for ( int fldIdx = 0; fldIdx < fields.count(); ++fldIdx )
{
QgsField attrField = fields.at( fldIdx );
if ( fieldValueConverter )
{
attrField = fieldValueConverter->fieldDefinition( fields.at( fldIdx ) );
}
QString name( attrField.name() );
if ( action == AppendToLayerAddFields )
{
int ogrIdx = OGR_FD_GetFieldIndex( defn, mCodec->fromUnicode( name ) );
if ( ogrIdx >= 0 )
{
mAttrIdxToOgrIdx.insert( fldIdx, ogrIdx );
continue;
}
}
OGRFieldType ogrType = OFTString; //default to string
int ogrWidth = attrField.length();
int ogrPrecision = attrField.precision();
if ( ogrPrecision > 0 )
++ogrWidth;
switch ( attrField.type() )
{
case QVariant::LongLong:
{
const char *pszDataTypes = GDALGetMetadataItem( poDriver, GDAL_DMD_CREATIONFIELDDATATYPES, nullptr );
if ( pszDataTypes && strstr( pszDataTypes, "Integer64" ) )
ogrType = OFTInteger64;
else
ogrType = OFTReal;
ogrWidth = ogrWidth > 0 && ogrWidth <= 20 ? ogrWidth : 20;
ogrPrecision = 0;
break;
}
case QVariant::String:
ogrType = OFTString;
if ( ( ogrWidth <= 0 || ogrWidth > 255 ) && mOgrDriverName == QLatin1String( "ESRI Shapefile" ) )
ogrWidth = 255;
break;
case QVariant::Int:
ogrType = OFTInteger;
ogrWidth = ogrWidth > 0 && ogrWidth <= 10 ? ogrWidth : 10;
ogrPrecision = 0;
break;
case QVariant::Bool:
ogrType = OFTInteger;
ogrWidth = 1;
ogrPrecision = 0;
break;
case QVariant::Double:
ogrType = OFTReal;
break;
case QVariant::Date:
ogrType = OFTDate;
break;
case QVariant::Time:
if ( mOgrDriverName == QLatin1String( "ESRI Shapefile" ) )
{
ogrType = OFTString;
ogrWidth = 12; // %02d:%02d:%06.3f
}
else
{
ogrType = OFTTime;
}
break;
case QVariant::DateTime:
if ( mOgrDriverName == QLatin1String( "ESRI Shapefile" ) )
{
ogrType = OFTString;
ogrWidth = 24; // "%04d/%02d/%02d %02d:%02d:%06.3f"
}
else
{
ogrType = OFTDateTime;
}
break;
case QVariant::ByteArray:
ogrType = OFTBinary;
break;
#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(2,4,0)
case QVariant::List:
// only string list supported at the moment, fall through to default for other types
if ( attrField.subType() == QVariant::String )
{
const char *pszDataTypes = GDALGetMetadataItem( poDriver, GDAL_DMD_CREATIONFIELDDATATYPES, nullptr );
if ( pszDataTypes && strstr( pszDataTypes, "StringList" ) )
{
ogrType = OFTStringList;
supportsStringList = true;
}
else
{
ogrType = OFTString;
ogrWidth = 255;
}
break;
}
//intentional fall-through
FALLTHROUGH
#endif
default:
//assert(0 && "invalid variant type!");
mErrorMessage = QObject::tr( "Unsupported type for field %1" )
.arg( attrField.name() );
mError = ErrAttributeTypeUnsupported;
return;
}
if ( mOgrDriverName == QLatin1String( "SQLite" ) && name.compare( QLatin1String( "ogc_fid" ), Qt::CaseInsensitive ) == 0 )
{
int i;
for ( i = 0; i < 10; i++ )
{
name = QStringLiteral( "ogc_fid%1" ).arg( i );
int j;
for ( j = 0; j < fields.size() && name.compare( fields.at( j ).name(), Qt::CaseInsensitive ) != 0; j++ )
;
if ( j == fields.size() )
break;
}
if ( i == 10 )
{
mErrorMessage = QObject::tr( "No available replacement for internal fieldname ogc_fid found" ).arg( attrField.name() );
mError = ErrAttributeCreationFailed;
return;
}
QgsMessageLog::logMessage( QObject::tr( "Reserved attribute name ogc_fid replaced with %1" ).arg( name ), QObject::tr( "OGR" ) );
}
// create field definition
gdal::ogr_field_def_unique_ptr fld( OGR_Fld_Create( mCodec->fromUnicode( name ), ogrType ) );
if ( ogrWidth > 0 )
{
OGR_Fld_SetWidth( fld.get(), ogrWidth );
}
if ( ogrPrecision >= 0 )
{
OGR_Fld_SetPrecision( fld.get(), ogrPrecision );
}
switch ( attrField.type() )
{
case QVariant::Bool:
OGR_Fld_SetSubType( fld.get(), OFSTBoolean );
break;
default:
break;
}
// create the field
QgsDebugMsg( "creating field " + attrField.name() +
" type " + QString( QVariant::typeToName( attrField.type() ) ) +
" width " + QString::number( ogrWidth ) +
" precision " + QString::number( ogrPrecision ) );
if ( OGR_L_CreateField( mLayer, fld.get(), true ) != OGRERR_NONE )
{
QgsDebugMsg( "error creating field " + attrField.name() );
mErrorMessage = QObject::tr( "Creation of field %1 failed (OGR error: %2)" )
.arg( attrField.name(),
QString::fromUtf8( CPLGetLastErrorMsg() ) );
mError = ErrAttributeCreationFailed;
return;
}
int ogrIdx = OGR_FD_GetFieldIndex( defn, mCodec->fromUnicode( name ) );
QgsDebugMsg( QStringLiteral( "returned field index for %1: %2" ).arg( name ).arg( ogrIdx ) );
if ( ogrIdx < 0 || existingIdxs.contains( ogrIdx ) )
{
// GDAL 1.7 not just truncates, but launders more aggressivly.
ogrIdx = OGR_FD_GetFieldCount( defn ) - 1;
if ( ogrIdx < 0 )
{
QgsDebugMsg( "error creating field " + attrField.name() );
mErrorMessage = QObject::tr( "Created field %1 not found (OGR error: %2)" )
.arg( attrField.name(),
QString::fromUtf8( CPLGetLastErrorMsg() ) );
mError = ErrAttributeCreationFailed;
return;
}
}
existingIdxs.insert( ogrIdx );
mAttrIdxToOgrIdx.insert( fldIdx, ogrIdx );
}
}
break;
case AppendToLayerNoNewFields:
{
for ( int fldIdx = 0; fldIdx < fields.count(); ++fldIdx )
{
QgsField attrField = fields.at( fldIdx );
QString name( attrField.name() );
int ogrIdx = OGR_FD_GetFieldIndex( defn, mCodec->fromUnicode( name ) );
if ( ogrIdx >= 0 )
mAttrIdxToOgrIdx.insert( fldIdx, ogrIdx );
}
}
break;
}
// Geopackages require a unique feature id. If the input feature stream cannot guarantee
// the uniqueness of the FID column, we drop it and let OGR generate new ones
if ( sinkFlags.testFlag( QgsFeatureSink::RegeneratePrimaryKey ) && driverName == QLatin1String( "GPKG" ) )
{
int fidIdx = fields.lookupField( QStringLiteral( "FID" ) );
if ( fidIdx >= 0 )
mAttrIdxToOgrIdx.remove( fidIdx );
}
QgsDebugMsg( QStringLiteral( "Done creating fields" ) );
mWkbType = geometryType;
if ( newFilename )
*newFilename = vectorFileName;
// enabling transaction on databases that support it
mUsingTransaction = true;
if ( OGRERR_NONE != OGR_L_StartTransaction( mLayer ) )
{
mUsingTransaction = false;
}
}
OGRGeometryH QgsVectorFileWriter::createEmptyGeometry( QgsWkbTypes::Type wkbType )
{
return OGR_G_CreateGeometry( ogrTypeFromWkbType( wkbType ) );
}
///@cond PRIVATE
class QgsVectorFileWriterMetadataContainer
{
public:
QgsVectorFileWriterMetadataContainer()
{
QMap<QString, QgsVectorFileWriter::Option *> datasetOptions;
QMap<QString, QgsVectorFileWriter::Option *> layerOptions;
// Arc/Info ASCII Coverage
datasetOptions.clear();
layerOptions.clear();
driverMetadata.insert( QStringLiteral( "AVCE00" ),
QgsVectorFileWriter::MetaData(
QStringLiteral( "Arc/Info ASCII Coverage" ),
QObject::tr( "Arc/Info ASCII Coverage" ),
QStringLiteral( "*.e00" ),
QStringLiteral( "e00" ),
datasetOptions,
layerOptions
)
);
// Atlas BNA
datasetOptions.clear();
layerOptions.clear();
datasetOptions.insert( QStringLiteral( "LINEFORMAT" ), new QgsVectorFileWriter::SetOption(
QObject::tr( "New BNA files are created by the "
"systems default line termination conventions. "
"This may be overridden here." ),
QStringList()
<< QStringLiteral( "CRLF" )
<< QStringLiteral( "LF" ),
QString(), // Default value
true // Allow None
) );
datasetOptions.insert( QStringLiteral( "MULTILINE" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "By default, BNA files are created in multi-line format. "
"For each record, the first line contains the identifiers and the "
"type/number of coordinates to follow. Each following line contains "
"a pair of coordinates." ),
true // Default value
) );
datasetOptions.insert( QStringLiteral( "NB_IDS" ), new QgsVectorFileWriter::SetOption(
QObject::tr( "BNA records may contain from 2 to 4 identifiers per record. "
"Some software packages only support a precise number of identifiers. "
"You can override the default value (2) by a precise value." ),
QStringList()
<< QStringLiteral( "2" )
<< QStringLiteral( "3" )
<< QStringLiteral( "4" )
<< QStringLiteral( "NB_SOURCE_FIELDS" ),
QStringLiteral( "2" ) // Default value
) );
datasetOptions.insert( QStringLiteral( "ELLIPSES_AS_ELLIPSES" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "The BNA writer will try to recognize ellipses and circles when writing a polygon. "
"This will only work if the feature has previously been read from a BNA file. "
"As some software packages do not support ellipses/circles in BNA data file, "
"it may be useful to tell the writer by specifying ELLIPSES_AS_ELLIPSES=NO not "
"to export them as such, but keep them as polygons." ),
true // Default value
) );
datasetOptions.insert( QStringLiteral( "NB_PAIRS_PER_LINE" ), new QgsVectorFileWriter::IntOption(
QObject::tr( "Limit the number of coordinate pairs per line in multiline format." ),
2 // Default value
) );
datasetOptions.insert( QStringLiteral( "COORDINATE_PRECISION" ), new QgsVectorFileWriter::IntOption(
QObject::tr( "Set the number of decimal for coordinates. Default value is 10." ),
10 // Default value
) );
driverMetadata.insert( QStringLiteral( "BNA" ),
QgsVectorFileWriter::MetaData(
QStringLiteral( "Atlas BNA" ),
QObject::tr( "Atlas BNA" ),
QStringLiteral( "*.bna" ),
QStringLiteral( "bna" ),
datasetOptions,
layerOptions
)
);
// Comma Separated Value
datasetOptions.clear();
layerOptions.clear();
layerOptions.insert( QStringLiteral( "LINEFORMAT" ), new QgsVectorFileWriter::SetOption(
QObject::tr( "By default when creating new .csv files they "
"are created with the line termination conventions "
"of the local platform (CR/LF on Win32 or LF on all other systems). "
"This may be overridden through the use of the LINEFORMAT option." ),
QStringList()
<< QStringLiteral( "CRLF" )
<< QStringLiteral( "LF" ),
QString(), // Default value
true // Allow None
) );
layerOptions.insert( QStringLiteral( "GEOMETRY" ), new QgsVectorFileWriter::SetOption(
QObject::tr( "By default, the geometry of a feature written to a .csv file is discarded. "
"It is possible to export the geometry in its WKT representation by "
"specifying GEOMETRY=AS_WKT. It is also possible to export point geometries "
"into their X,Y,Z components by specifying GEOMETRY=AS_XYZ, GEOMETRY=AS_XY "
"or GEOMETRY=AS_YX." ),
QStringList()
<< QStringLiteral( "AS_WKT" )
<< QStringLiteral( "AS_XYZ" )
<< QStringLiteral( "AS_XY" )
<< QStringLiteral( "AS_YX" ),
QString(), // Default value
true // Allow None
) );
layerOptions.insert( QStringLiteral( "CREATE_CSVT" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "Create the associated .csvt file to describe the type of each "
"column of the layer and its optional width and precision." ),
false // Default value
) );
layerOptions.insert( QStringLiteral( "SEPARATOR" ), new QgsVectorFileWriter::SetOption(
QObject::tr( "Field separator character." ),
QStringList()
<< QStringLiteral( "COMMA" )
<< QStringLiteral( "SEMICOLON" )
<< QStringLiteral( "TAB" ),
QStringLiteral( "COMMA" ) // Default value
) );
#if defined(GDAL_COMPUTE_VERSION) && GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(2,3,0)
layerOptions.insert( QStringLiteral( "STRING_QUOTING" ), new QgsVectorFileWriter::SetOption(
QObject::tr( "Double-quote strings. IF_AMBIGUOUS means that string values that look like numbers will be quoted." ),
QStringList()
<< QStringLiteral( "IF_NEEDED" )
<< QStringLiteral( "IF_AMBIGUOUS" )
<< QStringLiteral( "ALWAYS" ),
QStringLiteral( "IF_AMBIGUOUS" ) // Default value
) );
#endif
layerOptions.insert( QStringLiteral( "WRITE_BOM" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "Write a UTF-8 Byte Order Mark (BOM) at the start of the file." ),
false // Default value
) );
driverMetadata.insert( QStringLiteral( "CSV" ),
QgsVectorFileWriter::MetaData(
QStringLiteral( "Comma Separated Value [CSV]" ),
QObject::tr( "Comma Separated Value [CSV]" ),
QStringLiteral( "*.csv" ),
QStringLiteral( "csv" ),
datasetOptions,
layerOptions
)
);
// ESRI Shapefile
datasetOptions.clear();
layerOptions.clear();
layerOptions.insert( QStringLiteral( "SHPT" ), new QgsVectorFileWriter::SetOption(
QObject::tr( "Override the type of shapefile created. "
"Can be one of NULL for a simple .dbf file with no .shp file, POINT, "
"ARC, POLYGON or MULTIPOINT for 2D, or POINTZ, ARCZ, POLYGONZ or "
"MULTIPOINTZ for 3D;" ) +
QObject::tr( " POINTM, ARCM, POLYGONM or MULTIPOINTM for measured geometries"
" and POINTZM, ARCZM, POLYGONZM or MULTIPOINTZM for 3D measured"
" geometries." ) +
#if defined(GDAL_COMPUTE_VERSION) && GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(2,2,0)
QObject::tr( " MULTIPATCH files are supported since GDAL 2.2." ) +
#endif
""
, QStringList()
<< QStringLiteral( "NULL" )
<< QStringLiteral( "POINT" )
<< QStringLiteral( "ARC" )
<< QStringLiteral( "POLYGON" )
<< QStringLiteral( "MULTIPOINT" )
<< QStringLiteral( "POINTZ" )
<< QStringLiteral( "ARCZ" )
<< QStringLiteral( "POLYGONZ" )
<< QStringLiteral( "MULTIPOINTZ" )
<< QStringLiteral( "POINTM" )
<< QStringLiteral( "ARCM" )
<< QStringLiteral( "POLYGONM" )
<< QStringLiteral( "MULTIPOINTM" )
<< QStringLiteral( "POINTZM" )
<< QStringLiteral( "ARCZM" )
<< QStringLiteral( "POLYGONZM" )
<< QStringLiteral( "MULTIPOINTZM" )
#if defined(GDAL_COMPUTE_VERSION) && GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(2,2,0)
<< QStringLiteral( "MULTIPATCH" )
#endif
<< QString(),
QString(), // Default value
true // Allow None
) );
// there does not seem to be a reason to provide this option to the user again
// as we set encoding for shapefiles based on "fileEncoding" parameter passed to the writer
#if 0
layerOptions.insert( "ENCODING", new QgsVectorFileWriter::SetOption(
QObject::tr( "Set the encoding value in the DBF file. "
"The default value is LDID/87. It is not clear "
"what other values may be appropriate." ),
QStringList()
<< "LDID/87",
"LDID/87" // Default value
) );
#endif
layerOptions.insert( QStringLiteral( "RESIZE" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "Set to YES to resize fields to their optimal size." ),
false // Default value
) );
driverMetadata.insert( QStringLiteral( "ESRI" ),
QgsVectorFileWriter::MetaData(
QStringLiteral( "ESRI Shapefile" ),
QObject::tr( "ESRI Shapefile" ),
QStringLiteral( "*.shp" ),
QStringLiteral( "shp" ),
datasetOptions,
layerOptions
)
);
// DBF File
datasetOptions.clear();
layerOptions.clear();
driverMetadata.insert( QStringLiteral( "DBF File" ),
QgsVectorFileWriter::MetaData(
QStringLiteral( "DBF File" ),
QObject::tr( "DBF File" ),
QStringLiteral( "*.dbf" ),
QStringLiteral( "dbf" ),
datasetOptions,
layerOptions
)
);
// FMEObjects Gateway
datasetOptions.clear();
layerOptions.clear();
driverMetadata.insert( QStringLiteral( "FMEObjects Gateway" ),
QgsVectorFileWriter::MetaData(
QStringLiteral( "FMEObjects Gateway" ),
QObject::tr( "FMEObjects Gateway" ),
QStringLiteral( "*.fdd" ),
QStringLiteral( "fdd" ),
datasetOptions,
layerOptions
)
);
// GeoJSON
datasetOptions.clear();
layerOptions.clear();
layerOptions.insert( QStringLiteral( "WRITE_BBOX" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "Set to YES to write a bbox property with the bounding box "
"of the geometries at the feature and feature collection level." ),
false // Default value
) );
layerOptions.insert( QStringLiteral( "COORDINATE_PRECISION" ), new QgsVectorFileWriter::IntOption(
QObject::tr( "Maximum number of figures after decimal separator to write in coordinates. "
"Defaults to 15. Truncation will occur to remove trailing zeros." ),
15 // Default value
) );
driverMetadata.insert( QStringLiteral( "GeoJSON" ),
QgsVectorFileWriter::MetaData(
QStringLiteral( "GeoJSON" ),
QObject::tr( "GeoJSON" ),
QStringLiteral( "*.geojson" ),
QStringLiteral( "geojson" ),
datasetOptions,
layerOptions,
QStringLiteral( "UTF-8" )
)
);
// GeoJSONSeq
datasetOptions.clear();
layerOptions.clear();
layerOptions.insert( QStringLiteral( "COORDINATE_PRECISION" ), new QgsVectorFileWriter::IntOption(
QObject::tr( "Maximum number of figures after decimal separator to write in coordinates. "
"Defaults to 15. Truncation will occur to remove trailing zeros." ),
15 // Default value
) );
layerOptions.insert( QStringLiteral( "RS" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "Whether to start records with the RS=0x1E character (RFC 8142 standard). "
"Defaults to NO: Newline Delimited JSON (geojsonl). \n"
"If set to YES: RFC 8142 standard: GeoJSON Text Sequences (geojsons)." ),
false // Default value = NO
) );
driverMetadata.insert( QStringLiteral( "GeoJSONSeq" ),
QgsVectorFileWriter::MetaData(
QStringLiteral( "GeoJSON - Newline Delimited" ),
QObject::tr( "GeoJSON - Newline Delimited" ),
QStringLiteral( "*.geojsonl *.geojsons *.json" ),
QStringLiteral( "json" ), // add json for now
datasetOptions,
layerOptions,
QStringLiteral( "UTF-8" )
)
);
// GeoRSS
datasetOptions.clear();
layerOptions.clear();
datasetOptions.insert( QStringLiteral( "FORMAT" ), new QgsVectorFileWriter::SetOption(
QObject::tr( "whether the document must be in RSS 2.0 or Atom 1.0 format. "
"Default value : RSS" ),
QStringList()
<< QStringLiteral( "RSS" )
<< QStringLiteral( "ATOM" ),
QStringLiteral( "RSS" ) // Default value
) );
datasetOptions.insert( QStringLiteral( "GEOM_DIALECT" ), new QgsVectorFileWriter::SetOption(
QObject::tr( "The encoding of location information. Default value : SIMPLE. "
"W3C_GEO only supports point geometries. "
"SIMPLE or W3C_GEO only support geometries in geographic WGS84 coordinates." ),
QStringList()
<< QStringLiteral( "SIMPLE" )
<< QStringLiteral( "GML" )
<< QStringLiteral( "W3C_GEO" ),
QStringLiteral( "SIMPLE" ) // Default value
) );
datasetOptions.insert( QStringLiteral( "USE_EXTENSIONS" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "If defined to YES, extension fields will be written. "
"If the field name not found in the base schema matches "
"the foo_bar pattern, foo will be considered as the namespace "
"of the element, and a <foo:bar> element will be written. "
"Otherwise, elements will be written in the <ogr:> namespace." ),
false // Default value
) );
datasetOptions.insert( QStringLiteral( "WRITE_HEADER_AND_FOOTER" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "If defined to NO, only <entry> or <item> elements will be written. "
"The user will have to provide the appropriate header and footer of the document." ),
true // Default value
) );
datasetOptions.insert( QStringLiteral( "HEADER" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "XML content that will be put between the <channel> element and the "
"first <item> element for a RSS document, or between the xml tag and "
"the first <entry> element for an Atom document." ),
QString() // Default value
) );
datasetOptions.insert( QStringLiteral( "TITLE" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "Value put inside the <title> element in the header. "
"If not provided, a dummy value will be used as that element is compulsory." ),
QString() // Default value
) );
datasetOptions.insert( QStringLiteral( "DESCRIPTION" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "Value put inside the <description> element in the header. "
"If not provided, a dummy value will be used as that element is compulsory." ),
QString() // Default value
) );
datasetOptions.insert( QStringLiteral( "LINK" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "Value put inside the <link> element in the header. "
"If not provided, a dummy value will be used as that element is compulsory." ),
QString() // Default value
) );
datasetOptions.insert( QStringLiteral( "UPDATED" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "Value put inside the <updated> element in the header. "
"Should be formatted as a XML datetime. "
"If not provided, a dummy value will be used as that element is compulsory." ),
QString() // Default value
) );
datasetOptions.insert( QStringLiteral( "AUTHOR_NAME" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "Value put inside the <author><name> element in the header. "
"If not provided, a dummy value will be used as that element is compulsory." ),
QString() // Default value
) );
datasetOptions.insert( QStringLiteral( "ID" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "Value put inside the <id> element in the header. "
"If not provided, a dummy value will be used as that element is compulsory." ),
QString() // Default value
) );
driverMetadata.insert( QStringLiteral( "GeoRSS" ),
QgsVectorFileWriter::MetaData(
QStringLiteral( "GeoRSS" ),
QObject::tr( "GeoRSS" ),
QStringLiteral( "*.xml" ),
QStringLiteral( "xml" ),
datasetOptions,
layerOptions,
QStringLiteral( "UTF-8" )
)
);
// Geography Markup Language [GML]
datasetOptions.clear();
layerOptions.clear();
datasetOptions.insert( QStringLiteral( "XSISCHEMAURI" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "If provided, this URI will be inserted as the schema location. "
"Note that the schema file isn't actually accessed by OGR, so it "
"is up to the user to ensure it will match the schema of the OGR "
"produced GML data file." ),
QString() // Default value
) );
datasetOptions.insert( QStringLiteral( "XSISCHEMA" ), new QgsVectorFileWriter::SetOption(
QObject::tr( "This writes a GML application schema file to a corresponding "
".xsd file (with the same basename). If INTERNAL is used the "
"schema is written within the GML file, but this is experimental "
"and almost certainly not valid XML. "
"OFF disables schema generation (and is implicit if XSISCHEMAURI is used)." ),
QStringList()
<< QStringLiteral( "EXTERNAL" )
<< QStringLiteral( "INTERNAL" )
<< QStringLiteral( "OFF" ),
QStringLiteral( "EXTERNAL" ) // Default value
) );
datasetOptions.insert( QStringLiteral( "PREFIX" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "This is the prefix for the application target namespace." ),
QStringLiteral( "ogr" ) // Default value
) );
datasetOptions.insert( QStringLiteral( "STRIP_PREFIX" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "Can be set to TRUE to avoid writing the prefix of the "
"application target namespace in the GML file." ),
false // Default value
) );
datasetOptions.insert( QStringLiteral( "TARGET_NAMESPACE" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "Defaults to 'http://ogr.maptools.org/'. "
"This is the application target namespace." ),
QStringLiteral( "http://ogr.maptools.org/" ) // Default value
) );
datasetOptions.insert( QStringLiteral( "FORMAT" ), new QgsVectorFileWriter::SetOption(
QObject::tr( "If not specified, GML2 will be used." ),
QStringList()
<< QStringLiteral( "GML3" )
<< QStringLiteral( "GML3Deegree" )
<< QStringLiteral( "GML3.2" ),
QString(), // Default value
true // Allow None
) );
datasetOptions.insert( QStringLiteral( "GML3_LONGSRS" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "Only valid when FORMAT=GML3/GML3Degree/GML3.2. Default to YES. " //needs review here
"If YES, SRS with EPSG authority will be written with the "
"'urn:ogc:def:crs:EPSG::' prefix. In the case the SRS is a "
"geographic SRS without explicit AXIS order, but that the same "
"SRS authority code imported with ImportFromEPSGA() should be "
"treated as lat/long, then the function will take care of coordinate "
"order swapping. If set to NO, SRS with EPSG authority will be "
"written with the 'EPSG:' prefix, even if they are in lat/long order." ),
true // Default value
) );
datasetOptions.insert( QStringLiteral( "WRITE_FEATURE_BOUNDED_BY" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "only valid when FORMAT=GML3/GML3Degree/GML3.2) Default to YES. "
"If set to NO, the <gml:boundedBy> element will not be written for "
"each feature." ),
true // Default value
) );
datasetOptions.insert( QStringLiteral( "SPACE_INDENTATION" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "Default to YES. If YES, the output will be indented with spaces "
"for more readability, but at the expense of file size." ),
true // Default value
) );
driverMetadata.insert( QStringLiteral( "GML" ),
QgsVectorFileWriter::MetaData(
QStringLiteral( "Geography Markup Language [GML]" ),
QObject::tr( "Geography Markup Language [GML]" ),
QStringLiteral( "*.gml" ),
QStringLiteral( "gml" ),
datasetOptions,
layerOptions,
QStringLiteral( "UTF-8" )
)
);
// GeoPackage
datasetOptions.clear();
layerOptions.clear();
layerOptions.insert( QStringLiteral( "IDENTIFIER" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "Human-readable identifier (e.g. short name) for the layer content" ),
QString() // Default value
) );
layerOptions.insert( QStringLiteral( "DESCRIPTION" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "Human-readable description for the layer content" ),
QString() // Default value
) );
layerOptions.insert( QStringLiteral( "FID" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "Name for the feature identifier column" ),
QStringLiteral( "fid" ) // Default value
) );
layerOptions.insert( QStringLiteral( "GEOMETRY_NAME" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "Name for the geometry column" ),
QStringLiteral( "geom" ) // Default value
) );
layerOptions.insert( QStringLiteral( "SPATIAL_INDEX" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "If a spatial index must be created." ),
true // Default value
) );
driverMetadata.insert( QStringLiteral( "GPKG" ),
QgsVectorFileWriter::MetaData(
QStringLiteral( "GeoPackage" ),
QObject::tr( "GeoPackage" ),
QStringLiteral( "*.gpkg" ),
QStringLiteral( "gpkg" ),
datasetOptions,
layerOptions,
QStringLiteral( "UTF-8" )
)
);
// Generic Mapping Tools [GMT]
datasetOptions.clear();
layerOptions.clear();
driverMetadata.insert( QStringLiteral( "GMT" ),
QgsVectorFileWriter::MetaData(
QStringLiteral( "Generic Mapping Tools [GMT]" ),
QObject::tr( "Generic Mapping Tools [GMT]" ),
QStringLiteral( "*.gmt" ),
QStringLiteral( "gmt" ),
datasetOptions,
layerOptions
)
);
// GPS eXchange Format [GPX]
datasetOptions.clear();
layerOptions.clear();
layerOptions.insert( QStringLiteral( "FORCE_GPX_TRACK" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "By default when writing a layer whose features are of "
"type wkbLineString, the GPX driver chooses to write "
"them as routes. If FORCE_GPX_TRACK=YES is specified, "
"they will be written as tracks." ),
false // Default value
) );
layerOptions.insert( QStringLiteral( "FORCE_GPX_ROUTE" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "By default when writing a layer whose features are of "
"type wkbMultiLineString, the GPX driver chooses to write "
"them as tracks. If FORCE_GPX_ROUTE=YES is specified, "
"they will be written as routes, provided that the multilines "
"are composed of only one single line." ),
false // Default value
) );
datasetOptions.insert( QStringLiteral( "GPX_USE_EXTENSIONS" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "If GPX_USE_EXTENSIONS=YES is specified, "
"extra fields will be written inside the <extensions> tag." ),
false // Default value
) );
datasetOptions.insert( QStringLiteral( "GPX_EXTENSIONS_NS" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "Only used if GPX_USE_EXTENSIONS=YES and GPX_EXTENSIONS_NS_URL "
"is set. The namespace value used for extension tags. By default, 'ogr'." ),
QStringLiteral( "ogr" ) // Default value
) );
datasetOptions.insert( QStringLiteral( "GPX_EXTENSIONS_NS_URL" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "Only used if GPX_USE_EXTENSIONS=YES and GPX_EXTENSIONS_NS "
"is set. The namespace URI. By default, 'http://osgeo.org/gdal'." ),
QStringLiteral( "http://osgeo.org/gdal" ) // Default value
) );
datasetOptions.insert( QStringLiteral( "LINEFORMAT" ), new QgsVectorFileWriter::SetOption(
QObject::tr( "By default files are created with the line termination "
"conventions of the local platform (CR/LF on win32 or LF "
"on all other systems). This may be overridden through use "
"of the LINEFORMAT layer creation option which may have a value "
"of CRLF (DOS format) or LF (Unix format)." ),
QStringList()
<< QStringLiteral( "CRLF" )
<< QStringLiteral( "LF" ),
QString(), // Default value
true // Allow None
) );
driverMetadata.insert( QStringLiteral( "GPX" ),
QgsVectorFileWriter::MetaData(
QStringLiteral( "GPS eXchange Format [GPX]" ),
QObject::tr( "GPS eXchange Format [GPX]" ),
QStringLiteral( "*.gpx" ),
QStringLiteral( "gpx" ),
datasetOptions,
layerOptions,
QStringLiteral( "UTF-8" )
)
);
// INTERLIS 1
datasetOptions.clear();
layerOptions.clear();
driverMetadata.insert( QStringLiteral( "Interlis 1" ),
QgsVectorFileWriter::MetaData(
QStringLiteral( "INTERLIS 1" ),
QObject::tr( "INTERLIS 1" ),
QStringLiteral( "*.itf *.xml *.ili" ),
QStringLiteral( "ili" ),
datasetOptions,
layerOptions
)
);
// INTERLIS 2
datasetOptions.clear();
layerOptions.clear();
driverMetadata.insert( QStringLiteral( "Interlis 2" ),
QgsVectorFileWriter::MetaData(
QStringLiteral( "INTERLIS 2" ),
QObject::tr( "INTERLIS 2" ),
QStringLiteral( "*.xtf *.xml *.ili" ),
QStringLiteral( "ili" ),
datasetOptions,
layerOptions
)
);
// Keyhole Markup Language [KML]
datasetOptions.clear();
layerOptions.clear();
datasetOptions.insert( QStringLiteral( "NameField" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "Allows you to specify the field to use for the KML <name> element." ),
QStringLiteral( "Name" ) // Default value
) );
datasetOptions.insert( QStringLiteral( "DescriptionField" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "Allows you to specify the field to use for the KML <description> element." ),
QStringLiteral( "Description" ) // Default value
) );
datasetOptions.insert( QStringLiteral( "AltitudeMode" ), new QgsVectorFileWriter::SetOption(
QObject::tr( "Allows you to specify the AltitudeMode to use for KML geometries. "
"This will only affect 3D geometries and must be one of the valid KML options." ),
QStringList()
<< QStringLiteral( "clampToGround" )
<< QStringLiteral( "relativeToGround" )
<< QStringLiteral( "absolute" ),
QStringLiteral( "relativeToGround" ) // Default value
) );
#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(2,2,0)
datasetOptions.insert( QStringLiteral( "DOCUMENT_ID" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "The DOCUMENT_ID datasource creation option can be used to specified "
"the id of the root <Document> node. The default value is root_doc." ),
QStringLiteral( "root_doc" ) // Default value
) );
#endif
driverMetadata.insert( QStringLiteral( "KML" ),
QgsVectorFileWriter::MetaData(
QStringLiteral( "Keyhole Markup Language [KML]" ),
QObject::tr( "Keyhole Markup Language [KML]" ),
QStringLiteral( "*.kml" ),
QStringLiteral( "kml" ),
datasetOptions,
layerOptions,
QStringLiteral( "UTF-8" )
)
);
// Mapinfo
datasetOptions.clear();
layerOptions.clear();
auto insertMapInfoOptions = []( QMap<QString, QgsVectorFileWriter::Option *> &datasetOptions, QMap<QString, QgsVectorFileWriter::Option *> &layerOptions )
{
datasetOptions.insert( QStringLiteral( "SPATIAL_INDEX_MODE" ), new QgsVectorFileWriter::SetOption(
QObject::tr( "Use this to turn on 'quick spatial index mode'. "
"In this mode writing files can be about 5 times faster, "
"but spatial queries can be up to 30 times slower." ),
QStringList()
<< QStringLiteral( "QUICK" )
<< QStringLiteral( "OPTIMIZED" ),
QStringLiteral( "QUICK" ), // Default value
true // Allow None
) );
datasetOptions.insert( QStringLiteral( "BLOCK_SIZE" ), new QgsVectorFileWriter::IntOption(
QObject::tr( "(multiples of 512): Block size for .map files. Defaults "
"to 512. MapInfo 15.2 and above creates .tab files with a "
"blocksize of 16384 bytes. Any MapInfo version should be "
"able to handle block sizes from 512 to 32256." ),
512
) );
layerOptions.insert( QStringLiteral( "BOUNDS" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "xmin,ymin,xmax,ymax: Define custom layer bounds to increase the "
"accuracy of the coordinates. Note: the geometry of written "
"features must be within the defined box." ),
QString() // Default value
) );
};
insertMapInfoOptions( datasetOptions, layerOptions );
driverMetadata.insert( QStringLiteral( "MapInfo File" ),
QgsVectorFileWriter::MetaData(
QStringLiteral( "Mapinfo" ),
QObject::tr( "Mapinfo TAB" ),
QStringLiteral( "*.tab" ),
QStringLiteral( "tab" ),
datasetOptions,
layerOptions
)
);
datasetOptions.clear();
layerOptions.clear();
insertMapInfoOptions( datasetOptions, layerOptions );
// QGIS internal alias for MIF files
driverMetadata.insert( QStringLiteral( "MapInfo MIF" ),
QgsVectorFileWriter::MetaData(
QStringLiteral( "Mapinfo" ),
QObject::tr( "Mapinfo MIF" ),
QStringLiteral( "*.mif" ),
QStringLiteral( "mif" ),
datasetOptions,
layerOptions
)
);
// Microstation DGN
datasetOptions.clear();
layerOptions.clear();
datasetOptions.insert( QStringLiteral( "3D" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "Determine whether 2D (seed_2d.dgn) or 3D (seed_3d.dgn) "
"seed file should be used. This option is ignored if the SEED option is provided." ),
false // Default value
) );
datasetOptions.insert( QStringLiteral( "SEED" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "Override the seed file to use." ),
QString() // Default value
) );
datasetOptions.insert( QStringLiteral( "COPY_WHOLE_SEED_FILE" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "Indicate whether the whole seed file should be copied. "
"If not, only the first three elements will be copied." ),
false // Default value
) );
datasetOptions.insert( QStringLiteral( "COPY_SEED_FILE_COLOR_TABLE" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "Indicates whether the color table should be copied from the seed file." ),
false // Default value
) );
datasetOptions.insert( QStringLiteral( "MASTER_UNIT_NAME" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "Override the master unit name from the seed file with "
"the provided one or two character unit name." ),
QString() // Default value
) );
datasetOptions.insert( QStringLiteral( "SUB_UNIT_NAME" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "Override the sub unit name from the seed file with the provided "
"one or two character unit name." ),
QString() // Default value
) );
datasetOptions.insert( QStringLiteral( "SUB_UNITS_PER_MASTER_UNIT" ), new QgsVectorFileWriter::IntOption(
QObject::tr( "Override the number of subunits per master unit. "
"By default the seed file value is used." ),
0 // Default value
) );
datasetOptions.insert( QStringLiteral( "UOR_PER_SUB_UNIT" ), new QgsVectorFileWriter::IntOption(
QObject::tr( "Override the number of UORs (Units of Resolution) "
"per sub unit. By default the seed file value is used." ),
0 // Default value
) );
datasetOptions.insert( QStringLiteral( "ORIGIN" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "ORIGIN=x,y,z: Override the origin of the design plane. "
"By default the origin from the seed file is used." ),
QString() // Default value
) );
driverMetadata.insert( QStringLiteral( "DGN" ),
QgsVectorFileWriter::MetaData(
QStringLiteral( "Microstation DGN" ),
QObject::tr( "Microstation DGN" ),
QStringLiteral( "*.dgn" ),
QStringLiteral( "dgn" ),
datasetOptions,
layerOptions
)
);
// S-57 Base file
datasetOptions.clear();
layerOptions.clear();
datasetOptions.insert( QStringLiteral( "UPDATES" ), new QgsVectorFileWriter::SetOption(
QObject::tr( "Should update files be incorporated into the base data on the fly." ),
QStringList()
<< QStringLiteral( "APPLY" )
<< QStringLiteral( "IGNORE" ),
QStringLiteral( "APPLY" ) // Default value
) );
datasetOptions.insert( QStringLiteral( "SPLIT_MULTIPOINT" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "Should multipoint soundings be split into many single point sounding features. "
"Multipoint geometries are not well handled by many formats, "
"so it can be convenient to split single sounding features with many points "
"into many single point features." ),
false // Default value
) );
datasetOptions.insert( QStringLiteral( "ADD_SOUNDG_DEPTH" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "Should a DEPTH attribute be added on SOUNDG features and assign the depth "
"of the sounding. This should only be enabled when SPLIT_MULTIPOINT is "
"also enabled." ),
false // Default value
) );
datasetOptions.insert( QStringLiteral( "RETURN_PRIMITIVES" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "Should all the low level geometry primitives be returned as special "
"IsolatedNode, ConnectedNode, Edge and Face layers." ),
false // Default value
) );
datasetOptions.insert( QStringLiteral( "PRESERVE_EMPTY_NUMBERS" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "If enabled, numeric attributes assigned an empty string as a value will "
"be preserved as a special numeric value. This option should not generally "
"be needed, but may be useful when translated S-57 to S-57 losslessly." ),
false // Default value
) );
datasetOptions.insert( QStringLiteral( "LNAM_REFS" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "Should LNAM and LNAM_REFS fields be attached to features capturing "
"the feature to feature relationships in the FFPT group of the S-57 file." ),
true // Default value
) );
datasetOptions.insert( QStringLiteral( "RETURN_LINKAGES" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "Should additional attributes relating features to their underlying "
"geometric primitives be attached. These are the values of the FSPT group, "
"and are primarily needed when doing S-57 to S-57 translations." ),
false // Default value
) );
datasetOptions.insert( QStringLiteral( "RECODE_BY_DSSI" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "Should attribute values be recoded to UTF-8 from the character encoding "
"specified in the S57 DSSI record." ),
false // Default value
) );
// set OGR_S57_OPTIONS = "RETURN_PRIMITIVES=ON,RETURN_LINKAGES=ON,LNAM_REFS=ON"
driverMetadata.insert( QStringLiteral( "S57" ),
QgsVectorFileWriter::MetaData(
QStringLiteral( "S-57 Base file" ),
QObject::tr( "S-57 Base file" ),
QStringLiteral( "*.000" ),
QStringLiteral( "000" ),
datasetOptions,
layerOptions
)
);
// Spatial Data Transfer Standard [SDTS]
datasetOptions.clear();
layerOptions.clear();
driverMetadata.insert( QStringLiteral( "SDTS" ),
QgsVectorFileWriter::MetaData(
QStringLiteral( "Spatial Data Transfer Standard [SDTS]" ),
QObject::tr( "Spatial Data Transfer Standard [SDTS]" ),
QStringLiteral( "*catd.ddf" ),
QStringLiteral( "ddf" ),
datasetOptions,
layerOptions
)
);
// SQLite
datasetOptions.clear();
layerOptions.clear();
datasetOptions.insert( QStringLiteral( "METADATA" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "Can be used to avoid creating the geometry_columns and spatial_ref_sys "
"tables in a new database. By default these metadata tables are created "
"when a new database is created." ),
true // Default value
) );
// Will handle the SpatiaLite alias
datasetOptions.insert( QStringLiteral( "SPATIALITE" ), new QgsVectorFileWriter::HiddenOption(
QStringLiteral( "NO" )
) );
datasetOptions.insert( QStringLiteral( "INIT_WITH_EPSG" ), new QgsVectorFileWriter::HiddenOption(
QStringLiteral( "NO" )
) );
layerOptions.insert( QStringLiteral( "FORMAT" ), new QgsVectorFileWriter::SetOption(
QObject::tr( "Controls the format used for the geometry column. Defaults to WKB. "
"This is generally more space and processing efficient, but harder "
"to inspect or use in simple applications than WKT (Well Known Text)." ),
QStringList()
<< QStringLiteral( "WKB" )
<< QStringLiteral( "WKT" ),
QStringLiteral( "WKB" ) // Default value
) );
layerOptions.insert( QStringLiteral( "LAUNDER" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "Controls whether layer and field names will be laundered for easier use "
"in SQLite. Laundered names will be converted to lower case and some special "
"characters(' - #) will be changed to underscores." ),
true // Default value
) );
layerOptions.insert( QStringLiteral( "SPATIAL_INDEX" ), new QgsVectorFileWriter::HiddenOption(
QStringLiteral( "NO" )
) );
layerOptions.insert( QStringLiteral( "COMPRESS_GEOM" ), new QgsVectorFileWriter::HiddenOption(
QStringLiteral( "NO" )
) );
layerOptions.insert( QStringLiteral( "SRID" ), new QgsVectorFileWriter::HiddenOption(
QString()
) );
layerOptions.insert( QStringLiteral( "COMPRESS_COLUMNS" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "column_name1[,column_name2, …] A list of (String) columns that "
"must be compressed with ZLib DEFLATE algorithm. This might be beneficial "
"for databases that have big string blobs. However, use with care, since "
"the value of such columns will be seen as compressed binary content with "
"other SQLite utilities (or previous OGR versions). With OGR, when inserting, "
"modifying or querying compressed columns, compression/decompression is "
"done transparently. However, such columns cannot be (easily) queried with "
"an attribute filter or WHERE clause. Note: in table definition, such columns "
"have the 'VARCHAR_deflate' declaration type." ),
QString() // Default value
) );
driverMetadata.insert( QStringLiteral( "SQLite" ),
QgsVectorFileWriter::MetaData(
QStringLiteral( "SQLite" ),
QObject::tr( "SQLite" ),
QStringLiteral( "*.sqlite" ),
QStringLiteral( "sqlite" ),
datasetOptions,
layerOptions,
QStringLiteral( "UTF-8" )
)
);
// SpatiaLite
datasetOptions.clear();
layerOptions.clear();
datasetOptions.insert( QStringLiteral( "METADATA" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "Can be used to avoid creating the geometry_columns and spatial_ref_sys "
"tables in a new database. By default these metadata tables are created "
"when a new database is created." ),
true // Default value
) );
datasetOptions.insert( QStringLiteral( "SPATIALITE" ), new QgsVectorFileWriter::HiddenOption(
QStringLiteral( "YES" )
) );
datasetOptions.insert( QStringLiteral( "INIT_WITH_EPSG" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "Insert the content of the EPSG CSV files into the spatial_ref_sys table. "
"Set to NO for regular SQLite databases." ),
true // Default value
) );
layerOptions.insert( QStringLiteral( "FORMAT" ), new QgsVectorFileWriter::HiddenOption(
QStringLiteral( "SPATIALITE" )
) );
layerOptions.insert( QStringLiteral( "LAUNDER" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "Controls whether layer and field names will be laundered for easier use "
"in SQLite. Laundered names will be converted to lower case and some special "
"characters(' - #) will be changed to underscores." ),
true // Default value
) );
layerOptions.insert( QStringLiteral( "SPATIAL_INDEX" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "If the database is of the SpatiaLite flavor, and if OGR is linked "
"against libspatialite, this option can be used to control if a spatial "
"index must be created." ),
true // Default value
) );
layerOptions.insert( QStringLiteral( "COMPRESS_GEOM" ), new QgsVectorFileWriter::BoolOption(
QObject::tr( "If the format of the geometry BLOB is of the SpatiaLite flavor, "
"this option can be used to control if the compressed format for "
"geometries (LINESTRINGs, POLYGONs) must be used." ),
false // Default value
) );
layerOptions.insert( QStringLiteral( "SRID" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "Used to force the SRID number of the SRS associated with the layer. "
"When this option isn't specified and that a SRS is associated with the "
"layer, a search is made in the spatial_ref_sys to find a match for the "
"SRS, and, if there is no match, a new entry is inserted for the SRS in "
"the spatial_ref_sys table. When the SRID option is specified, this "
"search (and the eventual insertion of a new entry) will not be done: "
"the specified SRID is used as such." ),
QString() // Default value
) );
layerOptions.insert( QStringLiteral( "COMPRESS_COLUMNS" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "column_name1[,column_name2, …] A list of (String) columns that "
"must be compressed with ZLib DEFLATE algorithm. This might be beneficial "
"for databases that have big string blobs. However, use with care, since "
"the value of such columns will be seen as compressed binary content with "
"other SQLite utilities (or previous OGR versions). With OGR, when inserting, "
"modifying or queryings compressed columns, compression/decompression is "
"done transparently. However, such columns cannot be (easily) queried with "
"an attribute filter or WHERE clause. Note: in table definition, such columns "
"have the 'VARCHAR_deflate' declaration type." ),
QString() // Default value
) );
driverMetadata.insert( QStringLiteral( "SpatiaLite" ),
QgsVectorFileWriter::MetaData(
QStringLiteral( "SpatiaLite" ),
QObject::tr( "SpatiaLite" ),
QStringLiteral( "*.sqlite" ),
QStringLiteral( "sqlite" ),
datasetOptions,
layerOptions,
QStringLiteral( "UTF-8" )
)
);
// AutoCAD DXF
datasetOptions.clear();
layerOptions.clear();
datasetOptions.insert( QStringLiteral( "HEADER" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "Override the header file used - in place of header.dxf." ),
QString() // Default value
) );
datasetOptions.insert( QStringLiteral( "TRAILER" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "Override the trailer file used - in place of trailer.dxf." ),
QString() // Default value
) );
driverMetadata.insert( QStringLiteral( "DXF" ),
QgsVectorFileWriter::MetaData(
QStringLiteral( "AutoCAD DXF" ),
QObject::tr( "AutoCAD DXF" ),
QStringLiteral( "*.dxf" ),
QStringLiteral( "dxf" ),
datasetOptions,
layerOptions
)
);
// Geoconcept
datasetOptions.clear();
layerOptions.clear();
datasetOptions.insert( QStringLiteral( "EXTENSION" ), new QgsVectorFileWriter::SetOption(
QObject::tr( "Indicates the GeoConcept export file extension. "
"TXT was used by earlier releases of GeoConcept. GXT is currently used." ),
QStringList()
<< QStringLiteral( "GXT" )
<< QStringLiteral( "TXT" ),
QStringLiteral( "GXT" ) // Default value
) );
datasetOptions.insert( QStringLiteral( "CONFIG" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "Path to the GCT: the GCT file describes the GeoConcept types definitions: "
"In this file, every line must start with //# followed by a keyword. "
"Lines starting with // are comments." ),
QString() // Default value
) );
datasetOptions.insert( QStringLiteral( "FEATURETYPE" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "Defines the feature to be created. The TYPE corresponds to one of the Name "
"found in the GCT file for a type section. The SUBTYPE corresponds to one of "
"the Name found in the GCT file for a sub-type section within the previous "
"type section." ),
QString() // Default value
) );
driverMetadata.insert( QStringLiteral( "Geoconcept" ),
QgsVectorFileWriter::MetaData(
QStringLiteral( "Geoconcept" ),
QObject::tr( "Geoconcept" ),
QStringLiteral( "*.gxt *.txt" ),
QStringLiteral( "gxt" ),
datasetOptions,
layerOptions
)
);
// ESRI FileGDB
datasetOptions.clear();
layerOptions.clear();
layerOptions.insert( QStringLiteral( "FEATURE_DATASET" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "When this option is set, the new layer will be created inside the named "
"FeatureDataset folder. If the folder does not already exist, it will be created." ),
QString() // Default value
) );
layerOptions.insert( QStringLiteral( "GEOMETRY_NAME" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "Set name of geometry column in new layer. Defaults to 'SHAPE'." ),
QStringLiteral( "SHAPE" ) // Default value
) );
layerOptions.insert( QStringLiteral( "FID" ), new QgsVectorFileWriter::StringOption(
QObject::tr( "Name of the OID column to create. Defaults to 'OBJECTID'." ),
QStringLiteral( "OBJECTID" ) // Default value
) );
driverMetadata.insert( QStringLiteral( "FileGDB" ),
QgsVectorFileWriter::MetaData(
QStringLiteral( "ESRI FileGDB" ),
QObject::tr( "ESRI FileGDB" ),
QStringLiteral( "*.gdb" ),
QStringLiteral( "gdb" ),
datasetOptions,
layerOptions,
QStringLiteral( "UTF-8" )
)
);
// XLSX
datasetOptions.clear();
layerOptions.clear();
layerOptions.insert( QStringLiteral( "OGR_XLSX_FIELD_TYPES" ), new QgsVectorFileWriter::SetOption(
QObject::tr( "By default, the driver will try to detect the data type of fields. If set "
"to STRING, all fields will be of String type." ),
QStringList()
<< QStringLiteral( "AUTO" )
<< QStringLiteral( "STRING" ),
QStringLiteral( "AUTO" ), // Default value
false // Allow None
) );
layerOptions.insert( QStringLiteral( "OGR_XLSX_HEADERS" ), new QgsVectorFileWriter::SetOption(
QObject::tr( "By default, the driver will read the first lines of each sheet to detect "
"if the first line might be the name of columns. If set to FORCE, the driver "
"will consider the first line as the header line. If set to "
"DISABLE, it will be considered as the first feature. Otherwise "
"auto-detection will occur." ),
QStringList()
<< QStringLiteral( "FORCE" )
<< QStringLiteral( "DISABLE" )
<< QStringLiteral( "AUTO" ),
QStringLiteral( "AUTO" ), // Default value
false // Allow None
) );
driverMetadata.insert( QStringLiteral( "XLSX" ),
QgsVectorFileWriter::MetaData(
QStringLiteral( "MS Office Open XML spreadsheet" ),
QObject::tr( "MS Office Open XML spreadsheet [XLSX]" ),
QStringLiteral( "*.xlsx" ),
QStringLiteral( "xlsx" ),
datasetOptions,
layerOptions,
QStringLiteral( "UTF-8" )
)
);
// ODS
datasetOptions.clear();
layerOptions.clear();
layerOptions.insert( QStringLiteral( "OGR_ODS_FIELD_TYPES" ), new QgsVectorFileWriter::SetOption(
QObject::tr( "By default, the driver will try to detect the data type of fields. If set "
"to STRING, all fields will be of String type." ),
QStringList()
<< QStringLiteral( "AUTO" )
<< QStringLiteral( "STRING" ),
QStringLiteral( "AUTO" ), // Default value
false // Allow None
) );
layerOptions.insert( QStringLiteral( "OGR_ODS_HEADERS" ), new QgsVectorFileWriter::SetOption(
QObject::tr( "By default, the driver will read the first lines of each sheet to detect "
"if the first line might be the name of columns. If set to FORCE, the driver "
"will consider the first line as the header line. If set to "
"DISABLE, it will be considered as the first feature. Otherwise "
"auto-detection will occur." ),
QStringList()
<< QStringLiteral( "FORCE" )
<< QStringLiteral( "DISABLE" )
<< QStringLiteral( "AUTO" ),
QStringLiteral( "AUTO" ), // Default value
false // Allow None
) );
driverMetadata.insert( QStringLiteral( "ODS" ),
QgsVectorFileWriter::MetaData(
QStringLiteral( "Open Document Spreadsheet" ),
QObject::tr( "Open Document Spreadsheet [ODS]" ),
QStringLiteral( "*.ods" ),
QStringLiteral( "ods" ),
datasetOptions,
layerOptions,
QStringLiteral( "UTF-8" )
)
);
}
QgsVectorFileWriterMetadataContainer( const QgsVectorFileWriterMetadataContainer &other ) = delete;
QgsVectorFileWriterMetadataContainer &operator=( const QgsVectorFileWriterMetadataContainer &other ) = delete;
~QgsVectorFileWriterMetadataContainer()
{
for ( auto it = driverMetadata.constBegin(); it != driverMetadata.constEnd(); ++it )
{
for ( auto optionIt = it.value().driverOptions.constBegin(); optionIt != it.value().driverOptions.constEnd(); ++optionIt )
delete optionIt.value();
for ( auto optionIt = it.value().layerOptions.constBegin(); optionIt != it.value().layerOptions.constEnd(); ++optionIt )
delete optionIt.value();
}
}
QMap<QString, QgsVectorFileWriter::MetaData> driverMetadata;
};
///@endcond
bool QgsVectorFileWriter::driverMetadata( const QString &driverName, QgsVectorFileWriter::MetaData &driverMetadata )
{
static QgsVectorFileWriterMetadataContainer sDriverMetadata;
QMap<QString, MetaData>::ConstIterator it = sDriverMetadata.driverMetadata.constBegin();
for ( ; it != sDriverMetadata.driverMetadata.constEnd(); ++it )
{
if ( it.key().startsWith( driverName ) || it.value().longName.startsWith( driverName ) )
{
driverMetadata = it.value();
return true;
}
}
return false;
}
QStringList QgsVectorFileWriter::defaultDatasetOptions( const QString &driverName )
{
MetaData metadata;
bool ok = driverMetadata( driverName, metadata );
if ( !ok )
return QStringList();
return concatenateOptions( metadata.driverOptions );
}
QStringList QgsVectorFileWriter::defaultLayerOptions( const QString &driverName )
{
MetaData metadata;
bool ok = driverMetadata( driverName, metadata );
if ( !ok )
return QStringList();
return concatenateOptions( metadata.layerOptions );
}
OGRwkbGeometryType QgsVectorFileWriter::ogrTypeFromWkbType( QgsWkbTypes::Type type )
{
OGRwkbGeometryType ogrType = static_cast<OGRwkbGeometryType>( type );
if ( type >= QgsWkbTypes::PointZ && type <= QgsWkbTypes::GeometryCollectionZ )
{
ogrType = static_cast<OGRwkbGeometryType>( QgsWkbTypes::to25D( type ) );
}
return ogrType;
}
QgsVectorFileWriter::WriterError QgsVectorFileWriter::hasError()
{
return mError;
}
QString QgsVectorFileWriter::errorMessage()
{
return mErrorMessage;
}
bool QgsVectorFileWriter::addFeature( QgsFeature &feature, QgsFeatureSink::Flags )
{
return addFeatureWithStyle( feature, nullptr, QgsUnitTypes::DistanceMeters );
}
bool QgsVectorFileWriter::addFeatures( QgsFeatureList &features, QgsFeatureSink::Flags )
{
QgsFeatureList::iterator fIt = features.begin();
bool result = true;
for ( ; fIt != features.end(); ++fIt )
{
result = result && addFeatureWithStyle( *fIt, nullptr, QgsUnitTypes::DistanceMeters );
}
return result;
}
bool QgsVectorFileWriter::addFeatureWithStyle( QgsFeature &feature, QgsFeatureRenderer *renderer, QgsUnitTypes::DistanceUnit outputUnit )
{
// create the feature
gdal::ogr_feature_unique_ptr poFeature = createFeature( feature );
if ( !poFeature )
return false;
//add OGR feature style type
if ( mSymbologyExport != NoSymbology && renderer )
{
mRenderContext.expressionContext().setFeature( feature );
//SymbolLayerSymbology: concatenate ogr styles of all symbollayers
QgsSymbolList symbols = renderer->symbolsForFeature( feature, mRenderContext );
QString styleString;
QString currentStyle;
QgsSymbolList::const_iterator symbolIt = symbols.constBegin();
for ( ; symbolIt != symbols.constEnd(); ++symbolIt )
{
int nSymbolLayers = ( *symbolIt )->symbolLayerCount();
for ( int i = 0; i < nSymbolLayers; ++i )
{
#if 0
QMap< QgsSymbolLayer *, QString >::const_iterator it = mSymbolLayerTable.find( ( *symbolIt )->symbolLayer( i ) );
if ( it == mSymbolLayerTable.constEnd() )
{
continue;
}
#endif
double mmsf = mmScaleFactor( mSymbologyScale, ( *symbolIt )->outputUnit(), outputUnit );
double musf = mapUnitScaleFactor( mSymbologyScale, ( *symbolIt )->outputUnit(), outputUnit );
currentStyle = ( *symbolIt )->symbolLayer( i )->ogrFeatureStyle( mmsf, musf );//"@" + it.value();
if ( mSymbologyExport == FeatureSymbology )
{
if ( symbolIt != symbols.constBegin() || i != 0 )
{
styleString.append( ';' );
}
styleString.append( currentStyle );
}
else if ( mSymbologyExport == SymbolLayerSymbology )
{
OGR_F_SetStyleString( poFeature.get(), currentStyle.toLocal8Bit().constData() );
if ( !writeFeature( mLayer, poFeature.get() ) )
{
return false;
}
}
}
}
OGR_F_SetStyleString( poFeature.get(), styleString.toLocal8Bit().constData() );
}
if ( mSymbologyExport == NoSymbology || mSymbologyExport == FeatureSymbology )
{
if ( !writeFeature( mLayer, poFeature.get() ) )
{
return false;
}
}
return true;
}
gdal::ogr_feature_unique_ptr QgsVectorFileWriter::createFeature( const QgsFeature &feature )
{
QgsLocaleNumC l; // Make sure the decimal delimiter is a dot
Q_UNUSED( l );
gdal::ogr_feature_unique_ptr poFeature( OGR_F_Create( OGR_L_GetLayerDefn( mLayer ) ) );
qint64 fid = FID_TO_NUMBER( feature.id() );
if ( fid > std::numeric_limits<int>::max() )
{
QgsDebugMsg( QStringLiteral( "feature id %1 too large." ).arg( fid ) );
OGRErr err = OGR_F_SetFID( poFeature.get(), static_cast<long>( fid ) );
if ( err != OGRERR_NONE )
{
QgsDebugMsg( QStringLiteral( "Failed to set feature id to %1: %2 (OGR error: %3)" )
.arg( feature.id() )
.arg( err ).arg( CPLGetLastErrorMsg() )
);
}
}
// attribute handling
for ( QMap<int, int>::const_iterator it = mAttrIdxToOgrIdx.constBegin(); it != mAttrIdxToOgrIdx.constEnd(); ++it )
{
int fldIdx = it.key();
int ogrField = it.value();
QVariant attrValue = feature.attribute( fldIdx );
QgsField field = mFields.at( fldIdx );
if ( !attrValue.isValid() || attrValue.isNull() )
{
// Starting with GDAL 2.2, there are 2 concepts: unset fields and null fields
// whereas previously there was only unset fields. For a GeoJSON output,
// leaving a field unset will cause it to not appear at all in the output
// feature.
// When all features of a layer have a field unset, this would cause the
// field to not be present at all in the output, and thus on reading to
// have disappeared. #16812
#ifdef OGRNullMarker
OGR_F_SetFieldNull( poFeature.get(), ogrField );
#endif
continue;
}
if ( mFieldValueConverter )
{
field = mFieldValueConverter->fieldDefinition( field );
attrValue = mFieldValueConverter->convert( fldIdx, attrValue );
}
switch ( field.type() )
{
case QVariant::Int:
OGR_F_SetFieldInteger( poFeature.get(), ogrField, attrValue.toInt() );
break;
case QVariant::LongLong:
OGR_F_SetFieldInteger64( poFeature.get(), ogrField, attrValue.toLongLong() );
break;
case QVariant::Bool:
OGR_F_SetFieldInteger( poFeature.get(), ogrField, attrValue.toInt() );
break;
case QVariant::String:
OGR_F_SetFieldString( poFeature.get(), ogrField, mCodec->fromUnicode( attrValue.toString() ).constData() );
break;
case QVariant::Double:
OGR_F_SetFieldDouble( poFeature.get(), ogrField, attrValue.toDouble() );
break;
case QVariant::Date:
OGR_F_SetFieldDateTime( poFeature.get(), ogrField,
attrValue.toDate().year(),
attrValue.toDate().month(),
attrValue.toDate().day(),
0, 0, 0, 0 );
break;
case QVariant::DateTime:
if ( mOgrDriverName == QLatin1String( "ESRI Shapefile" ) )
{
OGR_F_SetFieldString( poFeature.get(), ogrField, mCodec->fromUnicode( attrValue.toDateTime().toString( QStringLiteral( "yyyy/MM/dd hh:mm:ss.zzz" ) ) ).constData() );
}
else
{
OGR_F_SetFieldDateTime( poFeature.get(), ogrField,
attrValue.toDateTime().date().year(),
attrValue.toDateTime().date().month(),
attrValue.toDateTime().date().day(),
attrValue.toDateTime().time().hour(),
attrValue.toDateTime().time().minute(),
attrValue.toDateTime().time().second(),
0 );
}
break;
case QVariant::Time:
if ( mOgrDriverName == QLatin1String( "ESRI Shapefile" ) )
{
OGR_F_SetFieldString( poFeature.get(), ogrField, mCodec->fromUnicode( attrValue.toString() ).constData() );
}
else
{
OGR_F_SetFieldDateTime( poFeature.get(), ogrField,
0, 0, 0,
attrValue.toTime().hour(),
attrValue.toTime().minute(),
attrValue.toTime().second(),
0 );
}
break;
case QVariant::ByteArray:
{
const QByteArray ba = attrValue.toByteArray();
OGR_F_SetFieldBinary( poFeature.get(), ogrField, ba.size(), const_cast< GByte * >( reinterpret_cast< const GByte * >( ba.data() ) ) );
break;
}
case QVariant::Invalid:
break;
#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(2,4,0)
case QVariant::List:
// only string list supported at the moment, fall through to default for other types
if ( field.subType() == QVariant::String )
{
QStringList list = attrValue.toStringList();
if ( supportsStringList )
{
int count = list.count();
char **lst = new char *[count + 1];
if ( count > 0 )
{
int pos = 0;
for ( QString string : list )
{
lst[pos] = mCodec->fromUnicode( string ).data();
pos++;
}
}
lst[count] = nullptr;
OGR_F_SetFieldStringList( poFeature.get(), ogrField, lst );
}
else
{
OGR_F_SetFieldString( poFeature.get(), ogrField, mCodec->fromUnicode( list.join( ',' ) ).constData() );
}
break;
}
//intentional fall-through
FALLTHROUGH
#endif
default:
mErrorMessage = QObject::tr( "Invalid variant type for field %1[%2]: received %3 with type %4" )
.arg( mFields.at( fldIdx ).name() )
.arg( ogrField )
.arg( attrValue.typeName(),
attrValue.toString() );
QgsMessageLog::logMessage( mErrorMessage, QObject::tr( "OGR" ) );
mError = ErrFeatureWriteFailed;
return nullptr;
}
}
if ( mWkbType != QgsWkbTypes::NoGeometry )
{
if ( feature.hasGeometry() )
{
// build geometry from WKB
QgsGeometry geom = feature.geometry();
// turn single geometry to multi geometry if needed
if ( QgsWkbTypes::flatType( geom.wkbType() ) != QgsWkbTypes::flatType( mWkbType ) &&
QgsWkbTypes::flatType( geom.wkbType() ) == QgsWkbTypes::flatType( QgsWkbTypes::singleType( mWkbType ) ) )
{
geom.convertToMultiType();
}
if ( geom.wkbType() != mWkbType )
{
OGRGeometryH mGeom2 = nullptr;
// If requested WKB type is 25D and geometry WKB type is 3D,
// we must force the use of 25D.
if ( mWkbType >= QgsWkbTypes::Point25D && mWkbType <= QgsWkbTypes::MultiPolygon25D )
{
//ND: I suspect there's a bug here, in that this is NOT converting the geometry's WKB type,
//so the exported WKB has a different type to what the OGRGeometry is expecting.
//possibly this is handled already in OGR, but it should be fixed regardless by actually converting
//geom to the correct WKB type
QgsWkbTypes::Type wkbType = geom.wkbType();
if ( wkbType >= QgsWkbTypes::PointZ && wkbType <= QgsWkbTypes::MultiPolygonZ )
{
QgsWkbTypes::Type wkbType25d = static_cast<QgsWkbTypes::Type>( geom.wkbType() - QgsWkbTypes::PointZ + QgsWkbTypes::Point25D );
mGeom2 = createEmptyGeometry( wkbType25d );
}
}
// drop m/z value if not present in output wkb type
if ( !QgsWkbTypes::hasZ( mWkbType ) && QgsWkbTypes::hasZ( geom.wkbType() ) )
geom.get()->dropZValue();
if ( !QgsWkbTypes::hasM( mWkbType ) && QgsWkbTypes::hasM( geom.wkbType() ) )
geom.get()->dropMValue();
// add m/z values if not present in the input wkb type -- this is needed for formats which determine
// geometry type based on features, e.g. geojson
if ( QgsWkbTypes::hasZ( mWkbType ) && !QgsWkbTypes::hasZ( geom.wkbType() ) )
geom.get()->addZValue( 0 );
if ( QgsWkbTypes::hasM( mWkbType ) && !QgsWkbTypes::hasM( geom.wkbType() ) )
geom.get()->addMValue( 0 );
if ( !mGeom2 )
{
// there's a problem when layer type is set as wkbtype Polygon
// although there are also features of type MultiPolygon
// (at least in OGR provider)
// If the feature's wkbtype is different from the layer's wkbtype,
// try to export it too.
//
// Btw. OGRGeometry must be exactly of the type of the geometry which it will receive
// i.e. Polygons can't be imported to OGRMultiPolygon
mGeom2 = createEmptyGeometry( geom.wkbType() );
}
if ( !mGeom2 )
{
mErrorMessage = QObject::tr( "Feature geometry not imported (OGR error: %1)" )
.arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
mError = ErrFeatureWriteFailed;
QgsMessageLog::logMessage( mErrorMessage, QObject::tr( "OGR" ) );
return nullptr;
}
QByteArray wkb( geom.asWkb() );
OGRErr err = OGR_G_ImportFromWkb( mGeom2, reinterpret_cast<unsigned char *>( const_cast<char *>( wkb.constData() ) ), wkb.length() );
if ( err != OGRERR_NONE )
{
mErrorMessage = QObject::tr( "Feature geometry not imported (OGR error: %1)" )
.arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
mError = ErrFeatureWriteFailed;
QgsMessageLog::logMessage( mErrorMessage, QObject::tr( "OGR" ) );
return nullptr;
}
// pass ownership to geometry
OGR_F_SetGeometryDirectly( poFeature.get(), mGeom2 );
}
else // wkb type matches
{
QByteArray wkb( geom.asWkb() );
OGRGeometryH ogrGeom = createEmptyGeometry( mWkbType );
OGRErr err = OGR_G_ImportFromWkb( ogrGeom, reinterpret_cast<unsigned char *>( const_cast<char *>( wkb.constData() ) ), wkb.length() );
if ( err != OGRERR_NONE )
{
mErrorMessage = QObject::tr( "Feature geometry not imported (OGR error: %1)" )
.arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
mError = ErrFeatureWriteFailed;
QgsMessageLog::logMessage( mErrorMessage, QObject::tr( "OGR" ) );
return nullptr;
}
// set geometry (ownership is passed to OGR)
OGR_F_SetGeometryDirectly( poFeature.get(), ogrGeom );
}
}
else
{
OGR_F_SetGeometryDirectly( poFeature.get(), createEmptyGeometry( mWkbType ) );
}
}
return poFeature;
}
void QgsVectorFileWriter::resetMap( const QgsAttributeList &attributes )
{
QMap<int, int> omap( mAttrIdxToOgrIdx );
mAttrIdxToOgrIdx.clear();
for ( int i = 0; i < attributes.size(); i++ )
{
if ( omap.find( i ) != omap.end() )
mAttrIdxToOgrIdx.insert( attributes[i], omap[i] );
}
}
bool QgsVectorFileWriter::writeFeature( OGRLayerH layer, OGRFeatureH feature )
{
if ( OGR_L_CreateFeature( layer, feature ) != OGRERR_NONE )
{
mErrorMessage = QObject::tr( "Feature creation error (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
mError = ErrFeatureWriteFailed;
QgsMessageLog::logMessage( mErrorMessage, QObject::tr( "OGR" ) );
return false;
}
return true;
}
QgsVectorFileWriter::~QgsVectorFileWriter()
{
if ( mUsingTransaction )
{
if ( OGRERR_NONE != OGR_L_CommitTransaction( mLayer ) )
{
QgsDebugMsg( QStringLiteral( "Error while committing transaction on OGRLayer." ) );
}
}
mDS.reset();
if ( mOgrRef )
{
OSRDestroySpatialReference( mOgrRef );
}
}
QgsVectorFileWriter::WriterError
QgsVectorFileWriter::writeAsVectorFormat( QgsVectorLayer *layer,
const QString &fileName,
const QString &fileEncoding,
const QgsCoordinateReferenceSystem &destCRS,
const QString &driverName,
bool onlySelected,
QString *errorMessage,
const QStringList &datasourceOptions,
const QStringList &layerOptions,
bool skipAttributeCreation,
QString *newFilename,
SymbologyExport symbologyExport,
double symbologyScale,
const QgsRectangle *filterExtent,
QgsWkbTypes::Type overrideGeometryType,
bool forceMulti,
bool includeZ,
const QgsAttributeList &attributes,
FieldValueConverter *fieldValueConverter,
QString *newLayer )
{
QgsCoordinateTransform ct;
if ( destCRS.isValid() && layer )
{
ct = QgsCoordinateTransform( layer->crs(), destCRS, layer->transformContext() );
}
QgsVectorFileWriter::WriterError error = writeAsVectorFormat( layer, fileName, fileEncoding, ct, driverName, onlySelected,
errorMessage, datasourceOptions, layerOptions, skipAttributeCreation,
newFilename, symbologyExport, symbologyScale, filterExtent,
overrideGeometryType, forceMulti, includeZ, attributes,
fieldValueConverter, newLayer );
return error;
}
QgsVectorFileWriter::WriterError QgsVectorFileWriter::writeAsVectorFormat( QgsVectorLayer *layer,
const QString &fileName,
const QString &fileEncoding,
const QgsCoordinateTransform &ct,
const QString &driverName,
bool onlySelected,
QString *errorMessage,
const QStringList &datasourceOptions,
const QStringList &layerOptions,
bool skipAttributeCreation,
QString *newFilename,
SymbologyExport symbologyExport,
double symbologyScale,
const QgsRectangle *filterExtent,
QgsWkbTypes::Type overrideGeometryType,
bool forceMulti,
bool includeZ,
const QgsAttributeList &attributes,
FieldValueConverter *fieldValueConverter,
QString *newLayer )
{
SaveVectorOptions options;
options.fileEncoding = fileEncoding;
options.ct = ct;
options.driverName = driverName;
options.onlySelectedFeatures = onlySelected;
options.datasourceOptions = datasourceOptions;
options.layerOptions = layerOptions;
options.skipAttributeCreation = skipAttributeCreation;
options.symbologyExport = symbologyExport;
options.symbologyScale = symbologyScale;
if ( filterExtent )
options.filterExtent = *filterExtent;
options.overrideGeometryType = overrideGeometryType;
options.forceMulti = forceMulti;
options.includeZ = includeZ;
options.attributes = attributes;
options.fieldValueConverter = fieldValueConverter;
return writeAsVectorFormat( layer, fileName, options, newFilename, errorMessage, newLayer );
}
QgsVectorFileWriter::SaveVectorOptions::SaveVectorOptions()
: driverName( QStringLiteral( "GPKG" ) )
{
}
QgsVectorFileWriter::WriterError QgsVectorFileWriter::prepareWriteAsVectorFormat( QgsVectorLayer *layer, const QgsVectorFileWriter::SaveVectorOptions &options, QgsVectorFileWriter::PreparedWriterDetails &details )
{
if ( !layer || !layer->isValid() )
{
return ErrInvalidLayer;
}
if ( layer->renderer() )
details.renderer.reset( layer->renderer()->clone() );
details.sourceCrs = layer->crs();
details.sourceWkbType = layer->wkbType();
details.sourceFields = layer->fields();
details.providerType = layer->providerType();
details.featureCount = options.onlySelectedFeatures ? layer->selectedFeatureCount() : layer->featureCount();
if ( layer->dataProvider() )
details.dataSourceUri = layer->dataProvider()->dataSourceUri();
details.storageType = layer->storageType();
details.selectedFeatureIds = layer->selectedFeatureIds();
details.providerUriParams = QgsProviderRegistry::instance()->decodeUri( layer->providerType(), layer->dataProvider()->dataSourceUri() );
if ( details.storageType == QLatin1String( "ESRI Shapefile" ) )
{
QgsFeatureRequest req;
if ( options.onlySelectedFeatures )
{
req.setFilterFids( details.selectedFeatureIds );
}
req.setNoAttributes();
details.geometryTypeScanIterator = layer->getFeatures( req );
}
details.expressionContext = QgsExpressionContext( QgsExpressionContextUtils::globalProjectLayerScopes( layer ) );
details.renderContext.setExpressionContext( details.expressionContext );
details.renderContext.setRendererScale( options.symbologyScale );
details.shallTransform = false;
if ( options.ct.isValid() )
{
// This means we should transform
details.outputCrs = options.ct.destinationCrs();
details.shallTransform = true;
}
else
{
// This means we shouldn't transform, use source CRS as output (if defined)
details.outputCrs = details.sourceCrs;
}
details.destWkbType = details.sourceWkbType;
if ( options.overrideGeometryType != QgsWkbTypes::Unknown )
{
details.destWkbType = QgsWkbTypes::flatType( options.overrideGeometryType );
if ( QgsWkbTypes::hasZ( options.overrideGeometryType ) || options.includeZ )
details.destWkbType = QgsWkbTypes::addZ( details.destWkbType );
}
if ( options.forceMulti )
{
details.destWkbType = QgsWkbTypes::multiType( details.destWkbType );
}
details.attributes = options.attributes;
if ( options.skipAttributeCreation )
details.attributes.clear();
else if ( details.attributes.isEmpty() )
{
const QgsAttributeList allAttributes = details.sourceFields.allAttributesList();
for ( int idx : allAttributes )
{
QgsField fld = details.sourceFields.at( idx );
if ( details.providerType == QLatin1String( "oracle" ) && fld.typeName().contains( QLatin1String( "SDO_GEOMETRY" ) ) )
continue;
details.attributes.append( idx );
}
}
if ( !details.attributes.isEmpty() )
{
for ( int attrIdx : qgis::as_const( details.attributes ) )
{
details.outputFields.append( details.sourceFields.at( attrIdx ) );
}
}
// not ideal - would be nice to avoid this happening in the preparation step if possible,
// but currently requires access to the layer's minimumValue/maximumValue methods
if ( details.providerType == QLatin1String( "spatialite" ) )
{
for ( int i = 0; i < details.outputFields.size(); i++ )
{
if ( details.outputFields.at( i ).type() == QVariant::LongLong )
{
QVariant min = layer->minimumValue( i );
QVariant max = layer->maximumValue( i );
if ( std::max( std::llabs( min.toLongLong() ), std::llabs( max.toLongLong() ) ) < std::numeric_limits<int>::max() )
{
details.outputFields[i].setType( QVariant::Int );
}
}
}
}
//add possible attributes needed by renderer
addRendererAttributes( details.renderer.get(), details.renderContext, details.sourceFields, details.attributes );
QgsFeatureRequest req;
req.setSubsetOfAttributes( details.attributes );
if ( options.onlySelectedFeatures )
req.setFilterFids( details.selectedFeatureIds );
if ( !options.filterExtent.isNull() )
{
QgsRectangle filterRect = options.filterExtent;
bool useFilterRect = true;
if ( details.shallTransform )
{
try
{
// map filter rect back from destination CRS to layer CRS
filterRect = options.ct.transformBoundingBox( filterRect, QgsCoordinateTransform::ReverseTransform );
}
catch ( QgsCsException & )
{
useFilterRect = false;
}
}
if ( useFilterRect )
{
req.setFilterRect( filterRect );
}
details.filterRectGeometry = QgsGeometry::fromRect( options.filterExtent );
details.filterRectEngine.reset( QgsGeometry::createGeometryEngine( details.filterRectGeometry.constGet() ) );
details.filterRectEngine->prepareGeometry();
}
details.sourceFeatureIterator = layer->getFeatures( req );
return NoError;
}
QgsVectorFileWriter::WriterError QgsVectorFileWriter::writeAsVectorFormat( PreparedWriterDetails &details, const QString &fileName, const QgsVectorFileWriter::SaveVectorOptions &options, QString *newFilename, QString *errorMessage, QString *newLayer )
{
QgsWkbTypes::Type destWkbType = details.destWkbType;
int lastProgressReport = 0;
long total = details.featureCount;
// Special rules for OGR layers
if ( details.providerType == QLatin1String( "ogr" ) && !details.dataSourceUri.isEmpty() )
{
QString srcFileName( details.providerUriParams.value( QLatin1String( "path" ) ).toString() );
if ( QFile::exists( srcFileName ) && QFileInfo( fileName ).canonicalFilePath() == QFileInfo( srcFileName ).canonicalFilePath() )
{
// Check the layer name too if it's a GPKG/SpatiaLite/SQLite OGR driver (pay attention: camel case in layerName)
QgsDataSourceUri uri( details.dataSourceUri );
if ( !( ( options.driverName == QLatin1String( "GPKG" ) ||
options.driverName == QLatin1String( "SpatiaLite" ) ||
options.driverName == QLatin1String( "SQLite" ) ) &&
options.layerName != details.providerUriParams.value( QLatin1String( "layerName" ) ) ) )
{
if ( errorMessage )
*errorMessage = QObject::tr( "Cannot overwrite a OGR layer in place" );
return ErrCreateDataSource;
}
}
// Shapefiles might contain multi types although wkbType() only reports singles
if ( details.storageType == QLatin1String( "ESRI Shapefile" ) && !QgsWkbTypes::isMultiType( destWkbType ) )
{
QgsFeatureIterator fit = details.geometryTypeScanIterator;
QgsFeature fet;
long scanned = 0;
while ( fit.nextFeature( fet ) )
{
if ( options.feedback && options.feedback->isCanceled() )
{
return Canceled;
}
if ( options.feedback )
{
//dedicate first 5% of progress bar to this scan
int newProgress = static_cast<int>( ( 5.0 * scanned ) / total );
if ( newProgress != lastProgressReport )
{
lastProgressReport = newProgress;
options.feedback->setProgress( lastProgressReport );
}
}
if ( fet.hasGeometry() && QgsWkbTypes::isMultiType( fet.geometry().wkbType() ) )
{
destWkbType = QgsWkbTypes::multiType( destWkbType );
break;
}
scanned++;
}
}
}
std::unique_ptr< QgsVectorFileWriter > writer =
qgis::make_unique< QgsVectorFileWriter >( fileName,
options.fileEncoding, details.outputFields, destWkbType,
details.outputCrs, options.driverName,
options.datasourceOptions,
options.layerOptions,
newFilename,
options.symbologyExport,
options.fieldValueConverter,
options.layerName,
options.actionOnExistingFile,
newLayer );
writer->setSymbologyScale( options.symbologyScale );
if ( newFilename )
{
QgsDebugMsg( "newFilename = " + *newFilename );
}
// check whether file creation was successful
WriterError err = writer->hasError();
if ( err != NoError )
{
if ( errorMessage )
*errorMessage = writer->errorMessage();
return err;
}
if ( errorMessage )
{
errorMessage->clear();
}
QgsFeature fet;
//create symbol table if needed
if ( writer->symbologyExport() != NoSymbology )
{
//writer->createSymbolLayerTable( layer, writer->mDS );
}
if ( writer->symbologyExport() == SymbolLayerSymbology )
{
QgsFeatureRenderer *r = details.renderer.get();
if ( r && r->capabilities() & QgsFeatureRenderer::SymbolLevels
&& r->usingSymbolLevels() )
{
QgsVectorFileWriter::WriterError error = writer->exportFeaturesSymbolLevels( details, details.sourceFeatureIterator, options.ct, errorMessage );
return ( error == NoError ) ? NoError : ErrFeatureWriteFailed;
}
}
int n = 0, errors = 0;
//unit type
QgsUnitTypes::DistanceUnit mapUnits = details.sourceCrs.mapUnits();
if ( options.ct.isValid() )
{
mapUnits = options.ct.destinationCrs().mapUnits();
}
writer->startRender( details.renderer.get(), details.sourceFields );
writer->resetMap( details.attributes );
// Reset mFields to layer fields, and not just exported fields
writer->mFields = details.sourceFields;
// write all features
long saved = 0;
int initialProgress = lastProgressReport;
while ( details.sourceFeatureIterator.nextFeature( fet ) )
{
if ( options.feedback && options.feedback->isCanceled() )
{
return Canceled;
}
saved++;
if ( options.feedback )
{
//avoid spamming progress reports
int newProgress = static_cast<int>( initialProgress + ( ( 100.0 - initialProgress ) * saved ) / total );
if ( newProgress < 100 && newProgress != lastProgressReport )
{
lastProgressReport = newProgress;
options.feedback->setProgress( lastProgressReport );
}
}
if ( details.shallTransform )
{
try
{
if ( fet.hasGeometry() )
{
QgsGeometry g = fet.geometry();
g.transform( options.ct );
fet.setGeometry( g );
}
}
catch ( QgsCsException &e )
{
QString msg = QObject::tr( "Failed to transform a point while drawing a feature with ID '%1'. Writing stopped. (Exception: %2)" )
.arg( fet.id() ).arg( e.what() );
QgsLogger::warning( msg );
if ( errorMessage )
*errorMessage = msg;
return ErrProjection;
}
}
if ( fet.hasGeometry() && details.filterRectEngine && !details.filterRectEngine->intersects( fet.geometry().constGet() ) )
continue;
if ( details.attributes.empty() && options.skipAttributeCreation )
{
fet.initAttributes( 0 );
}
if ( !writer->addFeatureWithStyle( fet, writer->mRenderer.get(), mapUnits ) )
{
WriterError err = writer->hasError();
if ( err != NoError && errorMessage )
{
if ( errorMessage->isEmpty() )
{
*errorMessage = QObject::tr( "Feature write errors:" );
}
*errorMessage += '\n' + writer->errorMessage();
}
errors++;
if ( errors > 1000 )
{
if ( errorMessage )
{
*errorMessage += QObject::tr( "Stopping after %1 errors" ).arg( errors );
}
n = -1;
break;
}
}
n++;
}
writer->stopRender();
if ( errors > 0 && errorMessage && n > 0 )
{
*errorMessage += QObject::tr( "\nOnly %1 of %2 features written." ).arg( n - errors ).arg( n );
}
return errors == 0 ? NoError : ErrFeatureWriteFailed;
}
QgsVectorFileWriter::WriterError
QgsVectorFileWriter::writeAsVectorFormat( QgsVectorLayer *layer,
const QString &fileName,
const SaveVectorOptions &options,
QString *newFilename,
QString *errorMessage,
QString *newLayer )
{
QgsVectorFileWriter::PreparedWriterDetails details;
WriterError err = prepareWriteAsVectorFormat( layer, options, details );
if ( err != NoError )
return err;
return writeAsVectorFormat( details, fileName, options, newFilename, errorMessage, newLayer );
}
bool QgsVectorFileWriter::deleteShapeFile( const QString &fileName )
{
QFileInfo fi( fileName );
QDir dir = fi.dir();
QStringList filter;
const char *suffixes[] = { ".shp", ".shx", ".dbf", ".prj", ".qix", ".qpj", ".cpg", ".sbn", ".sbx", ".idm", ".ind" };
for ( std::size_t i = 0; i < sizeof( suffixes ) / sizeof( *suffixes ); i++ )
{
filter << fi.completeBaseName() + suffixes[i];
}
bool ok = true;
const auto constEntryList = dir.entryList( filter );
for ( const QString &file : constEntryList )
{
QFile f( dir.canonicalPath() + '/' + file );
if ( !f.remove() )
{
QgsDebugMsg( QStringLiteral( "Removing file %1 failed: %2" ).arg( file, f.errorString() ) );
ok = false;
}
}
return ok;
}
void QgsVectorFileWriter::setSymbologyScale( double d )
{
mSymbologyScale = d;
mRenderContext.setRendererScale( mSymbologyScale );
}
QList< QgsVectorFileWriter::FilterFormatDetails > QgsVectorFileWriter::supportedFiltersAndFormats( const VectorFormatOptions options )
{
QList< FilterFormatDetails > results;
QgsApplication::registerOgrDrivers();
int const drvCount = OGRGetDriverCount();
for ( int i = 0; i < drvCount; ++i )
{
OGRSFDriverH drv = OGRGetDriver( i );
if ( drv )
{
QString drvName = OGR_Dr_GetName( drv );
#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(2,3,0)
GDALDriverH gdalDriver = GDALGetDriverByName( drvName.toLocal8Bit().constData() );
char **metadata = nullptr;
if ( gdalDriver )
{
metadata = GDALGetMetadata( gdalDriver, nullptr );
}
bool nonSpatialFormat = CSLFetchBoolean( metadata, GDAL_DCAP_NONSPATIAL, false );
#else
bool nonSpatialFormat = ( drvName == QLatin1String( "ODS" ) || drvName == QLatin1String( "XLSX" ) || drvName == QLatin1String( "XLS" ) );
#endif
if ( OGR_Dr_TestCapability( drv, "CreateDataSource" ) != 0 )
{
if ( options & SkipNonSpatialFormats )
{
// skip non-spatial formats
if ( nonSpatialFormat )
continue;
}
QString filterString = filterForDriver( drvName );
if ( filterString.isEmpty() )
continue;
MetaData metadata;
QStringList globs;
if ( driverMetadata( drvName, metadata ) && !metadata.glob.isEmpty() )
{
globs = metadata.glob.toLower().split( ' ' );
}
FilterFormatDetails details;
details.driverName = drvName;
details.filterString = filterString;
details.globs = globs;
results << details;
}
}
}
std::sort( results.begin(), results.end(), [options]( const FilterFormatDetails & a, const FilterFormatDetails & b ) -> bool
{
if ( options & SortRecommended )
{
if ( a.driverName == QLatin1String( "GPKG" ) )
return true; // Make https://twitter.com/shapefiIe a sad little fellow
else if ( b.driverName == QLatin1String( "GPKG" ) )
return false;
else if ( a.driverName == QLatin1String( "ESRI Shapefile" ) )
return true;
else if ( b.driverName == QLatin1String( "ESRI Shapefile" ) )
return false;
}
return a.filterString.toLower().localeAwareCompare( b.filterString.toLower() ) < 0;
} );
return results;
}
QStringList QgsVectorFileWriter::supportedFormatExtensions( const VectorFormatOptions options )
{
const auto formats = supportedFiltersAndFormats( options );
QSet< QString > extensions;
const QRegularExpression rx( QStringLiteral( "\\*\\.(.*)$" ) );
for ( const FilterFormatDetails &format : formats )
{
for ( const QString &glob : format.globs )
{
const QRegularExpressionMatch match = rx.match( glob );
if ( !match.hasMatch() )
continue;
const QString matched = match.captured( 1 );
extensions.insert( matched );
}
}
QStringList extensionList = extensions.toList();
std::sort( extensionList.begin(), extensionList.end(), [options]( const QString & a, const QString & b ) -> bool
{
if ( options & SortRecommended )
{
if ( a == QLatin1String( "gpkg" ) )
return true; // Make https://twitter.com/shapefiIe a sad little fellow
else if ( b == QLatin1String( "gpkg" ) )
return false;
else if ( a == QLatin1String( "shp" ) )
return true;
else if ( b == QLatin1String( "shp" ) )
return false;
}
return a.toLower().localeAwareCompare( b.toLower() ) < 0;
} );
return extensionList;
}
QList< QgsVectorFileWriter::DriverDetails > QgsVectorFileWriter::ogrDriverList( const VectorFormatOptions options )
{
QList< QgsVectorFileWriter::DriverDetails > results;
QgsApplication::registerOgrDrivers();
const int drvCount = OGRGetDriverCount();
QStringList writableDrivers;
for ( int i = 0; i < drvCount; ++i )
{
OGRSFDriverH drv = OGRGetDriver( i );
if ( drv )
{
QString drvName = OGR_Dr_GetName( drv );
if ( options & SkipNonSpatialFormats )
{
// skip non-spatial formats
// TODO - use GDAL metadata to determine this, when support exists in GDAL
if ( drvName == QLatin1String( "ODS" ) || drvName == QLatin1String( "XLSX" ) || drvName == QLatin1String( "XLS" ) )
continue;
}
if ( drvName == QLatin1String( "ESRI Shapefile" ) )
{
writableDrivers << QStringLiteral( "DBF file" );
}
if ( OGR_Dr_TestCapability( drv, "CreateDataSource" ) != 0 )
{
// Add separate format for Mapinfo MIF (MITAB is OGR default)
if ( drvName == QLatin1String( "MapInfo File" ) )
{
writableDrivers << QStringLiteral( "MapInfo MIF" );
}
else if ( drvName == QLatin1String( "SQLite" ) )
{
// Unfortunately it seems that there is no simple way to detect if
// OGR SQLite driver is compiled with SpatiaLite support.
// We have HAVE_SPATIALITE in QGIS, but that may differ from OGR
// http://lists.osgeo.org/pipermail/gdal-dev/2012-November/034580.html
// -> test if creation failes
QString option = QStringLiteral( "SPATIALITE=YES" );
char *options[2] = { CPLStrdup( option.toLocal8Bit().constData() ), nullptr };
OGRSFDriverH poDriver;
QgsApplication::registerOgrDrivers();
poDriver = OGRGetDriverByName( drvName.toLocal8Bit().constData() );
if ( poDriver )
{
gdal::ogr_datasource_unique_ptr ds( OGR_Dr_CreateDataSource( poDriver, QStringLiteral( "/vsimem/spatialitetest.sqlite" ).toUtf8().constData(), options ) );
if ( ds )
{
writableDrivers << QStringLiteral( "SpatiaLite" );
OGR_Dr_DeleteDataSource( poDriver, QStringLiteral( "/vsimem/spatialitetest.sqlite" ).toUtf8().constData() );
}
}
CPLFree( options[0] );
}
writableDrivers << drvName;
}
}
}
results.reserve( writableDrivers.count() );
for ( const QString &drvName : qgis::as_const( writableDrivers ) )
{
MetaData metadata;
if ( driverMetadata( drvName, metadata ) && !metadata.trLongName.isEmpty() )
{
DriverDetails details;
details.driverName = drvName;
details.longName = metadata.trLongName;
results << details;
}
}
std::sort( results.begin(), results.end(), [options]( const DriverDetails & a, const DriverDetails & b ) -> bool
{
if ( options & SortRecommended )
{
if ( a.driverName == QLatin1String( "GPKG" ) )
return true; // Make https://twitter.com/shapefiIe a sad little fellow
else if ( b.driverName == QLatin1String( "GPKG" ) )
return false;
else if ( a.driverName == QLatin1String( "ESRI Shapefile" ) )
return true;
else if ( b.driverName == QLatin1String( "ESRI Shapefile" ) )
return false;
}
return a.longName.toLower().localeAwareCompare( b.longName.toLower() ) < 0;
} );
return results;
}
QString QgsVectorFileWriter::driverForExtension( const QString &extension )
{
QString ext = extension.trimmed();
if ( ext.isEmpty() )
return QString();
if ( ext.startsWith( '.' ) )
ext.remove( 0, 1 );
GDALAllRegister();
int const drvCount = GDALGetDriverCount();
for ( int i = 0; i < drvCount; ++i )
{
GDALDriverH drv = GDALGetDriver( i );
if ( drv )
{
char **driverMetadata = GDALGetMetadata( drv, nullptr );
if ( CSLFetchBoolean( driverMetadata, GDAL_DCAP_CREATE, false ) && CSLFetchBoolean( driverMetadata, GDAL_DCAP_VECTOR, false ) )
{
QString drvName = GDALGetDriverShortName( drv );
QStringList driverExtensions = QString( GDALGetMetadataItem( drv, GDAL_DMD_EXTENSIONS, nullptr ) ).split( ' ' );
const auto constDriverExtensions = driverExtensions;
for ( const QString &driver : constDriverExtensions )
{
if ( driver.compare( ext, Qt::CaseInsensitive ) == 0 )
return drvName;
}
}
}
}
return QString();
}
QString QgsVectorFileWriter::fileFilterString( const VectorFormatOptions options )
{
QString filterString;
const auto driverFormats = supportedFiltersAndFormats( options );
for ( const FilterFormatDetails &details : driverFormats )
{
if ( !filterString.isEmpty() )
filterString += QLatin1String( ";;" );
filterString += details.filterString;
}
return filterString;
}
QString QgsVectorFileWriter::filterForDriver( const QString &driverName )
{
MetaData metadata;
if ( !driverMetadata( driverName, metadata ) || metadata.trLongName.isEmpty() || metadata.glob.isEmpty() )
return QString();
return QStringLiteral( "%1 (%2 %3)" ).arg( metadata.trLongName,
metadata.glob.toLower(),
metadata.glob.toUpper() );
}
QString QgsVectorFileWriter::convertCodecNameForEncodingOption( const QString &codecName )
{
if ( codecName == QLatin1String( "System" ) )
return QStringLiteral( "LDID/0" );
QRegExp re = QRegExp( QString( "(CP|windows-|ISO[ -])(.+)" ), Qt::CaseInsensitive );
if ( re.exactMatch( codecName ) )
{
QString c = re.cap( 2 ).remove( '-' );
bool isNumber;
c.toInt( &isNumber );
if ( isNumber )
return c;
}
return codecName;
}
void QgsVectorFileWriter::createSymbolLayerTable( QgsVectorLayer *vl, const QgsCoordinateTransform &ct, OGRDataSourceH ds )
{
if ( !vl || !ds )
{
return;
}
QgsFeatureRenderer *renderer = vl->renderer();
if ( !renderer )
{
return;
}
//unit type
QgsUnitTypes::DistanceUnit mapUnits = vl->crs().mapUnits();
if ( ct.isValid() )
{
mapUnits = ct.destinationCrs().mapUnits();
}
mSymbolLayerTable.clear();
OGRStyleTableH ogrStyleTable = OGR_STBL_Create();
OGRStyleMgrH styleManager = OGR_SM_Create( ogrStyleTable );
//get symbols
int nTotalLevels = 0;
QgsSymbolList symbolList = renderer->symbols( mRenderContext );
QgsSymbolList::iterator symbolIt = symbolList.begin();
for ( ; symbolIt != symbolList.end(); ++symbolIt )
{
double mmsf = mmScaleFactor( mSymbologyScale, ( *symbolIt )->outputUnit(), mapUnits );
double musf = mapUnitScaleFactor( mSymbologyScale, ( *symbolIt )->outputUnit(), mapUnits );
int nLevels = ( *symbolIt )->symbolLayerCount();
for ( int i = 0; i < nLevels; ++i )
{
mSymbolLayerTable.insert( ( *symbolIt )->symbolLayer( i ), QString::number( nTotalLevels ) );
OGR_SM_AddStyle( styleManager, QString::number( nTotalLevels ).toLocal8Bit(),
( *symbolIt )->symbolLayer( i )->ogrFeatureStyle( mmsf, musf ).toLocal8Bit() );
++nTotalLevels;
}
}
OGR_DS_SetStyleTableDirectly( ds, ogrStyleTable );
}
QgsVectorFileWriter::WriterError QgsVectorFileWriter::exportFeaturesSymbolLevels( const PreparedWriterDetails &details, QgsFeatureIterator &fit,
const QgsCoordinateTransform &ct, QString *errorMessage )
{
if ( !details.renderer )
return ErrInvalidLayer;
mRenderContext.expressionContext() = details.expressionContext;
QHash< QgsSymbol *, QList<QgsFeature> > features;
//unit type
QgsUnitTypes::DistanceUnit mapUnits = details.sourceCrs.mapUnits();
if ( ct.isValid() )
{
mapUnits = ct.destinationCrs().mapUnits();
}
startRender( details.renderer.get(), details.sourceFields );
//fetch features
QgsFeature fet;
QgsSymbol *featureSymbol = nullptr;
while ( fit.nextFeature( fet ) )
{
if ( ct.isValid() )
{
try
{
if ( fet.hasGeometry() )
{
QgsGeometry g = fet.geometry();
g.transform( ct );
fet.setGeometry( g );
}
}
catch ( QgsCsException &e )
{
QString msg = QObject::tr( "Failed to transform, writing stopped. (Exception: %1)" )
.arg( e.what() );
QgsLogger::warning( msg );
if ( errorMessage )
*errorMessage = msg;
return ErrProjection;
}
}
mRenderContext.expressionContext().setFeature( fet );
featureSymbol = mRenderer->symbolForFeature( fet, mRenderContext );
if ( !featureSymbol )
{
continue;
}
QHash< QgsSymbol *, QList<QgsFeature> >::iterator it = features.find( featureSymbol );
if ( it == features.end() )
{
it = features.insert( featureSymbol, QList<QgsFeature>() );
}
it.value().append( fet );
}
//find out order
QgsSymbolLevelOrder levels;
QgsSymbolList symbols = mRenderer->symbols( mRenderContext );
for ( int i = 0; i < symbols.count(); i++ )
{
QgsSymbol *sym = symbols[i];
for ( int j = 0; j < sym->symbolLayerCount(); j++ )
{
int level = sym->symbolLayer( j )->renderingPass();
if ( level < 0 || level >= 1000 ) // ignore invalid levels
continue;
QgsSymbolLevelItem item( sym, j );
while ( level >= levels.count() ) // append new empty levels
levels.append( QgsSymbolLevel() );
levels[level].append( item );
}
}
int nErrors = 0;
int nTotalFeatures = 0;
//export symbol layers and symbology
for ( int l = 0; l < levels.count(); l++ )
{
QgsSymbolLevel &level = levels[l];
for ( int i = 0; i < level.count(); i++ )
{
QgsSymbolLevelItem &item = level[i];
QHash< QgsSymbol *, QList<QgsFeature> >::iterator levelIt = features.find( item.symbol() );
if ( levelIt == features.end() )
{
++nErrors;
continue;
}
double mmsf = mmScaleFactor( mSymbologyScale, levelIt.key()->outputUnit(), mapUnits );
double musf = mapUnitScaleFactor( mSymbologyScale, levelIt.key()->outputUnit(), mapUnits );
int llayer = item.layer();
QList<QgsFeature> &featureList = levelIt.value();
QList<QgsFeature>::iterator featureIt = featureList.begin();
for ( ; featureIt != featureList.end(); ++featureIt )
{
++nTotalFeatures;
gdal::ogr_feature_unique_ptr ogrFeature = createFeature( *featureIt );
if ( !ogrFeature )
{
++nErrors;
continue;
}
QString styleString = levelIt.key()->symbolLayer( llayer )->ogrFeatureStyle( mmsf, musf );
if ( !styleString.isEmpty() )
{
OGR_F_SetStyleString( ogrFeature.get(), styleString.toLocal8Bit().constData() );
if ( !writeFeature( mLayer, ogrFeature.get() ) )
{
++nErrors;
}
}
}
}
}
stopRender();
if ( nErrors > 0 && errorMessage )
{
*errorMessage += QObject::tr( "\nOnly %1 of %2 features written." ).arg( nTotalFeatures - nErrors ).arg( nTotalFeatures );
}
return ( nErrors > 0 ) ? QgsVectorFileWriter::ErrFeatureWriteFailed : QgsVectorFileWriter::NoError;
}
double QgsVectorFileWriter::mmScaleFactor( double scale, QgsUnitTypes::RenderUnit symbolUnits, QgsUnitTypes::DistanceUnit mapUnits )
{
if ( symbolUnits == QgsUnitTypes::RenderMillimeters )
{
return 1.0;
}
else
{
//conversion factor map units -> mm
if ( mapUnits == QgsUnitTypes::DistanceMeters )
{
return 1000 / scale;
}
}
return 1.0; //todo: map units
}
double QgsVectorFileWriter::mapUnitScaleFactor( double scale, QgsUnitTypes::RenderUnit symbolUnits, QgsUnitTypes::DistanceUnit mapUnits )
{
if ( symbolUnits == QgsUnitTypes::RenderMapUnits )
{
return 1.0;
}
else
{
if ( symbolUnits == QgsUnitTypes::RenderMillimeters && mapUnits == QgsUnitTypes::DistanceMeters )
{
return scale / 1000;
}
}
return 1.0;
}
void QgsVectorFileWriter::startRender( QgsFeatureRenderer *sourceRenderer, const QgsFields &fields )
{
mRenderer = createSymbologyRenderer( sourceRenderer );
if ( !mRenderer )
{
return;
}
mRenderer->startRender( mRenderContext, fields );
}
void QgsVectorFileWriter::stopRender()
{
if ( !mRenderer )
{
return;
}
mRenderer->stopRender( mRenderContext );
}
std::unique_ptr<QgsFeatureRenderer> QgsVectorFileWriter::createSymbologyRenderer( QgsFeatureRenderer *sourceRenderer ) const
{
if ( mSymbologyExport == NoSymbology )
{
return nullptr;
}
if ( !sourceRenderer )
{
return nullptr;
}
return std::unique_ptr< QgsFeatureRenderer >( sourceRenderer->clone() );
}
void QgsVectorFileWriter::addRendererAttributes( QgsFeatureRenderer *renderer, QgsRenderContext &context, const QgsFields &fields, QgsAttributeList &attList )
{
if ( renderer )
{
const QSet<QString> rendererAttributes = renderer->usedAttributes( context );
for ( const QString &attr : rendererAttributes )
{
int index = fields.lookupField( attr );
if ( index != -1 )
{
attList.append( index );
}
}
}
}
QStringList QgsVectorFileWriter::concatenateOptions( const QMap<QString, QgsVectorFileWriter::Option *> &options )
{
QStringList list;
QMap<QString, QgsVectorFileWriter::Option *>::ConstIterator it;
for ( it = options.constBegin(); it != options.constEnd(); ++it )
{
QgsVectorFileWriter::Option *option = it.value();
switch ( option->type )
{
case QgsVectorFileWriter::Int:
{
QgsVectorFileWriter::IntOption *opt = dynamic_cast<QgsVectorFileWriter::IntOption *>( option );
if ( opt )
{
list.append( QStringLiteral( "%1=%2" ).arg( it.key() ).arg( opt->defaultValue ) );
}
break;
}
case QgsVectorFileWriter::Set:
{
QgsVectorFileWriter::SetOption *opt = dynamic_cast<QgsVectorFileWriter::SetOption *>( option );
if ( opt && !opt->defaultValue.isEmpty() )
{
list.append( QStringLiteral( "%1=%2" ).arg( it.key(), opt->defaultValue ) );
}
break;
}
case QgsVectorFileWriter::String:
{
QgsVectorFileWriter::StringOption *opt = dynamic_cast<QgsVectorFileWriter::StringOption *>( option );
if ( opt && !opt->defaultValue.isNull() )
{
list.append( QStringLiteral( "%1=%2" ).arg( it.key(), opt->defaultValue ) );
}
break;
}
case QgsVectorFileWriter::Hidden:
QgsVectorFileWriter::HiddenOption *opt = dynamic_cast<QgsVectorFileWriter::HiddenOption *>( option );
if ( opt )
{
list.append( QStringLiteral( "%1=%2" ).arg( it.key(), opt->mValue ) );
}
break;
}
}
return list;
}
QgsVectorFileWriter::EditionCapabilities QgsVectorFileWriter::editionCapabilities( const QString &datasetName )
{
OGRSFDriverH hDriver = nullptr;
gdal::ogr_datasource_unique_ptr hDS( myOGROpen( datasetName.toUtf8().constData(), TRUE, &hDriver ) );
if ( !hDS )
return nullptr;
QString drvName = OGR_Dr_GetName( hDriver );
QgsVectorFileWriter::EditionCapabilities caps = nullptr;
if ( OGR_DS_TestCapability( hDS.get(), ODsCCreateLayer ) )
{
// Shapefile driver returns True for a "foo.shp" dataset name,
// creating "bar.shp" new layer, but this would be a bit confusing
// for the user, so pretent that it does not support that
if ( !( drvName == QLatin1String( "ESRI Shapefile" ) && QFile::exists( datasetName ) ) )
caps |= CanAddNewLayer;
}
if ( OGR_DS_TestCapability( hDS.get(), ODsCDeleteLayer ) )
{
caps |= CanDeleteLayer;
}
int layer_count = OGR_DS_GetLayerCount( hDS.get() );
if ( layer_count )
{
OGRLayerH hLayer = OGR_DS_GetLayer( hDS.get(), 0 );
if ( hLayer )
{
if ( OGR_L_TestCapability( hLayer, OLCSequentialWrite ) )
{
caps |= CanAppendToExistingLayer;
if ( OGR_L_TestCapability( hLayer, OLCCreateField ) )
{
caps |= CanAddNewFieldsToExistingLayer;
}
}
}
}
return caps;
}
bool QgsVectorFileWriter::targetLayerExists( const QString &datasetName,
const QString &layerNameIn )
{
OGRSFDriverH hDriver = nullptr;
gdal::ogr_datasource_unique_ptr hDS( myOGROpen( datasetName.toUtf8().constData(), TRUE, &hDriver ) );
if ( !hDS )
return false;
QString layerName( layerNameIn );
if ( layerName.isEmpty() )
layerName = QFileInfo( datasetName ).baseName();
return OGR_DS_GetLayerByName( hDS.get(), layerName.toUtf8().constData() );
}
bool QgsVectorFileWriter::areThereNewFieldsToCreate( const QString &datasetName,
const QString &layerName,
QgsVectorLayer *layer,
const QgsAttributeList &attributes )
{
OGRSFDriverH hDriver = nullptr;
gdal::ogr_datasource_unique_ptr hDS( myOGROpen( datasetName.toUtf8().constData(), TRUE, &hDriver ) );
if ( !hDS )
return false;
OGRLayerH hLayer = OGR_DS_GetLayerByName( hDS.get(), layerName.toUtf8().constData() );
if ( !hLayer )
{
return false;
}
bool ret = false;
OGRFeatureDefnH defn = OGR_L_GetLayerDefn( hLayer );
const auto constAttributes = attributes;
for ( int idx : constAttributes )
{
QgsField fld = layer->fields().at( idx );
if ( OGR_FD_GetFieldIndex( defn, fld.name().toUtf8().constData() ) < 0 )
{
ret = true;
break;
}
}
return ret;
}
| 41.334974 | 251 | 0.539554 | [
"geometry",
"shape",
"vector",
"transform",
"3d"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.